drm/amd/pm: correct Polaris powertune table setup
[linux-2.6-microblaze.git] / drivers / gpu / drm / drm_dp_helper.c
1 /*
2  * Copyright © 2009 Keith Packard
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/i2c.h>
26 #include <linux/init.h>
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/sched.h>
30 #include <linux/seq_file.h>
31
32 #include <drm/drm_dp_helper.h>
33 #include <drm/drm_print.h>
34 #include <drm/drm_vblank.h>
35 #include <drm/drm_dp_mst_helper.h>
36
37 #include "drm_crtc_helper_internal.h"
38
39 /**
40  * DOC: dp helpers
41  *
42  * These functions contain some common logic and helpers at various abstraction
43  * levels to deal with Display Port sink devices and related things like DP aux
44  * channel transfers, EDID reading over DP aux channels, decoding certain DPCD
45  * blocks, ...
46  */
47
48 /* Helpers for DP link training */
49 static u8 dp_link_status(const u8 link_status[DP_LINK_STATUS_SIZE], int r)
50 {
51         return link_status[r - DP_LANE0_1_STATUS];
52 }
53
54 static u8 dp_get_lane_status(const u8 link_status[DP_LINK_STATUS_SIZE],
55                              int lane)
56 {
57         int i = DP_LANE0_1_STATUS + (lane >> 1);
58         int s = (lane & 1) * 4;
59         u8 l = dp_link_status(link_status, i);
60
61         return (l >> s) & 0xf;
62 }
63
64 bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
65                           int lane_count)
66 {
67         u8 lane_align;
68         u8 lane_status;
69         int lane;
70
71         lane_align = dp_link_status(link_status,
72                                     DP_LANE_ALIGN_STATUS_UPDATED);
73         if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
74                 return false;
75         for (lane = 0; lane < lane_count; lane++) {
76                 lane_status = dp_get_lane_status(link_status, lane);
77                 if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
78                         return false;
79         }
80         return true;
81 }
82 EXPORT_SYMBOL(drm_dp_channel_eq_ok);
83
84 bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
85                               int lane_count)
86 {
87         int lane;
88         u8 lane_status;
89
90         for (lane = 0; lane < lane_count; lane++) {
91                 lane_status = dp_get_lane_status(link_status, lane);
92                 if ((lane_status & DP_LANE_CR_DONE) == 0)
93                         return false;
94         }
95         return true;
96 }
97 EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
98
99 u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
100                                      int lane)
101 {
102         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
103         int s = ((lane & 1) ?
104                  DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
105                  DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
106         u8 l = dp_link_status(link_status, i);
107
108         return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
109 }
110 EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
111
112 u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
113                                           int lane)
114 {
115         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
116         int s = ((lane & 1) ?
117                  DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
118                  DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
119         u8 l = dp_link_status(link_status, i);
120
121         return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
122 }
123 EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
124
125 u8 drm_dp_get_adjust_request_post_cursor(const u8 link_status[DP_LINK_STATUS_SIZE],
126                                          unsigned int lane)
127 {
128         unsigned int offset = DP_ADJUST_REQUEST_POST_CURSOR2;
129         u8 value = dp_link_status(link_status, offset);
130
131         return (value >> (lane << 1)) & 0x3;
132 }
133 EXPORT_SYMBOL(drm_dp_get_adjust_request_post_cursor);
134
135 void drm_dp_link_train_clock_recovery_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
136 {
137         unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
138                                          DP_TRAINING_AUX_RD_MASK;
139
140         if (rd_interval > 4)
141                 DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
142                               rd_interval);
143
144         if (rd_interval == 0 || dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
145                 rd_interval = 100;
146         else
147                 rd_interval *= 4 * USEC_PER_MSEC;
148
149         usleep_range(rd_interval, rd_interval * 2);
150 }
151 EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
152
153 void drm_dp_link_train_channel_eq_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
154 {
155         unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
156                                          DP_TRAINING_AUX_RD_MASK;
157
158         if (rd_interval > 4)
159                 DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
160                               rd_interval);
161
162         if (rd_interval == 0)
163                 rd_interval = 400;
164         else
165                 rd_interval *= 4 * USEC_PER_MSEC;
166
167         usleep_range(rd_interval, rd_interval * 2);
168 }
169 EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
170
171 u8 drm_dp_link_rate_to_bw_code(int link_rate)
172 {
173         /* Spec says link_bw = link_rate / 0.27Gbps */
174         return link_rate / 27000;
175 }
176 EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
177
178 int drm_dp_bw_code_to_link_rate(u8 link_bw)
179 {
180         /* Spec says link_rate = link_bw * 0.27Gbps */
181         return link_bw * 27000;
182 }
183 EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
184
185 #define AUX_RETRY_INTERVAL 500 /* us */
186
187 static inline void
188 drm_dp_dump_access(const struct drm_dp_aux *aux,
189                    u8 request, uint offset, void *buffer, int ret)
190 {
191         const char *arrow = request == DP_AUX_NATIVE_READ ? "->" : "<-";
192
193         if (ret > 0)
194                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d) %*ph\n",
195                              aux->name, offset, arrow, ret, min(ret, 20), buffer);
196         else
197                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d)\n",
198                              aux->name, offset, arrow, ret);
199 }
200
201 /**
202  * DOC: dp helpers
203  *
204  * The DisplayPort AUX channel is an abstraction to allow generic, driver-
205  * independent access to AUX functionality. Drivers can take advantage of
206  * this by filling in the fields of the drm_dp_aux structure.
207  *
208  * Transactions are described using a hardware-independent drm_dp_aux_msg
209  * structure, which is passed into a driver's .transfer() implementation.
210  * Both native and I2C-over-AUX transactions are supported.
211  */
212
213 static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
214                               unsigned int offset, void *buffer, size_t size)
215 {
216         struct drm_dp_aux_msg msg;
217         unsigned int retry, native_reply;
218         int err = 0, ret = 0;
219
220         memset(&msg, 0, sizeof(msg));
221         msg.address = offset;
222         msg.request = request;
223         msg.buffer = buffer;
224         msg.size = size;
225
226         mutex_lock(&aux->hw_mutex);
227
228         /*
229          * The specification doesn't give any recommendation on how often to
230          * retry native transactions. We used to retry 7 times like for
231          * aux i2c transactions but real world devices this wasn't
232          * sufficient, bump to 32 which makes Dell 4k monitors happier.
233          */
234         for (retry = 0; retry < 32; retry++) {
235                 if (ret != 0 && ret != -ETIMEDOUT) {
236                         usleep_range(AUX_RETRY_INTERVAL,
237                                      AUX_RETRY_INTERVAL + 100);
238                 }
239
240                 ret = aux->transfer(aux, &msg);
241                 if (ret >= 0) {
242                         native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
243                         if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
244                                 if (ret == size)
245                                         goto unlock;
246
247                                 ret = -EPROTO;
248                         } else
249                                 ret = -EIO;
250                 }
251
252                 /*
253                  * We want the error we return to be the error we received on
254                  * the first transaction, since we may get a different error the
255                  * next time we retry
256                  */
257                 if (!err)
258                         err = ret;
259         }
260
261         DRM_DEBUG_KMS("%s: Too many retries, giving up. First error: %d\n",
262                       aux->name, err);
263         ret = err;
264
265 unlock:
266         mutex_unlock(&aux->hw_mutex);
267         return ret;
268 }
269
270 /**
271  * drm_dp_dpcd_read() - read a series of bytes from the DPCD
272  * @aux: DisplayPort AUX channel (SST or MST)
273  * @offset: address of the (first) register to read
274  * @buffer: buffer to store the register values
275  * @size: number of bytes in @buffer
276  *
277  * Returns the number of bytes transferred on success, or a negative error
278  * code on failure. -EIO is returned if the request was NAKed by the sink or
279  * if the retry count was exceeded. If not all bytes were transferred, this
280  * function returns -EPROTO. Errors from the underlying AUX channel transfer
281  * function, with the exception of -EBUSY (which causes the transaction to
282  * be retried), are propagated to the caller.
283  */
284 ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
285                          void *buffer, size_t size)
286 {
287         int ret;
288
289         /*
290          * HP ZR24w corrupts the first DPCD access after entering power save
291          * mode. Eg. on a read, the entire buffer will be filled with the same
292          * byte. Do a throw away read to avoid corrupting anything we care
293          * about. Afterwards things will work correctly until the monitor
294          * gets woken up and subsequently re-enters power save mode.
295          *
296          * The user pressing any button on the monitor is enough to wake it
297          * up, so there is no particularly good place to do the workaround.
298          * We just have to do it before any DPCD access and hope that the
299          * monitor doesn't power down exactly after the throw away read.
300          */
301         if (!aux->is_remote) {
302                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, DP_DPCD_REV,
303                                          buffer, 1);
304                 if (ret != 1)
305                         goto out;
306         }
307
308         if (aux->is_remote)
309                 ret = drm_dp_mst_dpcd_read(aux, offset, buffer, size);
310         else
311                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset,
312                                          buffer, size);
313
314 out:
315         drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, buffer, ret);
316         return ret;
317 }
318 EXPORT_SYMBOL(drm_dp_dpcd_read);
319
320 /**
321  * drm_dp_dpcd_write() - write a series of bytes to the DPCD
322  * @aux: DisplayPort AUX channel (SST or MST)
323  * @offset: address of the (first) register to write
324  * @buffer: buffer containing the values to write
325  * @size: number of bytes in @buffer
326  *
327  * Returns the number of bytes transferred on success, or a negative error
328  * code on failure. -EIO is returned if the request was NAKed by the sink or
329  * if the retry count was exceeded. If not all bytes were transferred, this
330  * function returns -EPROTO. Errors from the underlying AUX channel transfer
331  * function, with the exception of -EBUSY (which causes the transaction to
332  * be retried), are propagated to the caller.
333  */
334 ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
335                           void *buffer, size_t size)
336 {
337         int ret;
338
339         if (aux->is_remote)
340                 ret = drm_dp_mst_dpcd_write(aux, offset, buffer, size);
341         else
342                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset,
343                                          buffer, size);
344
345         drm_dp_dump_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer, ret);
346         return ret;
347 }
348 EXPORT_SYMBOL(drm_dp_dpcd_write);
349
350 /**
351  * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
352  * @aux: DisplayPort AUX channel
353  * @status: buffer to store the link status in (must be at least 6 bytes)
354  *
355  * Returns the number of bytes transferred on success or a negative error
356  * code on failure.
357  */
358 int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
359                                  u8 status[DP_LINK_STATUS_SIZE])
360 {
361         return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
362                                 DP_LINK_STATUS_SIZE);
363 }
364 EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
365
366 /**
367  * drm_dp_send_real_edid_checksum() - send back real edid checksum value
368  * @aux: DisplayPort AUX channel
369  * @real_edid_checksum: real edid checksum for the last block
370  *
371  * Returns:
372  * True on success
373  */
374 bool drm_dp_send_real_edid_checksum(struct drm_dp_aux *aux,
375                                     u8 real_edid_checksum)
376 {
377         u8 link_edid_read = 0, auto_test_req = 0, test_resp = 0;
378
379         if (drm_dp_dpcd_read(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
380                              &auto_test_req, 1) < 1) {
381                 DRM_ERROR("%s: DPCD failed read at register 0x%x\n",
382                           aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
383                 return false;
384         }
385         auto_test_req &= DP_AUTOMATED_TEST_REQUEST;
386
387         if (drm_dp_dpcd_read(aux, DP_TEST_REQUEST, &link_edid_read, 1) < 1) {
388                 DRM_ERROR("%s: DPCD failed read at register 0x%x\n",
389                           aux->name, DP_TEST_REQUEST);
390                 return false;
391         }
392         link_edid_read &= DP_TEST_LINK_EDID_READ;
393
394         if (!auto_test_req || !link_edid_read) {
395                 DRM_DEBUG_KMS("%s: Source DUT does not support TEST_EDID_READ\n",
396                               aux->name);
397                 return false;
398         }
399
400         if (drm_dp_dpcd_write(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
401                               &auto_test_req, 1) < 1) {
402                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
403                           aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
404                 return false;
405         }
406
407         /* send back checksum for the last edid extension block data */
408         if (drm_dp_dpcd_write(aux, DP_TEST_EDID_CHECKSUM,
409                               &real_edid_checksum, 1) < 1) {
410                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
411                           aux->name, DP_TEST_EDID_CHECKSUM);
412                 return false;
413         }
414
415         test_resp |= DP_TEST_EDID_CHECKSUM_WRITE;
416         if (drm_dp_dpcd_write(aux, DP_TEST_RESPONSE, &test_resp, 1) < 1) {
417                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
418                           aux->name, DP_TEST_RESPONSE);
419                 return false;
420         }
421
422         return true;
423 }
424 EXPORT_SYMBOL(drm_dp_send_real_edid_checksum);
425
426 static u8 drm_dp_downstream_port_count(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
427 {
428         u8 port_count = dpcd[DP_DOWN_STREAM_PORT_COUNT] & DP_PORT_COUNT_MASK;
429
430         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE && port_count > 4)
431                 port_count = 4;
432
433         return port_count;
434 }
435
436 static int drm_dp_read_extended_dpcd_caps(struct drm_dp_aux *aux,
437                                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
438 {
439         u8 dpcd_ext[6];
440         int ret;
441
442         /*
443          * Prior to DP1.3 the bit represented by
444          * DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT was reserved.
445          * If it is set DP_DPCD_REV at 0000h could be at a value less than
446          * the true capability of the panel. The only way to check is to
447          * then compare 0000h and 2200h.
448          */
449         if (!(dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
450               DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT))
451                 return 0;
452
453         ret = drm_dp_dpcd_read(aux, DP_DP13_DPCD_REV, &dpcd_ext,
454                                sizeof(dpcd_ext));
455         if (ret < 0)
456                 return ret;
457         if (ret != sizeof(dpcd_ext))
458                 return -EIO;
459
460         if (dpcd[DP_DPCD_REV] > dpcd_ext[DP_DPCD_REV]) {
461                 DRM_DEBUG_KMS("%s: Extended DPCD rev less than base DPCD rev (%d > %d)\n",
462                               aux->name, dpcd[DP_DPCD_REV],
463                               dpcd_ext[DP_DPCD_REV]);
464                 return 0;
465         }
466
467         if (!memcmp(dpcd, dpcd_ext, sizeof(dpcd_ext)))
468                 return 0;
469
470         DRM_DEBUG_KMS("%s: Base DPCD: %*ph\n",
471                       aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
472
473         memcpy(dpcd, dpcd_ext, sizeof(dpcd_ext));
474
475         return 0;
476 }
477
478 /**
479  * drm_dp_read_dpcd_caps() - read DPCD caps and extended DPCD caps if
480  * available
481  * @aux: DisplayPort AUX channel
482  * @dpcd: Buffer to store the resulting DPCD in
483  *
484  * Attempts to read the base DPCD caps for @aux. Additionally, this function
485  * checks for and reads the extended DPRX caps (%DP_DP13_DPCD_REV) if
486  * present.
487  *
488  * Returns: %0 if the DPCD was read successfully, negative error code
489  * otherwise.
490  */
491 int drm_dp_read_dpcd_caps(struct drm_dp_aux *aux,
492                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
493 {
494         int ret;
495
496         ret = drm_dp_dpcd_read(aux, DP_DPCD_REV, dpcd, DP_RECEIVER_CAP_SIZE);
497         if (ret < 0)
498                 return ret;
499         if (ret != DP_RECEIVER_CAP_SIZE || dpcd[DP_DPCD_REV] == 0)
500                 return -EIO;
501
502         ret = drm_dp_read_extended_dpcd_caps(aux, dpcd);
503         if (ret < 0)
504                 return ret;
505
506         DRM_DEBUG_KMS("%s: DPCD: %*ph\n",
507                       aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
508
509         return ret;
510 }
511 EXPORT_SYMBOL(drm_dp_read_dpcd_caps);
512
513 /**
514  * drm_dp_read_downstream_info() - read DPCD downstream port info if available
515  * @aux: DisplayPort AUX channel
516  * @dpcd: A cached copy of the port's DPCD
517  * @downstream_ports: buffer to store the downstream port info in
518  *
519  * See also:
520  * drm_dp_downstream_max_clock()
521  * drm_dp_downstream_max_bpc()
522  *
523  * Returns: 0 if either the downstream port info was read successfully or
524  * there was no downstream info to read, or a negative error code otherwise.
525  */
526 int drm_dp_read_downstream_info(struct drm_dp_aux *aux,
527                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
528                                 u8 downstream_ports[DP_MAX_DOWNSTREAM_PORTS])
529 {
530         int ret;
531         u8 len;
532
533         memset(downstream_ports, 0, DP_MAX_DOWNSTREAM_PORTS);
534
535         /* No downstream info to read */
536         if (!drm_dp_is_branch(dpcd) ||
537             dpcd[DP_DPCD_REV] < DP_DPCD_REV_10 ||
538             !(dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_PRESENT))
539                 return 0;
540
541         len = drm_dp_downstream_port_count(dpcd);
542         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE)
543                 len *= 4;
544
545         ret = drm_dp_dpcd_read(aux, DP_DOWNSTREAM_PORT_0, downstream_ports, len);
546         if (ret < 0)
547                 return ret;
548
549         return ret == len ? 0 : -EIO;
550 }
551 EXPORT_SYMBOL(drm_dp_read_downstream_info);
552
553 /**
554  * drm_dp_downstream_max_clock() - extract branch device max
555  *                                 pixel rate for legacy VGA
556  *                                 converter or max TMDS clock
557  *                                 rate for others
558  * @dpcd: DisplayPort configuration data
559  * @port_cap: port capabilities
560  *
561  * See also:
562  * drm_dp_read_downstream_info()
563  * drm_dp_downstream_max_bpc()
564  *
565  * Returns: Max clock in kHz on success or 0 if max clock not defined
566  */
567 int drm_dp_downstream_max_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
568                                 const u8 port_cap[4])
569 {
570         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
571         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
572                 DP_DETAILED_CAP_INFO_AVAILABLE;
573
574         if (!detailed_cap_info)
575                 return 0;
576
577         switch (type) {
578         case DP_DS_PORT_TYPE_VGA:
579                 return port_cap[1] * 8 * 1000;
580         case DP_DS_PORT_TYPE_DVI:
581         case DP_DS_PORT_TYPE_HDMI:
582         case DP_DS_PORT_TYPE_DP_DUALMODE:
583                 return port_cap[1] * 2500;
584         default:
585                 return 0;
586         }
587 }
588 EXPORT_SYMBOL(drm_dp_downstream_max_clock);
589
590 /**
591  * drm_dp_downstream_max_bpc() - extract branch device max
592  *                               bits per component
593  * @dpcd: DisplayPort configuration data
594  * @port_cap: port capabilities
595  *
596  * See also:
597  * drm_dp_read_downstream_info()
598  * drm_dp_downstream_max_clock()
599  *
600  * Returns: Max bpc on success or 0 if max bpc not defined
601  */
602 int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
603                               const u8 port_cap[4])
604 {
605         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
606         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
607                 DP_DETAILED_CAP_INFO_AVAILABLE;
608         int bpc;
609
610         if (!detailed_cap_info)
611                 return 0;
612
613         switch (type) {
614         case DP_DS_PORT_TYPE_VGA:
615         case DP_DS_PORT_TYPE_DVI:
616         case DP_DS_PORT_TYPE_HDMI:
617         case DP_DS_PORT_TYPE_DP_DUALMODE:
618                 bpc = port_cap[2] & DP_DS_MAX_BPC_MASK;
619
620                 switch (bpc) {
621                 case DP_DS_8BPC:
622                         return 8;
623                 case DP_DS_10BPC:
624                         return 10;
625                 case DP_DS_12BPC:
626                         return 12;
627                 case DP_DS_16BPC:
628                         return 16;
629                 }
630                 fallthrough;
631         default:
632                 return 0;
633         }
634 }
635 EXPORT_SYMBOL(drm_dp_downstream_max_bpc);
636
637 /**
638  * drm_dp_downstream_id() - identify branch device
639  * @aux: DisplayPort AUX channel
640  * @id: DisplayPort branch device id
641  *
642  * Returns branch device id on success or NULL on failure
643  */
644 int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
645 {
646         return drm_dp_dpcd_read(aux, DP_BRANCH_ID, id, 6);
647 }
648 EXPORT_SYMBOL(drm_dp_downstream_id);
649
650 /**
651  * drm_dp_downstream_debug() - debug DP branch devices
652  * @m: pointer for debugfs file
653  * @dpcd: DisplayPort configuration data
654  * @port_cap: port capabilities
655  * @aux: DisplayPort AUX channel
656  *
657  */
658 void drm_dp_downstream_debug(struct seq_file *m,
659                              const u8 dpcd[DP_RECEIVER_CAP_SIZE],
660                              const u8 port_cap[4], struct drm_dp_aux *aux)
661 {
662         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
663                                  DP_DETAILED_CAP_INFO_AVAILABLE;
664         int clk;
665         int bpc;
666         char id[7];
667         int len;
668         uint8_t rev[2];
669         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
670         bool branch_device = drm_dp_is_branch(dpcd);
671
672         seq_printf(m, "\tDP branch device present: %s\n",
673                    branch_device ? "yes" : "no");
674
675         if (!branch_device)
676                 return;
677
678         switch (type) {
679         case DP_DS_PORT_TYPE_DP:
680                 seq_puts(m, "\t\tType: DisplayPort\n");
681                 break;
682         case DP_DS_PORT_TYPE_VGA:
683                 seq_puts(m, "\t\tType: VGA\n");
684                 break;
685         case DP_DS_PORT_TYPE_DVI:
686                 seq_puts(m, "\t\tType: DVI\n");
687                 break;
688         case DP_DS_PORT_TYPE_HDMI:
689                 seq_puts(m, "\t\tType: HDMI\n");
690                 break;
691         case DP_DS_PORT_TYPE_NON_EDID:
692                 seq_puts(m, "\t\tType: others without EDID support\n");
693                 break;
694         case DP_DS_PORT_TYPE_DP_DUALMODE:
695                 seq_puts(m, "\t\tType: DP++\n");
696                 break;
697         case DP_DS_PORT_TYPE_WIRELESS:
698                 seq_puts(m, "\t\tType: Wireless\n");
699                 break;
700         default:
701                 seq_puts(m, "\t\tType: N/A\n");
702         }
703
704         memset(id, 0, sizeof(id));
705         drm_dp_downstream_id(aux, id);
706         seq_printf(m, "\t\tID: %s\n", id);
707
708         len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
709         if (len > 0)
710                 seq_printf(m, "\t\tHW: %d.%d\n",
711                            (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
712
713         len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
714         if (len > 0)
715                 seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
716
717         if (detailed_cap_info) {
718                 clk = drm_dp_downstream_max_clock(dpcd, port_cap);
719
720                 if (clk > 0) {
721                         if (type == DP_DS_PORT_TYPE_VGA)
722                                 seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
723                         else
724                                 seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
725                 }
726
727                 bpc = drm_dp_downstream_max_bpc(dpcd, port_cap);
728
729                 if (bpc > 0)
730                         seq_printf(m, "\t\tMax bpc: %d\n", bpc);
731         }
732 }
733 EXPORT_SYMBOL(drm_dp_downstream_debug);
734
735 /**
736  * drm_dp_subconnector_type() - get DP branch device type
737  *
738  */
739 enum drm_mode_subconnector
740 drm_dp_subconnector_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
741                          const u8 port_cap[4])
742 {
743         int type;
744         if (!drm_dp_is_branch(dpcd))
745                 return DRM_MODE_SUBCONNECTOR_Native;
746         /* DP 1.0 approach */
747         if (dpcd[DP_DPCD_REV] == DP_DPCD_REV_10) {
748                 type = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
749                        DP_DWN_STRM_PORT_TYPE_MASK;
750
751                 switch (type) {
752                 case DP_DWN_STRM_PORT_TYPE_TMDS:
753                         /* Can be HDMI or DVI-D, DVI-D is a safer option */
754                         return DRM_MODE_SUBCONNECTOR_DVID;
755                 case DP_DWN_STRM_PORT_TYPE_ANALOG:
756                         /* Can be VGA or DVI-A, VGA is more popular */
757                         return DRM_MODE_SUBCONNECTOR_VGA;
758                 case DP_DWN_STRM_PORT_TYPE_DP:
759                         return DRM_MODE_SUBCONNECTOR_DisplayPort;
760                 case DP_DWN_STRM_PORT_TYPE_OTHER:
761                 default:
762                         return DRM_MODE_SUBCONNECTOR_Unknown;
763                 }
764         }
765         type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
766
767         switch (type) {
768         case DP_DS_PORT_TYPE_DP:
769         case DP_DS_PORT_TYPE_DP_DUALMODE:
770                 return DRM_MODE_SUBCONNECTOR_DisplayPort;
771         case DP_DS_PORT_TYPE_VGA:
772                 return DRM_MODE_SUBCONNECTOR_VGA;
773         case DP_DS_PORT_TYPE_DVI:
774                 return DRM_MODE_SUBCONNECTOR_DVID;
775         case DP_DS_PORT_TYPE_HDMI:
776                 return DRM_MODE_SUBCONNECTOR_HDMIA;
777         case DP_DS_PORT_TYPE_WIRELESS:
778                 return DRM_MODE_SUBCONNECTOR_Wireless;
779         case DP_DS_PORT_TYPE_NON_EDID:
780         default:
781                 return DRM_MODE_SUBCONNECTOR_Unknown;
782         }
783 }
784 EXPORT_SYMBOL(drm_dp_subconnector_type);
785
786 /**
787  * drm_mode_set_dp_subconnector_property - set subconnector for DP connector
788  *
789  * Called by a driver on every detect event.
790  */
791 void drm_dp_set_subconnector_property(struct drm_connector *connector,
792                                       enum drm_connector_status status,
793                                       const u8 *dpcd,
794                                       const u8 port_cap[4])
795 {
796         enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
797
798         if (status == connector_status_connected)
799                 subconnector = drm_dp_subconnector_type(dpcd, port_cap);
800         drm_object_property_set_value(&connector->base,
801                         connector->dev->mode_config.dp_subconnector_property,
802                         subconnector);
803 }
804 EXPORT_SYMBOL(drm_dp_set_subconnector_property);
805
806 /**
807  * drm_dp_read_sink_count_cap() - Check whether a given connector has a valid sink
808  * count
809  * @connector: The DRM connector to check
810  * @dpcd: A cached copy of the connector's DPCD RX capabilities
811  * @desc: A cached copy of the connector's DP descriptor
812  *
813  * See also: drm_dp_read_sink_count()
814  *
815  * Returns: %True if the (e)DP connector has a valid sink count that should
816  * be probed, %false otherwise.
817  */
818 bool drm_dp_read_sink_count_cap(struct drm_connector *connector,
819                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
820                                 const struct drm_dp_desc *desc)
821 {
822         /* Some eDP panels don't set a valid value for the sink count */
823         return connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
824                 dpcd[DP_DPCD_REV] >= DP_DPCD_REV_11 &&
825                 dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_PRESENT &&
826                 !drm_dp_has_quirk(desc, 0, DP_DPCD_QUIRK_NO_SINK_COUNT);
827 }
828 EXPORT_SYMBOL(drm_dp_read_sink_count_cap);
829
830 /**
831  * drm_dp_read_sink_count() - Retrieve the sink count for a given sink
832  * @aux: The DP AUX channel to use
833  *
834  * See also: drm_dp_read_sink_count_cap()
835  *
836  * Returns: The current sink count reported by @aux, or a negative error code
837  * otherwise.
838  */
839 int drm_dp_read_sink_count(struct drm_dp_aux *aux)
840 {
841         u8 count;
842         int ret;
843
844         ret = drm_dp_dpcd_readb(aux, DP_SINK_COUNT, &count);
845         if (ret < 0)
846                 return ret;
847         if (ret != 1)
848                 return -EIO;
849
850         return DP_GET_SINK_COUNT(count);
851 }
852 EXPORT_SYMBOL(drm_dp_read_sink_count);
853
854 /*
855  * I2C-over-AUX implementation
856  */
857
858 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
859 {
860         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
861                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
862                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
863                I2C_FUNC_10BIT_ADDR;
864 }
865
866 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
867 {
868         /*
869          * In case of i2c defer or short i2c ack reply to a write,
870          * we need to switch to WRITE_STATUS_UPDATE to drain the
871          * rest of the message
872          */
873         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
874                 msg->request &= DP_AUX_I2C_MOT;
875                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
876         }
877 }
878
879 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
880 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
881 #define AUX_STOP_LEN 4
882 #define AUX_CMD_LEN 4
883 #define AUX_ADDRESS_LEN 20
884 #define AUX_REPLY_PAD_LEN 4
885 #define AUX_LENGTH_LEN 8
886
887 /*
888  * Calculate the duration of the AUX request/reply in usec. Gives the
889  * "best" case estimate, ie. successful while as short as possible.
890  */
891 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
892 {
893         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
894                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
895
896         if ((msg->request & DP_AUX_I2C_READ) == 0)
897                 len += msg->size * 8;
898
899         return len;
900 }
901
902 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
903 {
904         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
905                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
906
907         /*
908          * For read we expect what was asked. For writes there will
909          * be 0 or 1 data bytes. Assume 0 for the "best" case.
910          */
911         if (msg->request & DP_AUX_I2C_READ)
912                 len += msg->size * 8;
913
914         return len;
915 }
916
917 #define I2C_START_LEN 1
918 #define I2C_STOP_LEN 1
919 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
920 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
921
922 /*
923  * Calculate the length of the i2c transfer in usec, assuming
924  * the i2c bus speed is as specified. Gives the the "worst"
925  * case estimate, ie. successful while as long as possible.
926  * Doesn't account the the "MOT" bit, and instead assumes each
927  * message includes a START, ADDRESS and STOP. Neither does it
928  * account for additional random variables such as clock stretching.
929  */
930 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
931                                    int i2c_speed_khz)
932 {
933         /* AUX bitrate is 1MHz, i2c bitrate as specified */
934         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
935                              msg->size * I2C_DATA_LEN +
936                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
937 }
938
939 /*
940  * Deterine how many retries should be attempted to successfully transfer
941  * the specified message, based on the estimated durations of the
942  * i2c and AUX transfers.
943  */
944 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
945                               int i2c_speed_khz)
946 {
947         int aux_time_us = drm_dp_aux_req_duration(msg) +
948                 drm_dp_aux_reply_duration(msg);
949         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
950
951         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
952 }
953
954 /*
955  * FIXME currently assumes 10 kHz as some real world devices seem
956  * to require it. We should query/set the speed via DPCD if supported.
957  */
958 static int dp_aux_i2c_speed_khz __read_mostly = 10;
959 module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
960 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
961                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
962
963 /*
964  * Transfer a single I2C-over-AUX message and handle various error conditions,
965  * retrying the transaction as appropriate.  It is assumed that the
966  * &drm_dp_aux.transfer function does not modify anything in the msg other than the
967  * reply field.
968  *
969  * Returns bytes transferred on success, or a negative error code on failure.
970  */
971 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
972 {
973         unsigned int retry, defer_i2c;
974         int ret;
975         /*
976          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
977          * is required to retry at least seven times upon receiving AUX_DEFER
978          * before giving up the AUX transaction.
979          *
980          * We also try to account for the i2c bus speed.
981          */
982         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
983
984         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
985                 ret = aux->transfer(aux, msg);
986                 if (ret < 0) {
987                         if (ret == -EBUSY)
988                                 continue;
989
990                         /*
991                          * While timeouts can be errors, they're usually normal
992                          * behavior (for instance, when a driver tries to
993                          * communicate with a non-existant DisplayPort device).
994                          * Avoid spamming the kernel log with timeout errors.
995                          */
996                         if (ret == -ETIMEDOUT)
997                                 DRM_DEBUG_KMS_RATELIMITED("%s: transaction timed out\n",
998                                                           aux->name);
999                         else
1000                                 DRM_DEBUG_KMS("%s: transaction failed: %d\n",
1001                                               aux->name, ret);
1002                         return ret;
1003                 }
1004
1005
1006                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
1007                 case DP_AUX_NATIVE_REPLY_ACK:
1008                         /*
1009                          * For I2C-over-AUX transactions this isn't enough, we
1010                          * need to check for the I2C ACK reply.
1011                          */
1012                         break;
1013
1014                 case DP_AUX_NATIVE_REPLY_NACK:
1015                         DRM_DEBUG_KMS("%s: native nack (result=%d, size=%zu)\n",
1016                                       aux->name, ret, msg->size);
1017                         return -EREMOTEIO;
1018
1019                 case DP_AUX_NATIVE_REPLY_DEFER:
1020                         DRM_DEBUG_KMS("%s: native defer\n", aux->name);
1021                         /*
1022                          * We could check for I2C bit rate capabilities and if
1023                          * available adjust this interval. We could also be
1024                          * more careful with DP-to-legacy adapters where a
1025                          * long legacy cable may force very low I2C bit rates.
1026                          *
1027                          * For now just defer for long enough to hopefully be
1028                          * safe for all use-cases.
1029                          */
1030                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1031                         continue;
1032
1033                 default:
1034                         DRM_ERROR("%s: invalid native reply %#04x\n",
1035                                   aux->name, msg->reply);
1036                         return -EREMOTEIO;
1037                 }
1038
1039                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
1040                 case DP_AUX_I2C_REPLY_ACK:
1041                         /*
1042                          * Both native ACK and I2C ACK replies received. We
1043                          * can assume the transfer was successful.
1044                          */
1045                         if (ret != msg->size)
1046                                 drm_dp_i2c_msg_write_status_update(msg);
1047                         return ret;
1048
1049                 case DP_AUX_I2C_REPLY_NACK:
1050                         DRM_DEBUG_KMS("%s: I2C nack (result=%d, size=%zu)\n",
1051                                       aux->name, ret, msg->size);
1052                         aux->i2c_nack_count++;
1053                         return -EREMOTEIO;
1054
1055                 case DP_AUX_I2C_REPLY_DEFER:
1056                         DRM_DEBUG_KMS("%s: I2C defer\n", aux->name);
1057                         /* DP Compliance Test 4.2.2.5 Requirement:
1058                          * Must have at least 7 retries for I2C defers on the
1059                          * transaction to pass this test
1060                          */
1061                         aux->i2c_defer_count++;
1062                         if (defer_i2c < 7)
1063                                 defer_i2c++;
1064                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1065                         drm_dp_i2c_msg_write_status_update(msg);
1066
1067                         continue;
1068
1069                 default:
1070                         DRM_ERROR("%s: invalid I2C reply %#04x\n",
1071                                   aux->name, msg->reply);
1072                         return -EREMOTEIO;
1073                 }
1074         }
1075
1076         DRM_DEBUG_KMS("%s: Too many retries, giving up\n", aux->name);
1077         return -EREMOTEIO;
1078 }
1079
1080 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
1081                                        const struct i2c_msg *i2c_msg)
1082 {
1083         msg->request = (i2c_msg->flags & I2C_M_RD) ?
1084                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
1085         if (!(i2c_msg->flags & I2C_M_STOP))
1086                 msg->request |= DP_AUX_I2C_MOT;
1087 }
1088
1089 /*
1090  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
1091  *
1092  * Returns an error code on failure, or a recommended transfer size on success.
1093  */
1094 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
1095 {
1096         int err, ret = orig_msg->size;
1097         struct drm_dp_aux_msg msg = *orig_msg;
1098
1099         while (msg.size > 0) {
1100                 err = drm_dp_i2c_do_msg(aux, &msg);
1101                 if (err <= 0)
1102                         return err == 0 ? -EPROTO : err;
1103
1104                 if (err < msg.size && err < ret) {
1105                         DRM_DEBUG_KMS("%s: Partial I2C reply: requested %zu bytes got %d bytes\n",
1106                                       aux->name, msg.size, err);
1107                         ret = err;
1108                 }
1109
1110                 msg.size -= err;
1111                 msg.buffer += err;
1112         }
1113
1114         return ret;
1115 }
1116
1117 /*
1118  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
1119  * packets to be as large as possible. If not, the I2C transactions never
1120  * succeed. Hence the default is maximum.
1121  */
1122 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
1123 module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
1124 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
1125                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
1126
1127 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
1128                            int num)
1129 {
1130         struct drm_dp_aux *aux = adapter->algo_data;
1131         unsigned int i, j;
1132         unsigned transfer_size;
1133         struct drm_dp_aux_msg msg;
1134         int err = 0;
1135
1136         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
1137
1138         memset(&msg, 0, sizeof(msg));
1139
1140         for (i = 0; i < num; i++) {
1141                 msg.address = msgs[i].addr;
1142                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1143                 /* Send a bare address packet to start the transaction.
1144                  * Zero sized messages specify an address only (bare
1145                  * address) transaction.
1146                  */
1147                 msg.buffer = NULL;
1148                 msg.size = 0;
1149                 err = drm_dp_i2c_do_msg(aux, &msg);
1150
1151                 /*
1152                  * Reset msg.request in case in case it got
1153                  * changed into a WRITE_STATUS_UPDATE.
1154                  */
1155                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1156
1157                 if (err < 0)
1158                         break;
1159                 /* We want each transaction to be as large as possible, but
1160                  * we'll go to smaller sizes if the hardware gives us a
1161                  * short reply.
1162                  */
1163                 transfer_size = dp_aux_i2c_transfer_size;
1164                 for (j = 0; j < msgs[i].len; j += msg.size) {
1165                         msg.buffer = msgs[i].buf + j;
1166                         msg.size = min(transfer_size, msgs[i].len - j);
1167
1168                         err = drm_dp_i2c_drain_msg(aux, &msg);
1169
1170                         /*
1171                          * Reset msg.request in case in case it got
1172                          * changed into a WRITE_STATUS_UPDATE.
1173                          */
1174                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1175
1176                         if (err < 0)
1177                                 break;
1178                         transfer_size = err;
1179                 }
1180                 if (err < 0)
1181                         break;
1182         }
1183         if (err >= 0)
1184                 err = num;
1185         /* Send a bare address packet to close out the transaction.
1186          * Zero sized messages specify an address only (bare
1187          * address) transaction.
1188          */
1189         msg.request &= ~DP_AUX_I2C_MOT;
1190         msg.buffer = NULL;
1191         msg.size = 0;
1192         (void)drm_dp_i2c_do_msg(aux, &msg);
1193
1194         return err;
1195 }
1196
1197 static const struct i2c_algorithm drm_dp_i2c_algo = {
1198         .functionality = drm_dp_i2c_functionality,
1199         .master_xfer = drm_dp_i2c_xfer,
1200 };
1201
1202 static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
1203 {
1204         return container_of(i2c, struct drm_dp_aux, ddc);
1205 }
1206
1207 static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
1208 {
1209         mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
1210 }
1211
1212 static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
1213 {
1214         return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
1215 }
1216
1217 static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
1218 {
1219         mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
1220 }
1221
1222 static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
1223         .lock_bus = lock_bus,
1224         .trylock_bus = trylock_bus,
1225         .unlock_bus = unlock_bus,
1226 };
1227
1228 static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
1229 {
1230         u8 buf, count;
1231         int ret;
1232
1233         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1234         if (ret < 0)
1235                 return ret;
1236
1237         WARN_ON(!(buf & DP_TEST_SINK_START));
1238
1239         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
1240         if (ret < 0)
1241                 return ret;
1242
1243         count = buf & DP_TEST_COUNT_MASK;
1244         if (count == aux->crc_count)
1245                 return -EAGAIN; /* No CRC yet */
1246
1247         aux->crc_count = count;
1248
1249         /*
1250          * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
1251          * per component (RGB or CrYCb).
1252          */
1253         ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
1254         if (ret < 0)
1255                 return ret;
1256
1257         return 0;
1258 }
1259
1260 static void drm_dp_aux_crc_work(struct work_struct *work)
1261 {
1262         struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
1263                                               crc_work);
1264         struct drm_crtc *crtc;
1265         u8 crc_bytes[6];
1266         uint32_t crcs[3];
1267         int ret;
1268
1269         if (WARN_ON(!aux->crtc))
1270                 return;
1271
1272         crtc = aux->crtc;
1273         while (crtc->crc.opened) {
1274                 drm_crtc_wait_one_vblank(crtc);
1275                 if (!crtc->crc.opened)
1276                         break;
1277
1278                 ret = drm_dp_aux_get_crc(aux, crc_bytes);
1279                 if (ret == -EAGAIN) {
1280                         usleep_range(1000, 2000);
1281                         ret = drm_dp_aux_get_crc(aux, crc_bytes);
1282                 }
1283
1284                 if (ret == -EAGAIN) {
1285                         DRM_DEBUG_KMS("%s: Get CRC failed after retrying: %d\n",
1286                                       aux->name, ret);
1287                         continue;
1288                 } else if (ret) {
1289                         DRM_DEBUG_KMS("%s: Failed to get a CRC: %d\n",
1290                                       aux->name, ret);
1291                         continue;
1292                 }
1293
1294                 crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
1295                 crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
1296                 crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
1297                 drm_crtc_add_crc_entry(crtc, false, 0, crcs);
1298         }
1299 }
1300
1301 /**
1302  * drm_dp_remote_aux_init() - minimally initialise a remote aux channel
1303  * @aux: DisplayPort AUX channel
1304  *
1305  * Used for remote aux channel in general. Merely initialize the crc work
1306  * struct.
1307  */
1308 void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
1309 {
1310         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1311 }
1312 EXPORT_SYMBOL(drm_dp_remote_aux_init);
1313
1314 /**
1315  * drm_dp_aux_init() - minimally initialise an aux channel
1316  * @aux: DisplayPort AUX channel
1317  *
1318  * If you need to use the drm_dp_aux's i2c adapter prior to registering it
1319  * with the outside world, call drm_dp_aux_init() first. You must still
1320  * call drm_dp_aux_register() once the connector has been registered to
1321  * allow userspace access to the auxiliary DP channel.
1322  */
1323 void drm_dp_aux_init(struct drm_dp_aux *aux)
1324 {
1325         mutex_init(&aux->hw_mutex);
1326         mutex_init(&aux->cec.lock);
1327         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1328
1329         aux->ddc.algo = &drm_dp_i2c_algo;
1330         aux->ddc.algo_data = aux;
1331         aux->ddc.retries = 3;
1332
1333         aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
1334 }
1335 EXPORT_SYMBOL(drm_dp_aux_init);
1336
1337 /**
1338  * drm_dp_aux_register() - initialise and register aux channel
1339  * @aux: DisplayPort AUX channel
1340  *
1341  * Automatically calls drm_dp_aux_init() if this hasn't been done yet.
1342  * This should only be called when the underlying &struct drm_connector is
1343  * initialiazed already. Therefore the best place to call this is from
1344  * &drm_connector_funcs.late_register. Not that drivers which don't follow this
1345  * will Oops when CONFIG_DRM_DP_AUX_CHARDEV is enabled.
1346  *
1347  * Drivers which need to use the aux channel before that point (e.g. at driver
1348  * load time, before drm_dev_register() has been called) need to call
1349  * drm_dp_aux_init().
1350  *
1351  * Returns 0 on success or a negative error code on failure.
1352  */
1353 int drm_dp_aux_register(struct drm_dp_aux *aux)
1354 {
1355         int ret;
1356
1357         if (!aux->ddc.algo)
1358                 drm_dp_aux_init(aux);
1359
1360         aux->ddc.class = I2C_CLASS_DDC;
1361         aux->ddc.owner = THIS_MODULE;
1362         aux->ddc.dev.parent = aux->dev;
1363
1364         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
1365                 sizeof(aux->ddc.name));
1366
1367         ret = drm_dp_aux_register_devnode(aux);
1368         if (ret)
1369                 return ret;
1370
1371         ret = i2c_add_adapter(&aux->ddc);
1372         if (ret) {
1373                 drm_dp_aux_unregister_devnode(aux);
1374                 return ret;
1375         }
1376
1377         return 0;
1378 }
1379 EXPORT_SYMBOL(drm_dp_aux_register);
1380
1381 /**
1382  * drm_dp_aux_unregister() - unregister an AUX adapter
1383  * @aux: DisplayPort AUX channel
1384  */
1385 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
1386 {
1387         drm_dp_aux_unregister_devnode(aux);
1388         i2c_del_adapter(&aux->ddc);
1389 }
1390 EXPORT_SYMBOL(drm_dp_aux_unregister);
1391
1392 #define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
1393
1394 /**
1395  * drm_dp_psr_setup_time() - PSR setup in time usec
1396  * @psr_cap: PSR capabilities from DPCD
1397  *
1398  * Returns:
1399  * PSR setup time for the panel in microseconds,  negative
1400  * error code on failure.
1401  */
1402 int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
1403 {
1404         static const u16 psr_setup_time_us[] = {
1405                 PSR_SETUP_TIME(330),
1406                 PSR_SETUP_TIME(275),
1407                 PSR_SETUP_TIME(220),
1408                 PSR_SETUP_TIME(165),
1409                 PSR_SETUP_TIME(110),
1410                 PSR_SETUP_TIME(55),
1411                 PSR_SETUP_TIME(0),
1412         };
1413         int i;
1414
1415         i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
1416         if (i >= ARRAY_SIZE(psr_setup_time_us))
1417                 return -EINVAL;
1418
1419         return psr_setup_time_us[i];
1420 }
1421 EXPORT_SYMBOL(drm_dp_psr_setup_time);
1422
1423 #undef PSR_SETUP_TIME
1424
1425 /**
1426  * drm_dp_start_crc() - start capture of frame CRCs
1427  * @aux: DisplayPort AUX channel
1428  * @crtc: CRTC displaying the frames whose CRCs are to be captured
1429  *
1430  * Returns 0 on success or a negative error code on failure.
1431  */
1432 int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
1433 {
1434         u8 buf;
1435         int ret;
1436
1437         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1438         if (ret < 0)
1439                 return ret;
1440
1441         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
1442         if (ret < 0)
1443                 return ret;
1444
1445         aux->crc_count = 0;
1446         aux->crtc = crtc;
1447         schedule_work(&aux->crc_work);
1448
1449         return 0;
1450 }
1451 EXPORT_SYMBOL(drm_dp_start_crc);
1452
1453 /**
1454  * drm_dp_stop_crc() - stop capture of frame CRCs
1455  * @aux: DisplayPort AUX channel
1456  *
1457  * Returns 0 on success or a negative error code on failure.
1458  */
1459 int drm_dp_stop_crc(struct drm_dp_aux *aux)
1460 {
1461         u8 buf;
1462         int ret;
1463
1464         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1465         if (ret < 0)
1466                 return ret;
1467
1468         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
1469         if (ret < 0)
1470                 return ret;
1471
1472         flush_work(&aux->crc_work);
1473         aux->crtc = NULL;
1474
1475         return 0;
1476 }
1477 EXPORT_SYMBOL(drm_dp_stop_crc);
1478
1479 struct dpcd_quirk {
1480         u8 oui[3];
1481         u8 device_id[6];
1482         bool is_branch;
1483         u32 quirks;
1484 };
1485
1486 #define OUI(first, second, third) { (first), (second), (third) }
1487 #define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
1488         { (first), (second), (third), (fourth), (fifth), (sixth) }
1489
1490 #define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
1491
1492 static const struct dpcd_quirk dpcd_quirk_list[] = {
1493         /* Analogix 7737 needs reduced M and N at HBR2 link rates */
1494         { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1495         /* LG LP140WF6-SPM1 eDP panel */
1496         { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1497         /* Apple panels need some additional handling to support PSR */
1498         { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
1499         /* CH7511 seems to leave SINK_COUNT zeroed */
1500         { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
1501         /* Synaptics DP1.4 MST hubs can support DSC without virtual DPCD */
1502         { OUI(0x90, 0xCC, 0x24), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) },
1503         /* Apple MacBookPro 2017 15 inch eDP Retina panel reports too low DP_MAX_LINK_RATE */
1504         { OUI(0x00, 0x10, 0xfa), DEVICE_ID(101, 68, 21, 101, 98, 97), false, BIT(DP_DPCD_QUIRK_CAN_DO_MAX_LINK_RATE_3_24_GBPS) },
1505 };
1506
1507 #undef OUI
1508
1509 /*
1510  * Get a bit mask of DPCD quirks for the sink/branch device identified by
1511  * ident. The quirk data is shared but it's up to the drivers to act on the
1512  * data.
1513  *
1514  * For now, only the OUI (first three bytes) is used, but this may be extended
1515  * to device identification string and hardware/firmware revisions later.
1516  */
1517 static u32
1518 drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
1519 {
1520         const struct dpcd_quirk *quirk;
1521         u32 quirks = 0;
1522         int i;
1523         u8 any_device[] = DEVICE_ID_ANY;
1524
1525         for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
1526                 quirk = &dpcd_quirk_list[i];
1527
1528                 if (quirk->is_branch != is_branch)
1529                         continue;
1530
1531                 if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
1532                         continue;
1533
1534                 if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
1535                     memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
1536                         continue;
1537
1538                 quirks |= quirk->quirks;
1539         }
1540
1541         return quirks;
1542 }
1543
1544 #undef DEVICE_ID_ANY
1545 #undef DEVICE_ID
1546
1547 struct edid_quirk {
1548         u8 mfg_id[2];
1549         u8 prod_id[2];
1550         u32 quirks;
1551 };
1552
1553 #define MFG(first, second) { (first), (second) }
1554 #define PROD_ID(first, second) { (first), (second) }
1555
1556 /*
1557  * Some devices have unreliable OUIDs where they don't set the device ID
1558  * correctly, and as a result we need to use the EDID for finding additional
1559  * DP quirks in such cases.
1560  */
1561 static const struct edid_quirk edid_quirk_list[] = {
1562         /* Optional 4K AMOLED panel in the ThinkPad X1 Extreme 2nd Generation
1563          * only supports DPCD backlight controls
1564          */
1565         { MFG(0x4c, 0x83), PROD_ID(0x41, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1566         /*
1567          * Some Dell CML 2020 systems have panels support both AUX and PWM
1568          * backlight control, and some only support AUX backlight control. All
1569          * said panels start up in AUX mode by default, and we don't have any
1570          * support for disabling HDR mode on these panels which would be
1571          * required to switch to PWM backlight control mode (plus, I'm not
1572          * even sure we want PWM backlight controls over DPCD backlight
1573          * controls anyway...). Until we have a better way of detecting these,
1574          * force DPCD backlight mode on all of them.
1575          */
1576         { MFG(0x06, 0xaf), PROD_ID(0x9b, 0x32), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1577         { MFG(0x06, 0xaf), PROD_ID(0xeb, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1578         { MFG(0x4d, 0x10), PROD_ID(0xc7, 0x14), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1579         { MFG(0x4d, 0x10), PROD_ID(0xe6, 0x14), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1580         { MFG(0x4c, 0x83), PROD_ID(0x47, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1581 };
1582
1583 #undef MFG
1584 #undef PROD_ID
1585
1586 /**
1587  * drm_dp_get_edid_quirks() - Check the EDID of a DP device to find additional
1588  * DP-specific quirks
1589  * @edid: The EDID to check
1590  *
1591  * While OUIDs are meant to be used to recognize a DisplayPort device, a lot
1592  * of manufacturers don't seem to like following standards and neglect to fill
1593  * the dev-ID in, making it impossible to only use OUIDs for determining
1594  * quirks in some cases. This function can be used to check the EDID and look
1595  * up any additional DP quirks. The bits returned by this function correspond
1596  * to the quirk bits in &drm_dp_quirk.
1597  *
1598  * Returns: a bitmask of quirks, if any. The driver can check this using
1599  * drm_dp_has_quirk().
1600  */
1601 u32 drm_dp_get_edid_quirks(const struct edid *edid)
1602 {
1603         const struct edid_quirk *quirk;
1604         u32 quirks = 0;
1605         int i;
1606
1607         if (!edid)
1608                 return 0;
1609
1610         for (i = 0; i < ARRAY_SIZE(edid_quirk_list); i++) {
1611                 quirk = &edid_quirk_list[i];
1612                 if (memcmp(quirk->mfg_id, edid->mfg_id,
1613                            sizeof(edid->mfg_id)) == 0 &&
1614                     memcmp(quirk->prod_id, edid->prod_code,
1615                            sizeof(edid->prod_code)) == 0)
1616                         quirks |= quirk->quirks;
1617         }
1618
1619         DRM_DEBUG_KMS("DP sink: EDID mfg %*phD prod-ID %*phD quirks: 0x%04x\n",
1620                       (int)sizeof(edid->mfg_id), edid->mfg_id,
1621                       (int)sizeof(edid->prod_code), edid->prod_code, quirks);
1622
1623         return quirks;
1624 }
1625 EXPORT_SYMBOL(drm_dp_get_edid_quirks);
1626
1627 /**
1628  * drm_dp_read_desc - read sink/branch descriptor from DPCD
1629  * @aux: DisplayPort AUX channel
1630  * @desc: Device descriptor to fill from DPCD
1631  * @is_branch: true for branch devices, false for sink devices
1632  *
1633  * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
1634  * identification.
1635  *
1636  * Returns 0 on success or a negative error code on failure.
1637  */
1638 int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
1639                      bool is_branch)
1640 {
1641         struct drm_dp_dpcd_ident *ident = &desc->ident;
1642         unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
1643         int ret, dev_id_len;
1644
1645         ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
1646         if (ret < 0)
1647                 return ret;
1648
1649         desc->quirks = drm_dp_get_quirks(ident, is_branch);
1650
1651         dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
1652
1653         DRM_DEBUG_KMS("%s: DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
1654                       aux->name, is_branch ? "branch" : "sink",
1655                       (int)sizeof(ident->oui), ident->oui,
1656                       dev_id_len, ident->device_id,
1657                       ident->hw_rev >> 4, ident->hw_rev & 0xf,
1658                       ident->sw_major_rev, ident->sw_minor_rev,
1659                       desc->quirks);
1660
1661         return 0;
1662 }
1663 EXPORT_SYMBOL(drm_dp_read_desc);
1664
1665 /**
1666  * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
1667  * supported by the DSC sink.
1668  * @dsc_dpcd: DSC capabilities from DPCD
1669  * @is_edp: true if its eDP, false for DP
1670  *
1671  * Read the slice capabilities DPCD register from DSC sink to get
1672  * the maximum slice count supported. This is used to populate
1673  * the DSC parameters in the &struct drm_dsc_config by the driver.
1674  * Driver creates an infoframe using these parameters to populate
1675  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1676  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1677  *
1678  * Returns:
1679  * Maximum slice count supported by DSC sink or 0 its invalid
1680  */
1681 u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1682                                    bool is_edp)
1683 {
1684         u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
1685
1686         if (is_edp) {
1687                 /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
1688                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1689                         return 4;
1690                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1691                         return 2;
1692                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1693                         return 1;
1694         } else {
1695                 /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
1696                 u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
1697
1698                 if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
1699                         return 24;
1700                 if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
1701                         return 20;
1702                 if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
1703                         return 16;
1704                 if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
1705                         return 12;
1706                 if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
1707                         return 10;
1708                 if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
1709                         return 8;
1710                 if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
1711                         return 6;
1712                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1713                         return 4;
1714                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1715                         return 2;
1716                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1717                         return 1;
1718         }
1719
1720         return 0;
1721 }
1722 EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
1723
1724 /**
1725  * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
1726  * @dsc_dpcd: DSC capabilities from DPCD
1727  *
1728  * Read the DSC DPCD register to parse the line buffer depth in bits which is
1729  * number of bits of precision within the decoder line buffer supported by
1730  * the DSC sink. This is used to populate the DSC parameters in the
1731  * &struct drm_dsc_config by the driver.
1732  * Driver creates an infoframe using these parameters to populate
1733  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1734  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1735  *
1736  * Returns:
1737  * Line buffer depth supported by DSC panel or 0 its invalid
1738  */
1739 u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
1740 {
1741         u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
1742
1743         switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
1744         case DP_DSC_LINE_BUF_BIT_DEPTH_9:
1745                 return 9;
1746         case DP_DSC_LINE_BUF_BIT_DEPTH_10:
1747                 return 10;
1748         case DP_DSC_LINE_BUF_BIT_DEPTH_11:
1749                 return 11;
1750         case DP_DSC_LINE_BUF_BIT_DEPTH_12:
1751                 return 12;
1752         case DP_DSC_LINE_BUF_BIT_DEPTH_13:
1753                 return 13;
1754         case DP_DSC_LINE_BUF_BIT_DEPTH_14:
1755                 return 14;
1756         case DP_DSC_LINE_BUF_BIT_DEPTH_15:
1757                 return 15;
1758         case DP_DSC_LINE_BUF_BIT_DEPTH_16:
1759                 return 16;
1760         case DP_DSC_LINE_BUF_BIT_DEPTH_8:
1761                 return 8;
1762         }
1763
1764         return 0;
1765 }
1766 EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
1767
1768 /**
1769  * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
1770  * values supported by the DSC sink.
1771  * @dsc_dpcd: DSC capabilities from DPCD
1772  * @dsc_bpc: An array to be filled by this helper with supported
1773  *           input bpcs.
1774  *
1775  * Read the DSC DPCD from the sink device to parse the supported bits per
1776  * component values. This is used to populate the DSC parameters
1777  * in the &struct drm_dsc_config by the driver.
1778  * Driver creates an infoframe using these parameters to populate
1779  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1780  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1781  *
1782  * Returns:
1783  * Number of input BPC values parsed from the DPCD
1784  */
1785 int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1786                                          u8 dsc_bpc[3])
1787 {
1788         int num_bpc = 0;
1789         u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
1790
1791         if (color_depth & DP_DSC_12_BPC)
1792                 dsc_bpc[num_bpc++] = 12;
1793         if (color_depth & DP_DSC_10_BPC)
1794                 dsc_bpc[num_bpc++] = 10;
1795         if (color_depth & DP_DSC_8_BPC)
1796                 dsc_bpc[num_bpc++] = 8;
1797
1798         return num_bpc;
1799 }
1800 EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);
1801
1802 /**
1803  * drm_dp_get_phy_test_pattern() - get the requested pattern from the sink.
1804  * @aux: DisplayPort AUX channel
1805  * @data: DP phy compliance test parameters.
1806  *
1807  * Returns 0 on success or a negative error code on failure.
1808  */
1809 int drm_dp_get_phy_test_pattern(struct drm_dp_aux *aux,
1810                                 struct drm_dp_phy_test_params *data)
1811 {
1812         int err;
1813         u8 rate, lanes;
1814
1815         err = drm_dp_dpcd_readb(aux, DP_TEST_LINK_RATE, &rate);
1816         if (err < 0)
1817                 return err;
1818         data->link_rate = drm_dp_bw_code_to_link_rate(rate);
1819
1820         err = drm_dp_dpcd_readb(aux, DP_TEST_LANE_COUNT, &lanes);
1821         if (err < 0)
1822                 return err;
1823         data->num_lanes = lanes & DP_MAX_LANE_COUNT_MASK;
1824
1825         if (lanes & DP_ENHANCED_FRAME_CAP)
1826                 data->enhanced_frame_cap = true;
1827
1828         err = drm_dp_dpcd_readb(aux, DP_PHY_TEST_PATTERN, &data->phy_pattern);
1829         if (err < 0)
1830                 return err;
1831
1832         switch (data->phy_pattern) {
1833         case DP_PHY_TEST_PATTERN_80BIT_CUSTOM:
1834                 err = drm_dp_dpcd_read(aux, DP_TEST_80BIT_CUSTOM_PATTERN_7_0,
1835                                        &data->custom80, sizeof(data->custom80));
1836                 if (err < 0)
1837                         return err;
1838
1839                 break;
1840         case DP_PHY_TEST_PATTERN_CP2520:
1841                 err = drm_dp_dpcd_read(aux, DP_TEST_HBR2_SCRAMBLER_RESET,
1842                                        &data->hbr2_reset,
1843                                        sizeof(data->hbr2_reset));
1844                 if (err < 0)
1845                         return err;
1846         }
1847
1848         return 0;
1849 }
1850 EXPORT_SYMBOL(drm_dp_get_phy_test_pattern);
1851
1852 /**
1853  * drm_dp_set_phy_test_pattern() - set the pattern to the sink.
1854  * @aux: DisplayPort AUX channel
1855  * @data: DP phy compliance test parameters.
1856  * @dp_rev: DP revision to use for compliance testing
1857  *
1858  * Returns 0 on success or a negative error code on failure.
1859  */
1860 int drm_dp_set_phy_test_pattern(struct drm_dp_aux *aux,
1861                                 struct drm_dp_phy_test_params *data, u8 dp_rev)
1862 {
1863         int err, i;
1864         u8 link_config[2];
1865         u8 test_pattern;
1866
1867         link_config[0] = drm_dp_link_rate_to_bw_code(data->link_rate);
1868         link_config[1] = data->num_lanes;
1869         if (data->enhanced_frame_cap)
1870                 link_config[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
1871         err = drm_dp_dpcd_write(aux, DP_LINK_BW_SET, link_config, 2);
1872         if (err < 0)
1873                 return err;
1874
1875         test_pattern = data->phy_pattern;
1876         if (dp_rev < 0x12) {
1877                 test_pattern = (test_pattern << 2) &
1878                                DP_LINK_QUAL_PATTERN_11_MASK;
1879                 err = drm_dp_dpcd_writeb(aux, DP_TRAINING_PATTERN_SET,
1880                                          test_pattern);
1881                 if (err < 0)
1882                         return err;
1883         } else {
1884                 for (i = 0; i < data->num_lanes; i++) {
1885                         err = drm_dp_dpcd_writeb(aux,
1886                                                  DP_LINK_QUAL_LANE0_SET + i,
1887                                                  test_pattern);
1888                         if (err < 0)
1889                                 return err;
1890                 }
1891         }
1892
1893         return 0;
1894 }
1895 EXPORT_SYMBOL(drm_dp_set_phy_test_pattern);
1896
1897 static const char *dp_pixelformat_get_name(enum dp_pixelformat pixelformat)
1898 {
1899         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
1900                 return "Invalid";
1901
1902         switch (pixelformat) {
1903         case DP_PIXELFORMAT_RGB:
1904                 return "RGB";
1905         case DP_PIXELFORMAT_YUV444:
1906                 return "YUV444";
1907         case DP_PIXELFORMAT_YUV422:
1908                 return "YUV422";
1909         case DP_PIXELFORMAT_YUV420:
1910                 return "YUV420";
1911         case DP_PIXELFORMAT_Y_ONLY:
1912                 return "Y_ONLY";
1913         case DP_PIXELFORMAT_RAW:
1914                 return "RAW";
1915         default:
1916                 return "Reserved";
1917         }
1918 }
1919
1920 static const char *dp_colorimetry_get_name(enum dp_pixelformat pixelformat,
1921                                            enum dp_colorimetry colorimetry)
1922 {
1923         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
1924                 return "Invalid";
1925
1926         switch (colorimetry) {
1927         case DP_COLORIMETRY_DEFAULT:
1928                 switch (pixelformat) {
1929                 case DP_PIXELFORMAT_RGB:
1930                         return "sRGB";
1931                 case DP_PIXELFORMAT_YUV444:
1932                 case DP_PIXELFORMAT_YUV422:
1933                 case DP_PIXELFORMAT_YUV420:
1934                         return "BT.601";
1935                 case DP_PIXELFORMAT_Y_ONLY:
1936                         return "DICOM PS3.14";
1937                 case DP_PIXELFORMAT_RAW:
1938                         return "Custom Color Profile";
1939                 default:
1940                         return "Reserved";
1941                 }
1942         case DP_COLORIMETRY_RGB_WIDE_FIXED: /* and DP_COLORIMETRY_BT709_YCC */
1943                 switch (pixelformat) {
1944                 case DP_PIXELFORMAT_RGB:
1945                         return "Wide Fixed";
1946                 case DP_PIXELFORMAT_YUV444:
1947                 case DP_PIXELFORMAT_YUV422:
1948                 case DP_PIXELFORMAT_YUV420:
1949                         return "BT.709";
1950                 default:
1951                         return "Reserved";
1952                 }
1953         case DP_COLORIMETRY_RGB_WIDE_FLOAT: /* and DP_COLORIMETRY_XVYCC_601 */
1954                 switch (pixelformat) {
1955                 case DP_PIXELFORMAT_RGB:
1956                         return "Wide Float";
1957                 case DP_PIXELFORMAT_YUV444:
1958                 case DP_PIXELFORMAT_YUV422:
1959                 case DP_PIXELFORMAT_YUV420:
1960                         return "xvYCC 601";
1961                 default:
1962                         return "Reserved";
1963                 }
1964         case DP_COLORIMETRY_OPRGB: /* and DP_COLORIMETRY_XVYCC_709 */
1965                 switch (pixelformat) {
1966                 case DP_PIXELFORMAT_RGB:
1967                         return "OpRGB";
1968                 case DP_PIXELFORMAT_YUV444:
1969                 case DP_PIXELFORMAT_YUV422:
1970                 case DP_PIXELFORMAT_YUV420:
1971                         return "xvYCC 709";
1972                 default:
1973                         return "Reserved";
1974                 }
1975         case DP_COLORIMETRY_DCI_P3_RGB: /* and DP_COLORIMETRY_SYCC_601 */
1976                 switch (pixelformat) {
1977                 case DP_PIXELFORMAT_RGB:
1978                         return "DCI-P3";
1979                 case DP_PIXELFORMAT_YUV444:
1980                 case DP_PIXELFORMAT_YUV422:
1981                 case DP_PIXELFORMAT_YUV420:
1982                         return "sYCC 601";
1983                 default:
1984                         return "Reserved";
1985                 }
1986         case DP_COLORIMETRY_RGB_CUSTOM: /* and DP_COLORIMETRY_OPYCC_601 */
1987                 switch (pixelformat) {
1988                 case DP_PIXELFORMAT_RGB:
1989                         return "Custom Profile";
1990                 case DP_PIXELFORMAT_YUV444:
1991                 case DP_PIXELFORMAT_YUV422:
1992                 case DP_PIXELFORMAT_YUV420:
1993                         return "OpYCC 601";
1994                 default:
1995                         return "Reserved";
1996                 }
1997         case DP_COLORIMETRY_BT2020_RGB: /* and DP_COLORIMETRY_BT2020_CYCC */
1998                 switch (pixelformat) {
1999                 case DP_PIXELFORMAT_RGB:
2000                         return "BT.2020 RGB";
2001                 case DP_PIXELFORMAT_YUV444:
2002                 case DP_PIXELFORMAT_YUV422:
2003                 case DP_PIXELFORMAT_YUV420:
2004                         return "BT.2020 CYCC";
2005                 default:
2006                         return "Reserved";
2007                 }
2008         case DP_COLORIMETRY_BT2020_YCC:
2009                 switch (pixelformat) {
2010                 case DP_PIXELFORMAT_YUV444:
2011                 case DP_PIXELFORMAT_YUV422:
2012                 case DP_PIXELFORMAT_YUV420:
2013                         return "BT.2020 YCC";
2014                 default:
2015                         return "Reserved";
2016                 }
2017         default:
2018                 return "Invalid";
2019         }
2020 }
2021
2022 static const char *dp_dynamic_range_get_name(enum dp_dynamic_range dynamic_range)
2023 {
2024         switch (dynamic_range) {
2025         case DP_DYNAMIC_RANGE_VESA:
2026                 return "VESA range";
2027         case DP_DYNAMIC_RANGE_CTA:
2028                 return "CTA range";
2029         default:
2030                 return "Invalid";
2031         }
2032 }
2033
2034 static const char *dp_content_type_get_name(enum dp_content_type content_type)
2035 {
2036         switch (content_type) {
2037         case DP_CONTENT_TYPE_NOT_DEFINED:
2038                 return "Not defined";
2039         case DP_CONTENT_TYPE_GRAPHICS:
2040                 return "Graphics";
2041         case DP_CONTENT_TYPE_PHOTO:
2042                 return "Photo";
2043         case DP_CONTENT_TYPE_VIDEO:
2044                 return "Video";
2045         case DP_CONTENT_TYPE_GAME:
2046                 return "Game";
2047         default:
2048                 return "Reserved";
2049         }
2050 }
2051
2052 void drm_dp_vsc_sdp_log(const char *level, struct device *dev,
2053                         const struct drm_dp_vsc_sdp *vsc)
2054 {
2055 #define DP_SDP_LOG(fmt, ...) dev_printk(level, dev, fmt, ##__VA_ARGS__)
2056         DP_SDP_LOG("DP SDP: %s, revision %u, length %u\n", "VSC",
2057                    vsc->revision, vsc->length);
2058         DP_SDP_LOG("    pixelformat: %s\n",
2059                    dp_pixelformat_get_name(vsc->pixelformat));
2060         DP_SDP_LOG("    colorimetry: %s\n",
2061                    dp_colorimetry_get_name(vsc->pixelformat, vsc->colorimetry));
2062         DP_SDP_LOG("    bpc: %u\n", vsc->bpc);
2063         DP_SDP_LOG("    dynamic range: %s\n",
2064                    dp_dynamic_range_get_name(vsc->dynamic_range));
2065         DP_SDP_LOG("    content type: %s\n",
2066                    dp_content_type_get_name(vsc->content_type));
2067 #undef DP_SDP_LOG
2068 }
2069 EXPORT_SYMBOL(drm_dp_vsc_sdp_log);