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