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