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