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