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