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