Merge tag 'for-linus-5.11-rc5-tag' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-block.git] / drivers / gpu / drm / drm_dp_helper.c
1 /*
2  * Copyright © 2009 Keith Packard
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/i2c.h>
26 #include <linux/init.h>
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/sched.h>
30 #include <linux/seq_file.h>
31
32 #include <drm/drm_dp_helper.h>
33 #include <drm/drm_print.h>
34 #include <drm/drm_vblank.h>
35 #include <drm/drm_dp_mst_helper.h>
36
37 #include "drm_crtc_helper_internal.h"
38
39 /**
40  * DOC: dp helpers
41  *
42  * These functions contain some common logic and helpers at various abstraction
43  * levels to deal with Display Port sink devices and related things like DP aux
44  * channel transfers, EDID reading over DP aux channels, decoding certain DPCD
45  * blocks, ...
46  */
47
48 /* Helpers for DP link training */
49 static u8 dp_link_status(const u8 link_status[DP_LINK_STATUS_SIZE], int r)
50 {
51         return link_status[r - DP_LANE0_1_STATUS];
52 }
53
54 static u8 dp_get_lane_status(const u8 link_status[DP_LINK_STATUS_SIZE],
55                              int lane)
56 {
57         int i = DP_LANE0_1_STATUS + (lane >> 1);
58         int s = (lane & 1) * 4;
59         u8 l = dp_link_status(link_status, i);
60
61         return (l >> s) & 0xf;
62 }
63
64 bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
65                           int lane_count)
66 {
67         u8 lane_align;
68         u8 lane_status;
69         int lane;
70
71         lane_align = dp_link_status(link_status,
72                                     DP_LANE_ALIGN_STATUS_UPDATED);
73         if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
74                 return false;
75         for (lane = 0; lane < lane_count; lane++) {
76                 lane_status = dp_get_lane_status(link_status, lane);
77                 if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
78                         return false;
79         }
80         return true;
81 }
82 EXPORT_SYMBOL(drm_dp_channel_eq_ok);
83
84 bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
85                               int lane_count)
86 {
87         int lane;
88         u8 lane_status;
89
90         for (lane = 0; lane < lane_count; lane++) {
91                 lane_status = dp_get_lane_status(link_status, lane);
92                 if ((lane_status & DP_LANE_CR_DONE) == 0)
93                         return false;
94         }
95         return true;
96 }
97 EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
98
99 u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
100                                      int lane)
101 {
102         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
103         int s = ((lane & 1) ?
104                  DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
105                  DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
106         u8 l = dp_link_status(link_status, i);
107
108         return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
109 }
110 EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
111
112 u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
113                                           int lane)
114 {
115         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
116         int s = ((lane & 1) ?
117                  DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
118                  DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
119         u8 l = dp_link_status(link_status, i);
120
121         return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
122 }
123 EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
124
125 u8 drm_dp_get_adjust_request_post_cursor(const u8 link_status[DP_LINK_STATUS_SIZE],
126                                          unsigned int lane)
127 {
128         unsigned int offset = DP_ADJUST_REQUEST_POST_CURSOR2;
129         u8 value = dp_link_status(link_status, offset);
130
131         return (value >> (lane << 1)) & 0x3;
132 }
133 EXPORT_SYMBOL(drm_dp_get_adjust_request_post_cursor);
134
135 void drm_dp_link_train_clock_recovery_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
136 {
137         unsigned long 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 %lu, out of range (max 4)\n",
142                               rd_interval);
143
144         if (rd_interval == 0 || dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
145                 rd_interval = 100;
146         else
147                 rd_interval *= 4 * USEC_PER_MSEC;
148
149         usleep_range(rd_interval, rd_interval * 2);
150 }
151 EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
152
153 static void __drm_dp_link_train_channel_eq_delay(unsigned long rd_interval)
154 {
155         if (rd_interval > 4)
156                 DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
157                               rd_interval);
158
159         if (rd_interval == 0)
160                 rd_interval = 400;
161         else
162                 rd_interval *= 4 * USEC_PER_MSEC;
163
164         usleep_range(rd_interval, rd_interval * 2);
165 }
166
167 void drm_dp_link_train_channel_eq_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
168 {
169         __drm_dp_link_train_channel_eq_delay(dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
170                                              DP_TRAINING_AUX_RD_MASK);
171 }
172 EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
173
174 void drm_dp_lttpr_link_train_clock_recovery_delay(void)
175 {
176         usleep_range(100, 200);
177 }
178 EXPORT_SYMBOL(drm_dp_lttpr_link_train_clock_recovery_delay);
179
180 static u8 dp_lttpr_phy_cap(const u8 phy_cap[DP_LTTPR_PHY_CAP_SIZE], int r)
181 {
182         return phy_cap[r - DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER1];
183 }
184
185 void drm_dp_lttpr_link_train_channel_eq_delay(const u8 phy_cap[DP_LTTPR_PHY_CAP_SIZE])
186 {
187         u8 interval = dp_lttpr_phy_cap(phy_cap,
188                                        DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER1) &
189                       DP_TRAINING_AUX_RD_MASK;
190
191         __drm_dp_link_train_channel_eq_delay(interval);
192 }
193 EXPORT_SYMBOL(drm_dp_lttpr_link_train_channel_eq_delay);
194
195 u8 drm_dp_link_rate_to_bw_code(int link_rate)
196 {
197         /* Spec says link_bw = link_rate / 0.27Gbps */
198         return link_rate / 27000;
199 }
200 EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
201
202 int drm_dp_bw_code_to_link_rate(u8 link_bw)
203 {
204         /* Spec says link_rate = link_bw * 0.27Gbps */
205         return link_bw * 27000;
206 }
207 EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
208
209 #define AUX_RETRY_INTERVAL 500 /* us */
210
211 static inline void
212 drm_dp_dump_access(const struct drm_dp_aux *aux,
213                    u8 request, uint offset, void *buffer, int ret)
214 {
215         const char *arrow = request == DP_AUX_NATIVE_READ ? "->" : "<-";
216
217         if (ret > 0)
218                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d) %*ph\n",
219                              aux->name, offset, arrow, ret, min(ret, 20), buffer);
220         else
221                 DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d)\n",
222                              aux->name, offset, arrow, ret);
223 }
224
225 /**
226  * DOC: dp helpers
227  *
228  * The DisplayPort AUX channel is an abstraction to allow generic, driver-
229  * independent access to AUX functionality. Drivers can take advantage of
230  * this by filling in the fields of the drm_dp_aux structure.
231  *
232  * Transactions are described using a hardware-independent drm_dp_aux_msg
233  * structure, which is passed into a driver's .transfer() implementation.
234  * Both native and I2C-over-AUX transactions are supported.
235  */
236
237 static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
238                               unsigned int offset, void *buffer, size_t size)
239 {
240         struct drm_dp_aux_msg msg;
241         unsigned int retry, native_reply;
242         int err = 0, ret = 0;
243
244         memset(&msg, 0, sizeof(msg));
245         msg.address = offset;
246         msg.request = request;
247         msg.buffer = buffer;
248         msg.size = size;
249
250         mutex_lock(&aux->hw_mutex);
251
252         /*
253          * The specification doesn't give any recommendation on how often to
254          * retry native transactions. We used to retry 7 times like for
255          * aux i2c transactions but real world devices this wasn't
256          * sufficient, bump to 32 which makes Dell 4k monitors happier.
257          */
258         for (retry = 0; retry < 32; retry++) {
259                 if (ret != 0 && ret != -ETIMEDOUT) {
260                         usleep_range(AUX_RETRY_INTERVAL,
261                                      AUX_RETRY_INTERVAL + 100);
262                 }
263
264                 ret = aux->transfer(aux, &msg);
265                 if (ret >= 0) {
266                         native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
267                         if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
268                                 if (ret == size)
269                                         goto unlock;
270
271                                 ret = -EPROTO;
272                         } else
273                                 ret = -EIO;
274                 }
275
276                 /*
277                  * We want the error we return to be the error we received on
278                  * the first transaction, since we may get a different error the
279                  * next time we retry
280                  */
281                 if (!err)
282                         err = ret;
283         }
284
285         DRM_DEBUG_KMS("%s: Too many retries, giving up. First error: %d\n",
286                       aux->name, err);
287         ret = err;
288
289 unlock:
290         mutex_unlock(&aux->hw_mutex);
291         return ret;
292 }
293
294 /**
295  * drm_dp_dpcd_read() - read a series of bytes from the DPCD
296  * @aux: DisplayPort AUX channel (SST or MST)
297  * @offset: address of the (first) register to read
298  * @buffer: buffer to store the register values
299  * @size: number of bytes in @buffer
300  *
301  * Returns the number of bytes transferred on success, or a negative error
302  * code on failure. -EIO is returned if the request was NAKed by the sink or
303  * if the retry count was exceeded. If not all bytes were transferred, this
304  * function returns -EPROTO. Errors from the underlying AUX channel transfer
305  * function, with the exception of -EBUSY (which causes the transaction to
306  * be retried), are propagated to the caller.
307  */
308 ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
309                          void *buffer, size_t size)
310 {
311         int ret;
312
313         /*
314          * HP ZR24w corrupts the first DPCD access after entering power save
315          * mode. Eg. on a read, the entire buffer will be filled with the same
316          * byte. Do a throw away read to avoid corrupting anything we care
317          * about. Afterwards things will work correctly until the monitor
318          * gets woken up and subsequently re-enters power save mode.
319          *
320          * The user pressing any button on the monitor is enough to wake it
321          * up, so there is no particularly good place to do the workaround.
322          * We just have to do it before any DPCD access and hope that the
323          * monitor doesn't power down exactly after the throw away read.
324          */
325         if (!aux->is_remote) {
326                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, DP_DPCD_REV,
327                                          buffer, 1);
328                 if (ret != 1)
329                         goto out;
330         }
331
332         if (aux->is_remote)
333                 ret = drm_dp_mst_dpcd_read(aux, offset, buffer, size);
334         else
335                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset,
336                                          buffer, size);
337
338 out:
339         drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, buffer, ret);
340         return ret;
341 }
342 EXPORT_SYMBOL(drm_dp_dpcd_read);
343
344 /**
345  * drm_dp_dpcd_write() - write a series of bytes to the DPCD
346  * @aux: DisplayPort AUX channel (SST or MST)
347  * @offset: address of the (first) register to write
348  * @buffer: buffer containing the values to write
349  * @size: number of bytes in @buffer
350  *
351  * Returns the number of bytes transferred on success, or a negative error
352  * code on failure. -EIO is returned if the request was NAKed by the sink or
353  * if the retry count was exceeded. If not all bytes were transferred, this
354  * function returns -EPROTO. Errors from the underlying AUX channel transfer
355  * function, with the exception of -EBUSY (which causes the transaction to
356  * be retried), are propagated to the caller.
357  */
358 ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
359                           void *buffer, size_t size)
360 {
361         int ret;
362
363         if (aux->is_remote)
364                 ret = drm_dp_mst_dpcd_write(aux, offset, buffer, size);
365         else
366                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset,
367                                          buffer, size);
368
369         drm_dp_dump_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer, ret);
370         return ret;
371 }
372 EXPORT_SYMBOL(drm_dp_dpcd_write);
373
374 /**
375  * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
376  * @aux: DisplayPort AUX channel
377  * @status: buffer to store the link status in (must be at least 6 bytes)
378  *
379  * Returns the number of bytes transferred on success or a negative error
380  * code on failure.
381  */
382 int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
383                                  u8 status[DP_LINK_STATUS_SIZE])
384 {
385         return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
386                                 DP_LINK_STATUS_SIZE);
387 }
388 EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
389
390 /**
391  * drm_dp_dpcd_read_phy_link_status - get the link status information for a DP PHY
392  * @aux: DisplayPort AUX channel
393  * @dp_phy: the DP PHY to get the link status for
394  * @link_status: buffer to return the status in
395  *
396  * Fetch the AUX DPCD registers for the DPRX or an LTTPR PHY link status. The
397  * layout of the returned @link_status matches the DPCD register layout of the
398  * DPRX PHY link status.
399  *
400  * Returns 0 if the information was read successfully or a negative error code
401  * on failure.
402  */
403 int drm_dp_dpcd_read_phy_link_status(struct drm_dp_aux *aux,
404                                      enum drm_dp_phy dp_phy,
405                                      u8 link_status[DP_LINK_STATUS_SIZE])
406 {
407         int ret;
408
409         if (dp_phy == DP_PHY_DPRX) {
410                 ret = drm_dp_dpcd_read(aux,
411                                        DP_LANE0_1_STATUS,
412                                        link_status,
413                                        DP_LINK_STATUS_SIZE);
414
415                 if (ret < 0)
416                         return ret;
417
418                 WARN_ON(ret != DP_LINK_STATUS_SIZE);
419
420                 return 0;
421         }
422
423         ret = drm_dp_dpcd_read(aux,
424                                DP_LANE0_1_STATUS_PHY_REPEATER(dp_phy),
425                                link_status,
426                                DP_LINK_STATUS_SIZE - 1);
427
428         if (ret < 0)
429                 return ret;
430
431         WARN_ON(ret != DP_LINK_STATUS_SIZE - 1);
432
433         /* Convert the LTTPR to the sink PHY link status layout */
434         memmove(&link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS + 1],
435                 &link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS],
436                 DP_LINK_STATUS_SIZE - (DP_SINK_STATUS - DP_LANE0_1_STATUS) - 1);
437         link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS] = 0;
438
439         return 0;
440 }
441 EXPORT_SYMBOL(drm_dp_dpcd_read_phy_link_status);
442
443 static bool is_edid_digital_input_dp(const struct edid *edid)
444 {
445         return edid && edid->revision >= 4 &&
446                 edid->input & DRM_EDID_INPUT_DIGITAL &&
447                 (edid->input & DRM_EDID_DIGITAL_TYPE_MASK) == DRM_EDID_DIGITAL_TYPE_DP;
448 }
449
450 /**
451  * drm_dp_downstream_is_type() - is the downstream facing port of certain type?
452  * @dpcd: DisplayPort configuration data
453  * @port_cap: port capabilities
454  * @type: port type to be checked. Can be:
455  *        %DP_DS_PORT_TYPE_DP, %DP_DS_PORT_TYPE_VGA, %DP_DS_PORT_TYPE_DVI,
456  *        %DP_DS_PORT_TYPE_HDMI, %DP_DS_PORT_TYPE_NON_EDID,
457  *        %DP_DS_PORT_TYPE_DP_DUALMODE or %DP_DS_PORT_TYPE_WIRELESS.
458  *
459  * Caveat: Only works with DPCD 1.1+ port caps.
460  *
461  * Returns: whether the downstream facing port matches the type.
462  */
463 bool drm_dp_downstream_is_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
464                                const u8 port_cap[4], u8 type)
465 {
466         return drm_dp_is_branch(dpcd) &&
467                 dpcd[DP_DPCD_REV] >= 0x11 &&
468                 (port_cap[0] & DP_DS_PORT_TYPE_MASK) == type;
469 }
470 EXPORT_SYMBOL(drm_dp_downstream_is_type);
471
472 /**
473  * drm_dp_downstream_is_tmds() - is the downstream facing port TMDS?
474  * @dpcd: DisplayPort configuration data
475  * @port_cap: port capabilities
476  * @edid: EDID
477  *
478  * Returns: whether the downstream facing port is TMDS (HDMI/DVI).
479  */
480 bool drm_dp_downstream_is_tmds(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
481                                const u8 port_cap[4],
482                                const struct edid *edid)
483 {
484         if (dpcd[DP_DPCD_REV] < 0x11) {
485                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
486                 case DP_DWN_STRM_PORT_TYPE_TMDS:
487                         return true;
488                 default:
489                         return false;
490                 }
491         }
492
493         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
494         case DP_DS_PORT_TYPE_DP_DUALMODE:
495                 if (is_edid_digital_input_dp(edid))
496                         return false;
497                 fallthrough;
498         case DP_DS_PORT_TYPE_DVI:
499         case DP_DS_PORT_TYPE_HDMI:
500                 return true;
501         default:
502                 return false;
503         }
504 }
505 EXPORT_SYMBOL(drm_dp_downstream_is_tmds);
506
507 /**
508  * drm_dp_send_real_edid_checksum() - send back real edid checksum value
509  * @aux: DisplayPort AUX channel
510  * @real_edid_checksum: real edid checksum for the last block
511  *
512  * Returns:
513  * True on success
514  */
515 bool drm_dp_send_real_edid_checksum(struct drm_dp_aux *aux,
516                                     u8 real_edid_checksum)
517 {
518         u8 link_edid_read = 0, auto_test_req = 0, test_resp = 0;
519
520         if (drm_dp_dpcd_read(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
521                              &auto_test_req, 1) < 1) {
522                 DRM_ERROR("%s: DPCD failed read at register 0x%x\n",
523                           aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
524                 return false;
525         }
526         auto_test_req &= DP_AUTOMATED_TEST_REQUEST;
527
528         if (drm_dp_dpcd_read(aux, DP_TEST_REQUEST, &link_edid_read, 1) < 1) {
529                 DRM_ERROR("%s: DPCD failed read at register 0x%x\n",
530                           aux->name, DP_TEST_REQUEST);
531                 return false;
532         }
533         link_edid_read &= DP_TEST_LINK_EDID_READ;
534
535         if (!auto_test_req || !link_edid_read) {
536                 DRM_DEBUG_KMS("%s: Source DUT does not support TEST_EDID_READ\n",
537                               aux->name);
538                 return false;
539         }
540
541         if (drm_dp_dpcd_write(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
542                               &auto_test_req, 1) < 1) {
543                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
544                           aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
545                 return false;
546         }
547
548         /* send back checksum for the last edid extension block data */
549         if (drm_dp_dpcd_write(aux, DP_TEST_EDID_CHECKSUM,
550                               &real_edid_checksum, 1) < 1) {
551                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
552                           aux->name, DP_TEST_EDID_CHECKSUM);
553                 return false;
554         }
555
556         test_resp |= DP_TEST_EDID_CHECKSUM_WRITE;
557         if (drm_dp_dpcd_write(aux, DP_TEST_RESPONSE, &test_resp, 1) < 1) {
558                 DRM_ERROR("%s: DPCD failed write at register 0x%x\n",
559                           aux->name, DP_TEST_RESPONSE);
560                 return false;
561         }
562
563         return true;
564 }
565 EXPORT_SYMBOL(drm_dp_send_real_edid_checksum);
566
567 static u8 drm_dp_downstream_port_count(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
568 {
569         u8 port_count = dpcd[DP_DOWN_STREAM_PORT_COUNT] & DP_PORT_COUNT_MASK;
570
571         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE && port_count > 4)
572                 port_count = 4;
573
574         return port_count;
575 }
576
577 static int drm_dp_read_extended_dpcd_caps(struct drm_dp_aux *aux,
578                                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
579 {
580         u8 dpcd_ext[6];
581         int ret;
582
583         /*
584          * Prior to DP1.3 the bit represented by
585          * DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT was reserved.
586          * If it is set DP_DPCD_REV at 0000h could be at a value less than
587          * the true capability of the panel. The only way to check is to
588          * then compare 0000h and 2200h.
589          */
590         if (!(dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
591               DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT))
592                 return 0;
593
594         ret = drm_dp_dpcd_read(aux, DP_DP13_DPCD_REV, &dpcd_ext,
595                                sizeof(dpcd_ext));
596         if (ret < 0)
597                 return ret;
598         if (ret != sizeof(dpcd_ext))
599                 return -EIO;
600
601         if (dpcd[DP_DPCD_REV] > dpcd_ext[DP_DPCD_REV]) {
602                 DRM_DEBUG_KMS("%s: Extended DPCD rev less than base DPCD rev (%d > %d)\n",
603                               aux->name, dpcd[DP_DPCD_REV],
604                               dpcd_ext[DP_DPCD_REV]);
605                 return 0;
606         }
607
608         if (!memcmp(dpcd, dpcd_ext, sizeof(dpcd_ext)))
609                 return 0;
610
611         DRM_DEBUG_KMS("%s: Base DPCD: %*ph\n",
612                       aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
613
614         memcpy(dpcd, dpcd_ext, sizeof(dpcd_ext));
615
616         return 0;
617 }
618
619 /**
620  * drm_dp_read_dpcd_caps() - read DPCD caps and extended DPCD caps if
621  * available
622  * @aux: DisplayPort AUX channel
623  * @dpcd: Buffer to store the resulting DPCD in
624  *
625  * Attempts to read the base DPCD caps for @aux. Additionally, this function
626  * checks for and reads the extended DPRX caps (%DP_DP13_DPCD_REV) if
627  * present.
628  *
629  * Returns: %0 if the DPCD was read successfully, negative error code
630  * otherwise.
631  */
632 int drm_dp_read_dpcd_caps(struct drm_dp_aux *aux,
633                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
634 {
635         int ret;
636
637         ret = drm_dp_dpcd_read(aux, DP_DPCD_REV, dpcd, DP_RECEIVER_CAP_SIZE);
638         if (ret < 0)
639                 return ret;
640         if (ret != DP_RECEIVER_CAP_SIZE || dpcd[DP_DPCD_REV] == 0)
641                 return -EIO;
642
643         ret = drm_dp_read_extended_dpcd_caps(aux, dpcd);
644         if (ret < 0)
645                 return ret;
646
647         DRM_DEBUG_KMS("%s: DPCD: %*ph\n",
648                       aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
649
650         return ret;
651 }
652 EXPORT_SYMBOL(drm_dp_read_dpcd_caps);
653
654 /**
655  * drm_dp_read_downstream_info() - read DPCD downstream port info if available
656  * @aux: DisplayPort AUX channel
657  * @dpcd: A cached copy of the port's DPCD
658  * @downstream_ports: buffer to store the downstream port info in
659  *
660  * See also:
661  * drm_dp_downstream_max_clock()
662  * drm_dp_downstream_max_bpc()
663  *
664  * Returns: 0 if either the downstream port info was read successfully or
665  * there was no downstream info to read, or a negative error code otherwise.
666  */
667 int drm_dp_read_downstream_info(struct drm_dp_aux *aux,
668                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
669                                 u8 downstream_ports[DP_MAX_DOWNSTREAM_PORTS])
670 {
671         int ret;
672         u8 len;
673
674         memset(downstream_ports, 0, DP_MAX_DOWNSTREAM_PORTS);
675
676         /* No downstream info to read */
677         if (!drm_dp_is_branch(dpcd) ||
678             dpcd[DP_DPCD_REV] < DP_DPCD_REV_10 ||
679             !(dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_PRESENT))
680                 return 0;
681
682         len = drm_dp_downstream_port_count(dpcd);
683         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE)
684                 len *= 4;
685
686         ret = drm_dp_dpcd_read(aux, DP_DOWNSTREAM_PORT_0, downstream_ports, len);
687         if (ret < 0)
688                 return ret;
689         if (ret != len)
690                 return -EIO;
691
692         DRM_DEBUG_KMS("%s: DPCD DFP: %*ph\n",
693                       aux->name, len, downstream_ports);
694
695         return 0;
696 }
697 EXPORT_SYMBOL(drm_dp_read_downstream_info);
698
699 /**
700  * drm_dp_downstream_max_dotclock() - extract downstream facing port max dot clock
701  * @dpcd: DisplayPort configuration data
702  * @port_cap: port capabilities
703  *
704  * Returns: Downstream facing port max dot clock in kHz on success,
705  * or 0 if max clock not defined
706  */
707 int drm_dp_downstream_max_dotclock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
708                                    const u8 port_cap[4])
709 {
710         if (!drm_dp_is_branch(dpcd))
711                 return 0;
712
713         if (dpcd[DP_DPCD_REV] < 0x11)
714                 return 0;
715
716         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
717         case DP_DS_PORT_TYPE_VGA:
718                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
719                         return 0;
720                 return port_cap[1] * 8000;
721         default:
722                 return 0;
723         }
724 }
725 EXPORT_SYMBOL(drm_dp_downstream_max_dotclock);
726
727 /**
728  * drm_dp_downstream_max_tmds_clock() - extract downstream facing port max TMDS clock
729  * @dpcd: DisplayPort configuration data
730  * @port_cap: port capabilities
731  * @edid: EDID
732  *
733  * Returns: HDMI/DVI downstream facing port max TMDS clock in kHz on success,
734  * or 0 if max TMDS clock not defined
735  */
736 int drm_dp_downstream_max_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
737                                      const u8 port_cap[4],
738                                      const struct edid *edid)
739 {
740         if (!drm_dp_is_branch(dpcd))
741                 return 0;
742
743         if (dpcd[DP_DPCD_REV] < 0x11) {
744                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
745                 case DP_DWN_STRM_PORT_TYPE_TMDS:
746                         return 165000;
747                 default:
748                         return 0;
749                 }
750         }
751
752         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
753         case DP_DS_PORT_TYPE_DP_DUALMODE:
754                 if (is_edid_digital_input_dp(edid))
755                         return 0;
756                 /*
757                  * It's left up to the driver to check the
758                  * DP dual mode adapter's max TMDS clock.
759                  *
760                  * Unfortunatley it looks like branch devices
761                  * may not fordward that the DP dual mode i2c
762                  * access so we just usually get i2c nak :(
763                  */
764                 fallthrough;
765         case DP_DS_PORT_TYPE_HDMI:
766                  /*
767                   * We should perhaps assume 165 MHz when detailed cap
768                   * info is not available. But looks like many typical
769                   * branch devices fall into that category and so we'd
770                   * probably end up with users complaining that they can't
771                   * get high resolution modes with their favorite dongle.
772                   *
773                   * So let's limit to 300 MHz instead since DPCD 1.4
774                   * HDMI 2.0 DFPs are required to have the detailed cap
775                   * info. So it's more likely we're dealing with a HDMI 1.4
776                   * compatible* device here.
777                   */
778                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
779                         return 300000;
780                 return port_cap[1] * 2500;
781         case DP_DS_PORT_TYPE_DVI:
782                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
783                         return 165000;
784                 /* FIXME what to do about DVI dual link? */
785                 return port_cap[1] * 2500;
786         default:
787                 return 0;
788         }
789 }
790 EXPORT_SYMBOL(drm_dp_downstream_max_tmds_clock);
791
792 /**
793  * drm_dp_downstream_min_tmds_clock() - extract downstream facing port min TMDS clock
794  * @dpcd: DisplayPort configuration data
795  * @port_cap: port capabilities
796  * @edid: EDID
797  *
798  * Returns: HDMI/DVI downstream facing port min TMDS clock in kHz on success,
799  * or 0 if max TMDS clock not defined
800  */
801 int drm_dp_downstream_min_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
802                                      const u8 port_cap[4],
803                                      const struct edid *edid)
804 {
805         if (!drm_dp_is_branch(dpcd))
806                 return 0;
807
808         if (dpcd[DP_DPCD_REV] < 0x11) {
809                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
810                 case DP_DWN_STRM_PORT_TYPE_TMDS:
811                         return 25000;
812                 default:
813                         return 0;
814                 }
815         }
816
817         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
818         case DP_DS_PORT_TYPE_DP_DUALMODE:
819                 if (is_edid_digital_input_dp(edid))
820                         return 0;
821                 fallthrough;
822         case DP_DS_PORT_TYPE_DVI:
823         case DP_DS_PORT_TYPE_HDMI:
824                 /*
825                  * Unclear whether the protocol converter could
826                  * utilize pixel replication. Assume it won't.
827                  */
828                 return 25000;
829         default:
830                 return 0;
831         }
832 }
833 EXPORT_SYMBOL(drm_dp_downstream_min_tmds_clock);
834
835 /**
836  * drm_dp_downstream_max_bpc() - extract downstream facing port max
837  *                               bits per component
838  * @dpcd: DisplayPort configuration data
839  * @port_cap: downstream facing port capabilities
840  * @edid: EDID
841  *
842  * Returns: Max bpc on success or 0 if max bpc not defined
843  */
844 int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
845                               const u8 port_cap[4],
846                               const struct edid *edid)
847 {
848         if (!drm_dp_is_branch(dpcd))
849                 return 0;
850
851         if (dpcd[DP_DPCD_REV] < 0x11) {
852                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
853                 case DP_DWN_STRM_PORT_TYPE_DP:
854                         return 0;
855                 default:
856                         return 8;
857                 }
858         }
859
860         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
861         case DP_DS_PORT_TYPE_DP:
862                 return 0;
863         case DP_DS_PORT_TYPE_DP_DUALMODE:
864                 if (is_edid_digital_input_dp(edid))
865                         return 0;
866                 fallthrough;
867         case DP_DS_PORT_TYPE_HDMI:
868         case DP_DS_PORT_TYPE_DVI:
869         case DP_DS_PORT_TYPE_VGA:
870                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
871                         return 8;
872
873                 switch (port_cap[2] & DP_DS_MAX_BPC_MASK) {
874                 case DP_DS_8BPC:
875                         return 8;
876                 case DP_DS_10BPC:
877                         return 10;
878                 case DP_DS_12BPC:
879                         return 12;
880                 case DP_DS_16BPC:
881                         return 16;
882                 default:
883                         return 8;
884                 }
885                 break;
886         default:
887                 return 8;
888         }
889 }
890 EXPORT_SYMBOL(drm_dp_downstream_max_bpc);
891
892 /**
893  * drm_dp_downstream_420_passthrough() - determine downstream facing port
894  *                                       YCbCr 4:2:0 pass-through capability
895  * @dpcd: DisplayPort configuration data
896  * @port_cap: downstream facing port capabilities
897  *
898  * Returns: whether the downstream facing port can pass through YCbCr 4:2:0
899  */
900 bool drm_dp_downstream_420_passthrough(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
901                                        const u8 port_cap[4])
902 {
903         if (!drm_dp_is_branch(dpcd))
904                 return false;
905
906         if (dpcd[DP_DPCD_REV] < 0x13)
907                 return false;
908
909         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
910         case DP_DS_PORT_TYPE_DP:
911                 return true;
912         case DP_DS_PORT_TYPE_HDMI:
913                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
914                         return false;
915
916                 return port_cap[3] & DP_DS_HDMI_YCBCR420_PASS_THROUGH;
917         default:
918                 return false;
919         }
920 }
921 EXPORT_SYMBOL(drm_dp_downstream_420_passthrough);
922
923 /**
924  * drm_dp_downstream_444_to_420_conversion() - determine downstream facing port
925  *                                             YCbCr 4:4:4->4:2:0 conversion capability
926  * @dpcd: DisplayPort configuration data
927  * @port_cap: downstream facing port capabilities
928  *
929  * Returns: whether the downstream facing port can convert YCbCr 4:4:4 to 4:2:0
930  */
931 bool drm_dp_downstream_444_to_420_conversion(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
932                                              const u8 port_cap[4])
933 {
934         if (!drm_dp_is_branch(dpcd))
935                 return false;
936
937         if (dpcd[DP_DPCD_REV] < 0x13)
938                 return false;
939
940         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
941         case DP_DS_PORT_TYPE_HDMI:
942                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
943                         return false;
944
945                 return port_cap[3] & DP_DS_HDMI_YCBCR444_TO_420_CONV;
946         default:
947                 return false;
948         }
949 }
950 EXPORT_SYMBOL(drm_dp_downstream_444_to_420_conversion);
951
952 /**
953  * drm_dp_downstream_mode() - return a mode for downstream facing port
954  * @dev: DRM device
955  * @dpcd: DisplayPort configuration data
956  * @port_cap: port capabilities
957  *
958  * Provides a suitable mode for downstream facing ports without EDID.
959  *
960  * Returns: A new drm_display_mode on success or NULL on failure
961  */
962 struct drm_display_mode *
963 drm_dp_downstream_mode(struct drm_device *dev,
964                        const u8 dpcd[DP_RECEIVER_CAP_SIZE],
965                        const u8 port_cap[4])
966
967 {
968         u8 vic;
969
970         if (!drm_dp_is_branch(dpcd))
971                 return NULL;
972
973         if (dpcd[DP_DPCD_REV] < 0x11)
974                 return NULL;
975
976         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
977         case DP_DS_PORT_TYPE_NON_EDID:
978                 switch (port_cap[0] & DP_DS_NON_EDID_MASK) {
979                 case DP_DS_NON_EDID_720x480i_60:
980                         vic = 6;
981                         break;
982                 case DP_DS_NON_EDID_720x480i_50:
983                         vic = 21;
984                         break;
985                 case DP_DS_NON_EDID_1920x1080i_60:
986                         vic = 5;
987                         break;
988                 case DP_DS_NON_EDID_1920x1080i_50:
989                         vic = 20;
990                         break;
991                 case DP_DS_NON_EDID_1280x720_60:
992                         vic = 4;
993                         break;
994                 case DP_DS_NON_EDID_1280x720_50:
995                         vic = 19;
996                         break;
997                 default:
998                         return NULL;
999                 }
1000                 return drm_display_mode_from_cea_vic(dev, vic);
1001         default:
1002                 return NULL;
1003         }
1004 }
1005 EXPORT_SYMBOL(drm_dp_downstream_mode);
1006
1007 /**
1008  * drm_dp_downstream_id() - identify branch device
1009  * @aux: DisplayPort AUX channel
1010  * @id: DisplayPort branch device id
1011  *
1012  * Returns branch device id on success or NULL on failure
1013  */
1014 int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
1015 {
1016         return drm_dp_dpcd_read(aux, DP_BRANCH_ID, id, 6);
1017 }
1018 EXPORT_SYMBOL(drm_dp_downstream_id);
1019
1020 /**
1021  * drm_dp_downstream_debug() - debug DP branch devices
1022  * @m: pointer for debugfs file
1023  * @dpcd: DisplayPort configuration data
1024  * @port_cap: port capabilities
1025  * @edid: EDID
1026  * @aux: DisplayPort AUX channel
1027  *
1028  */
1029 void drm_dp_downstream_debug(struct seq_file *m,
1030                              const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1031                              const u8 port_cap[4],
1032                              const struct edid *edid,
1033                              struct drm_dp_aux *aux)
1034 {
1035         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
1036                                  DP_DETAILED_CAP_INFO_AVAILABLE;
1037         int clk;
1038         int bpc;
1039         char id[7];
1040         int len;
1041         uint8_t rev[2];
1042         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
1043         bool branch_device = drm_dp_is_branch(dpcd);
1044
1045         seq_printf(m, "\tDP branch device present: %s\n",
1046                    branch_device ? "yes" : "no");
1047
1048         if (!branch_device)
1049                 return;
1050
1051         switch (type) {
1052         case DP_DS_PORT_TYPE_DP:
1053                 seq_puts(m, "\t\tType: DisplayPort\n");
1054                 break;
1055         case DP_DS_PORT_TYPE_VGA:
1056                 seq_puts(m, "\t\tType: VGA\n");
1057                 break;
1058         case DP_DS_PORT_TYPE_DVI:
1059                 seq_puts(m, "\t\tType: DVI\n");
1060                 break;
1061         case DP_DS_PORT_TYPE_HDMI:
1062                 seq_puts(m, "\t\tType: HDMI\n");
1063                 break;
1064         case DP_DS_PORT_TYPE_NON_EDID:
1065                 seq_puts(m, "\t\tType: others without EDID support\n");
1066                 break;
1067         case DP_DS_PORT_TYPE_DP_DUALMODE:
1068                 seq_puts(m, "\t\tType: DP++\n");
1069                 break;
1070         case DP_DS_PORT_TYPE_WIRELESS:
1071                 seq_puts(m, "\t\tType: Wireless\n");
1072                 break;
1073         default:
1074                 seq_puts(m, "\t\tType: N/A\n");
1075         }
1076
1077         memset(id, 0, sizeof(id));
1078         drm_dp_downstream_id(aux, id);
1079         seq_printf(m, "\t\tID: %s\n", id);
1080
1081         len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
1082         if (len > 0)
1083                 seq_printf(m, "\t\tHW: %d.%d\n",
1084                            (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
1085
1086         len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
1087         if (len > 0)
1088                 seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
1089
1090         if (detailed_cap_info) {
1091                 clk = drm_dp_downstream_max_dotclock(dpcd, port_cap);
1092                 if (clk > 0)
1093                         seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
1094
1095                 clk = drm_dp_downstream_max_tmds_clock(dpcd, port_cap, edid);
1096                 if (clk > 0)
1097                         seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
1098
1099                 clk = drm_dp_downstream_min_tmds_clock(dpcd, port_cap, edid);
1100                 if (clk > 0)
1101                         seq_printf(m, "\t\tMin TMDS clock: %d kHz\n", clk);
1102
1103                 bpc = drm_dp_downstream_max_bpc(dpcd, port_cap, edid);
1104
1105                 if (bpc > 0)
1106                         seq_printf(m, "\t\tMax bpc: %d\n", bpc);
1107         }
1108 }
1109 EXPORT_SYMBOL(drm_dp_downstream_debug);
1110
1111 /**
1112  * drm_dp_subconnector_type() - get DP branch device type
1113  * @dpcd: DisplayPort configuration data
1114  * @port_cap: port capabilities
1115  */
1116 enum drm_mode_subconnector
1117 drm_dp_subconnector_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1118                          const u8 port_cap[4])
1119 {
1120         int type;
1121         if (!drm_dp_is_branch(dpcd))
1122                 return DRM_MODE_SUBCONNECTOR_Native;
1123         /* DP 1.0 approach */
1124         if (dpcd[DP_DPCD_REV] == DP_DPCD_REV_10) {
1125                 type = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
1126                        DP_DWN_STRM_PORT_TYPE_MASK;
1127
1128                 switch (type) {
1129                 case DP_DWN_STRM_PORT_TYPE_TMDS:
1130                         /* Can be HDMI or DVI-D, DVI-D is a safer option */
1131                         return DRM_MODE_SUBCONNECTOR_DVID;
1132                 case DP_DWN_STRM_PORT_TYPE_ANALOG:
1133                         /* Can be VGA or DVI-A, VGA is more popular */
1134                         return DRM_MODE_SUBCONNECTOR_VGA;
1135                 case DP_DWN_STRM_PORT_TYPE_DP:
1136                         return DRM_MODE_SUBCONNECTOR_DisplayPort;
1137                 case DP_DWN_STRM_PORT_TYPE_OTHER:
1138                 default:
1139                         return DRM_MODE_SUBCONNECTOR_Unknown;
1140                 }
1141         }
1142         type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
1143
1144         switch (type) {
1145         case DP_DS_PORT_TYPE_DP:
1146         case DP_DS_PORT_TYPE_DP_DUALMODE:
1147                 return DRM_MODE_SUBCONNECTOR_DisplayPort;
1148         case DP_DS_PORT_TYPE_VGA:
1149                 return DRM_MODE_SUBCONNECTOR_VGA;
1150         case DP_DS_PORT_TYPE_DVI:
1151                 return DRM_MODE_SUBCONNECTOR_DVID;
1152         case DP_DS_PORT_TYPE_HDMI:
1153                 return DRM_MODE_SUBCONNECTOR_HDMIA;
1154         case DP_DS_PORT_TYPE_WIRELESS:
1155                 return DRM_MODE_SUBCONNECTOR_Wireless;
1156         case DP_DS_PORT_TYPE_NON_EDID:
1157         default:
1158                 return DRM_MODE_SUBCONNECTOR_Unknown;
1159         }
1160 }
1161 EXPORT_SYMBOL(drm_dp_subconnector_type);
1162
1163 /**
1164  * drm_dp_set_subconnector_property - set subconnector for DP connector
1165  * @connector: connector to set property on
1166  * @status: connector status
1167  * @dpcd: DisplayPort configuration data
1168  * @port_cap: port capabilities
1169  *
1170  * Called by a driver on every detect event.
1171  */
1172 void drm_dp_set_subconnector_property(struct drm_connector *connector,
1173                                       enum drm_connector_status status,
1174                                       const u8 *dpcd,
1175                                       const u8 port_cap[4])
1176 {
1177         enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
1178
1179         if (status == connector_status_connected)
1180                 subconnector = drm_dp_subconnector_type(dpcd, port_cap);
1181         drm_object_property_set_value(&connector->base,
1182                         connector->dev->mode_config.dp_subconnector_property,
1183                         subconnector);
1184 }
1185 EXPORT_SYMBOL(drm_dp_set_subconnector_property);
1186
1187 /**
1188  * drm_dp_read_sink_count_cap() - Check whether a given connector has a valid sink
1189  * count
1190  * @connector: The DRM connector to check
1191  * @dpcd: A cached copy of the connector's DPCD RX capabilities
1192  * @desc: A cached copy of the connector's DP descriptor
1193  *
1194  * See also: drm_dp_read_sink_count()
1195  *
1196  * Returns: %True if the (e)DP connector has a valid sink count that should
1197  * be probed, %false otherwise.
1198  */
1199 bool drm_dp_read_sink_count_cap(struct drm_connector *connector,
1200                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1201                                 const struct drm_dp_desc *desc)
1202 {
1203         /* Some eDP panels don't set a valid value for the sink count */
1204         return connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
1205                 dpcd[DP_DPCD_REV] >= DP_DPCD_REV_11 &&
1206                 dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_PRESENT &&
1207                 !drm_dp_has_quirk(desc, 0, DP_DPCD_QUIRK_NO_SINK_COUNT);
1208 }
1209 EXPORT_SYMBOL(drm_dp_read_sink_count_cap);
1210
1211 /**
1212  * drm_dp_read_sink_count() - Retrieve the sink count for a given sink
1213  * @aux: The DP AUX channel to use
1214  *
1215  * See also: drm_dp_read_sink_count_cap()
1216  *
1217  * Returns: The current sink count reported by @aux, or a negative error code
1218  * otherwise.
1219  */
1220 int drm_dp_read_sink_count(struct drm_dp_aux *aux)
1221 {
1222         u8 count;
1223         int ret;
1224
1225         ret = drm_dp_dpcd_readb(aux, DP_SINK_COUNT, &count);
1226         if (ret < 0)
1227                 return ret;
1228         if (ret != 1)
1229                 return -EIO;
1230
1231         return DP_GET_SINK_COUNT(count);
1232 }
1233 EXPORT_SYMBOL(drm_dp_read_sink_count);
1234
1235 /*
1236  * I2C-over-AUX implementation
1237  */
1238
1239 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
1240 {
1241         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
1242                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
1243                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
1244                I2C_FUNC_10BIT_ADDR;
1245 }
1246
1247 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
1248 {
1249         /*
1250          * In case of i2c defer or short i2c ack reply to a write,
1251          * we need to switch to WRITE_STATUS_UPDATE to drain the
1252          * rest of the message
1253          */
1254         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
1255                 msg->request &= DP_AUX_I2C_MOT;
1256                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
1257         }
1258 }
1259
1260 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
1261 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
1262 #define AUX_STOP_LEN 4
1263 #define AUX_CMD_LEN 4
1264 #define AUX_ADDRESS_LEN 20
1265 #define AUX_REPLY_PAD_LEN 4
1266 #define AUX_LENGTH_LEN 8
1267
1268 /*
1269  * Calculate the duration of the AUX request/reply in usec. Gives the
1270  * "best" case estimate, ie. successful while as short as possible.
1271  */
1272 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
1273 {
1274         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
1275                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
1276
1277         if ((msg->request & DP_AUX_I2C_READ) == 0)
1278                 len += msg->size * 8;
1279
1280         return len;
1281 }
1282
1283 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
1284 {
1285         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
1286                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
1287
1288         /*
1289          * For read we expect what was asked. For writes there will
1290          * be 0 or 1 data bytes. Assume 0 for the "best" case.
1291          */
1292         if (msg->request & DP_AUX_I2C_READ)
1293                 len += msg->size * 8;
1294
1295         return len;
1296 }
1297
1298 #define I2C_START_LEN 1
1299 #define I2C_STOP_LEN 1
1300 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
1301 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
1302
1303 /*
1304  * Calculate the length of the i2c transfer in usec, assuming
1305  * the i2c bus speed is as specified. Gives the the "worst"
1306  * case estimate, ie. successful while as long as possible.
1307  * Doesn't account the the "MOT" bit, and instead assumes each
1308  * message includes a START, ADDRESS and STOP. Neither does it
1309  * account for additional random variables such as clock stretching.
1310  */
1311 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
1312                                    int i2c_speed_khz)
1313 {
1314         /* AUX bitrate is 1MHz, i2c bitrate as specified */
1315         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
1316                              msg->size * I2C_DATA_LEN +
1317                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
1318 }
1319
1320 /*
1321  * Deterine how many retries should be attempted to successfully transfer
1322  * the specified message, based on the estimated durations of the
1323  * i2c and AUX transfers.
1324  */
1325 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
1326                               int i2c_speed_khz)
1327 {
1328         int aux_time_us = drm_dp_aux_req_duration(msg) +
1329                 drm_dp_aux_reply_duration(msg);
1330         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
1331
1332         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
1333 }
1334
1335 /*
1336  * FIXME currently assumes 10 kHz as some real world devices seem
1337  * to require it. We should query/set the speed via DPCD if supported.
1338  */
1339 static int dp_aux_i2c_speed_khz __read_mostly = 10;
1340 module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
1341 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
1342                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
1343
1344 /*
1345  * Transfer a single I2C-over-AUX message and handle various error conditions,
1346  * retrying the transaction as appropriate.  It is assumed that the
1347  * &drm_dp_aux.transfer function does not modify anything in the msg other than the
1348  * reply field.
1349  *
1350  * Returns bytes transferred on success, or a negative error code on failure.
1351  */
1352 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
1353 {
1354         unsigned int retry, defer_i2c;
1355         int ret;
1356         /*
1357          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
1358          * is required to retry at least seven times upon receiving AUX_DEFER
1359          * before giving up the AUX transaction.
1360          *
1361          * We also try to account for the i2c bus speed.
1362          */
1363         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
1364
1365         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
1366                 ret = aux->transfer(aux, msg);
1367                 if (ret < 0) {
1368                         if (ret == -EBUSY)
1369                                 continue;
1370
1371                         /*
1372                          * While timeouts can be errors, they're usually normal
1373                          * behavior (for instance, when a driver tries to
1374                          * communicate with a non-existant DisplayPort device).
1375                          * Avoid spamming the kernel log with timeout errors.
1376                          */
1377                         if (ret == -ETIMEDOUT)
1378                                 DRM_DEBUG_KMS_RATELIMITED("%s: transaction timed out\n",
1379                                                           aux->name);
1380                         else
1381                                 DRM_DEBUG_KMS("%s: transaction failed: %d\n",
1382                                               aux->name, ret);
1383                         return ret;
1384                 }
1385
1386
1387                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
1388                 case DP_AUX_NATIVE_REPLY_ACK:
1389                         /*
1390                          * For I2C-over-AUX transactions this isn't enough, we
1391                          * need to check for the I2C ACK reply.
1392                          */
1393                         break;
1394
1395                 case DP_AUX_NATIVE_REPLY_NACK:
1396                         DRM_DEBUG_KMS("%s: native nack (result=%d, size=%zu)\n",
1397                                       aux->name, ret, msg->size);
1398                         return -EREMOTEIO;
1399
1400                 case DP_AUX_NATIVE_REPLY_DEFER:
1401                         DRM_DEBUG_KMS("%s: native defer\n", aux->name);
1402                         /*
1403                          * We could check for I2C bit rate capabilities and if
1404                          * available adjust this interval. We could also be
1405                          * more careful with DP-to-legacy adapters where a
1406                          * long legacy cable may force very low I2C bit rates.
1407                          *
1408                          * For now just defer for long enough to hopefully be
1409                          * safe for all use-cases.
1410                          */
1411                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1412                         continue;
1413
1414                 default:
1415                         DRM_ERROR("%s: invalid native reply %#04x\n",
1416                                   aux->name, msg->reply);
1417                         return -EREMOTEIO;
1418                 }
1419
1420                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
1421                 case DP_AUX_I2C_REPLY_ACK:
1422                         /*
1423                          * Both native ACK and I2C ACK replies received. We
1424                          * can assume the transfer was successful.
1425                          */
1426                         if (ret != msg->size)
1427                                 drm_dp_i2c_msg_write_status_update(msg);
1428                         return ret;
1429
1430                 case DP_AUX_I2C_REPLY_NACK:
1431                         DRM_DEBUG_KMS("%s: I2C nack (result=%d, size=%zu)\n",
1432                                       aux->name, ret, msg->size);
1433                         aux->i2c_nack_count++;
1434                         return -EREMOTEIO;
1435
1436                 case DP_AUX_I2C_REPLY_DEFER:
1437                         DRM_DEBUG_KMS("%s: I2C defer\n", aux->name);
1438                         /* DP Compliance Test 4.2.2.5 Requirement:
1439                          * Must have at least 7 retries for I2C defers on the
1440                          * transaction to pass this test
1441                          */
1442                         aux->i2c_defer_count++;
1443                         if (defer_i2c < 7)
1444                                 defer_i2c++;
1445                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1446                         drm_dp_i2c_msg_write_status_update(msg);
1447
1448                         continue;
1449
1450                 default:
1451                         DRM_ERROR("%s: invalid I2C reply %#04x\n",
1452                                   aux->name, msg->reply);
1453                         return -EREMOTEIO;
1454                 }
1455         }
1456
1457         DRM_DEBUG_KMS("%s: Too many retries, giving up\n", aux->name);
1458         return -EREMOTEIO;
1459 }
1460
1461 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
1462                                        const struct i2c_msg *i2c_msg)
1463 {
1464         msg->request = (i2c_msg->flags & I2C_M_RD) ?
1465                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
1466         if (!(i2c_msg->flags & I2C_M_STOP))
1467                 msg->request |= DP_AUX_I2C_MOT;
1468 }
1469
1470 /*
1471  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
1472  *
1473  * Returns an error code on failure, or a recommended transfer size on success.
1474  */
1475 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
1476 {
1477         int err, ret = orig_msg->size;
1478         struct drm_dp_aux_msg msg = *orig_msg;
1479
1480         while (msg.size > 0) {
1481                 err = drm_dp_i2c_do_msg(aux, &msg);
1482                 if (err <= 0)
1483                         return err == 0 ? -EPROTO : err;
1484
1485                 if (err < msg.size && err < ret) {
1486                         DRM_DEBUG_KMS("%s: Partial I2C reply: requested %zu bytes got %d bytes\n",
1487                                       aux->name, msg.size, err);
1488                         ret = err;
1489                 }
1490
1491                 msg.size -= err;
1492                 msg.buffer += err;
1493         }
1494
1495         return ret;
1496 }
1497
1498 /*
1499  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
1500  * packets to be as large as possible. If not, the I2C transactions never
1501  * succeed. Hence the default is maximum.
1502  */
1503 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
1504 module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
1505 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
1506                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
1507
1508 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
1509                            int num)
1510 {
1511         struct drm_dp_aux *aux = adapter->algo_data;
1512         unsigned int i, j;
1513         unsigned transfer_size;
1514         struct drm_dp_aux_msg msg;
1515         int err = 0;
1516
1517         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
1518
1519         memset(&msg, 0, sizeof(msg));
1520
1521         for (i = 0; i < num; i++) {
1522                 msg.address = msgs[i].addr;
1523                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1524                 /* Send a bare address packet to start the transaction.
1525                  * Zero sized messages specify an address only (bare
1526                  * address) transaction.
1527                  */
1528                 msg.buffer = NULL;
1529                 msg.size = 0;
1530                 err = drm_dp_i2c_do_msg(aux, &msg);
1531
1532                 /*
1533                  * Reset msg.request in case in case it got
1534                  * changed into a WRITE_STATUS_UPDATE.
1535                  */
1536                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1537
1538                 if (err < 0)
1539                         break;
1540                 /* We want each transaction to be as large as possible, but
1541                  * we'll go to smaller sizes if the hardware gives us a
1542                  * short reply.
1543                  */
1544                 transfer_size = dp_aux_i2c_transfer_size;
1545                 for (j = 0; j < msgs[i].len; j += msg.size) {
1546                         msg.buffer = msgs[i].buf + j;
1547                         msg.size = min(transfer_size, msgs[i].len - j);
1548
1549                         err = drm_dp_i2c_drain_msg(aux, &msg);
1550
1551                         /*
1552                          * Reset msg.request in case in case it got
1553                          * changed into a WRITE_STATUS_UPDATE.
1554                          */
1555                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1556
1557                         if (err < 0)
1558                                 break;
1559                         transfer_size = err;
1560                 }
1561                 if (err < 0)
1562                         break;
1563         }
1564         if (err >= 0)
1565                 err = num;
1566         /* Send a bare address packet to close out the transaction.
1567          * Zero sized messages specify an address only (bare
1568          * address) transaction.
1569          */
1570         msg.request &= ~DP_AUX_I2C_MOT;
1571         msg.buffer = NULL;
1572         msg.size = 0;
1573         (void)drm_dp_i2c_do_msg(aux, &msg);
1574
1575         return err;
1576 }
1577
1578 static const struct i2c_algorithm drm_dp_i2c_algo = {
1579         .functionality = drm_dp_i2c_functionality,
1580         .master_xfer = drm_dp_i2c_xfer,
1581 };
1582
1583 static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
1584 {
1585         return container_of(i2c, struct drm_dp_aux, ddc);
1586 }
1587
1588 static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
1589 {
1590         mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
1591 }
1592
1593 static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
1594 {
1595         return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
1596 }
1597
1598 static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
1599 {
1600         mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
1601 }
1602
1603 static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
1604         .lock_bus = lock_bus,
1605         .trylock_bus = trylock_bus,
1606         .unlock_bus = unlock_bus,
1607 };
1608
1609 static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
1610 {
1611         u8 buf, count;
1612         int ret;
1613
1614         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1615         if (ret < 0)
1616                 return ret;
1617
1618         WARN_ON(!(buf & DP_TEST_SINK_START));
1619
1620         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
1621         if (ret < 0)
1622                 return ret;
1623
1624         count = buf & DP_TEST_COUNT_MASK;
1625         if (count == aux->crc_count)
1626                 return -EAGAIN; /* No CRC yet */
1627
1628         aux->crc_count = count;
1629
1630         /*
1631          * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
1632          * per component (RGB or CrYCb).
1633          */
1634         ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
1635         if (ret < 0)
1636                 return ret;
1637
1638         return 0;
1639 }
1640
1641 static void drm_dp_aux_crc_work(struct work_struct *work)
1642 {
1643         struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
1644                                               crc_work);
1645         struct drm_crtc *crtc;
1646         u8 crc_bytes[6];
1647         uint32_t crcs[3];
1648         int ret;
1649
1650         if (WARN_ON(!aux->crtc))
1651                 return;
1652
1653         crtc = aux->crtc;
1654         while (crtc->crc.opened) {
1655                 drm_crtc_wait_one_vblank(crtc);
1656                 if (!crtc->crc.opened)
1657                         break;
1658
1659                 ret = drm_dp_aux_get_crc(aux, crc_bytes);
1660                 if (ret == -EAGAIN) {
1661                         usleep_range(1000, 2000);
1662                         ret = drm_dp_aux_get_crc(aux, crc_bytes);
1663                 }
1664
1665                 if (ret == -EAGAIN) {
1666                         DRM_DEBUG_KMS("%s: Get CRC failed after retrying: %d\n",
1667                                       aux->name, ret);
1668                         continue;
1669                 } else if (ret) {
1670                         DRM_DEBUG_KMS("%s: Failed to get a CRC: %d\n",
1671                                       aux->name, ret);
1672                         continue;
1673                 }
1674
1675                 crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
1676                 crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
1677                 crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
1678                 drm_crtc_add_crc_entry(crtc, false, 0, crcs);
1679         }
1680 }
1681
1682 /**
1683  * drm_dp_remote_aux_init() - minimally initialise a remote aux channel
1684  * @aux: DisplayPort AUX channel
1685  *
1686  * Used for remote aux channel in general. Merely initialize the crc work
1687  * struct.
1688  */
1689 void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
1690 {
1691         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1692 }
1693 EXPORT_SYMBOL(drm_dp_remote_aux_init);
1694
1695 /**
1696  * drm_dp_aux_init() - minimally initialise an aux channel
1697  * @aux: DisplayPort AUX channel
1698  *
1699  * If you need to use the drm_dp_aux's i2c adapter prior to registering it
1700  * with the outside world, call drm_dp_aux_init() first. You must still
1701  * call drm_dp_aux_register() once the connector has been registered to
1702  * allow userspace access to the auxiliary DP channel.
1703  */
1704 void drm_dp_aux_init(struct drm_dp_aux *aux)
1705 {
1706         mutex_init(&aux->hw_mutex);
1707         mutex_init(&aux->cec.lock);
1708         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1709
1710         aux->ddc.algo = &drm_dp_i2c_algo;
1711         aux->ddc.algo_data = aux;
1712         aux->ddc.retries = 3;
1713
1714         aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
1715 }
1716 EXPORT_SYMBOL(drm_dp_aux_init);
1717
1718 /**
1719  * drm_dp_aux_register() - initialise and register aux channel
1720  * @aux: DisplayPort AUX channel
1721  *
1722  * Automatically calls drm_dp_aux_init() if this hasn't been done yet.
1723  * This should only be called when the underlying &struct drm_connector is
1724  * initialiazed already. Therefore the best place to call this is from
1725  * &drm_connector_funcs.late_register. Not that drivers which don't follow this
1726  * will Oops when CONFIG_DRM_DP_AUX_CHARDEV is enabled.
1727  *
1728  * Drivers which need to use the aux channel before that point (e.g. at driver
1729  * load time, before drm_dev_register() has been called) need to call
1730  * drm_dp_aux_init().
1731  *
1732  * Returns 0 on success or a negative error code on failure.
1733  */
1734 int drm_dp_aux_register(struct drm_dp_aux *aux)
1735 {
1736         int ret;
1737
1738         if (!aux->ddc.algo)
1739                 drm_dp_aux_init(aux);
1740
1741         aux->ddc.class = I2C_CLASS_DDC;
1742         aux->ddc.owner = THIS_MODULE;
1743         aux->ddc.dev.parent = aux->dev;
1744
1745         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
1746                 sizeof(aux->ddc.name));
1747
1748         ret = drm_dp_aux_register_devnode(aux);
1749         if (ret)
1750                 return ret;
1751
1752         ret = i2c_add_adapter(&aux->ddc);
1753         if (ret) {
1754                 drm_dp_aux_unregister_devnode(aux);
1755                 return ret;
1756         }
1757
1758         return 0;
1759 }
1760 EXPORT_SYMBOL(drm_dp_aux_register);
1761
1762 /**
1763  * drm_dp_aux_unregister() - unregister an AUX adapter
1764  * @aux: DisplayPort AUX channel
1765  */
1766 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
1767 {
1768         drm_dp_aux_unregister_devnode(aux);
1769         i2c_del_adapter(&aux->ddc);
1770 }
1771 EXPORT_SYMBOL(drm_dp_aux_unregister);
1772
1773 #define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
1774
1775 /**
1776  * drm_dp_psr_setup_time() - PSR setup in time usec
1777  * @psr_cap: PSR capabilities from DPCD
1778  *
1779  * Returns:
1780  * PSR setup time for the panel in microseconds,  negative
1781  * error code on failure.
1782  */
1783 int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
1784 {
1785         static const u16 psr_setup_time_us[] = {
1786                 PSR_SETUP_TIME(330),
1787                 PSR_SETUP_TIME(275),
1788                 PSR_SETUP_TIME(220),
1789                 PSR_SETUP_TIME(165),
1790                 PSR_SETUP_TIME(110),
1791                 PSR_SETUP_TIME(55),
1792                 PSR_SETUP_TIME(0),
1793         };
1794         int i;
1795
1796         i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
1797         if (i >= ARRAY_SIZE(psr_setup_time_us))
1798                 return -EINVAL;
1799
1800         return psr_setup_time_us[i];
1801 }
1802 EXPORT_SYMBOL(drm_dp_psr_setup_time);
1803
1804 #undef PSR_SETUP_TIME
1805
1806 /**
1807  * drm_dp_start_crc() - start capture of frame CRCs
1808  * @aux: DisplayPort AUX channel
1809  * @crtc: CRTC displaying the frames whose CRCs are to be captured
1810  *
1811  * Returns 0 on success or a negative error code on failure.
1812  */
1813 int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
1814 {
1815         u8 buf;
1816         int ret;
1817
1818         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1819         if (ret < 0)
1820                 return ret;
1821
1822         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
1823         if (ret < 0)
1824                 return ret;
1825
1826         aux->crc_count = 0;
1827         aux->crtc = crtc;
1828         schedule_work(&aux->crc_work);
1829
1830         return 0;
1831 }
1832 EXPORT_SYMBOL(drm_dp_start_crc);
1833
1834 /**
1835  * drm_dp_stop_crc() - stop capture of frame CRCs
1836  * @aux: DisplayPort AUX channel
1837  *
1838  * Returns 0 on success or a negative error code on failure.
1839  */
1840 int drm_dp_stop_crc(struct drm_dp_aux *aux)
1841 {
1842         u8 buf;
1843         int ret;
1844
1845         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1846         if (ret < 0)
1847                 return ret;
1848
1849         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
1850         if (ret < 0)
1851                 return ret;
1852
1853         flush_work(&aux->crc_work);
1854         aux->crtc = NULL;
1855
1856         return 0;
1857 }
1858 EXPORT_SYMBOL(drm_dp_stop_crc);
1859
1860 struct dpcd_quirk {
1861         u8 oui[3];
1862         u8 device_id[6];
1863         bool is_branch;
1864         u32 quirks;
1865 };
1866
1867 #define OUI(first, second, third) { (first), (second), (third) }
1868 #define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
1869         { (first), (second), (third), (fourth), (fifth), (sixth) }
1870
1871 #define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
1872
1873 static const struct dpcd_quirk dpcd_quirk_list[] = {
1874         /* Analogix 7737 needs reduced M and N at HBR2 link rates */
1875         { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1876         /* LG LP140WF6-SPM1 eDP panel */
1877         { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1878         /* Apple panels need some additional handling to support PSR */
1879         { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
1880         /* CH7511 seems to leave SINK_COUNT zeroed */
1881         { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
1882         /* Synaptics DP1.4 MST hubs can support DSC without virtual DPCD */
1883         { OUI(0x90, 0xCC, 0x24), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) },
1884         /* Apple MacBookPro 2017 15 inch eDP Retina panel reports too low DP_MAX_LINK_RATE */
1885         { OUI(0x00, 0x10, 0xfa), DEVICE_ID(101, 68, 21, 101, 98, 97), false, BIT(DP_DPCD_QUIRK_CAN_DO_MAX_LINK_RATE_3_24_GBPS) },
1886 };
1887
1888 #undef OUI
1889
1890 /*
1891  * Get a bit mask of DPCD quirks for the sink/branch device identified by
1892  * ident. The quirk data is shared but it's up to the drivers to act on the
1893  * data.
1894  *
1895  * For now, only the OUI (first three bytes) is used, but this may be extended
1896  * to device identification string and hardware/firmware revisions later.
1897  */
1898 static u32
1899 drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
1900 {
1901         const struct dpcd_quirk *quirk;
1902         u32 quirks = 0;
1903         int i;
1904         u8 any_device[] = DEVICE_ID_ANY;
1905
1906         for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
1907                 quirk = &dpcd_quirk_list[i];
1908
1909                 if (quirk->is_branch != is_branch)
1910                         continue;
1911
1912                 if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
1913                         continue;
1914
1915                 if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
1916                     memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
1917                         continue;
1918
1919                 quirks |= quirk->quirks;
1920         }
1921
1922         return quirks;
1923 }
1924
1925 #undef DEVICE_ID_ANY
1926 #undef DEVICE_ID
1927
1928 struct edid_quirk {
1929         u8 mfg_id[2];
1930         u8 prod_id[2];
1931         u32 quirks;
1932 };
1933
1934 #define MFG(first, second) { (first), (second) }
1935 #define PROD_ID(first, second) { (first), (second) }
1936
1937 /*
1938  * Some devices have unreliable OUIDs where they don't set the device ID
1939  * correctly, and as a result we need to use the EDID for finding additional
1940  * DP quirks in such cases.
1941  */
1942 static const struct edid_quirk edid_quirk_list[] = {
1943         /* Optional 4K AMOLED panel in the ThinkPad X1 Extreme 2nd Generation
1944          * only supports DPCD backlight controls
1945          */
1946         { MFG(0x4c, 0x83), PROD_ID(0x41, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1947         /*
1948          * Some Dell CML 2020 systems have panels support both AUX and PWM
1949          * backlight control, and some only support AUX backlight control. All
1950          * said panels start up in AUX mode by default, and we don't have any
1951          * support for disabling HDR mode on these panels which would be
1952          * required to switch to PWM backlight control mode (plus, I'm not
1953          * even sure we want PWM backlight controls over DPCD backlight
1954          * controls anyway...). Until we have a better way of detecting these,
1955          * force DPCD backlight mode on all of them.
1956          */
1957         { MFG(0x06, 0xaf), PROD_ID(0x9b, 0x32), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1958         { MFG(0x06, 0xaf), PROD_ID(0xeb, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1959         { MFG(0x4d, 0x10), PROD_ID(0xc7, 0x14), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1960         { MFG(0x4d, 0x10), PROD_ID(0xe6, 0x14), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1961         { MFG(0x4c, 0x83), PROD_ID(0x47, 0x41), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1962         { MFG(0x09, 0xe5), PROD_ID(0xde, 0x08), BIT(DP_QUIRK_FORCE_DPCD_BACKLIGHT) },
1963 };
1964
1965 #undef MFG
1966 #undef PROD_ID
1967
1968 /**
1969  * drm_dp_get_edid_quirks() - Check the EDID of a DP device to find additional
1970  * DP-specific quirks
1971  * @edid: The EDID to check
1972  *
1973  * While OUIDs are meant to be used to recognize a DisplayPort device, a lot
1974  * of manufacturers don't seem to like following standards and neglect to fill
1975  * the dev-ID in, making it impossible to only use OUIDs for determining
1976  * quirks in some cases. This function can be used to check the EDID and look
1977  * up any additional DP quirks. The bits returned by this function correspond
1978  * to the quirk bits in &drm_dp_quirk.
1979  *
1980  * Returns: a bitmask of quirks, if any. The driver can check this using
1981  * drm_dp_has_quirk().
1982  */
1983 u32 drm_dp_get_edid_quirks(const struct edid *edid)
1984 {
1985         const struct edid_quirk *quirk;
1986         u32 quirks = 0;
1987         int i;
1988
1989         if (!edid)
1990                 return 0;
1991
1992         for (i = 0; i < ARRAY_SIZE(edid_quirk_list); i++) {
1993                 quirk = &edid_quirk_list[i];
1994                 if (memcmp(quirk->mfg_id, edid->mfg_id,
1995                            sizeof(edid->mfg_id)) == 0 &&
1996                     memcmp(quirk->prod_id, edid->prod_code,
1997                            sizeof(edid->prod_code)) == 0)
1998                         quirks |= quirk->quirks;
1999         }
2000
2001         DRM_DEBUG_KMS("DP sink: EDID mfg %*phD prod-ID %*phD quirks: 0x%04x\n",
2002                       (int)sizeof(edid->mfg_id), edid->mfg_id,
2003                       (int)sizeof(edid->prod_code), edid->prod_code, quirks);
2004
2005         return quirks;
2006 }
2007 EXPORT_SYMBOL(drm_dp_get_edid_quirks);
2008
2009 /**
2010  * drm_dp_read_desc - read sink/branch descriptor from DPCD
2011  * @aux: DisplayPort AUX channel
2012  * @desc: Device descriptor to fill from DPCD
2013  * @is_branch: true for branch devices, false for sink devices
2014  *
2015  * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
2016  * identification.
2017  *
2018  * Returns 0 on success or a negative error code on failure.
2019  */
2020 int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
2021                      bool is_branch)
2022 {
2023         struct drm_dp_dpcd_ident *ident = &desc->ident;
2024         unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
2025         int ret, dev_id_len;
2026
2027         ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
2028         if (ret < 0)
2029                 return ret;
2030
2031         desc->quirks = drm_dp_get_quirks(ident, is_branch);
2032
2033         dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
2034
2035         DRM_DEBUG_KMS("%s: DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
2036                       aux->name, is_branch ? "branch" : "sink",
2037                       (int)sizeof(ident->oui), ident->oui,
2038                       dev_id_len, ident->device_id,
2039                       ident->hw_rev >> 4, ident->hw_rev & 0xf,
2040                       ident->sw_major_rev, ident->sw_minor_rev,
2041                       desc->quirks);
2042
2043         return 0;
2044 }
2045 EXPORT_SYMBOL(drm_dp_read_desc);
2046
2047 /**
2048  * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
2049  * supported by the DSC sink.
2050  * @dsc_dpcd: DSC capabilities from DPCD
2051  * @is_edp: true if its eDP, false for DP
2052  *
2053  * Read the slice capabilities DPCD register from DSC sink to get
2054  * the maximum slice count supported. This is used to populate
2055  * the DSC parameters in the &struct drm_dsc_config by the driver.
2056  * Driver creates an infoframe using these parameters to populate
2057  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2058  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2059  *
2060  * Returns:
2061  * Maximum slice count supported by DSC sink or 0 its invalid
2062  */
2063 u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
2064                                    bool is_edp)
2065 {
2066         u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
2067
2068         if (is_edp) {
2069                 /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
2070                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
2071                         return 4;
2072                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
2073                         return 2;
2074                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
2075                         return 1;
2076         } else {
2077                 /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
2078                 u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
2079
2080                 if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
2081                         return 24;
2082                 if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
2083                         return 20;
2084                 if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
2085                         return 16;
2086                 if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
2087                         return 12;
2088                 if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
2089                         return 10;
2090                 if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
2091                         return 8;
2092                 if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
2093                         return 6;
2094                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
2095                         return 4;
2096                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
2097                         return 2;
2098                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
2099                         return 1;
2100         }
2101
2102         return 0;
2103 }
2104 EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
2105
2106 /**
2107  * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
2108  * @dsc_dpcd: DSC capabilities from DPCD
2109  *
2110  * Read the DSC DPCD register to parse the line buffer depth in bits which is
2111  * number of bits of precision within the decoder line buffer supported by
2112  * the DSC sink. This is used to populate the DSC parameters in the
2113  * &struct drm_dsc_config by the driver.
2114  * Driver creates an infoframe using these parameters to populate
2115  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2116  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2117  *
2118  * Returns:
2119  * Line buffer depth supported by DSC panel or 0 its invalid
2120  */
2121 u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
2122 {
2123         u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
2124
2125         switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
2126         case DP_DSC_LINE_BUF_BIT_DEPTH_9:
2127                 return 9;
2128         case DP_DSC_LINE_BUF_BIT_DEPTH_10:
2129                 return 10;
2130         case DP_DSC_LINE_BUF_BIT_DEPTH_11:
2131                 return 11;
2132         case DP_DSC_LINE_BUF_BIT_DEPTH_12:
2133                 return 12;
2134         case DP_DSC_LINE_BUF_BIT_DEPTH_13:
2135                 return 13;
2136         case DP_DSC_LINE_BUF_BIT_DEPTH_14:
2137                 return 14;
2138         case DP_DSC_LINE_BUF_BIT_DEPTH_15:
2139                 return 15;
2140         case DP_DSC_LINE_BUF_BIT_DEPTH_16:
2141                 return 16;
2142         case DP_DSC_LINE_BUF_BIT_DEPTH_8:
2143                 return 8;
2144         }
2145
2146         return 0;
2147 }
2148 EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
2149
2150 /**
2151  * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
2152  * values supported by the DSC sink.
2153  * @dsc_dpcd: DSC capabilities from DPCD
2154  * @dsc_bpc: An array to be filled by this helper with supported
2155  *           input bpcs.
2156  *
2157  * Read the DSC DPCD from the sink device to parse the supported bits per
2158  * component values. This is used to populate the DSC parameters
2159  * in the &struct drm_dsc_config by the driver.
2160  * Driver creates an infoframe using these parameters to populate
2161  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2162  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2163  *
2164  * Returns:
2165  * Number of input BPC values parsed from the DPCD
2166  */
2167 int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
2168                                          u8 dsc_bpc[3])
2169 {
2170         int num_bpc = 0;
2171         u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
2172
2173         if (color_depth & DP_DSC_12_BPC)
2174                 dsc_bpc[num_bpc++] = 12;
2175         if (color_depth & DP_DSC_10_BPC)
2176                 dsc_bpc[num_bpc++] = 10;
2177         if (color_depth & DP_DSC_8_BPC)
2178                 dsc_bpc[num_bpc++] = 8;
2179
2180         return num_bpc;
2181 }
2182 EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);
2183
2184 /**
2185  * drm_dp_read_lttpr_common_caps - read the LTTPR common capabilities
2186  * @aux: DisplayPort AUX channel
2187  * @caps: buffer to return the capability info in
2188  *
2189  * Read capabilities common to all LTTPRs.
2190  *
2191  * Returns 0 on success or a negative error code on failure.
2192  */
2193 int drm_dp_read_lttpr_common_caps(struct drm_dp_aux *aux,
2194                                   u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2195 {
2196         int ret;
2197
2198         ret = drm_dp_dpcd_read(aux,
2199                                DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV,
2200                                caps, DP_LTTPR_COMMON_CAP_SIZE);
2201         if (ret < 0)
2202                 return ret;
2203
2204         WARN_ON(ret != DP_LTTPR_COMMON_CAP_SIZE);
2205
2206         return 0;
2207 }
2208 EXPORT_SYMBOL(drm_dp_read_lttpr_common_caps);
2209
2210 /**
2211  * drm_dp_read_lttpr_phy_caps - read the capabilities for a given LTTPR PHY
2212  * @aux: DisplayPort AUX channel
2213  * @dp_phy: LTTPR PHY to read the capabilities for
2214  * @caps: buffer to return the capability info in
2215  *
2216  * Read the capabilities for the given LTTPR PHY.
2217  *
2218  * Returns 0 on success or a negative error code on failure.
2219  */
2220 int drm_dp_read_lttpr_phy_caps(struct drm_dp_aux *aux,
2221                                enum drm_dp_phy dp_phy,
2222                                u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2223 {
2224         int ret;
2225
2226         ret = drm_dp_dpcd_read(aux,
2227                                DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER(dp_phy),
2228                                caps, DP_LTTPR_PHY_CAP_SIZE);
2229         if (ret < 0)
2230                 return ret;
2231
2232         WARN_ON(ret != DP_LTTPR_PHY_CAP_SIZE);
2233
2234         return 0;
2235 }
2236 EXPORT_SYMBOL(drm_dp_read_lttpr_phy_caps);
2237
2238 static u8 dp_lttpr_common_cap(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE], int r)
2239 {
2240         return caps[r - DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV];
2241 }
2242
2243 /**
2244  * drm_dp_lttpr_count - get the number of detected LTTPRs
2245  * @caps: LTTPR common capabilities
2246  *
2247  * Get the number of detected LTTPRs from the LTTPR common capabilities info.
2248  *
2249  * Returns:
2250  *   -ERANGE if more than supported number (8) of LTTPRs are detected
2251  *   -EINVAL if the DP_PHY_REPEATER_CNT register contains an invalid value
2252  *   otherwise the number of detected LTTPRs
2253  */
2254 int drm_dp_lttpr_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2255 {
2256         u8 count = dp_lttpr_common_cap(caps, DP_PHY_REPEATER_CNT);
2257
2258         switch (hweight8(count)) {
2259         case 0:
2260                 return 0;
2261         case 1:
2262                 return 8 - ilog2(count);
2263         case 8:
2264                 return -ERANGE;
2265         default:
2266                 return -EINVAL;
2267         }
2268 }
2269 EXPORT_SYMBOL(drm_dp_lttpr_count);
2270
2271 /**
2272  * drm_dp_lttpr_max_link_rate - get the maximum link rate supported by all LTTPRs
2273  * @caps: LTTPR common capabilities
2274  *
2275  * Returns the maximum link rate supported by all detected LTTPRs.
2276  */
2277 int drm_dp_lttpr_max_link_rate(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2278 {
2279         u8 rate = dp_lttpr_common_cap(caps, DP_MAX_LINK_RATE_PHY_REPEATER);
2280
2281         return drm_dp_bw_code_to_link_rate(rate);
2282 }
2283 EXPORT_SYMBOL(drm_dp_lttpr_max_link_rate);
2284
2285 /**
2286  * drm_dp_lttpr_max_lane_count - get the maximum lane count supported by all LTTPRs
2287  * @caps: LTTPR common capabilities
2288  *
2289  * Returns the maximum lane count supported by all detected LTTPRs.
2290  */
2291 int drm_dp_lttpr_max_lane_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2292 {
2293         u8 max_lanes = dp_lttpr_common_cap(caps, DP_MAX_LANE_COUNT_PHY_REPEATER);
2294
2295         return max_lanes & DP_MAX_LANE_COUNT_MASK;
2296 }
2297 EXPORT_SYMBOL(drm_dp_lttpr_max_lane_count);
2298
2299 /**
2300  * drm_dp_lttpr_voltage_swing_level_3_supported - check for LTTPR vswing3 support
2301  * @caps: LTTPR PHY capabilities
2302  *
2303  * Returns true if the @caps for an LTTPR TX PHY indicate support for
2304  * voltage swing level 3.
2305  */
2306 bool
2307 drm_dp_lttpr_voltage_swing_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2308 {
2309         u8 txcap = dp_lttpr_phy_cap(caps, DP_TRANSMITTER_CAPABILITY_PHY_REPEATER1);
2310
2311         return txcap & DP_VOLTAGE_SWING_LEVEL_3_SUPPORTED;
2312 }
2313 EXPORT_SYMBOL(drm_dp_lttpr_voltage_swing_level_3_supported);
2314
2315 /**
2316  * drm_dp_lttpr_pre_emphasis_level_3_supported - check for LTTPR preemph3 support
2317  * @caps: LTTPR PHY capabilities
2318  *
2319  * Returns true if the @caps for an LTTPR TX PHY indicate support for
2320  * pre-emphasis level 3.
2321  */
2322 bool
2323 drm_dp_lttpr_pre_emphasis_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2324 {
2325         u8 txcap = dp_lttpr_phy_cap(caps, DP_TRANSMITTER_CAPABILITY_PHY_REPEATER1);
2326
2327         return txcap & DP_PRE_EMPHASIS_LEVEL_3_SUPPORTED;
2328 }
2329 EXPORT_SYMBOL(drm_dp_lttpr_pre_emphasis_level_3_supported);
2330
2331 /**
2332  * drm_dp_get_phy_test_pattern() - get the requested pattern from the sink.
2333  * @aux: DisplayPort AUX channel
2334  * @data: DP phy compliance test parameters.
2335  *
2336  * Returns 0 on success or a negative error code on failure.
2337  */
2338 int drm_dp_get_phy_test_pattern(struct drm_dp_aux *aux,
2339                                 struct drm_dp_phy_test_params *data)
2340 {
2341         int err;
2342         u8 rate, lanes;
2343
2344         err = drm_dp_dpcd_readb(aux, DP_TEST_LINK_RATE, &rate);
2345         if (err < 0)
2346                 return err;
2347         data->link_rate = drm_dp_bw_code_to_link_rate(rate);
2348
2349         err = drm_dp_dpcd_readb(aux, DP_TEST_LANE_COUNT, &lanes);
2350         if (err < 0)
2351                 return err;
2352         data->num_lanes = lanes & DP_MAX_LANE_COUNT_MASK;
2353
2354         if (lanes & DP_ENHANCED_FRAME_CAP)
2355                 data->enhanced_frame_cap = true;
2356
2357         err = drm_dp_dpcd_readb(aux, DP_PHY_TEST_PATTERN, &data->phy_pattern);
2358         if (err < 0)
2359                 return err;
2360
2361         switch (data->phy_pattern) {
2362         case DP_PHY_TEST_PATTERN_80BIT_CUSTOM:
2363                 err = drm_dp_dpcd_read(aux, DP_TEST_80BIT_CUSTOM_PATTERN_7_0,
2364                                        &data->custom80, sizeof(data->custom80));
2365                 if (err < 0)
2366                         return err;
2367
2368                 break;
2369         case DP_PHY_TEST_PATTERN_CP2520:
2370                 err = drm_dp_dpcd_read(aux, DP_TEST_HBR2_SCRAMBLER_RESET,
2371                                        &data->hbr2_reset,
2372                                        sizeof(data->hbr2_reset));
2373                 if (err < 0)
2374                         return err;
2375         }
2376
2377         return 0;
2378 }
2379 EXPORT_SYMBOL(drm_dp_get_phy_test_pattern);
2380
2381 /**
2382  * drm_dp_set_phy_test_pattern() - set the pattern to the sink.
2383  * @aux: DisplayPort AUX channel
2384  * @data: DP phy compliance test parameters.
2385  * @dp_rev: DP revision to use for compliance testing
2386  *
2387  * Returns 0 on success or a negative error code on failure.
2388  */
2389 int drm_dp_set_phy_test_pattern(struct drm_dp_aux *aux,
2390                                 struct drm_dp_phy_test_params *data, u8 dp_rev)
2391 {
2392         int err, i;
2393         u8 link_config[2];
2394         u8 test_pattern;
2395
2396         link_config[0] = drm_dp_link_rate_to_bw_code(data->link_rate);
2397         link_config[1] = data->num_lanes;
2398         if (data->enhanced_frame_cap)
2399                 link_config[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
2400         err = drm_dp_dpcd_write(aux, DP_LINK_BW_SET, link_config, 2);
2401         if (err < 0)
2402                 return err;
2403
2404         test_pattern = data->phy_pattern;
2405         if (dp_rev < 0x12) {
2406                 test_pattern = (test_pattern << 2) &
2407                                DP_LINK_QUAL_PATTERN_11_MASK;
2408                 err = drm_dp_dpcd_writeb(aux, DP_TRAINING_PATTERN_SET,
2409                                          test_pattern);
2410                 if (err < 0)
2411                         return err;
2412         } else {
2413                 for (i = 0; i < data->num_lanes; i++) {
2414                         err = drm_dp_dpcd_writeb(aux,
2415                                                  DP_LINK_QUAL_LANE0_SET + i,
2416                                                  test_pattern);
2417                         if (err < 0)
2418                                 return err;
2419                 }
2420         }
2421
2422         return 0;
2423 }
2424 EXPORT_SYMBOL(drm_dp_set_phy_test_pattern);
2425
2426 static const char *dp_pixelformat_get_name(enum dp_pixelformat pixelformat)
2427 {
2428         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
2429                 return "Invalid";
2430
2431         switch (pixelformat) {
2432         case DP_PIXELFORMAT_RGB:
2433                 return "RGB";
2434         case DP_PIXELFORMAT_YUV444:
2435                 return "YUV444";
2436         case DP_PIXELFORMAT_YUV422:
2437                 return "YUV422";
2438         case DP_PIXELFORMAT_YUV420:
2439                 return "YUV420";
2440         case DP_PIXELFORMAT_Y_ONLY:
2441                 return "Y_ONLY";
2442         case DP_PIXELFORMAT_RAW:
2443                 return "RAW";
2444         default:
2445                 return "Reserved";
2446         }
2447 }
2448
2449 static const char *dp_colorimetry_get_name(enum dp_pixelformat pixelformat,
2450                                            enum dp_colorimetry colorimetry)
2451 {
2452         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
2453                 return "Invalid";
2454
2455         switch (colorimetry) {
2456         case DP_COLORIMETRY_DEFAULT:
2457                 switch (pixelformat) {
2458                 case DP_PIXELFORMAT_RGB:
2459                         return "sRGB";
2460                 case DP_PIXELFORMAT_YUV444:
2461                 case DP_PIXELFORMAT_YUV422:
2462                 case DP_PIXELFORMAT_YUV420:
2463                         return "BT.601";
2464                 case DP_PIXELFORMAT_Y_ONLY:
2465                         return "DICOM PS3.14";
2466                 case DP_PIXELFORMAT_RAW:
2467                         return "Custom Color Profile";
2468                 default:
2469                         return "Reserved";
2470                 }
2471         case DP_COLORIMETRY_RGB_WIDE_FIXED: /* and DP_COLORIMETRY_BT709_YCC */
2472                 switch (pixelformat) {
2473                 case DP_PIXELFORMAT_RGB:
2474                         return "Wide Fixed";
2475                 case DP_PIXELFORMAT_YUV444:
2476                 case DP_PIXELFORMAT_YUV422:
2477                 case DP_PIXELFORMAT_YUV420:
2478                         return "BT.709";
2479                 default:
2480                         return "Reserved";
2481                 }
2482         case DP_COLORIMETRY_RGB_WIDE_FLOAT: /* and DP_COLORIMETRY_XVYCC_601 */
2483                 switch (pixelformat) {
2484                 case DP_PIXELFORMAT_RGB:
2485                         return "Wide Float";
2486                 case DP_PIXELFORMAT_YUV444:
2487                 case DP_PIXELFORMAT_YUV422:
2488                 case DP_PIXELFORMAT_YUV420:
2489                         return "xvYCC 601";
2490                 default:
2491                         return "Reserved";
2492                 }
2493         case DP_COLORIMETRY_OPRGB: /* and DP_COLORIMETRY_XVYCC_709 */
2494                 switch (pixelformat) {
2495                 case DP_PIXELFORMAT_RGB:
2496                         return "OpRGB";
2497                 case DP_PIXELFORMAT_YUV444:
2498                 case DP_PIXELFORMAT_YUV422:
2499                 case DP_PIXELFORMAT_YUV420:
2500                         return "xvYCC 709";
2501                 default:
2502                         return "Reserved";
2503                 }
2504         case DP_COLORIMETRY_DCI_P3_RGB: /* and DP_COLORIMETRY_SYCC_601 */
2505                 switch (pixelformat) {
2506                 case DP_PIXELFORMAT_RGB:
2507                         return "DCI-P3";
2508                 case DP_PIXELFORMAT_YUV444:
2509                 case DP_PIXELFORMAT_YUV422:
2510                 case DP_PIXELFORMAT_YUV420:
2511                         return "sYCC 601";
2512                 default:
2513                         return "Reserved";
2514                 }
2515         case DP_COLORIMETRY_RGB_CUSTOM: /* and DP_COLORIMETRY_OPYCC_601 */
2516                 switch (pixelformat) {
2517                 case DP_PIXELFORMAT_RGB:
2518                         return "Custom Profile";
2519                 case DP_PIXELFORMAT_YUV444:
2520                 case DP_PIXELFORMAT_YUV422:
2521                 case DP_PIXELFORMAT_YUV420:
2522                         return "OpYCC 601";
2523                 default:
2524                         return "Reserved";
2525                 }
2526         case DP_COLORIMETRY_BT2020_RGB: /* and DP_COLORIMETRY_BT2020_CYCC */
2527                 switch (pixelformat) {
2528                 case DP_PIXELFORMAT_RGB:
2529                         return "BT.2020 RGB";
2530                 case DP_PIXELFORMAT_YUV444:
2531                 case DP_PIXELFORMAT_YUV422:
2532                 case DP_PIXELFORMAT_YUV420:
2533                         return "BT.2020 CYCC";
2534                 default:
2535                         return "Reserved";
2536                 }
2537         case DP_COLORIMETRY_BT2020_YCC:
2538                 switch (pixelformat) {
2539                 case DP_PIXELFORMAT_YUV444:
2540                 case DP_PIXELFORMAT_YUV422:
2541                 case DP_PIXELFORMAT_YUV420:
2542                         return "BT.2020 YCC";
2543                 default:
2544                         return "Reserved";
2545                 }
2546         default:
2547                 return "Invalid";
2548         }
2549 }
2550
2551 static const char *dp_dynamic_range_get_name(enum dp_dynamic_range dynamic_range)
2552 {
2553         switch (dynamic_range) {
2554         case DP_DYNAMIC_RANGE_VESA:
2555                 return "VESA range";
2556         case DP_DYNAMIC_RANGE_CTA:
2557                 return "CTA range";
2558         default:
2559                 return "Invalid";
2560         }
2561 }
2562
2563 static const char *dp_content_type_get_name(enum dp_content_type content_type)
2564 {
2565         switch (content_type) {
2566         case DP_CONTENT_TYPE_NOT_DEFINED:
2567                 return "Not defined";
2568         case DP_CONTENT_TYPE_GRAPHICS:
2569                 return "Graphics";
2570         case DP_CONTENT_TYPE_PHOTO:
2571                 return "Photo";
2572         case DP_CONTENT_TYPE_VIDEO:
2573                 return "Video";
2574         case DP_CONTENT_TYPE_GAME:
2575                 return "Game";
2576         default:
2577                 return "Reserved";
2578         }
2579 }
2580
2581 void drm_dp_vsc_sdp_log(const char *level, struct device *dev,
2582                         const struct drm_dp_vsc_sdp *vsc)
2583 {
2584 #define DP_SDP_LOG(fmt, ...) dev_printk(level, dev, fmt, ##__VA_ARGS__)
2585         DP_SDP_LOG("DP SDP: %s, revision %u, length %u\n", "VSC",
2586                    vsc->revision, vsc->length);
2587         DP_SDP_LOG("    pixelformat: %s\n",
2588                    dp_pixelformat_get_name(vsc->pixelformat));
2589         DP_SDP_LOG("    colorimetry: %s\n",
2590                    dp_colorimetry_get_name(vsc->pixelformat, vsc->colorimetry));
2591         DP_SDP_LOG("    bpc: %u\n", vsc->bpc);
2592         DP_SDP_LOG("    dynamic range: %s\n",
2593                    dp_dynamic_range_get_name(vsc->dynamic_range));
2594         DP_SDP_LOG("    content type: %s\n",
2595                    dp_content_type_get_name(vsc->content_type));
2596 #undef DP_SDP_LOG
2597 }
2598 EXPORT_SYMBOL(drm_dp_vsc_sdp_log);