drm/display: Remove duplicate 'the' in two places.
[linux-2.6-microblaze.git] / drivers / gpu / drm / display / 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 #include <linux/string_helpers.h>
32
33 #include <drm/display/drm_dp_helper.h>
34 #include <drm/display/drm_dp_mst_helper.h>
35 #include <drm/drm_edid.h>
36 #include <drm/drm_print.h>
37 #include <drm/drm_vblank.h>
38 #include <drm/drm_panel.h>
39
40 #include "drm_dp_helper_internal.h"
41
42 struct dp_aux_backlight {
43         struct backlight_device *base;
44         struct drm_dp_aux *aux;
45         struct drm_edp_backlight_info info;
46         bool enabled;
47 };
48
49 /**
50  * DOC: dp helpers
51  *
52  * These functions contain some common logic and helpers at various abstraction
53  * levels to deal with Display Port sink devices and related things like DP aux
54  * channel transfers, EDID reading over DP aux channels, decoding certain DPCD
55  * blocks, ...
56  */
57
58 /* Helpers for DP link training */
59 static u8 dp_link_status(const u8 link_status[DP_LINK_STATUS_SIZE], int r)
60 {
61         return link_status[r - DP_LANE0_1_STATUS];
62 }
63
64 static u8 dp_get_lane_status(const u8 link_status[DP_LINK_STATUS_SIZE],
65                              int lane)
66 {
67         int i = DP_LANE0_1_STATUS + (lane >> 1);
68         int s = (lane & 1) * 4;
69         u8 l = dp_link_status(link_status, i);
70
71         return (l >> s) & 0xf;
72 }
73
74 bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
75                           int lane_count)
76 {
77         u8 lane_align;
78         u8 lane_status;
79         int lane;
80
81         lane_align = dp_link_status(link_status,
82                                     DP_LANE_ALIGN_STATUS_UPDATED);
83         if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
84                 return false;
85         for (lane = 0; lane < lane_count; lane++) {
86                 lane_status = dp_get_lane_status(link_status, lane);
87                 if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
88                         return false;
89         }
90         return true;
91 }
92 EXPORT_SYMBOL(drm_dp_channel_eq_ok);
93
94 bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
95                               int lane_count)
96 {
97         int lane;
98         u8 lane_status;
99
100         for (lane = 0; lane < lane_count; lane++) {
101                 lane_status = dp_get_lane_status(link_status, lane);
102                 if ((lane_status & DP_LANE_CR_DONE) == 0)
103                         return false;
104         }
105         return true;
106 }
107 EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
108
109 u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
110                                      int lane)
111 {
112         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
113         int s = ((lane & 1) ?
114                  DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
115                  DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
116         u8 l = dp_link_status(link_status, i);
117
118         return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
119 }
120 EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
121
122 u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
123                                           int lane)
124 {
125         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
126         int s = ((lane & 1) ?
127                  DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
128                  DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
129         u8 l = dp_link_status(link_status, i);
130
131         return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
132 }
133 EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
134
135 /* DP 2.0 128b/132b */
136 u8 drm_dp_get_adjust_tx_ffe_preset(const u8 link_status[DP_LINK_STATUS_SIZE],
137                                    int lane)
138 {
139         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
140         int s = ((lane & 1) ?
141                  DP_ADJUST_TX_FFE_PRESET_LANE1_SHIFT :
142                  DP_ADJUST_TX_FFE_PRESET_LANE0_SHIFT);
143         u8 l = dp_link_status(link_status, i);
144
145         return (l >> s) & 0xf;
146 }
147 EXPORT_SYMBOL(drm_dp_get_adjust_tx_ffe_preset);
148
149 /* DP 2.0 errata for 128b/132b */
150 bool drm_dp_128b132b_lane_channel_eq_done(const u8 link_status[DP_LINK_STATUS_SIZE],
151                                           int lane_count)
152 {
153         u8 lane_align, lane_status;
154         int lane;
155
156         lane_align = dp_link_status(link_status, DP_LANE_ALIGN_STATUS_UPDATED);
157         if (!(lane_align & DP_INTERLANE_ALIGN_DONE))
158                 return false;
159
160         for (lane = 0; lane < lane_count; lane++) {
161                 lane_status = dp_get_lane_status(link_status, lane);
162                 if (!(lane_status & DP_LANE_CHANNEL_EQ_DONE))
163                         return false;
164         }
165         return true;
166 }
167 EXPORT_SYMBOL(drm_dp_128b132b_lane_channel_eq_done);
168
169 /* DP 2.0 errata for 128b/132b */
170 bool drm_dp_128b132b_lane_symbol_locked(const u8 link_status[DP_LINK_STATUS_SIZE],
171                                         int lane_count)
172 {
173         u8 lane_status;
174         int lane;
175
176         for (lane = 0; lane < lane_count; lane++) {
177                 lane_status = dp_get_lane_status(link_status, lane);
178                 if (!(lane_status & DP_LANE_SYMBOL_LOCKED))
179                         return false;
180         }
181         return true;
182 }
183 EXPORT_SYMBOL(drm_dp_128b132b_lane_symbol_locked);
184
185 /* DP 2.0 errata for 128b/132b */
186 bool drm_dp_128b132b_eq_interlane_align_done(const u8 link_status[DP_LINK_STATUS_SIZE])
187 {
188         u8 status = dp_link_status(link_status, DP_LANE_ALIGN_STATUS_UPDATED);
189
190         return status & DP_128B132B_DPRX_EQ_INTERLANE_ALIGN_DONE;
191 }
192 EXPORT_SYMBOL(drm_dp_128b132b_eq_interlane_align_done);
193
194 /* DP 2.0 errata for 128b/132b */
195 bool drm_dp_128b132b_cds_interlane_align_done(const u8 link_status[DP_LINK_STATUS_SIZE])
196 {
197         u8 status = dp_link_status(link_status, DP_LANE_ALIGN_STATUS_UPDATED);
198
199         return status & DP_128B132B_DPRX_CDS_INTERLANE_ALIGN_DONE;
200 }
201 EXPORT_SYMBOL(drm_dp_128b132b_cds_interlane_align_done);
202
203 /* DP 2.0 errata for 128b/132b */
204 bool drm_dp_128b132b_link_training_failed(const u8 link_status[DP_LINK_STATUS_SIZE])
205 {
206         u8 status = dp_link_status(link_status, DP_LANE_ALIGN_STATUS_UPDATED);
207
208         return status & DP_128B132B_LT_FAILED;
209 }
210 EXPORT_SYMBOL(drm_dp_128b132b_link_training_failed);
211
212 static int __8b10b_clock_recovery_delay_us(const struct drm_dp_aux *aux, u8 rd_interval)
213 {
214         if (rd_interval > 4)
215                 drm_dbg_kms(aux->drm_dev, "%s: invalid AUX interval 0x%02x (max 4)\n",
216                             aux->name, rd_interval);
217
218         if (rd_interval == 0)
219                 return 100;
220
221         return rd_interval * 4 * USEC_PER_MSEC;
222 }
223
224 static int __8b10b_channel_eq_delay_us(const struct drm_dp_aux *aux, u8 rd_interval)
225 {
226         if (rd_interval > 4)
227                 drm_dbg_kms(aux->drm_dev, "%s: invalid AUX interval 0x%02x (max 4)\n",
228                             aux->name, rd_interval);
229
230         if (rd_interval == 0)
231                 return 400;
232
233         return rd_interval * 4 * USEC_PER_MSEC;
234 }
235
236 static int __128b132b_channel_eq_delay_us(const struct drm_dp_aux *aux, u8 rd_interval)
237 {
238         switch (rd_interval) {
239         default:
240                 drm_dbg_kms(aux->drm_dev, "%s: invalid AUX interval 0x%02x\n",
241                             aux->name, rd_interval);
242                 fallthrough;
243         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_400_US:
244                 return 400;
245         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_4_MS:
246                 return 4000;
247         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_8_MS:
248                 return 8000;
249         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_12_MS:
250                 return 12000;
251         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_16_MS:
252                 return 16000;
253         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_32_MS:
254                 return 32000;
255         case DP_128B132B_TRAINING_AUX_RD_INTERVAL_64_MS:
256                 return 64000;
257         }
258 }
259
260 /*
261  * The link training delays are different for:
262  *
263  *  - Clock recovery vs. channel equalization
264  *  - DPRX vs. LTTPR
265  *  - 128b/132b vs. 8b/10b
266  *  - DPCD rev 1.3 vs. later
267  *
268  * Get the correct delay in us, reading DPCD if necessary.
269  */
270 static int __read_delay(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE],
271                         enum drm_dp_phy dp_phy, bool uhbr, bool cr)
272 {
273         int (*parse)(const struct drm_dp_aux *aux, u8 rd_interval);
274         unsigned int offset;
275         u8 rd_interval, mask;
276
277         if (dp_phy == DP_PHY_DPRX) {
278                 if (uhbr) {
279                         if (cr)
280                                 return 100;
281
282                         offset = DP_128B132B_TRAINING_AUX_RD_INTERVAL;
283                         mask = DP_128B132B_TRAINING_AUX_RD_INTERVAL_MASK;
284                         parse = __128b132b_channel_eq_delay_us;
285                 } else {
286                         if (cr && dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
287                                 return 100;
288
289                         offset = DP_TRAINING_AUX_RD_INTERVAL;
290                         mask = DP_TRAINING_AUX_RD_MASK;
291                         if (cr)
292                                 parse = __8b10b_clock_recovery_delay_us;
293                         else
294                                 parse = __8b10b_channel_eq_delay_us;
295                 }
296         } else {
297                 if (uhbr) {
298                         offset = DP_128B132B_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER(dp_phy);
299                         mask = DP_128B132B_TRAINING_AUX_RD_INTERVAL_MASK;
300                         parse = __128b132b_channel_eq_delay_us;
301                 } else {
302                         if (cr)
303                                 return 100;
304
305                         offset = DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER(dp_phy);
306                         mask = DP_TRAINING_AUX_RD_MASK;
307                         parse = __8b10b_channel_eq_delay_us;
308                 }
309         }
310
311         if (offset < DP_RECEIVER_CAP_SIZE) {
312                 rd_interval = dpcd[offset];
313         } else {
314                 if (drm_dp_dpcd_readb(aux, offset, &rd_interval) != 1) {
315                         drm_dbg_kms(aux->drm_dev, "%s: failed rd interval read\n",
316                                     aux->name);
317                         /* arbitrary default delay */
318                         return 400;
319                 }
320         }
321
322         return parse(aux, rd_interval & mask);
323 }
324
325 int drm_dp_read_clock_recovery_delay(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE],
326                                      enum drm_dp_phy dp_phy, bool uhbr)
327 {
328         return __read_delay(aux, dpcd, dp_phy, uhbr, true);
329 }
330 EXPORT_SYMBOL(drm_dp_read_clock_recovery_delay);
331
332 int drm_dp_read_channel_eq_delay(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE],
333                                  enum drm_dp_phy dp_phy, bool uhbr)
334 {
335         return __read_delay(aux, dpcd, dp_phy, uhbr, false);
336 }
337 EXPORT_SYMBOL(drm_dp_read_channel_eq_delay);
338
339 /* Per DP 2.0 Errata */
340 int drm_dp_128b132b_read_aux_rd_interval(struct drm_dp_aux *aux)
341 {
342         int unit;
343         u8 val;
344
345         if (drm_dp_dpcd_readb(aux, DP_128B132B_TRAINING_AUX_RD_INTERVAL, &val) != 1) {
346                 drm_err(aux->drm_dev, "%s: failed rd interval read\n",
347                         aux->name);
348                 /* default to max */
349                 val = DP_128B132B_TRAINING_AUX_RD_INTERVAL_MASK;
350         }
351
352         unit = (val & DP_128B132B_TRAINING_AUX_RD_INTERVAL_1MS_UNIT) ? 1 : 2;
353         val &= DP_128B132B_TRAINING_AUX_RD_INTERVAL_MASK;
354
355         return (val + 1) * unit * 1000;
356 }
357 EXPORT_SYMBOL(drm_dp_128b132b_read_aux_rd_interval);
358
359 void drm_dp_link_train_clock_recovery_delay(const struct drm_dp_aux *aux,
360                                             const u8 dpcd[DP_RECEIVER_CAP_SIZE])
361 {
362         u8 rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
363                 DP_TRAINING_AUX_RD_MASK;
364         int delay_us;
365
366         if (dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
367                 delay_us = 100;
368         else
369                 delay_us = __8b10b_clock_recovery_delay_us(aux, rd_interval);
370
371         usleep_range(delay_us, delay_us * 2);
372 }
373 EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
374
375 static void __drm_dp_link_train_channel_eq_delay(const struct drm_dp_aux *aux,
376                                                  u8 rd_interval)
377 {
378         int delay_us = __8b10b_channel_eq_delay_us(aux, rd_interval);
379
380         usleep_range(delay_us, delay_us * 2);
381 }
382
383 void drm_dp_link_train_channel_eq_delay(const struct drm_dp_aux *aux,
384                                         const u8 dpcd[DP_RECEIVER_CAP_SIZE])
385 {
386         __drm_dp_link_train_channel_eq_delay(aux,
387                                              dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
388                                              DP_TRAINING_AUX_RD_MASK);
389 }
390 EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
391
392 void drm_dp_lttpr_link_train_clock_recovery_delay(void)
393 {
394         usleep_range(100, 200);
395 }
396 EXPORT_SYMBOL(drm_dp_lttpr_link_train_clock_recovery_delay);
397
398 static u8 dp_lttpr_phy_cap(const u8 phy_cap[DP_LTTPR_PHY_CAP_SIZE], int r)
399 {
400         return phy_cap[r - DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER1];
401 }
402
403 void drm_dp_lttpr_link_train_channel_eq_delay(const struct drm_dp_aux *aux,
404                                               const u8 phy_cap[DP_LTTPR_PHY_CAP_SIZE])
405 {
406         u8 interval = dp_lttpr_phy_cap(phy_cap,
407                                        DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER1) &
408                       DP_TRAINING_AUX_RD_MASK;
409
410         __drm_dp_link_train_channel_eq_delay(aux, interval);
411 }
412 EXPORT_SYMBOL(drm_dp_lttpr_link_train_channel_eq_delay);
413
414 u8 drm_dp_link_rate_to_bw_code(int link_rate)
415 {
416         switch (link_rate) {
417         case 1000000:
418                 return DP_LINK_BW_10;
419         case 1350000:
420                 return DP_LINK_BW_13_5;
421         case 2000000:
422                 return DP_LINK_BW_20;
423         default:
424                 /* Spec says link_bw = link_rate / 0.27Gbps */
425                 return link_rate / 27000;
426         }
427 }
428 EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
429
430 int drm_dp_bw_code_to_link_rate(u8 link_bw)
431 {
432         switch (link_bw) {
433         case DP_LINK_BW_10:
434                 return 1000000;
435         case DP_LINK_BW_13_5:
436                 return 1350000;
437         case DP_LINK_BW_20:
438                 return 2000000;
439         default:
440                 /* Spec says link_rate = link_bw * 0.27Gbps */
441                 return link_bw * 27000;
442         }
443 }
444 EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
445
446 #define AUX_RETRY_INTERVAL 500 /* us */
447
448 static inline void
449 drm_dp_dump_access(const struct drm_dp_aux *aux,
450                    u8 request, uint offset, void *buffer, int ret)
451 {
452         const char *arrow = request == DP_AUX_NATIVE_READ ? "->" : "<-";
453
454         if (ret > 0)
455                 drm_dbg_dp(aux->drm_dev, "%s: 0x%05x AUX %s (ret=%3d) %*ph\n",
456                            aux->name, offset, arrow, ret, min(ret, 20), buffer);
457         else
458                 drm_dbg_dp(aux->drm_dev, "%s: 0x%05x AUX %s (ret=%3d)\n",
459                            aux->name, offset, arrow, ret);
460 }
461
462 /**
463  * DOC: dp helpers
464  *
465  * The DisplayPort AUX channel is an abstraction to allow generic, driver-
466  * independent access to AUX functionality. Drivers can take advantage of
467  * this by filling in the fields of the drm_dp_aux structure.
468  *
469  * Transactions are described using a hardware-independent drm_dp_aux_msg
470  * structure, which is passed into a driver's .transfer() implementation.
471  * Both native and I2C-over-AUX transactions are supported.
472  */
473
474 static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
475                               unsigned int offset, void *buffer, size_t size)
476 {
477         struct drm_dp_aux_msg msg;
478         unsigned int retry, native_reply;
479         int err = 0, ret = 0;
480
481         memset(&msg, 0, sizeof(msg));
482         msg.address = offset;
483         msg.request = request;
484         msg.buffer = buffer;
485         msg.size = size;
486
487         mutex_lock(&aux->hw_mutex);
488
489         /*
490          * The specification doesn't give any recommendation on how often to
491          * retry native transactions. We used to retry 7 times like for
492          * aux i2c transactions but real world devices this wasn't
493          * sufficient, bump to 32 which makes Dell 4k monitors happier.
494          */
495         for (retry = 0; retry < 32; retry++) {
496                 if (ret != 0 && ret != -ETIMEDOUT) {
497                         usleep_range(AUX_RETRY_INTERVAL,
498                                      AUX_RETRY_INTERVAL + 100);
499                 }
500
501                 ret = aux->transfer(aux, &msg);
502                 if (ret >= 0) {
503                         native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
504                         if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
505                                 if (ret == size)
506                                         goto unlock;
507
508                                 ret = -EPROTO;
509                         } else
510                                 ret = -EIO;
511                 }
512
513                 /*
514                  * We want the error we return to be the error we received on
515                  * the first transaction, since we may get a different error the
516                  * next time we retry
517                  */
518                 if (!err)
519                         err = ret;
520         }
521
522         drm_dbg_kms(aux->drm_dev, "%s: Too many retries, giving up. First error: %d\n",
523                     aux->name, err);
524         ret = err;
525
526 unlock:
527         mutex_unlock(&aux->hw_mutex);
528         return ret;
529 }
530
531 /**
532  * drm_dp_dpcd_probe() - probe a given DPCD address with a 1-byte read access
533  * @aux: DisplayPort AUX channel (SST)
534  * @offset: address of the register to probe
535  *
536  * Probe the provided DPCD address by reading 1 byte from it. The function can
537  * be used to trigger some side-effect the read access has, like waking up the
538  * sink, without the need for the read-out value.
539  *
540  * Returns 0 if the read access suceeded, or a negative error code on failure.
541  */
542 int drm_dp_dpcd_probe(struct drm_dp_aux *aux, unsigned int offset)
543 {
544         u8 buffer;
545         int ret;
546
547         ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset, &buffer, 1);
548         WARN_ON(ret == 0);
549
550         drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, &buffer, ret);
551
552         return ret < 0 ? ret : 0;
553 }
554 EXPORT_SYMBOL(drm_dp_dpcd_probe);
555
556 /**
557  * drm_dp_dpcd_read() - read a series of bytes from the DPCD
558  * @aux: DisplayPort AUX channel (SST or MST)
559  * @offset: address of the (first) register to read
560  * @buffer: buffer to store the register values
561  * @size: number of bytes in @buffer
562  *
563  * Returns the number of bytes transferred on success, or a negative error
564  * code on failure. -EIO is returned if the request was NAKed by the sink or
565  * if the retry count was exceeded. If not all bytes were transferred, this
566  * function returns -EPROTO. Errors from the underlying AUX channel transfer
567  * function, with the exception of -EBUSY (which causes the transaction to
568  * be retried), are propagated to the caller.
569  */
570 ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
571                          void *buffer, size_t size)
572 {
573         int ret;
574
575         /*
576          * HP ZR24w corrupts the first DPCD access after entering power save
577          * mode. Eg. on a read, the entire buffer will be filled with the same
578          * byte. Do a throw away read to avoid corrupting anything we care
579          * about. Afterwards things will work correctly until the monitor
580          * gets woken up and subsequently re-enters power save mode.
581          *
582          * The user pressing any button on the monitor is enough to wake it
583          * up, so there is no particularly good place to do the workaround.
584          * We just have to do it before any DPCD access and hope that the
585          * monitor doesn't power down exactly after the throw away read.
586          */
587         if (!aux->is_remote) {
588                 ret = drm_dp_dpcd_probe(aux, DP_DPCD_REV);
589                 if (ret < 0)
590                         return ret;
591         }
592
593         if (aux->is_remote)
594                 ret = drm_dp_mst_dpcd_read(aux, offset, buffer, size);
595         else
596                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset,
597                                          buffer, size);
598
599         drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, buffer, ret);
600         return ret;
601 }
602 EXPORT_SYMBOL(drm_dp_dpcd_read);
603
604 /**
605  * drm_dp_dpcd_write() - write a series of bytes to the DPCD
606  * @aux: DisplayPort AUX channel (SST or MST)
607  * @offset: address of the (first) register to write
608  * @buffer: buffer containing the values to write
609  * @size: number of bytes in @buffer
610  *
611  * Returns the number of bytes transferred on success, or a negative error
612  * code on failure. -EIO is returned if the request was NAKed by the sink or
613  * if the retry count was exceeded. If not all bytes were transferred, this
614  * function returns -EPROTO. Errors from the underlying AUX channel transfer
615  * function, with the exception of -EBUSY (which causes the transaction to
616  * be retried), are propagated to the caller.
617  */
618 ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
619                           void *buffer, size_t size)
620 {
621         int ret;
622
623         if (aux->is_remote)
624                 ret = drm_dp_mst_dpcd_write(aux, offset, buffer, size);
625         else
626                 ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset,
627                                          buffer, size);
628
629         drm_dp_dump_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer, ret);
630         return ret;
631 }
632 EXPORT_SYMBOL(drm_dp_dpcd_write);
633
634 /**
635  * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
636  * @aux: DisplayPort AUX channel
637  * @status: buffer to store the link status in (must be at least 6 bytes)
638  *
639  * Returns the number of bytes transferred on success or a negative error
640  * code on failure.
641  */
642 int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
643                                  u8 status[DP_LINK_STATUS_SIZE])
644 {
645         return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
646                                 DP_LINK_STATUS_SIZE);
647 }
648 EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
649
650 /**
651  * drm_dp_dpcd_read_phy_link_status - get the link status information for a DP PHY
652  * @aux: DisplayPort AUX channel
653  * @dp_phy: the DP PHY to get the link status for
654  * @link_status: buffer to return the status in
655  *
656  * Fetch the AUX DPCD registers for the DPRX or an LTTPR PHY link status. The
657  * layout of the returned @link_status matches the DPCD register layout of the
658  * DPRX PHY link status.
659  *
660  * Returns 0 if the information was read successfully or a negative error code
661  * on failure.
662  */
663 int drm_dp_dpcd_read_phy_link_status(struct drm_dp_aux *aux,
664                                      enum drm_dp_phy dp_phy,
665                                      u8 link_status[DP_LINK_STATUS_SIZE])
666 {
667         int ret;
668
669         if (dp_phy == DP_PHY_DPRX) {
670                 ret = drm_dp_dpcd_read(aux,
671                                        DP_LANE0_1_STATUS,
672                                        link_status,
673                                        DP_LINK_STATUS_SIZE);
674
675                 if (ret < 0)
676                         return ret;
677
678                 WARN_ON(ret != DP_LINK_STATUS_SIZE);
679
680                 return 0;
681         }
682
683         ret = drm_dp_dpcd_read(aux,
684                                DP_LANE0_1_STATUS_PHY_REPEATER(dp_phy),
685                                link_status,
686                                DP_LINK_STATUS_SIZE - 1);
687
688         if (ret < 0)
689                 return ret;
690
691         WARN_ON(ret != DP_LINK_STATUS_SIZE - 1);
692
693         /* Convert the LTTPR to the sink PHY link status layout */
694         memmove(&link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS + 1],
695                 &link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS],
696                 DP_LINK_STATUS_SIZE - (DP_SINK_STATUS - DP_LANE0_1_STATUS) - 1);
697         link_status[DP_SINK_STATUS - DP_LANE0_1_STATUS] = 0;
698
699         return 0;
700 }
701 EXPORT_SYMBOL(drm_dp_dpcd_read_phy_link_status);
702
703 static bool is_edid_digital_input_dp(const struct edid *edid)
704 {
705         return edid && edid->revision >= 4 &&
706                 edid->input & DRM_EDID_INPUT_DIGITAL &&
707                 (edid->input & DRM_EDID_DIGITAL_TYPE_MASK) == DRM_EDID_DIGITAL_TYPE_DP;
708 }
709
710 /**
711  * drm_dp_downstream_is_type() - is the downstream facing port of certain type?
712  * @dpcd: DisplayPort configuration data
713  * @port_cap: port capabilities
714  * @type: port type to be checked. Can be:
715  *        %DP_DS_PORT_TYPE_DP, %DP_DS_PORT_TYPE_VGA, %DP_DS_PORT_TYPE_DVI,
716  *        %DP_DS_PORT_TYPE_HDMI, %DP_DS_PORT_TYPE_NON_EDID,
717  *        %DP_DS_PORT_TYPE_DP_DUALMODE or %DP_DS_PORT_TYPE_WIRELESS.
718  *
719  * Caveat: Only works with DPCD 1.1+ port caps.
720  *
721  * Returns: whether the downstream facing port matches the type.
722  */
723 bool drm_dp_downstream_is_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
724                                const u8 port_cap[4], u8 type)
725 {
726         return drm_dp_is_branch(dpcd) &&
727                 dpcd[DP_DPCD_REV] >= 0x11 &&
728                 (port_cap[0] & DP_DS_PORT_TYPE_MASK) == type;
729 }
730 EXPORT_SYMBOL(drm_dp_downstream_is_type);
731
732 /**
733  * drm_dp_downstream_is_tmds() - is the downstream facing port TMDS?
734  * @dpcd: DisplayPort configuration data
735  * @port_cap: port capabilities
736  * @edid: EDID
737  *
738  * Returns: whether the downstream facing port is TMDS (HDMI/DVI).
739  */
740 bool drm_dp_downstream_is_tmds(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
741                                const u8 port_cap[4],
742                                const struct edid *edid)
743 {
744         if (dpcd[DP_DPCD_REV] < 0x11) {
745                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
746                 case DP_DWN_STRM_PORT_TYPE_TMDS:
747                         return true;
748                 default:
749                         return false;
750                 }
751         }
752
753         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
754         case DP_DS_PORT_TYPE_DP_DUALMODE:
755                 if (is_edid_digital_input_dp(edid))
756                         return false;
757                 fallthrough;
758         case DP_DS_PORT_TYPE_DVI:
759         case DP_DS_PORT_TYPE_HDMI:
760                 return true;
761         default:
762                 return false;
763         }
764 }
765 EXPORT_SYMBOL(drm_dp_downstream_is_tmds);
766
767 /**
768  * drm_dp_send_real_edid_checksum() - send back real edid checksum value
769  * @aux: DisplayPort AUX channel
770  * @real_edid_checksum: real edid checksum for the last block
771  *
772  * Returns:
773  * True on success
774  */
775 bool drm_dp_send_real_edid_checksum(struct drm_dp_aux *aux,
776                                     u8 real_edid_checksum)
777 {
778         u8 link_edid_read = 0, auto_test_req = 0, test_resp = 0;
779
780         if (drm_dp_dpcd_read(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
781                              &auto_test_req, 1) < 1) {
782                 drm_err(aux->drm_dev, "%s: DPCD failed read at register 0x%x\n",
783                         aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
784                 return false;
785         }
786         auto_test_req &= DP_AUTOMATED_TEST_REQUEST;
787
788         if (drm_dp_dpcd_read(aux, DP_TEST_REQUEST, &link_edid_read, 1) < 1) {
789                 drm_err(aux->drm_dev, "%s: DPCD failed read at register 0x%x\n",
790                         aux->name, DP_TEST_REQUEST);
791                 return false;
792         }
793         link_edid_read &= DP_TEST_LINK_EDID_READ;
794
795         if (!auto_test_req || !link_edid_read) {
796                 drm_dbg_kms(aux->drm_dev, "%s: Source DUT does not support TEST_EDID_READ\n",
797                             aux->name);
798                 return false;
799         }
800
801         if (drm_dp_dpcd_write(aux, DP_DEVICE_SERVICE_IRQ_VECTOR,
802                               &auto_test_req, 1) < 1) {
803                 drm_err(aux->drm_dev, "%s: DPCD failed write at register 0x%x\n",
804                         aux->name, DP_DEVICE_SERVICE_IRQ_VECTOR);
805                 return false;
806         }
807
808         /* send back checksum for the last edid extension block data */
809         if (drm_dp_dpcd_write(aux, DP_TEST_EDID_CHECKSUM,
810                               &real_edid_checksum, 1) < 1) {
811                 drm_err(aux->drm_dev, "%s: DPCD failed write at register 0x%x\n",
812                         aux->name, DP_TEST_EDID_CHECKSUM);
813                 return false;
814         }
815
816         test_resp |= DP_TEST_EDID_CHECKSUM_WRITE;
817         if (drm_dp_dpcd_write(aux, DP_TEST_RESPONSE, &test_resp, 1) < 1) {
818                 drm_err(aux->drm_dev, "%s: DPCD failed write at register 0x%x\n",
819                         aux->name, DP_TEST_RESPONSE);
820                 return false;
821         }
822
823         return true;
824 }
825 EXPORT_SYMBOL(drm_dp_send_real_edid_checksum);
826
827 static u8 drm_dp_downstream_port_count(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
828 {
829         u8 port_count = dpcd[DP_DOWN_STREAM_PORT_COUNT] & DP_PORT_COUNT_MASK;
830
831         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE && port_count > 4)
832                 port_count = 4;
833
834         return port_count;
835 }
836
837 static int drm_dp_read_extended_dpcd_caps(struct drm_dp_aux *aux,
838                                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
839 {
840         u8 dpcd_ext[DP_RECEIVER_CAP_SIZE];
841         int ret;
842
843         /*
844          * Prior to DP1.3 the bit represented by
845          * DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT was reserved.
846          * If it is set DP_DPCD_REV at 0000h could be at a value less than
847          * the true capability of the panel. The only way to check is to
848          * then compare 0000h and 2200h.
849          */
850         if (!(dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
851               DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT))
852                 return 0;
853
854         ret = drm_dp_dpcd_read(aux, DP_DP13_DPCD_REV, &dpcd_ext,
855                                sizeof(dpcd_ext));
856         if (ret < 0)
857                 return ret;
858         if (ret != sizeof(dpcd_ext))
859                 return -EIO;
860
861         if (dpcd[DP_DPCD_REV] > dpcd_ext[DP_DPCD_REV]) {
862                 drm_dbg_kms(aux->drm_dev,
863                             "%s: Extended DPCD rev less than base DPCD rev (%d > %d)\n",
864                             aux->name, dpcd[DP_DPCD_REV], dpcd_ext[DP_DPCD_REV]);
865                 return 0;
866         }
867
868         if (!memcmp(dpcd, dpcd_ext, sizeof(dpcd_ext)))
869                 return 0;
870
871         drm_dbg_kms(aux->drm_dev, "%s: Base DPCD: %*ph\n", aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
872
873         memcpy(dpcd, dpcd_ext, sizeof(dpcd_ext));
874
875         return 0;
876 }
877
878 /**
879  * drm_dp_read_dpcd_caps() - read DPCD caps and extended DPCD caps if
880  * available
881  * @aux: DisplayPort AUX channel
882  * @dpcd: Buffer to store the resulting DPCD in
883  *
884  * Attempts to read the base DPCD caps for @aux. Additionally, this function
885  * checks for and reads the extended DPRX caps (%DP_DP13_DPCD_REV) if
886  * present.
887  *
888  * Returns: %0 if the DPCD was read successfully, negative error code
889  * otherwise.
890  */
891 int drm_dp_read_dpcd_caps(struct drm_dp_aux *aux,
892                           u8 dpcd[DP_RECEIVER_CAP_SIZE])
893 {
894         int ret;
895
896         ret = drm_dp_dpcd_read(aux, DP_DPCD_REV, dpcd, DP_RECEIVER_CAP_SIZE);
897         if (ret < 0)
898                 return ret;
899         if (ret != DP_RECEIVER_CAP_SIZE || dpcd[DP_DPCD_REV] == 0)
900                 return -EIO;
901
902         ret = drm_dp_read_extended_dpcd_caps(aux, dpcd);
903         if (ret < 0)
904                 return ret;
905
906         drm_dbg_kms(aux->drm_dev, "%s: DPCD: %*ph\n", aux->name, DP_RECEIVER_CAP_SIZE, dpcd);
907
908         return ret;
909 }
910 EXPORT_SYMBOL(drm_dp_read_dpcd_caps);
911
912 /**
913  * drm_dp_read_downstream_info() - read DPCD downstream port info if available
914  * @aux: DisplayPort AUX channel
915  * @dpcd: A cached copy of the port's DPCD
916  * @downstream_ports: buffer to store the downstream port info in
917  *
918  * See also:
919  * drm_dp_downstream_max_clock()
920  * drm_dp_downstream_max_bpc()
921  *
922  * Returns: 0 if either the downstream port info was read successfully or
923  * there was no downstream info to read, or a negative error code otherwise.
924  */
925 int drm_dp_read_downstream_info(struct drm_dp_aux *aux,
926                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
927                                 u8 downstream_ports[DP_MAX_DOWNSTREAM_PORTS])
928 {
929         int ret;
930         u8 len;
931
932         memset(downstream_ports, 0, DP_MAX_DOWNSTREAM_PORTS);
933
934         /* No downstream info to read */
935         if (!drm_dp_is_branch(dpcd) || dpcd[DP_DPCD_REV] == DP_DPCD_REV_10)
936                 return 0;
937
938         /* Some branches advertise having 0 downstream ports, despite also advertising they have a
939          * downstream port present. The DP spec isn't clear on if this is allowed or not, but since
940          * some branches do it we need to handle it regardless.
941          */
942         len = drm_dp_downstream_port_count(dpcd);
943         if (!len)
944                 return 0;
945
946         if (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE)
947                 len *= 4;
948
949         ret = drm_dp_dpcd_read(aux, DP_DOWNSTREAM_PORT_0, downstream_ports, len);
950         if (ret < 0)
951                 return ret;
952         if (ret != len)
953                 return -EIO;
954
955         drm_dbg_kms(aux->drm_dev, "%s: DPCD DFP: %*ph\n", aux->name, len, downstream_ports);
956
957         return 0;
958 }
959 EXPORT_SYMBOL(drm_dp_read_downstream_info);
960
961 /**
962  * drm_dp_downstream_max_dotclock() - extract downstream facing port max dot clock
963  * @dpcd: DisplayPort configuration data
964  * @port_cap: port capabilities
965  *
966  * Returns: Downstream facing port max dot clock in kHz on success,
967  * or 0 if max clock not defined
968  */
969 int drm_dp_downstream_max_dotclock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
970                                    const u8 port_cap[4])
971 {
972         if (!drm_dp_is_branch(dpcd))
973                 return 0;
974
975         if (dpcd[DP_DPCD_REV] < 0x11)
976                 return 0;
977
978         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
979         case DP_DS_PORT_TYPE_VGA:
980                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
981                         return 0;
982                 return port_cap[1] * 8000;
983         default:
984                 return 0;
985         }
986 }
987 EXPORT_SYMBOL(drm_dp_downstream_max_dotclock);
988
989 /**
990  * drm_dp_downstream_max_tmds_clock() - extract downstream facing port max TMDS clock
991  * @dpcd: DisplayPort configuration data
992  * @port_cap: port capabilities
993  * @edid: EDID
994  *
995  * Returns: HDMI/DVI downstream facing port max TMDS clock in kHz on success,
996  * or 0 if max TMDS clock not defined
997  */
998 int drm_dp_downstream_max_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
999                                      const u8 port_cap[4],
1000                                      const struct edid *edid)
1001 {
1002         if (!drm_dp_is_branch(dpcd))
1003                 return 0;
1004
1005         if (dpcd[DP_DPCD_REV] < 0x11) {
1006                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
1007                 case DP_DWN_STRM_PORT_TYPE_TMDS:
1008                         return 165000;
1009                 default:
1010                         return 0;
1011                 }
1012         }
1013
1014         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1015         case DP_DS_PORT_TYPE_DP_DUALMODE:
1016                 if (is_edid_digital_input_dp(edid))
1017                         return 0;
1018                 /*
1019                  * It's left up to the driver to check the
1020                  * DP dual mode adapter's max TMDS clock.
1021                  *
1022                  * Unfortunately it looks like branch devices
1023                  * may not fordward that the DP dual mode i2c
1024                  * access so we just usually get i2c nak :(
1025                  */
1026                 fallthrough;
1027         case DP_DS_PORT_TYPE_HDMI:
1028                  /*
1029                   * We should perhaps assume 165 MHz when detailed cap
1030                   * info is not available. But looks like many typical
1031                   * branch devices fall into that category and so we'd
1032                   * probably end up with users complaining that they can't
1033                   * get high resolution modes with their favorite dongle.
1034                   *
1035                   * So let's limit to 300 MHz instead since DPCD 1.4
1036                   * HDMI 2.0 DFPs are required to have the detailed cap
1037                   * info. So it's more likely we're dealing with a HDMI 1.4
1038                   * compatible* device here.
1039                   */
1040                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1041                         return 300000;
1042                 return port_cap[1] * 2500;
1043         case DP_DS_PORT_TYPE_DVI:
1044                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1045                         return 165000;
1046                 /* FIXME what to do about DVI dual link? */
1047                 return port_cap[1] * 2500;
1048         default:
1049                 return 0;
1050         }
1051 }
1052 EXPORT_SYMBOL(drm_dp_downstream_max_tmds_clock);
1053
1054 /**
1055  * drm_dp_downstream_min_tmds_clock() - extract downstream facing port min TMDS clock
1056  * @dpcd: DisplayPort configuration data
1057  * @port_cap: port capabilities
1058  * @edid: EDID
1059  *
1060  * Returns: HDMI/DVI downstream facing port min TMDS clock in kHz on success,
1061  * or 0 if max TMDS clock not defined
1062  */
1063 int drm_dp_downstream_min_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1064                                      const u8 port_cap[4],
1065                                      const struct edid *edid)
1066 {
1067         if (!drm_dp_is_branch(dpcd))
1068                 return 0;
1069
1070         if (dpcd[DP_DPCD_REV] < 0x11) {
1071                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
1072                 case DP_DWN_STRM_PORT_TYPE_TMDS:
1073                         return 25000;
1074                 default:
1075                         return 0;
1076                 }
1077         }
1078
1079         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1080         case DP_DS_PORT_TYPE_DP_DUALMODE:
1081                 if (is_edid_digital_input_dp(edid))
1082                         return 0;
1083                 fallthrough;
1084         case DP_DS_PORT_TYPE_DVI:
1085         case DP_DS_PORT_TYPE_HDMI:
1086                 /*
1087                  * Unclear whether the protocol converter could
1088                  * utilize pixel replication. Assume it won't.
1089                  */
1090                 return 25000;
1091         default:
1092                 return 0;
1093         }
1094 }
1095 EXPORT_SYMBOL(drm_dp_downstream_min_tmds_clock);
1096
1097 /**
1098  * drm_dp_downstream_max_bpc() - extract downstream facing port max
1099  *                               bits per component
1100  * @dpcd: DisplayPort configuration data
1101  * @port_cap: downstream facing port capabilities
1102  * @edid: EDID
1103  *
1104  * Returns: Max bpc on success or 0 if max bpc not defined
1105  */
1106 int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1107                               const u8 port_cap[4],
1108                               const struct edid *edid)
1109 {
1110         if (!drm_dp_is_branch(dpcd))
1111                 return 0;
1112
1113         if (dpcd[DP_DPCD_REV] < 0x11) {
1114                 switch (dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_TYPE_MASK) {
1115                 case DP_DWN_STRM_PORT_TYPE_DP:
1116                         return 0;
1117                 default:
1118                         return 8;
1119                 }
1120         }
1121
1122         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1123         case DP_DS_PORT_TYPE_DP:
1124                 return 0;
1125         case DP_DS_PORT_TYPE_DP_DUALMODE:
1126                 if (is_edid_digital_input_dp(edid))
1127                         return 0;
1128                 fallthrough;
1129         case DP_DS_PORT_TYPE_HDMI:
1130         case DP_DS_PORT_TYPE_DVI:
1131         case DP_DS_PORT_TYPE_VGA:
1132                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1133                         return 8;
1134
1135                 switch (port_cap[2] & DP_DS_MAX_BPC_MASK) {
1136                 case DP_DS_8BPC:
1137                         return 8;
1138                 case DP_DS_10BPC:
1139                         return 10;
1140                 case DP_DS_12BPC:
1141                         return 12;
1142                 case DP_DS_16BPC:
1143                         return 16;
1144                 default:
1145                         return 8;
1146                 }
1147                 break;
1148         default:
1149                 return 8;
1150         }
1151 }
1152 EXPORT_SYMBOL(drm_dp_downstream_max_bpc);
1153
1154 /**
1155  * drm_dp_downstream_420_passthrough() - determine downstream facing port
1156  *                                       YCbCr 4:2:0 pass-through capability
1157  * @dpcd: DisplayPort configuration data
1158  * @port_cap: downstream facing port capabilities
1159  *
1160  * Returns: whether the downstream facing port can pass through YCbCr 4:2:0
1161  */
1162 bool drm_dp_downstream_420_passthrough(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1163                                        const u8 port_cap[4])
1164 {
1165         if (!drm_dp_is_branch(dpcd))
1166                 return false;
1167
1168         if (dpcd[DP_DPCD_REV] < 0x13)
1169                 return false;
1170
1171         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1172         case DP_DS_PORT_TYPE_DP:
1173                 return true;
1174         case DP_DS_PORT_TYPE_HDMI:
1175                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1176                         return false;
1177
1178                 return port_cap[3] & DP_DS_HDMI_YCBCR420_PASS_THROUGH;
1179         default:
1180                 return false;
1181         }
1182 }
1183 EXPORT_SYMBOL(drm_dp_downstream_420_passthrough);
1184
1185 /**
1186  * drm_dp_downstream_444_to_420_conversion() - determine downstream facing port
1187  *                                             YCbCr 4:4:4->4:2:0 conversion capability
1188  * @dpcd: DisplayPort configuration data
1189  * @port_cap: downstream facing port capabilities
1190  *
1191  * Returns: whether the downstream facing port can convert YCbCr 4:4:4 to 4:2:0
1192  */
1193 bool drm_dp_downstream_444_to_420_conversion(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1194                                              const u8 port_cap[4])
1195 {
1196         if (!drm_dp_is_branch(dpcd))
1197                 return false;
1198
1199         if (dpcd[DP_DPCD_REV] < 0x13)
1200                 return false;
1201
1202         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1203         case DP_DS_PORT_TYPE_HDMI:
1204                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1205                         return false;
1206
1207                 return port_cap[3] & DP_DS_HDMI_YCBCR444_TO_420_CONV;
1208         default:
1209                 return false;
1210         }
1211 }
1212 EXPORT_SYMBOL(drm_dp_downstream_444_to_420_conversion);
1213
1214 /**
1215  * drm_dp_downstream_rgb_to_ycbcr_conversion() - determine downstream facing port
1216  *                                               RGB->YCbCr conversion capability
1217  * @dpcd: DisplayPort configuration data
1218  * @port_cap: downstream facing port capabilities
1219  * @color_spc: Colorspace for which conversion cap is sought
1220  *
1221  * Returns: whether the downstream facing port can convert RGB->YCbCr for a given
1222  * colorspace.
1223  */
1224 bool drm_dp_downstream_rgb_to_ycbcr_conversion(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1225                                                const u8 port_cap[4],
1226                                                u8 color_spc)
1227 {
1228         if (!drm_dp_is_branch(dpcd))
1229                 return false;
1230
1231         if (dpcd[DP_DPCD_REV] < 0x13)
1232                 return false;
1233
1234         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1235         case DP_DS_PORT_TYPE_HDMI:
1236                 if ((dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DETAILED_CAP_INFO_AVAILABLE) == 0)
1237                         return false;
1238
1239                 return port_cap[3] & color_spc;
1240         default:
1241                 return false;
1242         }
1243 }
1244 EXPORT_SYMBOL(drm_dp_downstream_rgb_to_ycbcr_conversion);
1245
1246 /**
1247  * drm_dp_downstream_mode() - return a mode for downstream facing port
1248  * @dev: DRM device
1249  * @dpcd: DisplayPort configuration data
1250  * @port_cap: port capabilities
1251  *
1252  * Provides a suitable mode for downstream facing ports without EDID.
1253  *
1254  * Returns: A new drm_display_mode on success or NULL on failure
1255  */
1256 struct drm_display_mode *
1257 drm_dp_downstream_mode(struct drm_device *dev,
1258                        const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1259                        const u8 port_cap[4])
1260
1261 {
1262         u8 vic;
1263
1264         if (!drm_dp_is_branch(dpcd))
1265                 return NULL;
1266
1267         if (dpcd[DP_DPCD_REV] < 0x11)
1268                 return NULL;
1269
1270         switch (port_cap[0] & DP_DS_PORT_TYPE_MASK) {
1271         case DP_DS_PORT_TYPE_NON_EDID:
1272                 switch (port_cap[0] & DP_DS_NON_EDID_MASK) {
1273                 case DP_DS_NON_EDID_720x480i_60:
1274                         vic = 6;
1275                         break;
1276                 case DP_DS_NON_EDID_720x480i_50:
1277                         vic = 21;
1278                         break;
1279                 case DP_DS_NON_EDID_1920x1080i_60:
1280                         vic = 5;
1281                         break;
1282                 case DP_DS_NON_EDID_1920x1080i_50:
1283                         vic = 20;
1284                         break;
1285                 case DP_DS_NON_EDID_1280x720_60:
1286                         vic = 4;
1287                         break;
1288                 case DP_DS_NON_EDID_1280x720_50:
1289                         vic = 19;
1290                         break;
1291                 default:
1292                         return NULL;
1293                 }
1294                 return drm_display_mode_from_cea_vic(dev, vic);
1295         default:
1296                 return NULL;
1297         }
1298 }
1299 EXPORT_SYMBOL(drm_dp_downstream_mode);
1300
1301 /**
1302  * drm_dp_downstream_id() - identify branch device
1303  * @aux: DisplayPort AUX channel
1304  * @id: DisplayPort branch device id
1305  *
1306  * Returns branch device id on success or NULL on failure
1307  */
1308 int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
1309 {
1310         return drm_dp_dpcd_read(aux, DP_BRANCH_ID, id, 6);
1311 }
1312 EXPORT_SYMBOL(drm_dp_downstream_id);
1313
1314 /**
1315  * drm_dp_downstream_debug() - debug DP branch devices
1316  * @m: pointer for debugfs file
1317  * @dpcd: DisplayPort configuration data
1318  * @port_cap: port capabilities
1319  * @edid: EDID
1320  * @aux: DisplayPort AUX channel
1321  *
1322  */
1323 void drm_dp_downstream_debug(struct seq_file *m,
1324                              const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1325                              const u8 port_cap[4],
1326                              const struct edid *edid,
1327                              struct drm_dp_aux *aux)
1328 {
1329         bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
1330                                  DP_DETAILED_CAP_INFO_AVAILABLE;
1331         int clk;
1332         int bpc;
1333         char id[7];
1334         int len;
1335         uint8_t rev[2];
1336         int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
1337         bool branch_device = drm_dp_is_branch(dpcd);
1338
1339         seq_printf(m, "\tDP branch device present: %s\n",
1340                    str_yes_no(branch_device));
1341
1342         if (!branch_device)
1343                 return;
1344
1345         switch (type) {
1346         case DP_DS_PORT_TYPE_DP:
1347                 seq_puts(m, "\t\tType: DisplayPort\n");
1348                 break;
1349         case DP_DS_PORT_TYPE_VGA:
1350                 seq_puts(m, "\t\tType: VGA\n");
1351                 break;
1352         case DP_DS_PORT_TYPE_DVI:
1353                 seq_puts(m, "\t\tType: DVI\n");
1354                 break;
1355         case DP_DS_PORT_TYPE_HDMI:
1356                 seq_puts(m, "\t\tType: HDMI\n");
1357                 break;
1358         case DP_DS_PORT_TYPE_NON_EDID:
1359                 seq_puts(m, "\t\tType: others without EDID support\n");
1360                 break;
1361         case DP_DS_PORT_TYPE_DP_DUALMODE:
1362                 seq_puts(m, "\t\tType: DP++\n");
1363                 break;
1364         case DP_DS_PORT_TYPE_WIRELESS:
1365                 seq_puts(m, "\t\tType: Wireless\n");
1366                 break;
1367         default:
1368                 seq_puts(m, "\t\tType: N/A\n");
1369         }
1370
1371         memset(id, 0, sizeof(id));
1372         drm_dp_downstream_id(aux, id);
1373         seq_printf(m, "\t\tID: %s\n", id);
1374
1375         len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
1376         if (len > 0)
1377                 seq_printf(m, "\t\tHW: %d.%d\n",
1378                            (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
1379
1380         len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
1381         if (len > 0)
1382                 seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
1383
1384         if (detailed_cap_info) {
1385                 clk = drm_dp_downstream_max_dotclock(dpcd, port_cap);
1386                 if (clk > 0)
1387                         seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
1388
1389                 clk = drm_dp_downstream_max_tmds_clock(dpcd, port_cap, edid);
1390                 if (clk > 0)
1391                         seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
1392
1393                 clk = drm_dp_downstream_min_tmds_clock(dpcd, port_cap, edid);
1394                 if (clk > 0)
1395                         seq_printf(m, "\t\tMin TMDS clock: %d kHz\n", clk);
1396
1397                 bpc = drm_dp_downstream_max_bpc(dpcd, port_cap, edid);
1398
1399                 if (bpc > 0)
1400                         seq_printf(m, "\t\tMax bpc: %d\n", bpc);
1401         }
1402 }
1403 EXPORT_SYMBOL(drm_dp_downstream_debug);
1404
1405 /**
1406  * drm_dp_subconnector_type() - get DP branch device type
1407  * @dpcd: DisplayPort configuration data
1408  * @port_cap: port capabilities
1409  */
1410 enum drm_mode_subconnector
1411 drm_dp_subconnector_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1412                          const u8 port_cap[4])
1413 {
1414         int type;
1415         if (!drm_dp_is_branch(dpcd))
1416                 return DRM_MODE_SUBCONNECTOR_Native;
1417         /* DP 1.0 approach */
1418         if (dpcd[DP_DPCD_REV] == DP_DPCD_REV_10) {
1419                 type = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
1420                        DP_DWN_STRM_PORT_TYPE_MASK;
1421
1422                 switch (type) {
1423                 case DP_DWN_STRM_PORT_TYPE_TMDS:
1424                         /* Can be HDMI or DVI-D, DVI-D is a safer option */
1425                         return DRM_MODE_SUBCONNECTOR_DVID;
1426                 case DP_DWN_STRM_PORT_TYPE_ANALOG:
1427                         /* Can be VGA or DVI-A, VGA is more popular */
1428                         return DRM_MODE_SUBCONNECTOR_VGA;
1429                 case DP_DWN_STRM_PORT_TYPE_DP:
1430                         return DRM_MODE_SUBCONNECTOR_DisplayPort;
1431                 case DP_DWN_STRM_PORT_TYPE_OTHER:
1432                 default:
1433                         return DRM_MODE_SUBCONNECTOR_Unknown;
1434                 }
1435         }
1436         type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
1437
1438         switch (type) {
1439         case DP_DS_PORT_TYPE_DP:
1440         case DP_DS_PORT_TYPE_DP_DUALMODE:
1441                 return DRM_MODE_SUBCONNECTOR_DisplayPort;
1442         case DP_DS_PORT_TYPE_VGA:
1443                 return DRM_MODE_SUBCONNECTOR_VGA;
1444         case DP_DS_PORT_TYPE_DVI:
1445                 return DRM_MODE_SUBCONNECTOR_DVID;
1446         case DP_DS_PORT_TYPE_HDMI:
1447                 return DRM_MODE_SUBCONNECTOR_HDMIA;
1448         case DP_DS_PORT_TYPE_WIRELESS:
1449                 return DRM_MODE_SUBCONNECTOR_Wireless;
1450         case DP_DS_PORT_TYPE_NON_EDID:
1451         default:
1452                 return DRM_MODE_SUBCONNECTOR_Unknown;
1453         }
1454 }
1455 EXPORT_SYMBOL(drm_dp_subconnector_type);
1456
1457 /**
1458  * drm_dp_set_subconnector_property - set subconnector for DP connector
1459  * @connector: connector to set property on
1460  * @status: connector status
1461  * @dpcd: DisplayPort configuration data
1462  * @port_cap: port capabilities
1463  *
1464  * Called by a driver on every detect event.
1465  */
1466 void drm_dp_set_subconnector_property(struct drm_connector *connector,
1467                                       enum drm_connector_status status,
1468                                       const u8 *dpcd,
1469                                       const u8 port_cap[4])
1470 {
1471         enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
1472
1473         if (status == connector_status_connected)
1474                 subconnector = drm_dp_subconnector_type(dpcd, port_cap);
1475         drm_object_property_set_value(&connector->base,
1476                         connector->dev->mode_config.dp_subconnector_property,
1477                         subconnector);
1478 }
1479 EXPORT_SYMBOL(drm_dp_set_subconnector_property);
1480
1481 /**
1482  * drm_dp_read_sink_count_cap() - Check whether a given connector has a valid sink
1483  * count
1484  * @connector: The DRM connector to check
1485  * @dpcd: A cached copy of the connector's DPCD RX capabilities
1486  * @desc: A cached copy of the connector's DP descriptor
1487  *
1488  * See also: drm_dp_read_sink_count()
1489  *
1490  * Returns: %True if the (e)DP connector has a valid sink count that should
1491  * be probed, %false otherwise.
1492  */
1493 bool drm_dp_read_sink_count_cap(struct drm_connector *connector,
1494                                 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
1495                                 const struct drm_dp_desc *desc)
1496 {
1497         /* Some eDP panels don't set a valid value for the sink count */
1498         return connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
1499                 dpcd[DP_DPCD_REV] >= DP_DPCD_REV_11 &&
1500                 dpcd[DP_DOWNSTREAMPORT_PRESENT] & DP_DWN_STRM_PORT_PRESENT &&
1501                 !drm_dp_has_quirk(desc, DP_DPCD_QUIRK_NO_SINK_COUNT);
1502 }
1503 EXPORT_SYMBOL(drm_dp_read_sink_count_cap);
1504
1505 /**
1506  * drm_dp_read_sink_count() - Retrieve the sink count for a given sink
1507  * @aux: The DP AUX channel to use
1508  *
1509  * See also: drm_dp_read_sink_count_cap()
1510  *
1511  * Returns: The current sink count reported by @aux, or a negative error code
1512  * otherwise.
1513  */
1514 int drm_dp_read_sink_count(struct drm_dp_aux *aux)
1515 {
1516         u8 count;
1517         int ret;
1518
1519         ret = drm_dp_dpcd_readb(aux, DP_SINK_COUNT, &count);
1520         if (ret < 0)
1521                 return ret;
1522         if (ret != 1)
1523                 return -EIO;
1524
1525         return DP_GET_SINK_COUNT(count);
1526 }
1527 EXPORT_SYMBOL(drm_dp_read_sink_count);
1528
1529 /*
1530  * I2C-over-AUX implementation
1531  */
1532
1533 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
1534 {
1535         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
1536                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
1537                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
1538                I2C_FUNC_10BIT_ADDR;
1539 }
1540
1541 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
1542 {
1543         /*
1544          * In case of i2c defer or short i2c ack reply to a write,
1545          * we need to switch to WRITE_STATUS_UPDATE to drain the
1546          * rest of the message
1547          */
1548         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
1549                 msg->request &= DP_AUX_I2C_MOT;
1550                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
1551         }
1552 }
1553
1554 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
1555 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
1556 #define AUX_STOP_LEN 4
1557 #define AUX_CMD_LEN 4
1558 #define AUX_ADDRESS_LEN 20
1559 #define AUX_REPLY_PAD_LEN 4
1560 #define AUX_LENGTH_LEN 8
1561
1562 /*
1563  * Calculate the duration of the AUX request/reply in usec. Gives the
1564  * "best" case estimate, ie. successful while as short as possible.
1565  */
1566 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
1567 {
1568         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
1569                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
1570
1571         if ((msg->request & DP_AUX_I2C_READ) == 0)
1572                 len += msg->size * 8;
1573
1574         return len;
1575 }
1576
1577 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
1578 {
1579         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
1580                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
1581
1582         /*
1583          * For read we expect what was asked. For writes there will
1584          * be 0 or 1 data bytes. Assume 0 for the "best" case.
1585          */
1586         if (msg->request & DP_AUX_I2C_READ)
1587                 len += msg->size * 8;
1588
1589         return len;
1590 }
1591
1592 #define I2C_START_LEN 1
1593 #define I2C_STOP_LEN 1
1594 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
1595 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
1596
1597 /*
1598  * Calculate the length of the i2c transfer in usec, assuming
1599  * the i2c bus speed is as specified. Gives the the "worst"
1600  * case estimate, ie. successful while as long as possible.
1601  * Doesn't account the "MOT" bit, and instead assumes each
1602  * message includes a START, ADDRESS and STOP. Neither does it
1603  * account for additional random variables such as clock stretching.
1604  */
1605 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
1606                                    int i2c_speed_khz)
1607 {
1608         /* AUX bitrate is 1MHz, i2c bitrate as specified */
1609         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
1610                              msg->size * I2C_DATA_LEN +
1611                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
1612 }
1613
1614 /*
1615  * Determine how many retries should be attempted to successfully transfer
1616  * the specified message, based on the estimated durations of the
1617  * i2c and AUX transfers.
1618  */
1619 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
1620                               int i2c_speed_khz)
1621 {
1622         int aux_time_us = drm_dp_aux_req_duration(msg) +
1623                 drm_dp_aux_reply_duration(msg);
1624         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
1625
1626         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
1627 }
1628
1629 /*
1630  * FIXME currently assumes 10 kHz as some real world devices seem
1631  * to require it. We should query/set the speed via DPCD if supported.
1632  */
1633 static int dp_aux_i2c_speed_khz __read_mostly = 10;
1634 module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
1635 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
1636                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
1637
1638 /*
1639  * Transfer a single I2C-over-AUX message and handle various error conditions,
1640  * retrying the transaction as appropriate.  It is assumed that the
1641  * &drm_dp_aux.transfer function does not modify anything in the msg other than the
1642  * reply field.
1643  *
1644  * Returns bytes transferred on success, or a negative error code on failure.
1645  */
1646 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
1647 {
1648         unsigned int retry, defer_i2c;
1649         int ret;
1650         /*
1651          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
1652          * is required to retry at least seven times upon receiving AUX_DEFER
1653          * before giving up the AUX transaction.
1654          *
1655          * We also try to account for the i2c bus speed.
1656          */
1657         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
1658
1659         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
1660                 ret = aux->transfer(aux, msg);
1661                 if (ret < 0) {
1662                         if (ret == -EBUSY)
1663                                 continue;
1664
1665                         /*
1666                          * While timeouts can be errors, they're usually normal
1667                          * behavior (for instance, when a driver tries to
1668                          * communicate with a non-existent DisplayPort device).
1669                          * Avoid spamming the kernel log with timeout errors.
1670                          */
1671                         if (ret == -ETIMEDOUT)
1672                                 drm_dbg_kms_ratelimited(aux->drm_dev, "%s: transaction timed out\n",
1673                                                         aux->name);
1674                         else
1675                                 drm_dbg_kms(aux->drm_dev, "%s: transaction failed: %d\n",
1676                                             aux->name, ret);
1677                         return ret;
1678                 }
1679
1680
1681                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
1682                 case DP_AUX_NATIVE_REPLY_ACK:
1683                         /*
1684                          * For I2C-over-AUX transactions this isn't enough, we
1685                          * need to check for the I2C ACK reply.
1686                          */
1687                         break;
1688
1689                 case DP_AUX_NATIVE_REPLY_NACK:
1690                         drm_dbg_kms(aux->drm_dev, "%s: native nack (result=%d, size=%zu)\n",
1691                                     aux->name, ret, msg->size);
1692                         return -EREMOTEIO;
1693
1694                 case DP_AUX_NATIVE_REPLY_DEFER:
1695                         drm_dbg_kms(aux->drm_dev, "%s: native defer\n", aux->name);
1696                         /*
1697                          * We could check for I2C bit rate capabilities and if
1698                          * available adjust this interval. We could also be
1699                          * more careful with DP-to-legacy adapters where a
1700                          * long legacy cable may force very low I2C bit rates.
1701                          *
1702                          * For now just defer for long enough to hopefully be
1703                          * safe for all use-cases.
1704                          */
1705                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1706                         continue;
1707
1708                 default:
1709                         drm_err(aux->drm_dev, "%s: invalid native reply %#04x\n",
1710                                 aux->name, msg->reply);
1711                         return -EREMOTEIO;
1712                 }
1713
1714                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
1715                 case DP_AUX_I2C_REPLY_ACK:
1716                         /*
1717                          * Both native ACK and I2C ACK replies received. We
1718                          * can assume the transfer was successful.
1719                          */
1720                         if (ret != msg->size)
1721                                 drm_dp_i2c_msg_write_status_update(msg);
1722                         return ret;
1723
1724                 case DP_AUX_I2C_REPLY_NACK:
1725                         drm_dbg_kms(aux->drm_dev, "%s: I2C nack (result=%d, size=%zu)\n",
1726                                     aux->name, ret, msg->size);
1727                         aux->i2c_nack_count++;
1728                         return -EREMOTEIO;
1729
1730                 case DP_AUX_I2C_REPLY_DEFER:
1731                         drm_dbg_kms(aux->drm_dev, "%s: I2C defer\n", aux->name);
1732                         /* DP Compliance Test 4.2.2.5 Requirement:
1733                          * Must have at least 7 retries for I2C defers on the
1734                          * transaction to pass this test
1735                          */
1736                         aux->i2c_defer_count++;
1737                         if (defer_i2c < 7)
1738                                 defer_i2c++;
1739                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
1740                         drm_dp_i2c_msg_write_status_update(msg);
1741
1742                         continue;
1743
1744                 default:
1745                         drm_err(aux->drm_dev, "%s: invalid I2C reply %#04x\n",
1746                                 aux->name, msg->reply);
1747                         return -EREMOTEIO;
1748                 }
1749         }
1750
1751         drm_dbg_kms(aux->drm_dev, "%s: Too many retries, giving up\n", aux->name);
1752         return -EREMOTEIO;
1753 }
1754
1755 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
1756                                        const struct i2c_msg *i2c_msg)
1757 {
1758         msg->request = (i2c_msg->flags & I2C_M_RD) ?
1759                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
1760         if (!(i2c_msg->flags & I2C_M_STOP))
1761                 msg->request |= DP_AUX_I2C_MOT;
1762 }
1763
1764 /*
1765  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
1766  *
1767  * Returns an error code on failure, or a recommended transfer size on success.
1768  */
1769 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
1770 {
1771         int err, ret = orig_msg->size;
1772         struct drm_dp_aux_msg msg = *orig_msg;
1773
1774         while (msg.size > 0) {
1775                 err = drm_dp_i2c_do_msg(aux, &msg);
1776                 if (err <= 0)
1777                         return err == 0 ? -EPROTO : err;
1778
1779                 if (err < msg.size && err < ret) {
1780                         drm_dbg_kms(aux->drm_dev,
1781                                     "%s: Partial I2C reply: requested %zu bytes got %d bytes\n",
1782                                     aux->name, msg.size, err);
1783                         ret = err;
1784                 }
1785
1786                 msg.size -= err;
1787                 msg.buffer += err;
1788         }
1789
1790         return ret;
1791 }
1792
1793 /*
1794  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
1795  * packets to be as large as possible. If not, the I2C transactions never
1796  * succeed. Hence the default is maximum.
1797  */
1798 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
1799 module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
1800 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
1801                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
1802
1803 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
1804                            int num)
1805 {
1806         struct drm_dp_aux *aux = adapter->algo_data;
1807         unsigned int i, j;
1808         unsigned transfer_size;
1809         struct drm_dp_aux_msg msg;
1810         int err = 0;
1811
1812         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
1813
1814         memset(&msg, 0, sizeof(msg));
1815
1816         for (i = 0; i < num; i++) {
1817                 msg.address = msgs[i].addr;
1818                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1819                 /* Send a bare address packet to start the transaction.
1820                  * Zero sized messages specify an address only (bare
1821                  * address) transaction.
1822                  */
1823                 msg.buffer = NULL;
1824                 msg.size = 0;
1825                 err = drm_dp_i2c_do_msg(aux, &msg);
1826
1827                 /*
1828                  * Reset msg.request in case in case it got
1829                  * changed into a WRITE_STATUS_UPDATE.
1830                  */
1831                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1832
1833                 if (err < 0)
1834                         break;
1835                 /* We want each transaction to be as large as possible, but
1836                  * we'll go to smaller sizes if the hardware gives us a
1837                  * short reply.
1838                  */
1839                 transfer_size = dp_aux_i2c_transfer_size;
1840                 for (j = 0; j < msgs[i].len; j += msg.size) {
1841                         msg.buffer = msgs[i].buf + j;
1842                         msg.size = min(transfer_size, msgs[i].len - j);
1843
1844                         err = drm_dp_i2c_drain_msg(aux, &msg);
1845
1846                         /*
1847                          * Reset msg.request in case in case it got
1848                          * changed into a WRITE_STATUS_UPDATE.
1849                          */
1850                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
1851
1852                         if (err < 0)
1853                                 break;
1854                         transfer_size = err;
1855                 }
1856                 if (err < 0)
1857                         break;
1858         }
1859         if (err >= 0)
1860                 err = num;
1861         /* Send a bare address packet to close out the transaction.
1862          * Zero sized messages specify an address only (bare
1863          * address) transaction.
1864          */
1865         msg.request &= ~DP_AUX_I2C_MOT;
1866         msg.buffer = NULL;
1867         msg.size = 0;
1868         (void)drm_dp_i2c_do_msg(aux, &msg);
1869
1870         return err;
1871 }
1872
1873 static const struct i2c_algorithm drm_dp_i2c_algo = {
1874         .functionality = drm_dp_i2c_functionality,
1875         .master_xfer = drm_dp_i2c_xfer,
1876 };
1877
1878 static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
1879 {
1880         return container_of(i2c, struct drm_dp_aux, ddc);
1881 }
1882
1883 static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
1884 {
1885         mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
1886 }
1887
1888 static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
1889 {
1890         return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
1891 }
1892
1893 static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
1894 {
1895         mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
1896 }
1897
1898 static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
1899         .lock_bus = lock_bus,
1900         .trylock_bus = trylock_bus,
1901         .unlock_bus = unlock_bus,
1902 };
1903
1904 static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
1905 {
1906         u8 buf, count;
1907         int ret;
1908
1909         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1910         if (ret < 0)
1911                 return ret;
1912
1913         WARN_ON(!(buf & DP_TEST_SINK_START));
1914
1915         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
1916         if (ret < 0)
1917                 return ret;
1918
1919         count = buf & DP_TEST_COUNT_MASK;
1920         if (count == aux->crc_count)
1921                 return -EAGAIN; /* No CRC yet */
1922
1923         aux->crc_count = count;
1924
1925         /*
1926          * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
1927          * per component (RGB or CrYCb).
1928          */
1929         ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
1930         if (ret < 0)
1931                 return ret;
1932
1933         return 0;
1934 }
1935
1936 static void drm_dp_aux_crc_work(struct work_struct *work)
1937 {
1938         struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
1939                                               crc_work);
1940         struct drm_crtc *crtc;
1941         u8 crc_bytes[6];
1942         uint32_t crcs[3];
1943         int ret;
1944
1945         if (WARN_ON(!aux->crtc))
1946                 return;
1947
1948         crtc = aux->crtc;
1949         while (crtc->crc.opened) {
1950                 drm_crtc_wait_one_vblank(crtc);
1951                 if (!crtc->crc.opened)
1952                         break;
1953
1954                 ret = drm_dp_aux_get_crc(aux, crc_bytes);
1955                 if (ret == -EAGAIN) {
1956                         usleep_range(1000, 2000);
1957                         ret = drm_dp_aux_get_crc(aux, crc_bytes);
1958                 }
1959
1960                 if (ret == -EAGAIN) {
1961                         drm_dbg_kms(aux->drm_dev, "%s: Get CRC failed after retrying: %d\n",
1962                                     aux->name, ret);
1963                         continue;
1964                 } else if (ret) {
1965                         drm_dbg_kms(aux->drm_dev, "%s: Failed to get a CRC: %d\n", aux->name, ret);
1966                         continue;
1967                 }
1968
1969                 crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
1970                 crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
1971                 crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
1972                 drm_crtc_add_crc_entry(crtc, false, 0, crcs);
1973         }
1974 }
1975
1976 /**
1977  * drm_dp_remote_aux_init() - minimally initialise a remote aux channel
1978  * @aux: DisplayPort AUX channel
1979  *
1980  * Used for remote aux channel in general. Merely initialize the crc work
1981  * struct.
1982  */
1983 void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
1984 {
1985         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
1986 }
1987 EXPORT_SYMBOL(drm_dp_remote_aux_init);
1988
1989 /**
1990  * drm_dp_aux_init() - minimally initialise an aux channel
1991  * @aux: DisplayPort AUX channel
1992  *
1993  * If you need to use the drm_dp_aux's i2c adapter prior to registering it with
1994  * the outside world, call drm_dp_aux_init() first. For drivers which are
1995  * grandparents to their AUX adapters (e.g. the AUX adapter is parented by a
1996  * &drm_connector), you must still call drm_dp_aux_register() once the connector
1997  * has been registered to allow userspace access to the auxiliary DP channel.
1998  * Likewise, for such drivers you should also assign &drm_dp_aux.drm_dev as
1999  * early as possible so that the &drm_device that corresponds to the AUX adapter
2000  * may be mentioned in debugging output from the DRM DP helpers.
2001  *
2002  * For devices which use a separate platform device for their AUX adapters, this
2003  * may be called as early as required by the driver.
2004  *
2005  */
2006 void drm_dp_aux_init(struct drm_dp_aux *aux)
2007 {
2008         mutex_init(&aux->hw_mutex);
2009         mutex_init(&aux->cec.lock);
2010         INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
2011
2012         aux->ddc.algo = &drm_dp_i2c_algo;
2013         aux->ddc.algo_data = aux;
2014         aux->ddc.retries = 3;
2015
2016         aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
2017 }
2018 EXPORT_SYMBOL(drm_dp_aux_init);
2019
2020 /**
2021  * drm_dp_aux_register() - initialise and register aux channel
2022  * @aux: DisplayPort AUX channel
2023  *
2024  * Automatically calls drm_dp_aux_init() if this hasn't been done yet. This
2025  * should only be called once the parent of @aux, &drm_dp_aux.dev, is
2026  * initialized. For devices which are grandparents of their AUX channels,
2027  * &drm_dp_aux.dev will typically be the &drm_connector &device which
2028  * corresponds to @aux. For these devices, it's advised to call
2029  * drm_dp_aux_register() in &drm_connector_funcs.late_register, and likewise to
2030  * call drm_dp_aux_unregister() in &drm_connector_funcs.early_unregister.
2031  * Functions which don't follow this will likely Oops when
2032  * %CONFIG_DRM_DP_AUX_CHARDEV is enabled.
2033  *
2034  * For devices where the AUX channel is a device that exists independently of
2035  * the &drm_device that uses it, such as SoCs and bridge devices, it is
2036  * recommended to call drm_dp_aux_register() after a &drm_device has been
2037  * assigned to &drm_dp_aux.drm_dev, and likewise to call
2038  * drm_dp_aux_unregister() once the &drm_device should no longer be associated
2039  * with the AUX channel (e.g. on bridge detach).
2040  *
2041  * Drivers which need to use the aux channel before either of the two points
2042  * mentioned above need to call drm_dp_aux_init() in order to use the AUX
2043  * channel before registration.
2044  *
2045  * Returns 0 on success or a negative error code on failure.
2046  */
2047 int drm_dp_aux_register(struct drm_dp_aux *aux)
2048 {
2049         int ret;
2050
2051         WARN_ON_ONCE(!aux->drm_dev);
2052
2053         if (!aux->ddc.algo)
2054                 drm_dp_aux_init(aux);
2055
2056         aux->ddc.class = I2C_CLASS_DDC;
2057         aux->ddc.owner = THIS_MODULE;
2058         aux->ddc.dev.parent = aux->dev;
2059
2060         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
2061                 sizeof(aux->ddc.name));
2062
2063         ret = drm_dp_aux_register_devnode(aux);
2064         if (ret)
2065                 return ret;
2066
2067         ret = i2c_add_adapter(&aux->ddc);
2068         if (ret) {
2069                 drm_dp_aux_unregister_devnode(aux);
2070                 return ret;
2071         }
2072
2073         return 0;
2074 }
2075 EXPORT_SYMBOL(drm_dp_aux_register);
2076
2077 /**
2078  * drm_dp_aux_unregister() - unregister an AUX adapter
2079  * @aux: DisplayPort AUX channel
2080  */
2081 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
2082 {
2083         drm_dp_aux_unregister_devnode(aux);
2084         i2c_del_adapter(&aux->ddc);
2085 }
2086 EXPORT_SYMBOL(drm_dp_aux_unregister);
2087
2088 #define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
2089
2090 /**
2091  * drm_dp_psr_setup_time() - PSR setup in time usec
2092  * @psr_cap: PSR capabilities from DPCD
2093  *
2094  * Returns:
2095  * PSR setup time for the panel in microseconds,  negative
2096  * error code on failure.
2097  */
2098 int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
2099 {
2100         static const u16 psr_setup_time_us[] = {
2101                 PSR_SETUP_TIME(330),
2102                 PSR_SETUP_TIME(275),
2103                 PSR_SETUP_TIME(220),
2104                 PSR_SETUP_TIME(165),
2105                 PSR_SETUP_TIME(110),
2106                 PSR_SETUP_TIME(55),
2107                 PSR_SETUP_TIME(0),
2108         };
2109         int i;
2110
2111         i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
2112         if (i >= ARRAY_SIZE(psr_setup_time_us))
2113                 return -EINVAL;
2114
2115         return psr_setup_time_us[i];
2116 }
2117 EXPORT_SYMBOL(drm_dp_psr_setup_time);
2118
2119 #undef PSR_SETUP_TIME
2120
2121 /**
2122  * drm_dp_start_crc() - start capture of frame CRCs
2123  * @aux: DisplayPort AUX channel
2124  * @crtc: CRTC displaying the frames whose CRCs are to be captured
2125  *
2126  * Returns 0 on success or a negative error code on failure.
2127  */
2128 int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
2129 {
2130         u8 buf;
2131         int ret;
2132
2133         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
2134         if (ret < 0)
2135                 return ret;
2136
2137         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
2138         if (ret < 0)
2139                 return ret;
2140
2141         aux->crc_count = 0;
2142         aux->crtc = crtc;
2143         schedule_work(&aux->crc_work);
2144
2145         return 0;
2146 }
2147 EXPORT_SYMBOL(drm_dp_start_crc);
2148
2149 /**
2150  * drm_dp_stop_crc() - stop capture of frame CRCs
2151  * @aux: DisplayPort AUX channel
2152  *
2153  * Returns 0 on success or a negative error code on failure.
2154  */
2155 int drm_dp_stop_crc(struct drm_dp_aux *aux)
2156 {
2157         u8 buf;
2158         int ret;
2159
2160         ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
2161         if (ret < 0)
2162                 return ret;
2163
2164         ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
2165         if (ret < 0)
2166                 return ret;
2167
2168         flush_work(&aux->crc_work);
2169         aux->crtc = NULL;
2170
2171         return 0;
2172 }
2173 EXPORT_SYMBOL(drm_dp_stop_crc);
2174
2175 struct dpcd_quirk {
2176         u8 oui[3];
2177         u8 device_id[6];
2178         bool is_branch;
2179         u32 quirks;
2180 };
2181
2182 #define OUI(first, second, third) { (first), (second), (third) }
2183 #define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
2184         { (first), (second), (third), (fourth), (fifth), (sixth) }
2185
2186 #define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
2187
2188 static const struct dpcd_quirk dpcd_quirk_list[] = {
2189         /* Analogix 7737 needs reduced M and N at HBR2 link rates */
2190         { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
2191         /* LG LP140WF6-SPM1 eDP panel */
2192         { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
2193         /* Apple panels need some additional handling to support PSR */
2194         { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
2195         /* CH7511 seems to leave SINK_COUNT zeroed */
2196         { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
2197         /* Synaptics DP1.4 MST hubs can support DSC without virtual DPCD */
2198         { OUI(0x90, 0xCC, 0x24), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) },
2199         /* Apple MacBookPro 2017 15 inch eDP Retina panel reports too low DP_MAX_LINK_RATE */
2200         { 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) },
2201 };
2202
2203 #undef OUI
2204
2205 /*
2206  * Get a bit mask of DPCD quirks for the sink/branch device identified by
2207  * ident. The quirk data is shared but it's up to the drivers to act on the
2208  * data.
2209  *
2210  * For now, only the OUI (first three bytes) is used, but this may be extended
2211  * to device identification string and hardware/firmware revisions later.
2212  */
2213 static u32
2214 drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
2215 {
2216         const struct dpcd_quirk *quirk;
2217         u32 quirks = 0;
2218         int i;
2219         u8 any_device[] = DEVICE_ID_ANY;
2220
2221         for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
2222                 quirk = &dpcd_quirk_list[i];
2223
2224                 if (quirk->is_branch != is_branch)
2225                         continue;
2226
2227                 if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
2228                         continue;
2229
2230                 if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
2231                     memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
2232                         continue;
2233
2234                 quirks |= quirk->quirks;
2235         }
2236
2237         return quirks;
2238 }
2239
2240 #undef DEVICE_ID_ANY
2241 #undef DEVICE_ID
2242
2243 /**
2244  * drm_dp_read_desc - read sink/branch descriptor from DPCD
2245  * @aux: DisplayPort AUX channel
2246  * @desc: Device descriptor to fill from DPCD
2247  * @is_branch: true for branch devices, false for sink devices
2248  *
2249  * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
2250  * identification.
2251  *
2252  * Returns 0 on success or a negative error code on failure.
2253  */
2254 int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
2255                      bool is_branch)
2256 {
2257         struct drm_dp_dpcd_ident *ident = &desc->ident;
2258         unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
2259         int ret, dev_id_len;
2260
2261         ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
2262         if (ret < 0)
2263                 return ret;
2264
2265         desc->quirks = drm_dp_get_quirks(ident, is_branch);
2266
2267         dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
2268
2269         drm_dbg_kms(aux->drm_dev,
2270                     "%s: DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
2271                     aux->name, is_branch ? "branch" : "sink",
2272                     (int)sizeof(ident->oui), ident->oui, dev_id_len,
2273                     ident->device_id, ident->hw_rev >> 4, ident->hw_rev & 0xf,
2274                     ident->sw_major_rev, ident->sw_minor_rev, desc->quirks);
2275
2276         return 0;
2277 }
2278 EXPORT_SYMBOL(drm_dp_read_desc);
2279
2280 /**
2281  * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
2282  * supported by the DSC sink.
2283  * @dsc_dpcd: DSC capabilities from DPCD
2284  * @is_edp: true if its eDP, false for DP
2285  *
2286  * Read the slice capabilities DPCD register from DSC sink to get
2287  * the maximum slice count supported. This is used to populate
2288  * the DSC parameters in the &struct drm_dsc_config by the driver.
2289  * Driver creates an infoframe using these parameters to populate
2290  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2291  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2292  *
2293  * Returns:
2294  * Maximum slice count supported by DSC sink or 0 its invalid
2295  */
2296 u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
2297                                    bool is_edp)
2298 {
2299         u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
2300
2301         if (is_edp) {
2302                 /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
2303                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
2304                         return 4;
2305                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
2306                         return 2;
2307                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
2308                         return 1;
2309         } else {
2310                 /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
2311                 u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
2312
2313                 if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
2314                         return 24;
2315                 if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
2316                         return 20;
2317                 if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
2318                         return 16;
2319                 if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
2320                         return 12;
2321                 if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
2322                         return 10;
2323                 if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
2324                         return 8;
2325                 if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
2326                         return 6;
2327                 if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
2328                         return 4;
2329                 if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
2330                         return 2;
2331                 if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
2332                         return 1;
2333         }
2334
2335         return 0;
2336 }
2337 EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
2338
2339 /**
2340  * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
2341  * @dsc_dpcd: DSC capabilities from DPCD
2342  *
2343  * Read the DSC DPCD register to parse the line buffer depth in bits which is
2344  * number of bits of precision within the decoder line buffer supported by
2345  * the DSC sink. This is used to populate the DSC parameters in the
2346  * &struct drm_dsc_config by the driver.
2347  * Driver creates an infoframe using these parameters to populate
2348  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2349  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2350  *
2351  * Returns:
2352  * Line buffer depth supported by DSC panel or 0 its invalid
2353  */
2354 u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
2355 {
2356         u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
2357
2358         switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
2359         case DP_DSC_LINE_BUF_BIT_DEPTH_9:
2360                 return 9;
2361         case DP_DSC_LINE_BUF_BIT_DEPTH_10:
2362                 return 10;
2363         case DP_DSC_LINE_BUF_BIT_DEPTH_11:
2364                 return 11;
2365         case DP_DSC_LINE_BUF_BIT_DEPTH_12:
2366                 return 12;
2367         case DP_DSC_LINE_BUF_BIT_DEPTH_13:
2368                 return 13;
2369         case DP_DSC_LINE_BUF_BIT_DEPTH_14:
2370                 return 14;
2371         case DP_DSC_LINE_BUF_BIT_DEPTH_15:
2372                 return 15;
2373         case DP_DSC_LINE_BUF_BIT_DEPTH_16:
2374                 return 16;
2375         case DP_DSC_LINE_BUF_BIT_DEPTH_8:
2376                 return 8;
2377         }
2378
2379         return 0;
2380 }
2381 EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
2382
2383 /**
2384  * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
2385  * values supported by the DSC sink.
2386  * @dsc_dpcd: DSC capabilities from DPCD
2387  * @dsc_bpc: An array to be filled by this helper with supported
2388  *           input bpcs.
2389  *
2390  * Read the DSC DPCD from the sink device to parse the supported bits per
2391  * component values. This is used to populate the DSC parameters
2392  * in the &struct drm_dsc_config by the driver.
2393  * Driver creates an infoframe using these parameters to populate
2394  * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
2395  * infoframe using the helper function drm_dsc_pps_infoframe_pack()
2396  *
2397  * Returns:
2398  * Number of input BPC values parsed from the DPCD
2399  */
2400 int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
2401                                          u8 dsc_bpc[3])
2402 {
2403         int num_bpc = 0;
2404         u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
2405
2406         if (color_depth & DP_DSC_12_BPC)
2407                 dsc_bpc[num_bpc++] = 12;
2408         if (color_depth & DP_DSC_10_BPC)
2409                 dsc_bpc[num_bpc++] = 10;
2410         if (color_depth & DP_DSC_8_BPC)
2411                 dsc_bpc[num_bpc++] = 8;
2412
2413         return num_bpc;
2414 }
2415 EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);
2416
2417 static int drm_dp_read_lttpr_regs(struct drm_dp_aux *aux,
2418                                   const u8 dpcd[DP_RECEIVER_CAP_SIZE], int address,
2419                                   u8 *buf, int buf_size)
2420 {
2421         /*
2422          * At least the DELL P2715Q monitor with a DPCD_REV < 0x14 returns
2423          * corrupted values when reading from the 0xF0000- range with a block
2424          * size bigger than 1.
2425          */
2426         int block_size = dpcd[DP_DPCD_REV] < 0x14 ? 1 : buf_size;
2427         int offset;
2428         int ret;
2429
2430         for (offset = 0; offset < buf_size; offset += block_size) {
2431                 ret = drm_dp_dpcd_read(aux,
2432                                        address + offset,
2433                                        &buf[offset], block_size);
2434                 if (ret < 0)
2435                         return ret;
2436
2437                 WARN_ON(ret != block_size);
2438         }
2439
2440         return 0;
2441 }
2442
2443 /**
2444  * drm_dp_read_lttpr_common_caps - read the LTTPR common capabilities
2445  * @aux: DisplayPort AUX channel
2446  * @dpcd: DisplayPort configuration data
2447  * @caps: buffer to return the capability info in
2448  *
2449  * Read capabilities common to all LTTPRs.
2450  *
2451  * Returns 0 on success or a negative error code on failure.
2452  */
2453 int drm_dp_read_lttpr_common_caps(struct drm_dp_aux *aux,
2454                                   const u8 dpcd[DP_RECEIVER_CAP_SIZE],
2455                                   u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2456 {
2457         return drm_dp_read_lttpr_regs(aux, dpcd,
2458                                       DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV,
2459                                       caps, DP_LTTPR_COMMON_CAP_SIZE);
2460 }
2461 EXPORT_SYMBOL(drm_dp_read_lttpr_common_caps);
2462
2463 /**
2464  * drm_dp_read_lttpr_phy_caps - read the capabilities for a given LTTPR PHY
2465  * @aux: DisplayPort AUX channel
2466  * @dpcd: DisplayPort configuration data
2467  * @dp_phy: LTTPR PHY to read the capabilities for
2468  * @caps: buffer to return the capability info in
2469  *
2470  * Read the capabilities for the given LTTPR PHY.
2471  *
2472  * Returns 0 on success or a negative error code on failure.
2473  */
2474 int drm_dp_read_lttpr_phy_caps(struct drm_dp_aux *aux,
2475                                const u8 dpcd[DP_RECEIVER_CAP_SIZE],
2476                                enum drm_dp_phy dp_phy,
2477                                u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2478 {
2479         return drm_dp_read_lttpr_regs(aux, dpcd,
2480                                       DP_TRAINING_AUX_RD_INTERVAL_PHY_REPEATER(dp_phy),
2481                                       caps, DP_LTTPR_PHY_CAP_SIZE);
2482 }
2483 EXPORT_SYMBOL(drm_dp_read_lttpr_phy_caps);
2484
2485 static u8 dp_lttpr_common_cap(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE], int r)
2486 {
2487         return caps[r - DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV];
2488 }
2489
2490 /**
2491  * drm_dp_lttpr_count - get the number of detected LTTPRs
2492  * @caps: LTTPR common capabilities
2493  *
2494  * Get the number of detected LTTPRs from the LTTPR common capabilities info.
2495  *
2496  * Returns:
2497  *   -ERANGE if more than supported number (8) of LTTPRs are detected
2498  *   -EINVAL if the DP_PHY_REPEATER_CNT register contains an invalid value
2499  *   otherwise the number of detected LTTPRs
2500  */
2501 int drm_dp_lttpr_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2502 {
2503         u8 count = dp_lttpr_common_cap(caps, DP_PHY_REPEATER_CNT);
2504
2505         switch (hweight8(count)) {
2506         case 0:
2507                 return 0;
2508         case 1:
2509                 return 8 - ilog2(count);
2510         case 8:
2511                 return -ERANGE;
2512         default:
2513                 return -EINVAL;
2514         }
2515 }
2516 EXPORT_SYMBOL(drm_dp_lttpr_count);
2517
2518 /**
2519  * drm_dp_lttpr_max_link_rate - get the maximum link rate supported by all LTTPRs
2520  * @caps: LTTPR common capabilities
2521  *
2522  * Returns the maximum link rate supported by all detected LTTPRs.
2523  */
2524 int drm_dp_lttpr_max_link_rate(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2525 {
2526         u8 rate = dp_lttpr_common_cap(caps, DP_MAX_LINK_RATE_PHY_REPEATER);
2527
2528         return drm_dp_bw_code_to_link_rate(rate);
2529 }
2530 EXPORT_SYMBOL(drm_dp_lttpr_max_link_rate);
2531
2532 /**
2533  * drm_dp_lttpr_max_lane_count - get the maximum lane count supported by all LTTPRs
2534  * @caps: LTTPR common capabilities
2535  *
2536  * Returns the maximum lane count supported by all detected LTTPRs.
2537  */
2538 int drm_dp_lttpr_max_lane_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
2539 {
2540         u8 max_lanes = dp_lttpr_common_cap(caps, DP_MAX_LANE_COUNT_PHY_REPEATER);
2541
2542         return max_lanes & DP_MAX_LANE_COUNT_MASK;
2543 }
2544 EXPORT_SYMBOL(drm_dp_lttpr_max_lane_count);
2545
2546 /**
2547  * drm_dp_lttpr_voltage_swing_level_3_supported - check for LTTPR vswing3 support
2548  * @caps: LTTPR PHY capabilities
2549  *
2550  * Returns true if the @caps for an LTTPR TX PHY indicate support for
2551  * voltage swing level 3.
2552  */
2553 bool
2554 drm_dp_lttpr_voltage_swing_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2555 {
2556         u8 txcap = dp_lttpr_phy_cap(caps, DP_TRANSMITTER_CAPABILITY_PHY_REPEATER1);
2557
2558         return txcap & DP_VOLTAGE_SWING_LEVEL_3_SUPPORTED;
2559 }
2560 EXPORT_SYMBOL(drm_dp_lttpr_voltage_swing_level_3_supported);
2561
2562 /**
2563  * drm_dp_lttpr_pre_emphasis_level_3_supported - check for LTTPR preemph3 support
2564  * @caps: LTTPR PHY capabilities
2565  *
2566  * Returns true if the @caps for an LTTPR TX PHY indicate support for
2567  * pre-emphasis level 3.
2568  */
2569 bool
2570 drm_dp_lttpr_pre_emphasis_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
2571 {
2572         u8 txcap = dp_lttpr_phy_cap(caps, DP_TRANSMITTER_CAPABILITY_PHY_REPEATER1);
2573
2574         return txcap & DP_PRE_EMPHASIS_LEVEL_3_SUPPORTED;
2575 }
2576 EXPORT_SYMBOL(drm_dp_lttpr_pre_emphasis_level_3_supported);
2577
2578 /**
2579  * drm_dp_get_phy_test_pattern() - get the requested pattern from the sink.
2580  * @aux: DisplayPort AUX channel
2581  * @data: DP phy compliance test parameters.
2582  *
2583  * Returns 0 on success or a negative error code on failure.
2584  */
2585 int drm_dp_get_phy_test_pattern(struct drm_dp_aux *aux,
2586                                 struct drm_dp_phy_test_params *data)
2587 {
2588         int err;
2589         u8 rate, lanes;
2590
2591         err = drm_dp_dpcd_readb(aux, DP_TEST_LINK_RATE, &rate);
2592         if (err < 0)
2593                 return err;
2594         data->link_rate = drm_dp_bw_code_to_link_rate(rate);
2595
2596         err = drm_dp_dpcd_readb(aux, DP_TEST_LANE_COUNT, &lanes);
2597         if (err < 0)
2598                 return err;
2599         data->num_lanes = lanes & DP_MAX_LANE_COUNT_MASK;
2600
2601         if (lanes & DP_ENHANCED_FRAME_CAP)
2602                 data->enhanced_frame_cap = true;
2603
2604         err = drm_dp_dpcd_readb(aux, DP_PHY_TEST_PATTERN, &data->phy_pattern);
2605         if (err < 0)
2606                 return err;
2607
2608         switch (data->phy_pattern) {
2609         case DP_PHY_TEST_PATTERN_80BIT_CUSTOM:
2610                 err = drm_dp_dpcd_read(aux, DP_TEST_80BIT_CUSTOM_PATTERN_7_0,
2611                                        &data->custom80, sizeof(data->custom80));
2612                 if (err < 0)
2613                         return err;
2614
2615                 break;
2616         case DP_PHY_TEST_PATTERN_CP2520:
2617                 err = drm_dp_dpcd_read(aux, DP_TEST_HBR2_SCRAMBLER_RESET,
2618                                        &data->hbr2_reset,
2619                                        sizeof(data->hbr2_reset));
2620                 if (err < 0)
2621                         return err;
2622         }
2623
2624         return 0;
2625 }
2626 EXPORT_SYMBOL(drm_dp_get_phy_test_pattern);
2627
2628 /**
2629  * drm_dp_set_phy_test_pattern() - set the pattern to the sink.
2630  * @aux: DisplayPort AUX channel
2631  * @data: DP phy compliance test parameters.
2632  * @dp_rev: DP revision to use for compliance testing
2633  *
2634  * Returns 0 on success or a negative error code on failure.
2635  */
2636 int drm_dp_set_phy_test_pattern(struct drm_dp_aux *aux,
2637                                 struct drm_dp_phy_test_params *data, u8 dp_rev)
2638 {
2639         int err, i;
2640         u8 link_config[2];
2641         u8 test_pattern;
2642
2643         link_config[0] = drm_dp_link_rate_to_bw_code(data->link_rate);
2644         link_config[1] = data->num_lanes;
2645         if (data->enhanced_frame_cap)
2646                 link_config[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
2647         err = drm_dp_dpcd_write(aux, DP_LINK_BW_SET, link_config, 2);
2648         if (err < 0)
2649                 return err;
2650
2651         test_pattern = data->phy_pattern;
2652         if (dp_rev < 0x12) {
2653                 test_pattern = (test_pattern << 2) &
2654                                DP_LINK_QUAL_PATTERN_11_MASK;
2655                 err = drm_dp_dpcd_writeb(aux, DP_TRAINING_PATTERN_SET,
2656                                          test_pattern);
2657                 if (err < 0)
2658                         return err;
2659         } else {
2660                 for (i = 0; i < data->num_lanes; i++) {
2661                         err = drm_dp_dpcd_writeb(aux,
2662                                                  DP_LINK_QUAL_LANE0_SET + i,
2663                                                  test_pattern);
2664                         if (err < 0)
2665                                 return err;
2666                 }
2667         }
2668
2669         return 0;
2670 }
2671 EXPORT_SYMBOL(drm_dp_set_phy_test_pattern);
2672
2673 static const char *dp_pixelformat_get_name(enum dp_pixelformat pixelformat)
2674 {
2675         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
2676                 return "Invalid";
2677
2678         switch (pixelformat) {
2679         case DP_PIXELFORMAT_RGB:
2680                 return "RGB";
2681         case DP_PIXELFORMAT_YUV444:
2682                 return "YUV444";
2683         case DP_PIXELFORMAT_YUV422:
2684                 return "YUV422";
2685         case DP_PIXELFORMAT_YUV420:
2686                 return "YUV420";
2687         case DP_PIXELFORMAT_Y_ONLY:
2688                 return "Y_ONLY";
2689         case DP_PIXELFORMAT_RAW:
2690                 return "RAW";
2691         default:
2692                 return "Reserved";
2693         }
2694 }
2695
2696 static const char *dp_colorimetry_get_name(enum dp_pixelformat pixelformat,
2697                                            enum dp_colorimetry colorimetry)
2698 {
2699         if (pixelformat < 0 || pixelformat > DP_PIXELFORMAT_RESERVED)
2700                 return "Invalid";
2701
2702         switch (colorimetry) {
2703         case DP_COLORIMETRY_DEFAULT:
2704                 switch (pixelformat) {
2705                 case DP_PIXELFORMAT_RGB:
2706                         return "sRGB";
2707                 case DP_PIXELFORMAT_YUV444:
2708                 case DP_PIXELFORMAT_YUV422:
2709                 case DP_PIXELFORMAT_YUV420:
2710                         return "BT.601";
2711                 case DP_PIXELFORMAT_Y_ONLY:
2712                         return "DICOM PS3.14";
2713                 case DP_PIXELFORMAT_RAW:
2714                         return "Custom Color Profile";
2715                 default:
2716                         return "Reserved";
2717                 }
2718         case DP_COLORIMETRY_RGB_WIDE_FIXED: /* and DP_COLORIMETRY_BT709_YCC */
2719                 switch (pixelformat) {
2720                 case DP_PIXELFORMAT_RGB:
2721                         return "Wide Fixed";
2722                 case DP_PIXELFORMAT_YUV444:
2723                 case DP_PIXELFORMAT_YUV422:
2724                 case DP_PIXELFORMAT_YUV420:
2725                         return "BT.709";
2726                 default:
2727                         return "Reserved";
2728                 }
2729         case DP_COLORIMETRY_RGB_WIDE_FLOAT: /* and DP_COLORIMETRY_XVYCC_601 */
2730                 switch (pixelformat) {
2731                 case DP_PIXELFORMAT_RGB:
2732                         return "Wide Float";
2733                 case DP_PIXELFORMAT_YUV444:
2734                 case DP_PIXELFORMAT_YUV422:
2735                 case DP_PIXELFORMAT_YUV420:
2736                         return "xvYCC 601";
2737                 default:
2738                         return "Reserved";
2739                 }
2740         case DP_COLORIMETRY_OPRGB: /* and DP_COLORIMETRY_XVYCC_709 */
2741                 switch (pixelformat) {
2742                 case DP_PIXELFORMAT_RGB:
2743                         return "OpRGB";
2744                 case DP_PIXELFORMAT_YUV444:
2745                 case DP_PIXELFORMAT_YUV422:
2746                 case DP_PIXELFORMAT_YUV420:
2747                         return "xvYCC 709";
2748                 default:
2749                         return "Reserved";
2750                 }
2751         case DP_COLORIMETRY_DCI_P3_RGB: /* and DP_COLORIMETRY_SYCC_601 */
2752                 switch (pixelformat) {
2753                 case DP_PIXELFORMAT_RGB:
2754                         return "DCI-P3";
2755                 case DP_PIXELFORMAT_YUV444:
2756                 case DP_PIXELFORMAT_YUV422:
2757                 case DP_PIXELFORMAT_YUV420:
2758                         return "sYCC 601";
2759                 default:
2760                         return "Reserved";
2761                 }
2762         case DP_COLORIMETRY_RGB_CUSTOM: /* and DP_COLORIMETRY_OPYCC_601 */
2763                 switch (pixelformat) {
2764                 case DP_PIXELFORMAT_RGB:
2765                         return "Custom Profile";
2766                 case DP_PIXELFORMAT_YUV444:
2767                 case DP_PIXELFORMAT_YUV422:
2768                 case DP_PIXELFORMAT_YUV420:
2769                         return "OpYCC 601";
2770                 default:
2771                         return "Reserved";
2772                 }
2773         case DP_COLORIMETRY_BT2020_RGB: /* and DP_COLORIMETRY_BT2020_CYCC */
2774                 switch (pixelformat) {
2775                 case DP_PIXELFORMAT_RGB:
2776                         return "BT.2020 RGB";
2777                 case DP_PIXELFORMAT_YUV444:
2778                 case DP_PIXELFORMAT_YUV422:
2779                 case DP_PIXELFORMAT_YUV420:
2780                         return "BT.2020 CYCC";
2781                 default:
2782                         return "Reserved";
2783                 }
2784         case DP_COLORIMETRY_BT2020_YCC:
2785                 switch (pixelformat) {
2786                 case DP_PIXELFORMAT_YUV444:
2787                 case DP_PIXELFORMAT_YUV422:
2788                 case DP_PIXELFORMAT_YUV420:
2789                         return "BT.2020 YCC";
2790                 default:
2791                         return "Reserved";
2792                 }
2793         default:
2794                 return "Invalid";
2795         }
2796 }
2797
2798 static const char *dp_dynamic_range_get_name(enum dp_dynamic_range dynamic_range)
2799 {
2800         switch (dynamic_range) {
2801         case DP_DYNAMIC_RANGE_VESA:
2802                 return "VESA range";
2803         case DP_DYNAMIC_RANGE_CTA:
2804                 return "CTA range";
2805         default:
2806                 return "Invalid";
2807         }
2808 }
2809
2810 static const char *dp_content_type_get_name(enum dp_content_type content_type)
2811 {
2812         switch (content_type) {
2813         case DP_CONTENT_TYPE_NOT_DEFINED:
2814                 return "Not defined";
2815         case DP_CONTENT_TYPE_GRAPHICS:
2816                 return "Graphics";
2817         case DP_CONTENT_TYPE_PHOTO:
2818                 return "Photo";
2819         case DP_CONTENT_TYPE_VIDEO:
2820                 return "Video";
2821         case DP_CONTENT_TYPE_GAME:
2822                 return "Game";
2823         default:
2824                 return "Reserved";
2825         }
2826 }
2827
2828 void drm_dp_vsc_sdp_log(const char *level, struct device *dev,
2829                         const struct drm_dp_vsc_sdp *vsc)
2830 {
2831 #define DP_SDP_LOG(fmt, ...) dev_printk(level, dev, fmt, ##__VA_ARGS__)
2832         DP_SDP_LOG("DP SDP: %s, revision %u, length %u\n", "VSC",
2833                    vsc->revision, vsc->length);
2834         DP_SDP_LOG("    pixelformat: %s\n",
2835                    dp_pixelformat_get_name(vsc->pixelformat));
2836         DP_SDP_LOG("    colorimetry: %s\n",
2837                    dp_colorimetry_get_name(vsc->pixelformat, vsc->colorimetry));
2838         DP_SDP_LOG("    bpc: %u\n", vsc->bpc);
2839         DP_SDP_LOG("    dynamic range: %s\n",
2840                    dp_dynamic_range_get_name(vsc->dynamic_range));
2841         DP_SDP_LOG("    content type: %s\n",
2842                    dp_content_type_get_name(vsc->content_type));
2843 #undef DP_SDP_LOG
2844 }
2845 EXPORT_SYMBOL(drm_dp_vsc_sdp_log);
2846
2847 /**
2848  * drm_dp_get_pcon_max_frl_bw() - maximum frl supported by PCON
2849  * @dpcd: DisplayPort configuration data
2850  * @port_cap: port capabilities
2851  *
2852  * Returns maximum frl bandwidth supported by PCON in GBPS,
2853  * returns 0 if not supported.
2854  */
2855 int drm_dp_get_pcon_max_frl_bw(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
2856                                const u8 port_cap[4])
2857 {
2858         int bw;
2859         u8 buf;
2860
2861         buf = port_cap[2];
2862         bw = buf & DP_PCON_MAX_FRL_BW;
2863
2864         switch (bw) {
2865         case DP_PCON_MAX_9GBPS:
2866                 return 9;
2867         case DP_PCON_MAX_18GBPS:
2868                 return 18;
2869         case DP_PCON_MAX_24GBPS:
2870                 return 24;
2871         case DP_PCON_MAX_32GBPS:
2872                 return 32;
2873         case DP_PCON_MAX_40GBPS:
2874                 return 40;
2875         case DP_PCON_MAX_48GBPS:
2876                 return 48;
2877         case DP_PCON_MAX_0GBPS:
2878         default:
2879                 return 0;
2880         }
2881
2882         return 0;
2883 }
2884 EXPORT_SYMBOL(drm_dp_get_pcon_max_frl_bw);
2885
2886 /**
2887  * drm_dp_pcon_frl_prepare() - Prepare PCON for FRL.
2888  * @aux: DisplayPort AUX channel
2889  * @enable_frl_ready_hpd: Configure DP_PCON_ENABLE_HPD_READY.
2890  *
2891  * Returns 0 if success, else returns negative error code.
2892  */
2893 int drm_dp_pcon_frl_prepare(struct drm_dp_aux *aux, bool enable_frl_ready_hpd)
2894 {
2895         int ret;
2896         u8 buf = DP_PCON_ENABLE_SOURCE_CTL_MODE |
2897                  DP_PCON_ENABLE_LINK_FRL_MODE;
2898
2899         if (enable_frl_ready_hpd)
2900                 buf |= DP_PCON_ENABLE_HPD_READY;
2901
2902         ret = drm_dp_dpcd_writeb(aux, DP_PCON_HDMI_LINK_CONFIG_1, buf);
2903
2904         return ret;
2905 }
2906 EXPORT_SYMBOL(drm_dp_pcon_frl_prepare);
2907
2908 /**
2909  * drm_dp_pcon_is_frl_ready() - Is PCON ready for FRL
2910  * @aux: DisplayPort AUX channel
2911  *
2912  * Returns true if success, else returns false.
2913  */
2914 bool drm_dp_pcon_is_frl_ready(struct drm_dp_aux *aux)
2915 {
2916         int ret;
2917         u8 buf;
2918
2919         ret = drm_dp_dpcd_readb(aux, DP_PCON_HDMI_TX_LINK_STATUS, &buf);
2920         if (ret < 0)
2921                 return false;
2922
2923         if (buf & DP_PCON_FRL_READY)
2924                 return true;
2925
2926         return false;
2927 }
2928 EXPORT_SYMBOL(drm_dp_pcon_is_frl_ready);
2929
2930 /**
2931  * drm_dp_pcon_frl_configure_1() - Set HDMI LINK Configuration-Step1
2932  * @aux: DisplayPort AUX channel
2933  * @max_frl_gbps: maximum frl bw to be configured between PCON and HDMI sink
2934  * @frl_mode: FRL Training mode, it can be either Concurrent or Sequential.
2935  * In Concurrent Mode, the FRL link bring up can be done along with
2936  * DP Link training. In Sequential mode, the FRL link bring up is done prior to
2937  * the DP Link training.
2938  *
2939  * Returns 0 if success, else returns negative error code.
2940  */
2941
2942 int drm_dp_pcon_frl_configure_1(struct drm_dp_aux *aux, int max_frl_gbps,
2943                                 u8 frl_mode)
2944 {
2945         int ret;
2946         u8 buf;
2947
2948         ret = drm_dp_dpcd_readb(aux, DP_PCON_HDMI_LINK_CONFIG_1, &buf);
2949         if (ret < 0)
2950                 return ret;
2951
2952         if (frl_mode == DP_PCON_ENABLE_CONCURRENT_LINK)
2953                 buf |= DP_PCON_ENABLE_CONCURRENT_LINK;
2954         else
2955                 buf &= ~DP_PCON_ENABLE_CONCURRENT_LINK;
2956
2957         switch (max_frl_gbps) {
2958         case 9:
2959                 buf |=  DP_PCON_ENABLE_MAX_BW_9GBPS;
2960                 break;
2961         case 18:
2962                 buf |=  DP_PCON_ENABLE_MAX_BW_18GBPS;
2963                 break;
2964         case 24:
2965                 buf |=  DP_PCON_ENABLE_MAX_BW_24GBPS;
2966                 break;
2967         case 32:
2968                 buf |=  DP_PCON_ENABLE_MAX_BW_32GBPS;
2969                 break;
2970         case 40:
2971                 buf |=  DP_PCON_ENABLE_MAX_BW_40GBPS;
2972                 break;
2973         case 48:
2974                 buf |=  DP_PCON_ENABLE_MAX_BW_48GBPS;
2975                 break;
2976         case 0:
2977                 buf |=  DP_PCON_ENABLE_MAX_BW_0GBPS;
2978                 break;
2979         default:
2980                 return -EINVAL;
2981         }
2982
2983         ret = drm_dp_dpcd_writeb(aux, DP_PCON_HDMI_LINK_CONFIG_1, buf);
2984         if (ret < 0)
2985                 return ret;
2986
2987         return 0;
2988 }
2989 EXPORT_SYMBOL(drm_dp_pcon_frl_configure_1);
2990
2991 /**
2992  * drm_dp_pcon_frl_configure_2() - Set HDMI Link configuration Step-2
2993  * @aux: DisplayPort AUX channel
2994  * @max_frl_mask : Max FRL BW to be tried by the PCON with HDMI Sink
2995  * @frl_type : FRL training type, can be Extended, or Normal.
2996  * In Normal FRL training, the PCON tries each frl bw from the max_frl_mask
2997  * starting from min, and stops when link training is successful. In Extended
2998  * FRL training, all frl bw selected in the mask are trained by the PCON.
2999  *
3000  * Returns 0 if success, else returns negative error code.
3001  */
3002 int drm_dp_pcon_frl_configure_2(struct drm_dp_aux *aux, int max_frl_mask,
3003                                 u8 frl_type)
3004 {
3005         int ret;
3006         u8 buf = max_frl_mask;
3007
3008         if (frl_type == DP_PCON_FRL_LINK_TRAIN_EXTENDED)
3009                 buf |= DP_PCON_FRL_LINK_TRAIN_EXTENDED;
3010         else
3011                 buf &= ~DP_PCON_FRL_LINK_TRAIN_EXTENDED;
3012
3013         ret = drm_dp_dpcd_writeb(aux, DP_PCON_HDMI_LINK_CONFIG_2, buf);
3014         if (ret < 0)
3015                 return ret;
3016
3017         return 0;
3018 }
3019 EXPORT_SYMBOL(drm_dp_pcon_frl_configure_2);
3020
3021 /**
3022  * drm_dp_pcon_reset_frl_config() - Re-Set HDMI Link configuration.
3023  * @aux: DisplayPort AUX channel
3024  *
3025  * Returns 0 if success, else returns negative error code.
3026  */
3027 int drm_dp_pcon_reset_frl_config(struct drm_dp_aux *aux)
3028 {
3029         int ret;
3030
3031         ret = drm_dp_dpcd_writeb(aux, DP_PCON_HDMI_LINK_CONFIG_1, 0x0);
3032         if (ret < 0)
3033                 return ret;
3034
3035         return 0;
3036 }
3037 EXPORT_SYMBOL(drm_dp_pcon_reset_frl_config);
3038
3039 /**
3040  * drm_dp_pcon_frl_enable() - Enable HDMI link through FRL
3041  * @aux: DisplayPort AUX channel
3042  *
3043  * Returns 0 if success, else returns negative error code.
3044  */
3045 int drm_dp_pcon_frl_enable(struct drm_dp_aux *aux)
3046 {
3047         int ret;
3048         u8 buf = 0;
3049
3050         ret = drm_dp_dpcd_readb(aux, DP_PCON_HDMI_LINK_CONFIG_1, &buf);
3051         if (ret < 0)
3052                 return ret;
3053         if (!(buf & DP_PCON_ENABLE_SOURCE_CTL_MODE)) {
3054                 drm_dbg_kms(aux->drm_dev, "%s: PCON in Autonomous mode, can't enable FRL\n",
3055                             aux->name);
3056                 return -EINVAL;
3057         }
3058         buf |= DP_PCON_ENABLE_HDMI_LINK;
3059         ret = drm_dp_dpcd_writeb(aux, DP_PCON_HDMI_LINK_CONFIG_1, buf);
3060         if (ret < 0)
3061                 return ret;
3062
3063         return 0;
3064 }
3065 EXPORT_SYMBOL(drm_dp_pcon_frl_enable);
3066
3067 /**
3068  * drm_dp_pcon_hdmi_link_active() - check if the PCON HDMI LINK status is active.
3069  * @aux: DisplayPort AUX channel
3070  *
3071  * Returns true if link is active else returns false.
3072  */
3073 bool drm_dp_pcon_hdmi_link_active(struct drm_dp_aux *aux)
3074 {
3075         u8 buf;
3076         int ret;
3077
3078         ret = drm_dp_dpcd_readb(aux, DP_PCON_HDMI_TX_LINK_STATUS, &buf);
3079         if (ret < 0)
3080                 return false;
3081
3082         return buf & DP_PCON_HDMI_TX_LINK_ACTIVE;
3083 }
3084 EXPORT_SYMBOL(drm_dp_pcon_hdmi_link_active);
3085
3086 /**
3087  * drm_dp_pcon_hdmi_link_mode() - get the PCON HDMI LINK MODE
3088  * @aux: DisplayPort AUX channel
3089  * @frl_trained_mask: pointer to store bitmask of the trained bw configuration.
3090  * Valid only if the MODE returned is FRL. For Normal Link training mode
3091  * only 1 of the bits will be set, but in case of Extended mode, more than
3092  * one bits can be set.
3093  *
3094  * Returns the link mode : TMDS or FRL on success, else returns negative error
3095  * code.
3096  */
3097 int drm_dp_pcon_hdmi_link_mode(struct drm_dp_aux *aux, u8 *frl_trained_mask)
3098 {
3099         u8 buf;
3100         int mode;
3101         int ret;
3102
3103         ret = drm_dp_dpcd_readb(aux, DP_PCON_HDMI_POST_FRL_STATUS, &buf);
3104         if (ret < 0)
3105                 return ret;
3106
3107         mode = buf & DP_PCON_HDMI_LINK_MODE;
3108
3109         if (frl_trained_mask && DP_PCON_HDMI_MODE_FRL == mode)
3110                 *frl_trained_mask = (buf & DP_PCON_HDMI_FRL_TRAINED_BW) >> 1;
3111
3112         return mode;
3113 }
3114 EXPORT_SYMBOL(drm_dp_pcon_hdmi_link_mode);
3115
3116 /**
3117  * drm_dp_pcon_hdmi_frl_link_error_count() - print the error count per lane
3118  * during link failure between PCON and HDMI sink
3119  * @aux: DisplayPort AUX channel
3120  * @connector: DRM connector
3121  * code.
3122  **/
3123
3124 void drm_dp_pcon_hdmi_frl_link_error_count(struct drm_dp_aux *aux,
3125                                            struct drm_connector *connector)
3126 {
3127         u8 buf, error_count;
3128         int i, num_error;
3129         struct drm_hdmi_info *hdmi = &connector->display_info.hdmi;
3130
3131         for (i = 0; i < hdmi->max_lanes; i++) {
3132                 if (drm_dp_dpcd_readb(aux, DP_PCON_HDMI_ERROR_STATUS_LN0 + i, &buf) < 0)
3133                         return;
3134
3135                 error_count = buf & DP_PCON_HDMI_ERROR_COUNT_MASK;
3136                 switch (error_count) {
3137                 case DP_PCON_HDMI_ERROR_COUNT_HUNDRED_PLUS:
3138                         num_error = 100;
3139                         break;
3140                 case DP_PCON_HDMI_ERROR_COUNT_TEN_PLUS:
3141                         num_error = 10;
3142                         break;
3143                 case DP_PCON_HDMI_ERROR_COUNT_THREE_PLUS:
3144                         num_error = 3;
3145                         break;
3146                 default:
3147                         num_error = 0;
3148                 }
3149
3150                 drm_err(aux->drm_dev, "%s: More than %d errors since the last read for lane %d",
3151                         aux->name, num_error, i);
3152         }
3153 }
3154 EXPORT_SYMBOL(drm_dp_pcon_hdmi_frl_link_error_count);
3155
3156 /*
3157  * drm_dp_pcon_enc_is_dsc_1_2 - Does PCON Encoder supports DSC 1.2
3158  * @pcon_dsc_dpcd: DSC capabilities of the PCON DSC Encoder
3159  *
3160  * Returns true is PCON encoder is DSC 1.2 else returns false.
3161  */
3162 bool drm_dp_pcon_enc_is_dsc_1_2(const u8 pcon_dsc_dpcd[DP_PCON_DSC_ENCODER_CAP_SIZE])
3163 {
3164         u8 buf;
3165         u8 major_v, minor_v;
3166
3167         buf = pcon_dsc_dpcd[DP_PCON_DSC_VERSION - DP_PCON_DSC_ENCODER];
3168         major_v = (buf & DP_PCON_DSC_MAJOR_MASK) >> DP_PCON_DSC_MAJOR_SHIFT;
3169         minor_v = (buf & DP_PCON_DSC_MINOR_MASK) >> DP_PCON_DSC_MINOR_SHIFT;
3170
3171         if (major_v == 1 && minor_v == 2)
3172                 return true;
3173
3174         return false;
3175 }
3176 EXPORT_SYMBOL(drm_dp_pcon_enc_is_dsc_1_2);
3177
3178 /*
3179  * drm_dp_pcon_dsc_max_slices - Get max slices supported by PCON DSC Encoder
3180  * @pcon_dsc_dpcd: DSC capabilities of the PCON DSC Encoder
3181  *
3182  * Returns maximum no. of slices supported by the PCON DSC Encoder.
3183  */
3184 int drm_dp_pcon_dsc_max_slices(const u8 pcon_dsc_dpcd[DP_PCON_DSC_ENCODER_CAP_SIZE])
3185 {
3186         u8 slice_cap1, slice_cap2;
3187
3188         slice_cap1 = pcon_dsc_dpcd[DP_PCON_DSC_SLICE_CAP_1 - DP_PCON_DSC_ENCODER];
3189         slice_cap2 = pcon_dsc_dpcd[DP_PCON_DSC_SLICE_CAP_2 - DP_PCON_DSC_ENCODER];
3190
3191         if (slice_cap2 & DP_PCON_DSC_24_PER_DSC_ENC)
3192                 return 24;
3193         if (slice_cap2 & DP_PCON_DSC_20_PER_DSC_ENC)
3194                 return 20;
3195         if (slice_cap2 & DP_PCON_DSC_16_PER_DSC_ENC)
3196                 return 16;
3197         if (slice_cap1 & DP_PCON_DSC_12_PER_DSC_ENC)
3198                 return 12;
3199         if (slice_cap1 & DP_PCON_DSC_10_PER_DSC_ENC)
3200                 return 10;
3201         if (slice_cap1 & DP_PCON_DSC_8_PER_DSC_ENC)
3202                 return 8;
3203         if (slice_cap1 & DP_PCON_DSC_6_PER_DSC_ENC)
3204                 return 6;
3205         if (slice_cap1 & DP_PCON_DSC_4_PER_DSC_ENC)
3206                 return 4;
3207         if (slice_cap1 & DP_PCON_DSC_2_PER_DSC_ENC)
3208                 return 2;
3209         if (slice_cap1 & DP_PCON_DSC_1_PER_DSC_ENC)
3210                 return 1;
3211
3212         return 0;
3213 }
3214 EXPORT_SYMBOL(drm_dp_pcon_dsc_max_slices);
3215
3216 /*
3217  * drm_dp_pcon_dsc_max_slice_width() - Get max slice width for Pcon DSC encoder
3218  * @pcon_dsc_dpcd: DSC capabilities of the PCON DSC Encoder
3219  *
3220  * Returns maximum width of the slices in pixel width i.e. no. of pixels x 320.
3221  */
3222 int drm_dp_pcon_dsc_max_slice_width(const u8 pcon_dsc_dpcd[DP_PCON_DSC_ENCODER_CAP_SIZE])
3223 {
3224         u8 buf;
3225
3226         buf = pcon_dsc_dpcd[DP_PCON_DSC_MAX_SLICE_WIDTH - DP_PCON_DSC_ENCODER];
3227
3228         return buf * DP_DSC_SLICE_WIDTH_MULTIPLIER;
3229 }
3230 EXPORT_SYMBOL(drm_dp_pcon_dsc_max_slice_width);
3231
3232 /*
3233  * drm_dp_pcon_dsc_bpp_incr() - Get bits per pixel increment for PCON DSC encoder
3234  * @pcon_dsc_dpcd: DSC capabilities of the PCON DSC Encoder
3235  *
3236  * Returns the bpp precision supported by the PCON encoder.
3237  */
3238 int drm_dp_pcon_dsc_bpp_incr(const u8 pcon_dsc_dpcd[DP_PCON_DSC_ENCODER_CAP_SIZE])
3239 {
3240         u8 buf;
3241
3242         buf = pcon_dsc_dpcd[DP_PCON_DSC_BPP_INCR - DP_PCON_DSC_ENCODER];
3243
3244         switch (buf & DP_PCON_DSC_BPP_INCR_MASK) {
3245         case DP_PCON_DSC_ONE_16TH_BPP:
3246                 return 16;
3247         case DP_PCON_DSC_ONE_8TH_BPP:
3248                 return 8;
3249         case DP_PCON_DSC_ONE_4TH_BPP:
3250                 return 4;
3251         case DP_PCON_DSC_ONE_HALF_BPP:
3252                 return 2;
3253         case DP_PCON_DSC_ONE_BPP:
3254                 return 1;
3255         }
3256
3257         return 0;
3258 }
3259 EXPORT_SYMBOL(drm_dp_pcon_dsc_bpp_incr);
3260
3261 static
3262 int drm_dp_pcon_configure_dsc_enc(struct drm_dp_aux *aux, u8 pps_buf_config)
3263 {
3264         u8 buf;
3265         int ret;
3266
3267         ret = drm_dp_dpcd_readb(aux, DP_PROTOCOL_CONVERTER_CONTROL_2, &buf);
3268         if (ret < 0)
3269                 return ret;
3270
3271         buf |= DP_PCON_ENABLE_DSC_ENCODER;
3272
3273         if (pps_buf_config <= DP_PCON_ENC_PPS_OVERRIDE_EN_BUFFER) {
3274                 buf &= ~DP_PCON_ENCODER_PPS_OVERRIDE_MASK;
3275                 buf |= pps_buf_config << 2;
3276         }
3277
3278         ret = drm_dp_dpcd_writeb(aux, DP_PROTOCOL_CONVERTER_CONTROL_2, buf);
3279         if (ret < 0)
3280                 return ret;
3281
3282         return 0;
3283 }
3284
3285 /**
3286  * drm_dp_pcon_pps_default() - Let PCON fill the default pps parameters
3287  * for DSC1.2 between PCON & HDMI2.1 sink
3288  * @aux: DisplayPort AUX channel
3289  *
3290  * Returns 0 on success, else returns negative error code.
3291  */
3292 int drm_dp_pcon_pps_default(struct drm_dp_aux *aux)
3293 {
3294         int ret;
3295
3296         ret = drm_dp_pcon_configure_dsc_enc(aux, DP_PCON_ENC_PPS_OVERRIDE_DISABLED);
3297         if (ret < 0)
3298                 return ret;
3299
3300         return 0;
3301 }
3302 EXPORT_SYMBOL(drm_dp_pcon_pps_default);
3303
3304 /**
3305  * drm_dp_pcon_pps_override_buf() - Configure PPS encoder override buffer for
3306  * HDMI sink
3307  * @aux: DisplayPort AUX channel
3308  * @pps_buf: 128 bytes to be written into PPS buffer for HDMI sink by PCON.
3309  *
3310  * Returns 0 on success, else returns negative error code.
3311  */
3312 int drm_dp_pcon_pps_override_buf(struct drm_dp_aux *aux, u8 pps_buf[128])
3313 {
3314         int ret;
3315
3316         ret = drm_dp_dpcd_write(aux, DP_PCON_HDMI_PPS_OVERRIDE_BASE, &pps_buf, 128);
3317         if (ret < 0)
3318                 return ret;
3319
3320         ret = drm_dp_pcon_configure_dsc_enc(aux, DP_PCON_ENC_PPS_OVERRIDE_EN_BUFFER);
3321         if (ret < 0)
3322                 return ret;
3323
3324         return 0;
3325 }
3326 EXPORT_SYMBOL(drm_dp_pcon_pps_override_buf);
3327
3328 /*
3329  * drm_dp_pcon_pps_override_param() - Write PPS parameters to DSC encoder
3330  * override registers
3331  * @aux: DisplayPort AUX channel
3332  * @pps_param: 3 Parameters (2 Bytes each) : Slice Width, Slice Height,
3333  * bits_per_pixel.
3334  *
3335  * Returns 0 on success, else returns negative error code.
3336  */
3337 int drm_dp_pcon_pps_override_param(struct drm_dp_aux *aux, u8 pps_param[6])
3338 {
3339         int ret;
3340
3341         ret = drm_dp_dpcd_write(aux, DP_PCON_HDMI_PPS_OVRD_SLICE_HEIGHT, &pps_param[0], 2);
3342         if (ret < 0)
3343                 return ret;
3344         ret = drm_dp_dpcd_write(aux, DP_PCON_HDMI_PPS_OVRD_SLICE_WIDTH, &pps_param[2], 2);
3345         if (ret < 0)
3346                 return ret;
3347         ret = drm_dp_dpcd_write(aux, DP_PCON_HDMI_PPS_OVRD_BPP, &pps_param[4], 2);
3348         if (ret < 0)
3349                 return ret;
3350
3351         ret = drm_dp_pcon_configure_dsc_enc(aux, DP_PCON_ENC_PPS_OVERRIDE_EN_BUFFER);
3352         if (ret < 0)
3353                 return ret;
3354
3355         return 0;
3356 }
3357 EXPORT_SYMBOL(drm_dp_pcon_pps_override_param);
3358
3359 /*
3360  * drm_dp_pcon_convert_rgb_to_ycbcr() - Configure the PCon to convert RGB to Ycbcr
3361  * @aux: displayPort AUX channel
3362  * @color_spc: Color-space/s for which conversion is to be enabled, 0 for disable.
3363  *
3364  * Returns 0 on success, else returns negative error code.
3365  */
3366 int drm_dp_pcon_convert_rgb_to_ycbcr(struct drm_dp_aux *aux, u8 color_spc)
3367 {
3368         int ret;
3369         u8 buf;
3370
3371         ret = drm_dp_dpcd_readb(aux, DP_PROTOCOL_CONVERTER_CONTROL_2, &buf);
3372         if (ret < 0)
3373                 return ret;
3374
3375         if (color_spc & DP_CONVERSION_RGB_YCBCR_MASK)
3376                 buf |= (color_spc & DP_CONVERSION_RGB_YCBCR_MASK);
3377         else
3378                 buf &= ~DP_CONVERSION_RGB_YCBCR_MASK;
3379
3380         ret = drm_dp_dpcd_writeb(aux, DP_PROTOCOL_CONVERTER_CONTROL_2, buf);
3381         if (ret < 0)
3382                 return ret;
3383
3384         return 0;
3385 }
3386 EXPORT_SYMBOL(drm_dp_pcon_convert_rgb_to_ycbcr);
3387
3388 /**
3389  * drm_edp_backlight_set_level() - Set the backlight level of an eDP panel via AUX
3390  * @aux: The DP AUX channel to use
3391  * @bl: Backlight capability info from drm_edp_backlight_init()
3392  * @level: The brightness level to set
3393  *
3394  * Sets the brightness level of an eDP panel's backlight. Note that the panel's backlight must
3395  * already have been enabled by the driver by calling drm_edp_backlight_enable().
3396  *
3397  * Returns: %0 on success, negative error code on failure
3398  */
3399 int drm_edp_backlight_set_level(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl,
3400                                 u16 level)
3401 {
3402         int ret;
3403         u8 buf[2] = { 0 };
3404
3405         /* The panel uses the PWM for controlling brightness levels */
3406         if (!bl->aux_set)
3407                 return 0;
3408
3409         if (bl->lsb_reg_used) {
3410                 buf[0] = (level & 0xff00) >> 8;
3411                 buf[1] = (level & 0x00ff);
3412         } else {
3413                 buf[0] = level;
3414         }
3415
3416         ret = drm_dp_dpcd_write(aux, DP_EDP_BACKLIGHT_BRIGHTNESS_MSB, buf, sizeof(buf));
3417         if (ret != sizeof(buf)) {
3418                 drm_err(aux->drm_dev,
3419                         "%s: Failed to write aux backlight level: %d\n",
3420                         aux->name, ret);
3421                 return ret < 0 ? ret : -EIO;
3422         }
3423
3424         return 0;
3425 }
3426 EXPORT_SYMBOL(drm_edp_backlight_set_level);
3427
3428 static int
3429 drm_edp_backlight_set_enable(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl,
3430                              bool enable)
3431 {
3432         int ret;
3433         u8 buf;
3434
3435         /* This panel uses the EDP_BL_PWR GPIO for enablement */
3436         if (!bl->aux_enable)
3437                 return 0;
3438
3439         ret = drm_dp_dpcd_readb(aux, DP_EDP_DISPLAY_CONTROL_REGISTER, &buf);
3440         if (ret != 1) {
3441                 drm_err(aux->drm_dev, "%s: Failed to read eDP display control register: %d\n",
3442                         aux->name, ret);
3443                 return ret < 0 ? ret : -EIO;
3444         }
3445         if (enable)
3446                 buf |= DP_EDP_BACKLIGHT_ENABLE;
3447         else
3448                 buf &= ~DP_EDP_BACKLIGHT_ENABLE;
3449
3450         ret = drm_dp_dpcd_writeb(aux, DP_EDP_DISPLAY_CONTROL_REGISTER, buf);
3451         if (ret != 1) {
3452                 drm_err(aux->drm_dev, "%s: Failed to write eDP display control register: %d\n",
3453                         aux->name, ret);
3454                 return ret < 0 ? ret : -EIO;
3455         }
3456
3457         return 0;
3458 }
3459
3460 /**
3461  * drm_edp_backlight_enable() - Enable an eDP panel's backlight using DPCD
3462  * @aux: The DP AUX channel to use
3463  * @bl: Backlight capability info from drm_edp_backlight_init()
3464  * @level: The initial backlight level to set via AUX, if there is one
3465  *
3466  * This function handles enabling DPCD backlight controls on a panel over DPCD, while additionally
3467  * restoring any important backlight state such as the given backlight level, the brightness byte
3468  * count, backlight frequency, etc.
3469  *
3470  * Note that certain panels do not support being enabled or disabled via DPCD, but instead require
3471  * that the driver handle enabling/disabling the panel through implementation-specific means using
3472  * the EDP_BL_PWR GPIO. For such panels, &drm_edp_backlight_info.aux_enable will be set to %false,
3473  * this function becomes a no-op, and the driver is expected to handle powering the panel on using
3474  * the EDP_BL_PWR GPIO.
3475  *
3476  * Returns: %0 on success, negative error code on failure.
3477  */
3478 int drm_edp_backlight_enable(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl,
3479                              const u16 level)
3480 {
3481         int ret;
3482         u8 dpcd_buf;
3483
3484         if (bl->aux_set)
3485                 dpcd_buf = DP_EDP_BACKLIGHT_CONTROL_MODE_DPCD;
3486         else
3487                 dpcd_buf = DP_EDP_BACKLIGHT_CONTROL_MODE_PWM;
3488
3489         if (bl->pwmgen_bit_count) {
3490                 ret = drm_dp_dpcd_writeb(aux, DP_EDP_PWMGEN_BIT_COUNT, bl->pwmgen_bit_count);
3491                 if (ret != 1)
3492                         drm_dbg_kms(aux->drm_dev, "%s: Failed to write aux pwmgen bit count: %d\n",
3493                                     aux->name, ret);
3494         }
3495
3496         if (bl->pwm_freq_pre_divider) {
3497                 ret = drm_dp_dpcd_writeb(aux, DP_EDP_BACKLIGHT_FREQ_SET, bl->pwm_freq_pre_divider);
3498                 if (ret != 1)
3499                         drm_dbg_kms(aux->drm_dev,
3500                                     "%s: Failed to write aux backlight frequency: %d\n",
3501                                     aux->name, ret);
3502                 else
3503                         dpcd_buf |= DP_EDP_BACKLIGHT_FREQ_AUX_SET_ENABLE;
3504         }
3505
3506         ret = drm_dp_dpcd_writeb(aux, DP_EDP_BACKLIGHT_MODE_SET_REGISTER, dpcd_buf);
3507         if (ret != 1) {
3508                 drm_dbg_kms(aux->drm_dev, "%s: Failed to write aux backlight mode: %d\n",
3509                             aux->name, ret);
3510                 return ret < 0 ? ret : -EIO;
3511         }
3512
3513         ret = drm_edp_backlight_set_level(aux, bl, level);
3514         if (ret < 0)
3515                 return ret;
3516         ret = drm_edp_backlight_set_enable(aux, bl, true);
3517         if (ret < 0)
3518                 return ret;
3519
3520         return 0;
3521 }
3522 EXPORT_SYMBOL(drm_edp_backlight_enable);
3523
3524 /**
3525  * drm_edp_backlight_disable() - Disable an eDP backlight using DPCD, if supported
3526  * @aux: The DP AUX channel to use
3527  * @bl: Backlight capability info from drm_edp_backlight_init()
3528  *
3529  * This function handles disabling DPCD backlight controls on a panel over AUX.
3530  *
3531  * Note that certain panels do not support being enabled or disabled via DPCD, but instead require
3532  * that the driver handle enabling/disabling the panel through implementation-specific means using
3533  * the EDP_BL_PWR GPIO. For such panels, &drm_edp_backlight_info.aux_enable will be set to %false,
3534  * this function becomes a no-op, and the driver is expected to handle powering the panel off using
3535  * the EDP_BL_PWR GPIO.
3536  *
3537  * Returns: %0 on success or no-op, negative error code on failure.
3538  */
3539 int drm_edp_backlight_disable(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl)
3540 {
3541         int ret;
3542
3543         ret = drm_edp_backlight_set_enable(aux, bl, false);
3544         if (ret < 0)
3545                 return ret;
3546
3547         return 0;
3548 }
3549 EXPORT_SYMBOL(drm_edp_backlight_disable);
3550
3551 static inline int
3552 drm_edp_backlight_probe_max(struct drm_dp_aux *aux, struct drm_edp_backlight_info *bl,
3553                             u16 driver_pwm_freq_hz, const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE])
3554 {
3555         int fxp, fxp_min, fxp_max, fxp_actual, f = 1;
3556         int ret;
3557         u8 pn, pn_min, pn_max;
3558
3559         if (!bl->aux_set)
3560                 return 0;
3561
3562         ret = drm_dp_dpcd_readb(aux, DP_EDP_PWMGEN_BIT_COUNT, &pn);
3563         if (ret != 1) {
3564                 drm_dbg_kms(aux->drm_dev, "%s: Failed to read pwmgen bit count cap: %d\n",
3565                             aux->name, ret);
3566                 return -ENODEV;
3567         }
3568
3569         pn &= DP_EDP_PWMGEN_BIT_COUNT_MASK;
3570         bl->max = (1 << pn) - 1;
3571         if (!driver_pwm_freq_hz)
3572                 return 0;
3573
3574         /*
3575          * Set PWM Frequency divider to match desired frequency provided by the driver.
3576          * The PWM Frequency is calculated as 27Mhz / (F x P).
3577          * - Where F = PWM Frequency Pre-Divider value programmed by field 7:0 of the
3578          *             EDP_BACKLIGHT_FREQ_SET register (DPCD Address 00728h)
3579          * - Where P = 2^Pn, where Pn is the value programmed by field 4:0 of the
3580          *             EDP_PWMGEN_BIT_COUNT register (DPCD Address 00724h)
3581          */
3582
3583         /* Find desired value of (F x P)
3584          * Note that, if F x P is out of supported range, the maximum value or minimum value will
3585          * applied automatically. So no need to check that.
3586          */
3587         fxp = DIV_ROUND_CLOSEST(1000 * DP_EDP_BACKLIGHT_FREQ_BASE_KHZ, driver_pwm_freq_hz);
3588
3589         /* Use highest possible value of Pn for more granularity of brightness adjustment while
3590          * satisfying the conditions below.
3591          * - Pn is in the range of Pn_min and Pn_max
3592          * - F is in the range of 1 and 255
3593          * - FxP is within 25% of desired value.
3594          *   Note: 25% is arbitrary value and may need some tweak.
3595          */
3596         ret = drm_dp_dpcd_readb(aux, DP_EDP_PWMGEN_BIT_COUNT_CAP_MIN, &pn_min);
3597         if (ret != 1) {
3598                 drm_dbg_kms(aux->drm_dev, "%s: Failed to read pwmgen bit count cap min: %d\n",
3599                             aux->name, ret);
3600                 return 0;
3601         }
3602         ret = drm_dp_dpcd_readb(aux, DP_EDP_PWMGEN_BIT_COUNT_CAP_MAX, &pn_max);
3603         if (ret != 1) {
3604                 drm_dbg_kms(aux->drm_dev, "%s: Failed to read pwmgen bit count cap max: %d\n",
3605                             aux->name, ret);
3606                 return 0;
3607         }
3608         pn_min &= DP_EDP_PWMGEN_BIT_COUNT_MASK;
3609         pn_max &= DP_EDP_PWMGEN_BIT_COUNT_MASK;
3610
3611         /* Ensure frequency is within 25% of desired value */
3612         fxp_min = DIV_ROUND_CLOSEST(fxp * 3, 4);
3613         fxp_max = DIV_ROUND_CLOSEST(fxp * 5, 4);
3614         if (fxp_min < (1 << pn_min) || (255 << pn_max) < fxp_max) {
3615                 drm_dbg_kms(aux->drm_dev,
3616                             "%s: Driver defined backlight frequency (%d) out of range\n",
3617                             aux->name, driver_pwm_freq_hz);
3618                 return 0;
3619         }
3620
3621         for (pn = pn_max; pn >= pn_min; pn--) {
3622                 f = clamp(DIV_ROUND_CLOSEST(fxp, 1 << pn), 1, 255);
3623                 fxp_actual = f << pn;
3624                 if (fxp_min <= fxp_actual && fxp_actual <= fxp_max)
3625                         break;
3626         }
3627
3628         ret = drm_dp_dpcd_writeb(aux, DP_EDP_PWMGEN_BIT_COUNT, pn);
3629         if (ret != 1) {
3630                 drm_dbg_kms(aux->drm_dev, "%s: Failed to write aux pwmgen bit count: %d\n",
3631                             aux->name, ret);
3632                 return 0;
3633         }
3634         bl->pwmgen_bit_count = pn;
3635         bl->max = (1 << pn) - 1;
3636
3637         if (edp_dpcd[2] & DP_EDP_BACKLIGHT_FREQ_AUX_SET_CAP) {
3638                 bl->pwm_freq_pre_divider = f;
3639                 drm_dbg_kms(aux->drm_dev, "%s: Using backlight frequency from driver (%dHz)\n",
3640                             aux->name, driver_pwm_freq_hz);
3641         }
3642
3643         return 0;
3644 }
3645
3646 static inline int
3647 drm_edp_backlight_probe_state(struct drm_dp_aux *aux, struct drm_edp_backlight_info *bl,
3648                               u8 *current_mode)
3649 {
3650         int ret;
3651         u8 buf[2];
3652         u8 mode_reg;
3653
3654         ret = drm_dp_dpcd_readb(aux, DP_EDP_BACKLIGHT_MODE_SET_REGISTER, &mode_reg);
3655         if (ret != 1) {
3656                 drm_dbg_kms(aux->drm_dev, "%s: Failed to read backlight mode: %d\n",
3657                             aux->name, ret);
3658                 return ret < 0 ? ret : -EIO;
3659         }
3660
3661         *current_mode = (mode_reg & DP_EDP_BACKLIGHT_CONTROL_MODE_MASK);
3662         if (!bl->aux_set)
3663                 return 0;
3664
3665         if (*current_mode == DP_EDP_BACKLIGHT_CONTROL_MODE_DPCD) {
3666                 int size = 1 + bl->lsb_reg_used;
3667
3668                 ret = drm_dp_dpcd_read(aux, DP_EDP_BACKLIGHT_BRIGHTNESS_MSB, buf, size);
3669                 if (ret != size) {
3670                         drm_dbg_kms(aux->drm_dev, "%s: Failed to read backlight level: %d\n",
3671                                     aux->name, ret);
3672                         return ret < 0 ? ret : -EIO;
3673                 }
3674
3675                 if (bl->lsb_reg_used)
3676                         return (buf[0] << 8) | buf[1];
3677                 else
3678                         return buf[0];
3679         }
3680
3681         /*
3682          * If we're not in DPCD control mode yet, the programmed brightness value is meaningless and
3683          * the driver should assume max brightness
3684          */
3685         return bl->max;
3686 }
3687
3688 /**
3689  * drm_edp_backlight_init() - Probe a display panel's TCON using the standard VESA eDP backlight
3690  * interface.
3691  * @aux: The DP aux device to use for probing
3692  * @bl: The &drm_edp_backlight_info struct to fill out with information on the backlight
3693  * @driver_pwm_freq_hz: Optional PWM frequency from the driver in hz
3694  * @edp_dpcd: A cached copy of the eDP DPCD
3695  * @current_level: Where to store the probed brightness level, if any
3696  * @current_mode: Where to store the currently set backlight control mode
3697  *
3698  * Initializes a &drm_edp_backlight_info struct by probing @aux for it's backlight capabilities,
3699  * along with also probing the current and maximum supported brightness levels.
3700  *
3701  * If @driver_pwm_freq_hz is non-zero, this will be used as the backlight frequency. Otherwise, the
3702  * default frequency from the panel is used.
3703  *
3704  * Returns: %0 on success, negative error code on failure.
3705  */
3706 int
3707 drm_edp_backlight_init(struct drm_dp_aux *aux, struct drm_edp_backlight_info *bl,
3708                        u16 driver_pwm_freq_hz, const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE],
3709                        u16 *current_level, u8 *current_mode)
3710 {
3711         int ret;
3712
3713         if (edp_dpcd[1] & DP_EDP_BACKLIGHT_AUX_ENABLE_CAP)
3714                 bl->aux_enable = true;
3715         if (edp_dpcd[2] & DP_EDP_BACKLIGHT_BRIGHTNESS_AUX_SET_CAP)
3716                 bl->aux_set = true;
3717         if (edp_dpcd[2] & DP_EDP_BACKLIGHT_BRIGHTNESS_BYTE_COUNT)
3718                 bl->lsb_reg_used = true;
3719
3720         /* Sanity check caps */
3721         if (!bl->aux_set && !(edp_dpcd[2] & DP_EDP_BACKLIGHT_BRIGHTNESS_PWM_PIN_CAP)) {
3722                 drm_dbg_kms(aux->drm_dev,
3723                             "%s: Panel supports neither AUX or PWM brightness control? Aborting\n",
3724                             aux->name);
3725                 return -EINVAL;
3726         }
3727
3728         ret = drm_edp_backlight_probe_max(aux, bl, driver_pwm_freq_hz, edp_dpcd);
3729         if (ret < 0)
3730                 return ret;
3731
3732         ret = drm_edp_backlight_probe_state(aux, bl, current_mode);
3733         if (ret < 0)
3734                 return ret;
3735         *current_level = ret;
3736
3737         drm_dbg_kms(aux->drm_dev,
3738                     "%s: Found backlight: aux_set=%d aux_enable=%d mode=%d\n",
3739                     aux->name, bl->aux_set, bl->aux_enable, *current_mode);
3740         if (bl->aux_set) {
3741                 drm_dbg_kms(aux->drm_dev,
3742                             "%s: Backlight caps: level=%d/%d pwm_freq_pre_divider=%d lsb_reg_used=%d\n",
3743                             aux->name, *current_level, bl->max, bl->pwm_freq_pre_divider,
3744                             bl->lsb_reg_used);
3745         }
3746
3747         return 0;
3748 }
3749 EXPORT_SYMBOL(drm_edp_backlight_init);
3750
3751 #if IS_BUILTIN(CONFIG_BACKLIGHT_CLASS_DEVICE) || \
3752         (IS_MODULE(CONFIG_DRM_KMS_HELPER) && IS_MODULE(CONFIG_BACKLIGHT_CLASS_DEVICE))
3753
3754 static int dp_aux_backlight_update_status(struct backlight_device *bd)
3755 {
3756         struct dp_aux_backlight *bl = bl_get_data(bd);
3757         u16 brightness = backlight_get_brightness(bd);
3758         int ret = 0;
3759
3760         if (!backlight_is_blank(bd)) {
3761                 if (!bl->enabled) {
3762                         drm_edp_backlight_enable(bl->aux, &bl->info, brightness);
3763                         bl->enabled = true;
3764                         return 0;
3765                 }
3766                 ret = drm_edp_backlight_set_level(bl->aux, &bl->info, brightness);
3767         } else {
3768                 if (bl->enabled) {
3769                         drm_edp_backlight_disable(bl->aux, &bl->info);
3770                         bl->enabled = false;
3771                 }
3772         }
3773
3774         return ret;
3775 }
3776
3777 static const struct backlight_ops dp_aux_bl_ops = {
3778         .update_status = dp_aux_backlight_update_status,
3779 };
3780
3781 /**
3782  * drm_panel_dp_aux_backlight - create and use DP AUX backlight
3783  * @panel: DRM panel
3784  * @aux: The DP AUX channel to use
3785  *
3786  * Use this function to create and handle backlight if your panel
3787  * supports backlight control over DP AUX channel using DPCD
3788  * registers as per VESA's standard backlight control interface.
3789  *
3790  * When the panel is enabled backlight will be enabled after a
3791  * successful call to &drm_panel_funcs.enable()
3792  *
3793  * When the panel is disabled backlight will be disabled before the
3794  * call to &drm_panel_funcs.disable().
3795  *
3796  * A typical implementation for a panel driver supporting backlight
3797  * control over DP AUX will call this function at probe time.
3798  * Backlight will then be handled transparently without requiring
3799  * any intervention from the driver.
3800  *
3801  * drm_panel_dp_aux_backlight() must be called after the call to drm_panel_init().
3802  *
3803  * Return: 0 on success or a negative error code on failure.
3804  */
3805 int drm_panel_dp_aux_backlight(struct drm_panel *panel, struct drm_dp_aux *aux)
3806 {
3807         struct dp_aux_backlight *bl;
3808         struct backlight_properties props = { 0 };
3809         u16 current_level;
3810         u8 current_mode;
3811         u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE];
3812         int ret;
3813
3814         if (!panel || !panel->dev || !aux)
3815                 return -EINVAL;
3816
3817         ret = drm_dp_dpcd_read(aux, DP_EDP_DPCD_REV, edp_dpcd,
3818                                EDP_DISPLAY_CTL_CAP_SIZE);
3819         if (ret < 0)
3820                 return ret;
3821
3822         if (!drm_edp_backlight_supported(edp_dpcd)) {
3823                 DRM_DEV_INFO(panel->dev, "DP AUX backlight is not supported\n");
3824                 return 0;
3825         }
3826
3827         bl = devm_kzalloc(panel->dev, sizeof(*bl), GFP_KERNEL);
3828         if (!bl)
3829                 return -ENOMEM;
3830
3831         bl->aux = aux;
3832
3833         ret = drm_edp_backlight_init(aux, &bl->info, 0, edp_dpcd,
3834                                      &current_level, &current_mode);
3835         if (ret < 0)
3836                 return ret;
3837
3838         props.type = BACKLIGHT_RAW;
3839         props.brightness = current_level;
3840         props.max_brightness = bl->info.max;
3841
3842         bl->base = devm_backlight_device_register(panel->dev, "dp_aux_backlight",
3843                                                   panel->dev, bl,
3844                                                   &dp_aux_bl_ops, &props);
3845         if (IS_ERR(bl->base))
3846                 return PTR_ERR(bl->base);
3847
3848         backlight_disable(bl->base);
3849
3850         panel->backlight = bl->base;
3851
3852         return 0;
3853 }
3854 EXPORT_SYMBOL(drm_panel_dp_aux_backlight);
3855
3856 #endif