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