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