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