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