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