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