drm/etnaviv: Replace zero-length array with flexible-array member
[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         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 = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
474                              DP_DWN_STRM_PORT_PRESENT;
475
476         seq_printf(m, "\tDP branch device present: %s\n",
477                    branch_device ? "yes" : "no");
478
479         if (!branch_device)
480                 return;
481
482         switch (type) {
483         case DP_DS_PORT_TYPE_DP:
484                 seq_puts(m, "\t\tType: DisplayPort\n");
485                 break;
486         case DP_DS_PORT_TYPE_VGA:
487                 seq_puts(m, "\t\tType: VGA\n");
488                 break;
489         case DP_DS_PORT_TYPE_DVI:
490                 seq_puts(m, "\t\tType: DVI\n");
491                 break;
492         case DP_DS_PORT_TYPE_HDMI:
493                 seq_puts(m, "\t\tType: HDMI\n");
494                 break;
495         case DP_DS_PORT_TYPE_NON_EDID:
496                 seq_puts(m, "\t\tType: others without EDID support\n");
497                 break;
498         case DP_DS_PORT_TYPE_DP_DUALMODE:
499                 seq_puts(m, "\t\tType: DP++\n");
500                 break;
501         case DP_DS_PORT_TYPE_WIRELESS:
502                 seq_puts(m, "\t\tType: Wireless\n");
503                 break;
504         default:
505                 seq_puts(m, "\t\tType: N/A\n");
506         }
507
508         memset(id, 0, sizeof(id));
509         drm_dp_downstream_id(aux, id);
510         seq_printf(m, "\t\tID: %s\n", id);
511
512         len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
513         if (len > 0)
514                 seq_printf(m, "\t\tHW: %d.%d\n",
515                            (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
516
517         len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
518         if (len > 0)
519                 seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
520
521         if (detailed_cap_info) {
522                 clk = drm_dp_downstream_max_clock(dpcd, port_cap);
523
524                 if (clk > 0) {
525                         if (type == DP_DS_PORT_TYPE_VGA)
526                                 seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
527                         else
528                                 seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
529                 }
530
531                 bpc = drm_dp_downstream_max_bpc(dpcd, port_cap);
532
533                 if (bpc > 0)
534                         seq_printf(m, "\t\tMax bpc: %d\n", bpc);
535         }
536 }
537 EXPORT_SYMBOL(drm_dp_downstream_debug);
538
539 /*
540  * I2C-over-AUX implementation
541  */
542
543 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
544 {
545         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
546                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
547                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
548                I2C_FUNC_10BIT_ADDR;
549 }
550
551 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
552 {
553         /*
554          * In case of i2c defer or short i2c ack reply to a write,
555          * we need to switch to WRITE_STATUS_UPDATE to drain the
556          * rest of the message
557          */
558         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
559                 msg->request &= DP_AUX_I2C_MOT;
560                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
561         }
562 }
563
564 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
565 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
566 #define AUX_STOP_LEN 4
567 #define AUX_CMD_LEN 4
568 #define AUX_ADDRESS_LEN 20
569 #define AUX_REPLY_PAD_LEN 4
570 #define AUX_LENGTH_LEN 8
571
572 /*
573  * Calculate the duration of the AUX request/reply in usec. Gives the
574  * "best" case estimate, ie. successful while as short as possible.
575  */
576 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
577 {
578         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
579                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
580
581         if ((msg->request & DP_AUX_I2C_READ) == 0)
582                 len += msg->size * 8;
583
584         return len;
585 }
586
587 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
588 {
589         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
590                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
591
592         /*
593          * For read we expect what was asked. For writes there will
594          * be 0 or 1 data bytes. Assume 0 for the "best" case.
595          */
596         if (msg->request & DP_AUX_I2C_READ)
597                 len += msg->size * 8;
598
599         return len;
600 }
601
602 #define I2C_START_LEN 1
603 #define I2C_STOP_LEN 1
604 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
605 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
606
607 /*
608  * Calculate the length of the i2c transfer in usec, assuming
609  * the i2c bus speed is as specified. Gives the the "worst"
610  * case estimate, ie. successful while as long as possible.
611  * Doesn't account the the "MOT" bit, and instead assumes each
612  * message includes a START, ADDRESS and STOP. Neither does it
613  * account for additional random variables such as clock stretching.
614  */
615 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
616                                    int i2c_speed_khz)
617 {
618         /* AUX bitrate is 1MHz, i2c bitrate as specified */
619         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
620                              msg->size * I2C_DATA_LEN +
621                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
622 }
623
624 /*
625  * Deterine how many retries should be attempted to successfully transfer
626  * the specified message, based on the estimated durations of the
627  * i2c and AUX transfers.
628  */
629 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
630                               int i2c_speed_khz)
631 {
632         int aux_time_us = drm_dp_aux_req_duration(msg) +
633                 drm_dp_aux_reply_duration(msg);
634         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
635
636         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
637 }
638
639 /*
640  * FIXME currently assumes 10 kHz as some real world devices seem
641  * to require it. We should query/set the speed via DPCD if supported.
642  */
643 static int dp_aux_i2c_speed_khz __read_mostly = 10;
644 module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
645 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
646                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
647
648 /*
649  * Transfer a single I2C-over-AUX message and handle various error conditions,
650  * retrying the transaction as appropriate.  It is assumed that the
651  * &drm_dp_aux.transfer function does not modify anything in the msg other than the
652  * reply field.
653  *
654  * Returns bytes transferred on success, or a negative error code on failure.
655  */
656 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
657 {
658         unsigned int retry, defer_i2c;
659         int ret;
660         /*
661          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
662          * is required to retry at least seven times upon receiving AUX_DEFER
663          * before giving up the AUX transaction.
664          *
665          * We also try to account for the i2c bus speed.
666          */
667         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
668
669         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
670                 ret = aux->transfer(aux, msg);
671                 if (ret < 0) {
672                         if (ret == -EBUSY)
673                                 continue;
674
675                         /*
676                          * While timeouts can be errors, they're usually normal
677                          * behavior (for instance, when a driver tries to
678                          * communicate with a non-existant DisplayPort device).
679                          * Avoid spamming the kernel log with timeout errors.
680                          */
681                         if (ret == -ETIMEDOUT)
682                                 DRM_DEBUG_KMS_RATELIMITED("transaction timed out\n");
683                         else
684                                 DRM_DEBUG_KMS("transaction failed: %d\n", ret);
685
686                         return ret;
687                 }
688
689
690                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
691                 case DP_AUX_NATIVE_REPLY_ACK:
692                         /*
693                          * For I2C-over-AUX transactions this isn't enough, we
694                          * need to check for the I2C ACK reply.
695                          */
696                         break;
697
698                 case DP_AUX_NATIVE_REPLY_NACK:
699                         DRM_DEBUG_KMS("native nack (result=%d, size=%zu)\n", ret, msg->size);
700                         return -EREMOTEIO;
701
702                 case DP_AUX_NATIVE_REPLY_DEFER:
703                         DRM_DEBUG_KMS("native defer\n");
704                         /*
705                          * We could check for I2C bit rate capabilities and if
706                          * available adjust this interval. We could also be
707                          * more careful with DP-to-legacy adapters where a
708                          * long legacy cable may force very low I2C bit rates.
709                          *
710                          * For now just defer for long enough to hopefully be
711                          * safe for all use-cases.
712                          */
713                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
714                         continue;
715
716                 default:
717                         DRM_ERROR("invalid native reply %#04x\n", msg->reply);
718                         return -EREMOTEIO;
719                 }
720
721                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
722                 case DP_AUX_I2C_REPLY_ACK:
723                         /*
724                          * Both native ACK and I2C ACK replies received. We
725                          * can assume the transfer was successful.
726                          */
727                         if (ret != msg->size)
728                                 drm_dp_i2c_msg_write_status_update(msg);
729                         return ret;
730
731                 case DP_AUX_I2C_REPLY_NACK:
732                         DRM_DEBUG_KMS("I2C nack (result=%d, size=%zu)\n",
733                                       ret, msg->size);
734                         aux->i2c_nack_count++;
735                         return -EREMOTEIO;
736
737                 case DP_AUX_I2C_REPLY_DEFER:
738                         DRM_DEBUG_KMS("I2C defer\n");
739                         /* DP Compliance Test 4.2.2.5 Requirement:
740                          * Must have at least 7 retries for I2C defers on the
741                          * transaction to pass this test
742                          */
743                         aux->i2c_defer_count++;
744                         if (defer_i2c < 7)
745                                 defer_i2c++;
746                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
747                         drm_dp_i2c_msg_write_status_update(msg);
748
749                         continue;
750
751                 default:
752                         DRM_ERROR("invalid I2C reply %#04x\n", msg->reply);
753                         return -EREMOTEIO;
754                 }
755         }
756
757         DRM_DEBUG_KMS("too many retries, giving up\n");
758         return -EREMOTEIO;
759 }
760
761 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
762                                        const struct i2c_msg *i2c_msg)
763 {
764         msg->request = (i2c_msg->flags & I2C_M_RD) ?
765                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
766         if (!(i2c_msg->flags & I2C_M_STOP))
767                 msg->request |= DP_AUX_I2C_MOT;
768 }
769
770 /*
771  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
772  *
773  * Returns an error code on failure, or a recommended transfer size on success.
774  */
775 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
776 {
777         int err, ret = orig_msg->size;
778         struct drm_dp_aux_msg msg = *orig_msg;
779
780         while (msg.size > 0) {
781                 err = drm_dp_i2c_do_msg(aux, &msg);
782                 if (err <= 0)
783                         return err == 0 ? -EPROTO : err;
784
785                 if (err < msg.size && err < ret) {
786                         DRM_DEBUG_KMS("Partial I2C reply: requested %zu bytes got %d bytes\n",
787                                       msg.size, err);
788                         ret = err;
789                 }
790
791                 msg.size -= err;
792                 msg.buffer += err;
793         }
794
795         return ret;
796 }
797
798 /*
799  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
800  * packets to be as large as possible. If not, the I2C transactions never
801  * succeed. Hence the default is maximum.
802  */
803 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
804 module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
805 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
806                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
807
808 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
809                            int num)
810 {
811         struct drm_dp_aux *aux = adapter->algo_data;
812         unsigned int i, j;
813         unsigned transfer_size;
814         struct drm_dp_aux_msg msg;
815         int err = 0;
816
817         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
818
819         memset(&msg, 0, sizeof(msg));
820
821         for (i = 0; i < num; i++) {
822                 msg.address = msgs[i].addr;
823                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
824                 /* Send a bare address packet to start the transaction.
825                  * Zero sized messages specify an address only (bare
826                  * address) transaction.
827                  */
828                 msg.buffer = NULL;
829                 msg.size = 0;
830                 err = drm_dp_i2c_do_msg(aux, &msg);
831
832                 /*
833                  * Reset msg.request in case in case it got
834                  * changed into a WRITE_STATUS_UPDATE.
835                  */
836                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
837
838                 if (err < 0)
839                         break;
840                 /* We want each transaction to be as large as possible, but
841                  * we'll go to smaller sizes if the hardware gives us a
842                  * short reply.
843                  */
844                 transfer_size = dp_aux_i2c_transfer_size;
845                 for (j = 0; j < msgs[i].len; j += msg.size) {
846                         msg.buffer = msgs[i].buf + j;
847                         msg.size = min(transfer_size, msgs[i].len - j);
848
849                         err = drm_dp_i2c_drain_msg(aux, &msg);
850
851                         /*
852                          * Reset msg.request in case in case it got
853                          * changed into a WRITE_STATUS_UPDATE.
854                          */
855                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
856
857                         if (err < 0)
858                                 break;
859                         transfer_size = err;
860                 }
861                 if (err < 0)
862                         break;
863         }
864         if (err >= 0)
865                 err = num;
866         /* Send a bare address packet to close out the transaction.
867          * Zero sized messages specify an address only (bare
868          * address) transaction.
869          */
870         msg.request &= ~DP_AUX_I2C_MOT;
871         msg.buffer = NULL;
872         msg.size = 0;
873         (void)drm_dp_i2c_do_msg(aux, &msg);
874
875         return err;
876 }
877
878 static const struct i2c_algorithm drm_dp_i2c_algo = {
879         .functionality = drm_dp_i2c_functionality,
880         .master_xfer = drm_dp_i2c_xfer,
881 };
882
883 static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
884 {
885         return container_of(i2c, struct drm_dp_aux, ddc);
886 }
887
888 static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
889 {
890         mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
891 }
892
893 static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
894 {
895         return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
896 }
897
898 static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
899 {
900         mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
901 }
902
903 static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
904         .lock_bus = lock_bus,
905         .trylock_bus = trylock_bus,
906         .unlock_bus = unlock_bus,
907 };
908
909 static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
910 {
911         u8 buf, count;
912         int ret;
913
914         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
915         if (ret < 0)
916                 return ret;
917
918         WARN_ON(!(buf & DP_TEST_SINK_START));
919
920         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
921         if (ret < 0)
922                 return ret;
923
924         count = buf & DP_TEST_COUNT_MASK;
925         if (count == aux->crc_count)
926                 return -EAGAIN; /* No CRC yet */
927
928         aux->crc_count = count;
929
930         /*
931          * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
932          * per component (RGB or CrYCb).
933          */
934         ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
935         if (ret < 0)
936                 return ret;
937
938         return 0;
939 }
940
941 static void drm_dp_aux_crc_work(struct work_struct *work)
942 {
943         struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
944                                               crc_work);
945         struct drm_crtc *crtc;
946         u8 crc_bytes[6];
947         uint32_t crcs[3];
948         int ret;
949
950         if (WARN_ON(!aux->crtc))
951                 return;
952
953         crtc = aux->crtc;
954         while (crtc->crc.opened) {
955                 drm_crtc_wait_one_vblank(crtc);
956                 if (!crtc->crc.opened)
957                         break;
958
959                 ret = drm_dp_aux_get_crc(aux, crc_bytes);
960                 if (ret == -EAGAIN) {
961                         usleep_range(1000, 2000);
962                         ret = drm_dp_aux_get_crc(aux, crc_bytes);
963                 }
964
965                 if (ret == -EAGAIN) {
966                         DRM_DEBUG_KMS("Get CRC failed after retrying: %d\n",
967                                       ret);
968                         continue;
969                 } else if (ret) {
970                         DRM_DEBUG_KMS("Failed to get a CRC: %d\n", ret);
971                         continue;
972                 }
973
974                 crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
975                 crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
976                 crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
977                 drm_crtc_add_crc_entry(crtc, false, 0, crcs);
978         }
979 }
980
981 /**
982  * drm_dp_remote_aux_init() - minimally initialise a remote aux channel
983  * @aux: DisplayPort AUX channel
984  *
985  * Used for remote aux channel in general. Merely initialize the crc work
986  * struct.
987  */
988 void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
989 {
990         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
991 }
992 EXPORT_SYMBOL(drm_dp_remote_aux_init);
993
994 /**
995  * drm_dp_aux_init() - minimally initialise an aux channel
996  * @aux: DisplayPort AUX channel
997  *
998  * If you need to use the drm_dp_aux's i2c adapter prior to registering it
999  * with the outside world, call drm_dp_aux_init() first. You must still
1000  * call drm_dp_aux_register() once the connector has been registered to
1001  * allow userspace access to the auxiliary DP channel.
1002  */
1003 void drm_dp_aux_init(struct drm_dp_aux *aux)
1004 {
1005         mutex_init(&aux->hw_mutex);
1006         mutex_init(&aux->cec.lock);
1007         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1008
1009         aux->ddc.algo = &drm_dp_i2c_algo;
1010         aux->ddc.algo_data = aux;
1011         aux->ddc.retries = 3;
1012
1013         aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
1014 }
1015 EXPORT_SYMBOL(drm_dp_aux_init);
1016
1017 /**
1018  * drm_dp_aux_register() - initialise and register aux channel
1019  * @aux: DisplayPort AUX channel
1020  *
1021  * Automatically calls drm_dp_aux_init() if this hasn't been done yet.
1022  * This should only be called when the underlying &struct drm_connector is
1023  * initialiazed already. Therefore the best place to call this is from
1024  * &drm_connector_funcs.late_register. Not that drivers which don't follow this
1025  * will Oops when CONFIG_DRM_DP_AUX_CHARDEV is enabled.
1026  *
1027  * Drivers which need to use the aux channel before that point (e.g. at driver
1028  * load time, before drm_dev_register() has been called) need to call
1029  * drm_dp_aux_init().
1030  *
1031  * Returns 0 on success or a negative error code on failure.
1032  */
1033 int drm_dp_aux_register(struct drm_dp_aux *aux)
1034 {
1035         int ret;
1036
1037         if (!aux->ddc.algo)
1038                 drm_dp_aux_init(aux);
1039
1040         aux->ddc.class = I2C_CLASS_DDC;
1041         aux->ddc.owner = THIS_MODULE;
1042         aux->ddc.dev.parent = aux->dev;
1043
1044         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
1045                 sizeof(aux->ddc.name));
1046
1047         ret = drm_dp_aux_register_devnode(aux);
1048         if (ret)
1049                 return ret;
1050
1051         ret = i2c_add_adapter(&aux->ddc);
1052         if (ret) {
1053                 drm_dp_aux_unregister_devnode(aux);
1054                 return ret;
1055         }
1056
1057         return 0;
1058 }
1059 EXPORT_SYMBOL(drm_dp_aux_register);
1060
1061 /**
1062  * drm_dp_aux_unregister() - unregister an AUX adapter
1063  * @aux: DisplayPort AUX channel
1064  */
1065 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
1066 {
1067         drm_dp_aux_unregister_devnode(aux);
1068         i2c_del_adapter(&aux->ddc);
1069 }
1070 EXPORT_SYMBOL(drm_dp_aux_unregister);
1071
1072 #define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
1073
1074 /**
1075  * drm_dp_psr_setup_time() - PSR setup in time usec
1076  * @psr_cap: PSR capabilities from DPCD
1077  *
1078  * Returns:
1079  * PSR setup time for the panel in microseconds,  negative
1080  * error code on failure.
1081  */
1082 int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
1083 {
1084         static const u16 psr_setup_time_us[] = {
1085                 PSR_SETUP_TIME(330),
1086                 PSR_SETUP_TIME(275),
1087                 PSR_SETUP_TIME(220),
1088                 PSR_SETUP_TIME(165),
1089                 PSR_SETUP_TIME(110),
1090                 PSR_SETUP_TIME(55),
1091                 PSR_SETUP_TIME(0),
1092         };
1093         int i;
1094
1095         i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
1096         if (i >= ARRAY_SIZE(psr_setup_time_us))
1097                 return -EINVAL;
1098
1099         return psr_setup_time_us[i];
1100 }
1101 EXPORT_SYMBOL(drm_dp_psr_setup_time);
1102
1103 #undef PSR_SETUP_TIME
1104
1105 /**
1106  * drm_dp_start_crc() - start capture of frame CRCs
1107  * @aux: DisplayPort AUX channel
1108  * @crtc: CRTC displaying the frames whose CRCs are to be captured
1109  *
1110  * Returns 0 on success or a negative error code on failure.
1111  */
1112 int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
1113 {
1114         u8 buf;
1115         int ret;
1116
1117         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1118         if (ret < 0)
1119                 return ret;
1120
1121         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
1122         if (ret < 0)
1123                 return ret;
1124
1125         aux->crc_count = 0;
1126         aux->crtc = crtc;
1127         schedule_work(&aux->crc_work);
1128
1129         return 0;
1130 }
1131 EXPORT_SYMBOL(drm_dp_start_crc);
1132
1133 /**
1134  * drm_dp_stop_crc() - stop capture of frame CRCs
1135  * @aux: DisplayPort AUX channel
1136  *
1137  * Returns 0 on success or a negative error code on failure.
1138  */
1139 int drm_dp_stop_crc(struct drm_dp_aux *aux)
1140 {
1141         u8 buf;
1142         int ret;
1143
1144         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1145         if (ret < 0)
1146                 return ret;
1147
1148         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
1149         if (ret < 0)
1150                 return ret;
1151
1152         flush_work(&aux->crc_work);
1153         aux->crtc = NULL;
1154
1155         return 0;
1156 }
1157 EXPORT_SYMBOL(drm_dp_stop_crc);
1158
1159 struct dpcd_quirk {
1160         u8 oui[3];
1161         u8 device_id[6];
1162         bool is_branch;
1163         u32 quirks;
1164 };
1165
1166 #define OUI(first, second, third) { (first), (second), (third) }
1167 #define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
1168         { (first), (second), (third), (fourth), (fifth), (sixth) }
1169
1170 #define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
1171
1172 static const struct dpcd_quirk dpcd_quirk_list[] = {
1173         /* Analogix 7737 needs reduced M and N at HBR2 link rates */
1174         { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1175         /* LG LP140WF6-SPM1 eDP panel */
1176         { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1177         /* Apple panels need some additional handling to support PSR */
1178         { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
1179         /* CH7511 seems to leave SINK_COUNT zeroed */
1180         { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
1181         /* Synaptics DP1.4 MST hubs can support DSC without virtual DPCD */
1182         { OUI(0x90, 0xCC, 0x24), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) },
1183 };
1184
1185 #undef OUI
1186
1187 /*
1188  * Get a bit mask of DPCD quirks for the sink/branch device identified by
1189  * ident. The quirk data is shared but it's up to the drivers to act on the
1190  * data.
1191  *
1192  * For now, only the OUI (first three bytes) is used, but this may be extended
1193  * to device identification string and hardware/firmware revisions later.
1194  */
1195 static u32
1196 drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
1197 {
1198         const struct dpcd_quirk *quirk;
1199         u32 quirks = 0;
1200         int i;
1201         u8 any_device[] = DEVICE_ID_ANY;
1202
1203         for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
1204                 quirk = &dpcd_quirk_list[i];
1205
1206                 if (quirk->is_branch != is_branch)
1207                         continue;
1208
1209                 if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
1210                         continue;
1211
1212                 if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
1213                     memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
1214                         continue;
1215
1216                 quirks |= quirk->quirks;
1217         }
1218
1219         return quirks;
1220 }
1221
1222 #undef DEVICE_ID_ANY
1223 #undef DEVICE_ID
1224
1225 /**
1226  * drm_dp_read_desc - read sink/branch descriptor from DPCD
1227  * @aux: DisplayPort AUX channel
1228  * @desc: Device decriptor to fill from DPCD
1229  * @is_branch: true for branch devices, false for sink devices
1230  *
1231  * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
1232  * identification.
1233  *
1234  * Returns 0 on success or a negative error code on failure.
1235  */
1236 int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
1237                      bool is_branch)
1238 {
1239         struct drm_dp_dpcd_ident *ident = &desc->ident;
1240         unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
1241         int ret, dev_id_len;
1242
1243         ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
1244         if (ret < 0)
1245                 return ret;
1246
1247         desc->quirks = drm_dp_get_quirks(ident, is_branch);
1248
1249         dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
1250
1251         DRM_DEBUG_KMS("DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
1252                       is_branch ? "branch" : "sink",
1253                       (int)sizeof(ident->oui), ident->oui,
1254                       dev_id_len, ident->device_id,
1255                       ident->hw_rev >> 4, ident->hw_rev & 0xf,
1256                       ident->sw_major_rev, ident->sw_minor_rev,
1257                       desc->quirks);
1258
1259         return 0;
1260 }
1261 EXPORT_SYMBOL(drm_dp_read_desc);
1262
1263 /**
1264  * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
1265  * supported by the DSC sink.
1266  * @dsc_dpcd: DSC capabilities from DPCD
1267  * @is_edp: true if its eDP, false for DP
1268  *
1269  * Read the slice capabilities DPCD register from DSC sink to get
1270  * the maximum slice count supported. This is used to populate
1271  * the DSC parameters in the &struct drm_dsc_config by the driver.
1272  * Driver creates an infoframe using these parameters to populate
1273  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1274  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1275  *
1276  * Returns:
1277  * Maximum slice count supported by DSC sink or 0 its invalid
1278  */
1279 u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1280                                    bool is_edp)
1281 {
1282         u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
1283
1284         if (is_edp) {
1285                 /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
1286                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1287                         return 4;
1288                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1289                         return 2;
1290                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1291                         return 1;
1292         } else {
1293                 /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
1294                 u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
1295
1296                 if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
1297                         return 24;
1298                 if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
1299                         return 20;
1300                 if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
1301                         return 16;
1302                 if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
1303                         return 12;
1304                 if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
1305                         return 10;
1306                 if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
1307                         return 8;
1308                 if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
1309                         return 6;
1310                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1311                         return 4;
1312                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1313                         return 2;
1314                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1315                         return 1;
1316         }
1317
1318         return 0;
1319 }
1320 EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
1321
1322 /**
1323  * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
1324  * @dsc_dpcd: DSC capabilities from DPCD
1325  *
1326  * Read the DSC DPCD register to parse the line buffer depth in bits which is
1327  * number of bits of precision within the decoder line buffer supported by
1328  * the DSC sink. This is used to populate the DSC parameters in the
1329  * &struct drm_dsc_config by the driver.
1330  * Driver creates an infoframe using these parameters to populate
1331  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1332  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1333  *
1334  * Returns:
1335  * Line buffer depth supported by DSC panel or 0 its invalid
1336  */
1337 u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
1338 {
1339         u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
1340
1341         switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
1342         case DP_DSC_LINE_BUF_BIT_DEPTH_9:
1343                 return 9;
1344         case DP_DSC_LINE_BUF_BIT_DEPTH_10:
1345                 return 10;
1346         case DP_DSC_LINE_BUF_BIT_DEPTH_11:
1347                 return 11;
1348         case DP_DSC_LINE_BUF_BIT_DEPTH_12:
1349                 return 12;
1350         case DP_DSC_LINE_BUF_BIT_DEPTH_13:
1351                 return 13;
1352         case DP_DSC_LINE_BUF_BIT_DEPTH_14:
1353                 return 14;
1354         case DP_DSC_LINE_BUF_BIT_DEPTH_15:
1355                 return 15;
1356         case DP_DSC_LINE_BUF_BIT_DEPTH_16:
1357                 return 16;
1358         case DP_DSC_LINE_BUF_BIT_DEPTH_8:
1359                 return 8;
1360         }
1361
1362         return 0;
1363 }
1364 EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
1365
1366 /**
1367  * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
1368  * values supported by the DSC sink.
1369  * @dsc_dpcd: DSC capabilities from DPCD
1370  * @dsc_bpc: An array to be filled by this helper with supported
1371  *           input bpcs.
1372  *
1373  * Read the DSC DPCD from the sink device to parse the supported bits per
1374  * component values. This is used to populate the DSC parameters
1375  * in the &struct drm_dsc_config by the driver.
1376  * Driver creates an infoframe using these parameters to populate
1377  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1378  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1379  *
1380  * Returns:
1381  * Number of input BPC values parsed from the DPCD
1382  */
1383 int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1384                                          u8 dsc_bpc[3])
1385 {
1386         int num_bpc = 0;
1387         u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
1388
1389         if (color_depth & DP_DSC_12_BPC)
1390                 dsc_bpc[num_bpc++] = 12;
1391         if (color_depth & DP_DSC_10_BPC)
1392                 dsc_bpc[num_bpc++] = 10;
1393         if (color_depth & DP_DSC_8_BPC)
1394                 dsc_bpc[num_bpc++] = 8;
1395
1396         return num_bpc;
1397 }
1398 EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);