Merge tag 'drm-misc-next-2020-02-10' of git://anongit.freedesktop.org/drm/drm-misc...
[platform/kernel/linux-rpi.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         return (l >> s) & 0xf;
61 }
62
63 bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
64                           int lane_count)
65 {
66         u8 lane_align;
67         u8 lane_status;
68         int lane;
69
70         lane_align = dp_link_status(link_status,
71                                     DP_LANE_ALIGN_STATUS_UPDATED);
72         if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
73                 return false;
74         for (lane = 0; lane < lane_count; lane++) {
75                 lane_status = dp_get_lane_status(link_status, lane);
76                 if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
77                         return false;
78         }
79         return true;
80 }
81 EXPORT_SYMBOL(drm_dp_channel_eq_ok);
82
83 bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
84                               int lane_count)
85 {
86         int lane;
87         u8 lane_status;
88
89         for (lane = 0; lane < lane_count; lane++) {
90                 lane_status = dp_get_lane_status(link_status, lane);
91                 if ((lane_status & DP_LANE_CR_DONE) == 0)
92                         return false;
93         }
94         return true;
95 }
96 EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
97
98 u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
99                                      int lane)
100 {
101         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
102         int s = ((lane & 1) ?
103                  DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
104                  DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
105         u8 l = dp_link_status(link_status, i);
106
107         return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
108 }
109 EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
110
111 u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
112                                           int lane)
113 {
114         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
115         int s = ((lane & 1) ?
116                  DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
117                  DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
118         u8 l = dp_link_status(link_status, i);
119
120         return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
121 }
122 EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
123
124 u8 drm_dp_get_adjust_request_post_cursor(const u8 link_status[DP_LINK_STATUS_SIZE],
125                                          unsigned int lane)
126 {
127         unsigned int offset = DP_ADJUST_REQUEST_POST_CURSOR2;
128         u8 value = dp_link_status(link_status, offset);
129
130         return (value >> (lane << 1)) & 0x3;
131 }
132 EXPORT_SYMBOL(drm_dp_get_adjust_request_post_cursor);
133
134 void drm_dp_link_train_clock_recovery_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
135 {
136         unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
137                                          DP_TRAINING_AUX_RD_MASK;
138
139         if (rd_interval > 4)
140                 DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
141                               rd_interval);
142
143         if (rd_interval == 0 || dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
144                 rd_interval = 100;
145         else
146                 rd_interval *= 4 * USEC_PER_MSEC;
147
148         usleep_range(rd_interval, rd_interval * 2);
149 }
150 EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
151
152 void drm_dp_link_train_channel_eq_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
153 {
154         unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
155                                          DP_TRAINING_AUX_RD_MASK;
156
157         if (rd_interval > 4)
158                 DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
159                               rd_interval);
160
161         if (rd_interval == 0)
162                 rd_interval = 400;
163         else
164                 rd_interval *= 4 * USEC_PER_MSEC;
165
166         usleep_range(rd_interval, rd_interval * 2);
167 }
168 EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
169
170 u8 drm_dp_link_rate_to_bw_code(int link_rate)
171 {
172         /* Spec says link_bw = link_rate / 0.27Gbps */
173         return link_rate / 27000;
174 }
175 EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
176
177 int drm_dp_bw_code_to_link_rate(u8 link_bw)
178 {
179         /* Spec says link_rate = link_bw * 0.27Gbps */
180         return link_bw * 27000;
181 }
182 EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
183
184 #define AUX_RETRY_INTERVAL 500 /* us */
185
186 static inline void
187 drm_dp_dump_access(const struct drm_dp_aux *aux,
188                    u8 request, uint offset, void *buffer, int ret)
189 {
190         const char *arrow = request == DP_AUX_NATIVE_READ ? "->" : "<-";
191
192         if (ret > 0)
193                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d) %*ph\n",
194                              aux->name, offset, arrow, ret, min(ret, 20), buffer);
195         else
196                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d)\n",
197                              aux->name, offset, arrow, ret);
198 }
199
200 /**
201  * DOC: dp helpers
202  *
203  * The DisplayPort AUX channel is an abstraction to allow generic, driver-
204  * independent access to AUX functionality. Drivers can take advantage of
205  * this by filling in the fields of the drm_dp_aux structure.
206  *
207  * Transactions are described using a hardware-independent drm_dp_aux_msg
208  * structure, which is passed into a driver's .transfer() implementation.
209  * Both native and I2C-over-AUX transactions are supported.
210  */
211
212 static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
213                               unsigned int offset, void *buffer, size_t size)
214 {
215         struct drm_dp_aux_msg msg;
216         unsigned int retry, native_reply;
217         int err = 0, ret = 0;
218
219         memset(&msg, 0, sizeof(msg));
220         msg.address = offset;
221         msg.request = request;
222         msg.buffer = buffer;
223         msg.size = size;
224
225         mutex_lock(&aux->hw_mutex);
226
227         /*
228          * The specification doesn't give any recommendation on how often to
229          * retry native transactions. We used to retry 7 times like for
230          * aux i2c transactions but real world devices this wasn't
231          * sufficient, bump to 32 which makes Dell 4k monitors happier.
232          */
233         for (retry = 0; retry < 32; retry++) {
234                 if (ret != 0 && ret != -ETIMEDOUT) {
235                         usleep_range(AUX_RETRY_INTERVAL,
236                                      AUX_RETRY_INTERVAL + 100);
237                 }
238
239                 ret = aux->transfer(aux, &msg);
240                 if (ret >= 0) {
241                         native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
242                         if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
243                                 if (ret == size)
244                                         goto unlock;
245
246                                 ret = -EPROTO;
247                         } else
248                                 ret = -EIO;
249                 }
250
251                 /*
252                  * We want the error we return to be the error we received on
253                  * the first transaction, since we may get a different error the
254                  * next time we retry
255                  */
256                 if (!err)
257                         err = ret;
258         }
259
260         DRM_DEBUG_KMS("Too many retries, giving up. First error: %d\n", err);
261         ret = err;
262
263 unlock:
264         mutex_unlock(&aux->hw_mutex);
265         return ret;
266 }
267
268 /**
269  * drm_dp_dpcd_read() - read a series of bytes from the DPCD
270  * @aux: DisplayPort AUX channel (SST or MST)
271  * @offset: address of the (first) register to read
272  * @buffer: buffer to store the register values
273  * @size: number of bytes in @buffer
274  *
275  * Returns the number of bytes transferred on success, or a negative error
276  * code on failure. -EIO is returned if the request was NAKed by the sink or
277  * if the retry count was exceeded. If not all bytes were transferred, this
278  * function returns -EPROTO. Errors from the underlying AUX channel transfer
279  * function, with the exception of -EBUSY (which causes the transaction to
280  * be retried), are propagated to the caller.
281  */
282 ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
283                          void *buffer, size_t size)
284 {
285         int ret;
286
287         /*
288          * HP ZR24w corrupts the first DPCD access after entering power save
289          * mode. Eg. on a read, the entire buffer will be filled with the same
290          * byte. Do a throw away read to avoid corrupting anything we care
291          * about. Afterwards things will work correctly until the monitor
292          * gets woken up and subsequently re-enters power save mode.
293          *
294          * The user pressing any button on the monitor is enough to wake it
295          * up, so there is no particularly good place to do the workaround.
296          * We just have to do it before any DPCD access and hope that the
297          * monitor doesn't power down exactly after the throw away read.
298          */
299         if (!aux->is_remote) {
300                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, DP_DPCD_REV,
301                                          buffer, 1);
302                 if (ret != 1)
303                         goto out;
304         }
305
306         if (aux->is_remote)
307                 ret = drm_dp_mst_dpcd_read(aux, offset, buffer, size);
308         else
309                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset,
310                                          buffer, size);
311
312 out:
313         drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, buffer, ret);
314         return ret;
315 }
316 EXPORT_SYMBOL(drm_dp_dpcd_read);
317
318 /**
319  * drm_dp_dpcd_write() - write a series of bytes to the DPCD
320  * @aux: DisplayPort AUX channel (SST or MST)
321  * @offset: address of the (first) register to write
322  * @buffer: buffer containing the values to write
323  * @size: number of bytes in @buffer
324  *
325  * Returns the number of bytes transferred on success, or a negative error
326  * code on failure. -EIO is returned if the request was NAKed by the sink or
327  * if the retry count was exceeded. If not all bytes were transferred, this
328  * function returns -EPROTO. Errors from the underlying AUX channel transfer
329  * function, with the exception of -EBUSY (which causes the transaction to
330  * be retried), are propagated to the caller.
331  */
332 ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
333                           void *buffer, size_t size)
334 {
335         int ret;
336
337         if (aux->is_remote)
338                 ret = drm_dp_mst_dpcd_write(aux, offset, buffer, size);
339         else
340                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset,
341                                          buffer, size);
342
343         drm_dp_dump_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer, ret);
344         return ret;
345 }
346 EXPORT_SYMBOL(drm_dp_dpcd_write);
347
348 /**
349  * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
350  * @aux: DisplayPort AUX channel
351  * @status: buffer to store the link status in (must be at least 6 bytes)
352  *
353  * Returns the number of bytes transferred on success or a negative error
354  * code on failure.
355  */
356 int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
357                                  u8 status[DP_LINK_STATUS_SIZE])
358 {
359         return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
360                                 DP_LINK_STATUS_SIZE);
361 }
362 EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
363
364 /**
365  * drm_dp_downstream_max_clock() - extract branch device max
366  *                                 pixel rate for legacy VGA
367  *                                 converter or max TMDS clock
368  *                                 rate for others
369  * @dpcd: DisplayPort configuration data
370  * @port_cap: port capabilities
371  *
372  * Returns max clock in kHz on success or 0 if max clock not defined
373  */
374 int drm_dp_downstream_max_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
375                                 const u8 port_cap[4])
376 {
377         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
378         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
379                 DP_DETAILED_CAP_INFO_AVAILABLE;
380
381         if (!detailed_cap_info)
382                 return 0;
383
384         switch (type) {
385         case DP_DS_PORT_TYPE_VGA:
386                 return port_cap[1] * 8 * 1000;
387         case DP_DS_PORT_TYPE_DVI:
388         case DP_DS_PORT_TYPE_HDMI:
389         case DP_DS_PORT_TYPE_DP_DUALMODE:
390                 return port_cap[1] * 2500;
391         default:
392                 return 0;
393         }
394 }
395 EXPORT_SYMBOL(drm_dp_downstream_max_clock);
396
397 /**
398  * drm_dp_downstream_max_bpc() - extract branch device max
399  *                               bits per component
400  * @dpcd: DisplayPort configuration data
401  * @port_cap: port capabilities
402  *
403  * Returns max bpc on success or 0 if max bpc not defined
404  */
405 int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
406                               const u8 port_cap[4])
407 {
408         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
409         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
410                 DP_DETAILED_CAP_INFO_AVAILABLE;
411         int bpc;
412
413         if (!detailed_cap_info)
414                 return 0;
415
416         switch (type) {
417         case DP_DS_PORT_TYPE_VGA:
418         case DP_DS_PORT_TYPE_DVI:
419         case DP_DS_PORT_TYPE_HDMI:
420         case DP_DS_PORT_TYPE_DP_DUALMODE:
421                 bpc = port_cap[2] & DP_DS_MAX_BPC_MASK;
422
423                 switch (bpc) {
424                 case DP_DS_8BPC:
425                         return 8;
426                 case DP_DS_10BPC:
427                         return 10;
428                 case DP_DS_12BPC:
429                         return 12;
430                 case DP_DS_16BPC:
431                         return 16;
432                 }
433                 /* fall through */
434         default:
435                 return 0;
436         }
437 }
438 EXPORT_SYMBOL(drm_dp_downstream_max_bpc);
439
440 /**
441  * drm_dp_downstream_id() - identify branch device
442  * @aux: DisplayPort AUX channel
443  * @id: DisplayPort branch device id
444  *
445  * Returns branch device id on success or NULL on failure
446  */
447 int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
448 {
449         return drm_dp_dpcd_read(aux, DP_BRANCH_ID, id, 6);
450 }
451 EXPORT_SYMBOL(drm_dp_downstream_id);
452
453 /**
454  * drm_dp_downstream_debug() - debug DP branch devices
455  * @m: pointer for debugfs file
456  * @dpcd: DisplayPort configuration data
457  * @port_cap: port capabilities
458  * @aux: DisplayPort AUX channel
459  *
460  */
461 void drm_dp_downstream_debug(struct seq_file *m,
462                              const u8 dpcd[DP_RECEIVER_CAP_SIZE],
463                              const u8 port_cap[4], struct drm_dp_aux *aux)
464 {
465         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
466                                  DP_DETAILED_CAP_INFO_AVAILABLE;
467         int clk;
468         int bpc;
469         char id[7];
470         int len;
471         uint8_t rev[2];
472         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
473         bool branch_device = drm_dp_is_branch(dpcd);
474
475         seq_printf(m, "\tDP branch device present: %s\n",
476                    branch_device ? "yes" : "no");
477
478         if (!branch_device)
479                 return;
480
481         switch (type) {
482         case DP_DS_PORT_TYPE_DP:
483                 seq_puts(m, "\t\tType: DisplayPort\n");
484                 break;
485         case DP_DS_PORT_TYPE_VGA:
486                 seq_puts(m, "\t\tType: VGA\n");
487                 break;
488         case DP_DS_PORT_TYPE_DVI:
489                 seq_puts(m, "\t\tType: DVI\n");
490                 break;
491         case DP_DS_PORT_TYPE_HDMI:
492                 seq_puts(m, "\t\tType: HDMI\n");
493                 break;
494         case DP_DS_PORT_TYPE_NON_EDID:
495                 seq_puts(m, "\t\tType: others without EDID support\n");
496                 break;
497         case DP_DS_PORT_TYPE_DP_DUALMODE:
498                 seq_puts(m, "\t\tType: DP++\n");
499                 break;
500         case DP_DS_PORT_TYPE_WIRELESS:
501                 seq_puts(m, "\t\tType: Wireless\n");
502                 break;
503         default:
504                 seq_puts(m, "\t\tType: N/A\n");
505         }
506
507         memset(id, 0, sizeof(id));
508         drm_dp_downstream_id(aux, id);
509         seq_printf(m, "\t\tID: %s\n", id);
510
511         len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
512         if (len > 0)
513                 seq_printf(m, "\t\tHW: %d.%d\n",
514                            (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
515
516         len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
517         if (len > 0)
518                 seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
519
520         if (detailed_cap_info) {
521                 clk = drm_dp_downstream_max_clock(dpcd, port_cap);
522
523                 if (clk > 0) {
524                         if (type == DP_DS_PORT_TYPE_VGA)
525                                 seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
526                         else
527                                 seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
528                 }
529
530                 bpc = drm_dp_downstream_max_bpc(dpcd, port_cap);
531
532                 if (bpc > 0)
533                         seq_printf(m, "\t\tMax bpc: %d\n", bpc);
534         }
535 }
536 EXPORT_SYMBOL(drm_dp_downstream_debug);
537
538 /*
539  * I2C-over-AUX implementation
540  */
541
542 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
543 {
544         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
545                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
546                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
547                I2C_FUNC_10BIT_ADDR;
548 }
549
550 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
551 {
552         /*
553          * In case of i2c defer or short i2c ack reply to a write,
554          * we need to switch to WRITE_STATUS_UPDATE to drain the
555          * rest of the message
556          */
557         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
558                 msg->request &= DP_AUX_I2C_MOT;
559                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
560         }
561 }
562
563 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
564 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
565 #define AUX_STOP_LEN 4
566 #define AUX_CMD_LEN 4
567 #define AUX_ADDRESS_LEN 20
568 #define AUX_REPLY_PAD_LEN 4
569 #define AUX_LENGTH_LEN 8
570
571 /*
572  * Calculate the duration of the AUX request/reply in usec. Gives the
573  * "best" case estimate, ie. successful while as short as possible.
574  */
575 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
576 {
577         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
578                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
579
580         if ((msg->request & DP_AUX_I2C_READ) == 0)
581                 len += msg->size * 8;
582
583         return len;
584 }
585
586 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
587 {
588         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
589                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
590
591         /*
592          * For read we expect what was asked. For writes there will
593          * be 0 or 1 data bytes. Assume 0 for the "best" case.
594          */
595         if (msg->request & DP_AUX_I2C_READ)
596                 len += msg->size * 8;
597
598         return len;
599 }
600
601 #define I2C_START_LEN 1
602 #define I2C_STOP_LEN 1
603 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
604 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
605
606 /*
607  * Calculate the length of the i2c transfer in usec, assuming
608  * the i2c bus speed is as specified. Gives the the "worst"
609  * case estimate, ie. successful while as long as possible.
610  * Doesn't account the the "MOT" bit, and instead assumes each
611  * message includes a START, ADDRESS and STOP. Neither does it
612  * account for additional random variables such as clock stretching.
613  */
614 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
615                                    int i2c_speed_khz)
616 {
617         /* AUX bitrate is 1MHz, i2c bitrate as specified */
618         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
619                              msg->size * I2C_DATA_LEN +
620                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
621 }
622
623 /*
624  * Deterine how many retries should be attempted to successfully transfer
625  * the specified message, based on the estimated durations of the
626  * i2c and AUX transfers.
627  */
628 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
629                               int i2c_speed_khz)
630 {
631         int aux_time_us = drm_dp_aux_req_duration(msg) +
632                 drm_dp_aux_reply_duration(msg);
633         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
634
635         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
636 }
637
638 /*
639  * FIXME currently assumes 10 kHz as some real world devices seem
640  * to require it. We should query/set the speed via DPCD if supported.
641  */
642 static int dp_aux_i2c_speed_khz __read_mostly = 10;
643 module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
644 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
645                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
646
647 /*
648  * Transfer a single I2C-over-AUX message and handle various error conditions,
649  * retrying the transaction as appropriate.  It is assumed that the
650  * &drm_dp_aux.transfer function does not modify anything in the msg other than the
651  * reply field.
652  *
653  * Returns bytes transferred on success, or a negative error code on failure.
654  */
655 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
656 {
657         unsigned int retry, defer_i2c;
658         int ret;
659         /*
660          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
661          * is required to retry at least seven times upon receiving AUX_DEFER
662          * before giving up the AUX transaction.
663          *
664          * We also try to account for the i2c bus speed.
665          */
666         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
667
668         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
669                 ret = aux->transfer(aux, msg);
670                 if (ret < 0) {
671                         if (ret == -EBUSY)
672                                 continue;
673
674                         /*
675                          * While timeouts can be errors, they're usually normal
676                          * behavior (for instance, when a driver tries to
677                          * communicate with a non-existant DisplayPort device).
678                          * Avoid spamming the kernel log with timeout errors.
679                          */
680                         if (ret == -ETIMEDOUT)
681                                 DRM_DEBUG_KMS_RATELIMITED("transaction timed out\n");
682                         else
683                                 DRM_DEBUG_KMS("transaction failed: %d\n", ret);
684
685                         return ret;
686                 }
687
688
689                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
690                 case DP_AUX_NATIVE_REPLY_ACK:
691                         /*
692                          * For I2C-over-AUX transactions this isn't enough, we
693                          * need to check for the I2C ACK reply.
694                          */
695                         break;
696
697                 case DP_AUX_NATIVE_REPLY_NACK:
698                         DRM_DEBUG_KMS("native nack (result=%d, size=%zu)\n", ret, msg->size);
699                         return -EREMOTEIO;
700
701                 case DP_AUX_NATIVE_REPLY_DEFER:
702                         DRM_DEBUG_KMS("native defer\n");
703                         /*
704                          * We could check for I2C bit rate capabilities and if
705                          * available adjust this interval. We could also be
706                          * more careful with DP-to-legacy adapters where a
707                          * long legacy cable may force very low I2C bit rates.
708                          *
709                          * For now just defer for long enough to hopefully be
710                          * safe for all use-cases.
711                          */
712                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
713                         continue;
714
715                 default:
716                         DRM_ERROR("invalid native reply %#04x\n", msg->reply);
717                         return -EREMOTEIO;
718                 }
719
720                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
721                 case DP_AUX_I2C_REPLY_ACK:
722                         /*
723                          * Both native ACK and I2C ACK replies received. We
724                          * can assume the transfer was successful.
725                          */
726                         if (ret != msg->size)
727                                 drm_dp_i2c_msg_write_status_update(msg);
728                         return ret;
729
730                 case DP_AUX_I2C_REPLY_NACK:
731                         DRM_DEBUG_KMS("I2C nack (result=%d, size=%zu)\n",
732                                       ret, msg->size);
733                         aux->i2c_nack_count++;
734                         return -EREMOTEIO;
735
736                 case DP_AUX_I2C_REPLY_DEFER:
737                         DRM_DEBUG_KMS("I2C defer\n");
738                         /* DP Compliance Test 4.2.2.5 Requirement:
739                          * Must have at least 7 retries for I2C defers on the
740                          * transaction to pass this test
741                          */
742                         aux->i2c_defer_count++;
743                         if (defer_i2c < 7)
744                                 defer_i2c++;
745                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
746                         drm_dp_i2c_msg_write_status_update(msg);
747
748                         continue;
749
750                 default:
751                         DRM_ERROR("invalid I2C reply %#04x\n", msg->reply);
752                         return -EREMOTEIO;
753                 }
754         }
755
756         DRM_DEBUG_KMS("too many retries, giving up\n");
757         return -EREMOTEIO;
758 }
759
760 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
761                                        const struct i2c_msg *i2c_msg)
762 {
763         msg->request = (i2c_msg->flags & I2C_M_RD) ?
764                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
765         if (!(i2c_msg->flags & I2C_M_STOP))
766                 msg->request |= DP_AUX_I2C_MOT;
767 }
768
769 /*
770  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
771  *
772  * Returns an error code on failure, or a recommended transfer size on success.
773  */
774 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
775 {
776         int err, ret = orig_msg->size;
777         struct drm_dp_aux_msg msg = *orig_msg;
778
779         while (msg.size > 0) {
780                 err = drm_dp_i2c_do_msg(aux, &msg);
781                 if (err <= 0)
782                         return err == 0 ? -EPROTO : err;
783
784                 if (err < msg.size && err < ret) {
785                         DRM_DEBUG_KMS("Partial I2C reply: requested %zu bytes got %d bytes\n",
786                                       msg.size, err);
787                         ret = err;
788                 }
789
790                 msg.size -= err;
791                 msg.buffer += err;
792         }
793
794         return ret;
795 }
796
797 /*
798  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
799  * packets to be as large as possible. If not, the I2C transactions never
800  * succeed. Hence the default is maximum.
801  */
802 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
803 module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
804 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
805                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
806
807 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
808                            int num)
809 {
810         struct drm_dp_aux *aux = adapter->algo_data;
811         unsigned int i, j;
812         unsigned transfer_size;
813         struct drm_dp_aux_msg msg;
814         int err = 0;
815
816         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
817
818         memset(&msg, 0, sizeof(msg));
819
820         for (i = 0; i < num; i++) {
821                 msg.address = msgs[i].addr;
822                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
823                 /* Send a bare address packet to start the transaction.
824                  * Zero sized messages specify an address only (bare
825                  * address) transaction.
826                  */
827                 msg.buffer = NULL;
828                 msg.size = 0;
829                 err = drm_dp_i2c_do_msg(aux, &msg);
830
831                 /*
832                  * Reset msg.request in case in case it got
833                  * changed into a WRITE_STATUS_UPDATE.
834                  */
835                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
836
837                 if (err < 0)
838                         break;
839                 /* We want each transaction to be as large as possible, but
840                  * we'll go to smaller sizes if the hardware gives us a
841                  * short reply.
842                  */
843                 transfer_size = dp_aux_i2c_transfer_size;
844                 for (j = 0; j < msgs[i].len; j += msg.size) {
845                         msg.buffer = msgs[i].buf + j;
846                         msg.size = min(transfer_size, msgs[i].len - j);
847
848                         err = drm_dp_i2c_drain_msg(aux, &msg);
849
850                         /*
851                          * Reset msg.request in case in case it got
852                          * changed into a WRITE_STATUS_UPDATE.
853                          */
854                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
855
856                         if (err < 0)
857                                 break;
858                         transfer_size = err;
859                 }
860                 if (err < 0)
861                         break;
862         }
863         if (err >= 0)
864                 err = num;
865         /* Send a bare address packet to close out the transaction.
866          * Zero sized messages specify an address only (bare
867          * address) transaction.
868          */
869         msg.request &= ~DP_AUX_I2C_MOT;
870         msg.buffer = NULL;
871         msg.size = 0;
872         (void)drm_dp_i2c_do_msg(aux, &msg);
873
874         return err;
875 }
876
877 static const struct i2c_algorithm drm_dp_i2c_algo = {
878         .functionality = drm_dp_i2c_functionality,
879         .master_xfer = drm_dp_i2c_xfer,
880 };
881
882 static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
883 {
884         return container_of(i2c, struct drm_dp_aux, ddc);
885 }
886
887 static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
888 {
889         mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
890 }
891
892 static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
893 {
894         return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
895 }
896
897 static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
898 {
899         mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
900 }
901
902 static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
903         .lock_bus = lock_bus,
904         .trylock_bus = trylock_bus,
905         .unlock_bus = unlock_bus,
906 };
907
908 static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
909 {
910         u8 buf, count;
911         int ret;
912
913         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
914         if (ret < 0)
915                 return ret;
916
917         WARN_ON(!(buf & DP_TEST_SINK_START));
918
919         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
920         if (ret < 0)
921                 return ret;
922
923         count = buf & DP_TEST_COUNT_MASK;
924         if (count == aux->crc_count)
925                 return -EAGAIN; /* No CRC yet */
926
927         aux->crc_count = count;
928
929         /*
930          * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
931          * per component (RGB or CrYCb).
932          */
933         ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
934         if (ret < 0)
935                 return ret;
936
937         return 0;
938 }
939
940 static void drm_dp_aux_crc_work(struct work_struct *work)
941 {
942         struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
943                                               crc_work);
944         struct drm_crtc *crtc;
945         u8 crc_bytes[6];
946         uint32_t crcs[3];
947         int ret;
948
949         if (WARN_ON(!aux->crtc))
950                 return;
951
952         crtc = aux->crtc;
953         while (crtc->crc.opened) {
954                 drm_crtc_wait_one_vblank(crtc);
955                 if (!crtc->crc.opened)
956                         break;
957
958                 ret = drm_dp_aux_get_crc(aux, crc_bytes);
959                 if (ret == -EAGAIN) {
960                         usleep_range(1000, 2000);
961                         ret = drm_dp_aux_get_crc(aux, crc_bytes);
962                 }
963
964                 if (ret == -EAGAIN) {
965                         DRM_DEBUG_KMS("Get CRC failed after retrying: %d\n",
966                                       ret);
967                         continue;
968                 } else if (ret) {
969                         DRM_DEBUG_KMS("Failed to get a CRC: %d\n", ret);
970                         continue;
971                 }
972
973                 crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
974                 crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
975                 crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
976                 drm_crtc_add_crc_entry(crtc, false, 0, crcs);
977         }
978 }
979
980 /**
981  * drm_dp_remote_aux_init() - minimally initialise a remote aux channel
982  * @aux: DisplayPort AUX channel
983  *
984  * Used for remote aux channel in general. Merely initialize the crc work
985  * struct.
986  */
987 void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
988 {
989         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
990 }
991 EXPORT_SYMBOL(drm_dp_remote_aux_init);
992
993 /**
994  * drm_dp_aux_init() - minimally initialise an aux channel
995  * @aux: DisplayPort AUX channel
996  *
997  * If you need to use the drm_dp_aux's i2c adapter prior to registering it
998  * with the outside world, call drm_dp_aux_init() first. You must still
999  * call drm_dp_aux_register() once the connector has been registered to
1000  * allow userspace access to the auxiliary DP channel.
1001  */
1002 void drm_dp_aux_init(struct drm_dp_aux *aux)
1003 {
1004         mutex_init(&aux->hw_mutex);
1005         mutex_init(&aux->cec.lock);
1006         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1007
1008         aux->ddc.algo = &drm_dp_i2c_algo;
1009         aux->ddc.algo_data = aux;
1010         aux->ddc.retries = 3;
1011
1012         aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
1013 }
1014 EXPORT_SYMBOL(drm_dp_aux_init);
1015
1016 /**
1017  * drm_dp_aux_register() - initialise and register aux channel
1018  * @aux: DisplayPort AUX channel
1019  *
1020  * Automatically calls drm_dp_aux_init() if this hasn't been done yet.
1021  * This should only be called when the underlying &struct drm_connector is
1022  * initialiazed already. Therefore the best place to call this is from
1023  * &drm_connector_funcs.late_register. Not that drivers which don't follow this
1024  * will Oops when CONFIG_DRM_DP_AUX_CHARDEV is enabled.
1025  *
1026  * Drivers which need to use the aux channel before that point (e.g. at driver
1027  * load time, before drm_dev_register() has been called) need to call
1028  * drm_dp_aux_init().
1029  *
1030  * Returns 0 on success or a negative error code on failure.
1031  */
1032 int drm_dp_aux_register(struct drm_dp_aux *aux)
1033 {
1034         int ret;
1035
1036         if (!aux->ddc.algo)
1037                 drm_dp_aux_init(aux);
1038
1039         aux->ddc.class = I2C_CLASS_DDC;
1040         aux->ddc.owner = THIS_MODULE;
1041         aux->ddc.dev.parent = aux->dev;
1042
1043         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
1044                 sizeof(aux->ddc.name));
1045
1046         ret = drm_dp_aux_register_devnode(aux);
1047         if (ret)
1048                 return ret;
1049
1050         ret = i2c_add_adapter(&aux->ddc);
1051         if (ret) {
1052                 drm_dp_aux_unregister_devnode(aux);
1053                 return ret;
1054         }
1055
1056         return 0;
1057 }
1058 EXPORT_SYMBOL(drm_dp_aux_register);
1059
1060 /**
1061  * drm_dp_aux_unregister() - unregister an AUX adapter
1062  * @aux: DisplayPort AUX channel
1063  */
1064 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
1065 {
1066         drm_dp_aux_unregister_devnode(aux);
1067         i2c_del_adapter(&aux->ddc);
1068 }
1069 EXPORT_SYMBOL(drm_dp_aux_unregister);
1070
1071 #define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
1072
1073 /**
1074  * drm_dp_psr_setup_time() - PSR setup in time usec
1075  * @psr_cap: PSR capabilities from DPCD
1076  *
1077  * Returns:
1078  * PSR setup time for the panel in microseconds,  negative
1079  * error code on failure.
1080  */
1081 int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
1082 {
1083         static const u16 psr_setup_time_us[] = {
1084                 PSR_SETUP_TIME(330),
1085                 PSR_SETUP_TIME(275),
1086                 PSR_SETUP_TIME(220),
1087                 PSR_SETUP_TIME(165),
1088                 PSR_SETUP_TIME(110),
1089                 PSR_SETUP_TIME(55),
1090                 PSR_SETUP_TIME(0),
1091         };
1092         int i;
1093
1094         i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
1095         if (i >= ARRAY_SIZE(psr_setup_time_us))
1096                 return -EINVAL;
1097
1098         return psr_setup_time_us[i];
1099 }
1100 EXPORT_SYMBOL(drm_dp_psr_setup_time);
1101
1102 #undef PSR_SETUP_TIME
1103
1104 /**
1105  * drm_dp_start_crc() - start capture of frame CRCs
1106  * @aux: DisplayPort AUX channel
1107  * @crtc: CRTC displaying the frames whose CRCs are to be captured
1108  *
1109  * Returns 0 on success or a negative error code on failure.
1110  */
1111 int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
1112 {
1113         u8 buf;
1114         int ret;
1115
1116         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1117         if (ret < 0)
1118                 return ret;
1119
1120         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
1121         if (ret < 0)
1122                 return ret;
1123
1124         aux->crc_count = 0;
1125         aux->crtc = crtc;
1126         schedule_work(&aux->crc_work);
1127
1128         return 0;
1129 }
1130 EXPORT_SYMBOL(drm_dp_start_crc);
1131
1132 /**
1133  * drm_dp_stop_crc() - stop capture of frame CRCs
1134  * @aux: DisplayPort AUX channel
1135  *
1136  * Returns 0 on success or a negative error code on failure.
1137  */
1138 int drm_dp_stop_crc(struct drm_dp_aux *aux)
1139 {
1140         u8 buf;
1141         int ret;
1142
1143         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1144         if (ret < 0)
1145                 return ret;
1146
1147         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
1148         if (ret < 0)
1149                 return ret;
1150
1151         flush_work(&aux->crc_work);
1152         aux->crtc = NULL;
1153
1154         return 0;
1155 }
1156 EXPORT_SYMBOL(drm_dp_stop_crc);
1157
1158 struct dpcd_quirk {
1159         u8 oui[3];
1160         u8 device_id[6];
1161         bool is_branch;
1162         u32 quirks;
1163 };
1164
1165 #define OUI(first, second, third) { (first), (second), (third) }
1166 #define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
1167         { (first), (second), (third), (fourth), (fifth), (sixth) }
1168
1169 #define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
1170
1171 static const struct dpcd_quirk dpcd_quirk_list[] = {
1172         /* Analogix 7737 needs reduced M and N at HBR2 link rates */
1173         { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1174         /* LG LP140WF6-SPM1 eDP panel */
1175         { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1176         /* Apple panels need some additional handling to support PSR */
1177         { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
1178         /* CH7511 seems to leave SINK_COUNT zeroed */
1179         { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
1180         /* Synaptics DP1.4 MST hubs can support DSC without virtual DPCD */
1181         { OUI(0x90, 0xCC, 0x24), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) },
1182 };
1183
1184 #undef OUI
1185
1186 /*
1187  * Get a bit mask of DPCD quirks for the sink/branch device identified by
1188  * ident. The quirk data is shared but it's up to the drivers to act on the
1189  * data.
1190  *
1191  * For now, only the OUI (first three bytes) is used, but this may be extended
1192  * to device identification string and hardware/firmware revisions later.
1193  */
1194 static u32
1195 drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
1196 {
1197         const struct dpcd_quirk *quirk;
1198         u32 quirks = 0;
1199         int i;
1200         u8 any_device[] = DEVICE_ID_ANY;
1201
1202         for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
1203                 quirk = &dpcd_quirk_list[i];
1204
1205                 if (quirk->is_branch != is_branch)
1206                         continue;
1207
1208                 if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
1209                         continue;
1210
1211                 if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
1212                     memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
1213                         continue;
1214
1215                 quirks |= quirk->quirks;
1216         }
1217
1218         return quirks;
1219 }
1220
1221 #undef DEVICE_ID_ANY
1222 #undef DEVICE_ID
1223
1224 /**
1225  * drm_dp_read_desc - read sink/branch descriptor from DPCD
1226  * @aux: DisplayPort AUX channel
1227  * @desc: Device decriptor to fill from DPCD
1228  * @is_branch: true for branch devices, false for sink devices
1229  *
1230  * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
1231  * identification.
1232  *
1233  * Returns 0 on success or a negative error code on failure.
1234  */
1235 int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
1236                      bool is_branch)
1237 {
1238         struct drm_dp_dpcd_ident *ident = &desc->ident;
1239         unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
1240         int ret, dev_id_len;
1241
1242         ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
1243         if (ret < 0)
1244                 return ret;
1245
1246         desc->quirks = drm_dp_get_quirks(ident, is_branch);
1247
1248         dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
1249
1250         DRM_DEBUG_KMS("DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
1251                       is_branch ? "branch" : "sink",
1252                       (int)sizeof(ident->oui), ident->oui,
1253                       dev_id_len, ident->device_id,
1254                       ident->hw_rev >> 4, ident->hw_rev & 0xf,
1255                       ident->sw_major_rev, ident->sw_minor_rev,
1256                       desc->quirks);
1257
1258         return 0;
1259 }
1260 EXPORT_SYMBOL(drm_dp_read_desc);
1261
1262 /**
1263  * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
1264  * supported by the DSC sink.
1265  * @dsc_dpcd: DSC capabilities from DPCD
1266  * @is_edp: true if its eDP, false for DP
1267  *
1268  * Read the slice capabilities DPCD register from DSC sink to get
1269  * the maximum slice count supported. This is used to populate
1270  * the DSC parameters in the &struct drm_dsc_config by the driver.
1271  * Driver creates an infoframe using these parameters to populate
1272  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1273  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1274  *
1275  * Returns:
1276  * Maximum slice count supported by DSC sink or 0 its invalid
1277  */
1278 u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1279                                    bool is_edp)
1280 {
1281         u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
1282
1283         if (is_edp) {
1284                 /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
1285                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1286                         return 4;
1287                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1288                         return 2;
1289                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1290                         return 1;
1291         } else {
1292                 /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
1293                 u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
1294
1295                 if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
1296                         return 24;
1297                 if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
1298                         return 20;
1299                 if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
1300                         return 16;
1301                 if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
1302                         return 12;
1303                 if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
1304                         return 10;
1305                 if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
1306                         return 8;
1307                 if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
1308                         return 6;
1309                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1310                         return 4;
1311                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1312                         return 2;
1313                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1314                         return 1;
1315         }
1316
1317         return 0;
1318 }
1319 EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
1320
1321 /**
1322  * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
1323  * @dsc_dpcd: DSC capabilities from DPCD
1324  *
1325  * Read the DSC DPCD register to parse the line buffer depth in bits which is
1326  * number of bits of precision within the decoder line buffer supported by
1327  * the DSC sink. This is used to populate the DSC parameters in the
1328  * &struct drm_dsc_config by the driver.
1329  * Driver creates an infoframe using these parameters to populate
1330  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1331  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1332  *
1333  * Returns:
1334  * Line buffer depth supported by DSC panel or 0 its invalid
1335  */
1336 u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
1337 {
1338         u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
1339
1340         switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
1341         case DP_DSC_LINE_BUF_BIT_DEPTH_9:
1342                 return 9;
1343         case DP_DSC_LINE_BUF_BIT_DEPTH_10:
1344                 return 10;
1345         case DP_DSC_LINE_BUF_BIT_DEPTH_11:
1346                 return 11;
1347         case DP_DSC_LINE_BUF_BIT_DEPTH_12:
1348                 return 12;
1349         case DP_DSC_LINE_BUF_BIT_DEPTH_13:
1350                 return 13;
1351         case DP_DSC_LINE_BUF_BIT_DEPTH_14:
1352                 return 14;
1353         case DP_DSC_LINE_BUF_BIT_DEPTH_15:
1354                 return 15;
1355         case DP_DSC_LINE_BUF_BIT_DEPTH_16:
1356                 return 16;
1357         case DP_DSC_LINE_BUF_BIT_DEPTH_8:
1358                 return 8;
1359         }
1360
1361         return 0;
1362 }
1363 EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
1364
1365 /**
1366  * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
1367  * values supported by the DSC sink.
1368  * @dsc_dpcd: DSC capabilities from DPCD
1369  * @dsc_bpc: An array to be filled by this helper with supported
1370  *           input bpcs.
1371  *
1372  * Read the DSC DPCD from the sink device to parse the supported bits per
1373  * component values. This is used to populate the DSC parameters
1374  * in the &struct drm_dsc_config by the driver.
1375  * Driver creates an infoframe using these parameters to populate
1376  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1377  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1378  *
1379  * Returns:
1380  * Number of input BPC values parsed from the DPCD
1381  */
1382 int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1383                                          u8 dsc_bpc[3])
1384 {
1385         int num_bpc = 0;
1386         u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
1387
1388         if (color_depth & DP_DSC_12_BPC)
1389                 dsc_bpc[num_bpc++] = 12;
1390         if (color_depth & DP_DSC_10_BPC)
1391                 dsc_bpc[num_bpc++] = 10;
1392         if (color_depth & DP_DSC_8_BPC)
1393                 dsc_bpc[num_bpc++] = 8;
1394
1395         return num_bpc;
1396 }
1397 EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);