xref: /linux/drivers/gpu/drm/amd/display/dc/link/link_detection.c (revision 5946dbe1c802efef3b12a4eecab1471f725f4ca9)
1 /*
2  * Copyright 2022 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25 
26 /* FILE POLICY AND INTENDED USAGE:
27  * This file manages link detection states and receiver states by using various
28  * link protocols. It also provides helper functions to interpret certain
29  * capabilities or status based on the states it manages or retrieve them
30  * directly from connected receivers.
31  */
32 
33 #include "link_dpms.h"
34 #include "link_detection.h"
35 #include "link_hwss.h"
36 #include "protocols/link_edp_panel_control.h"
37 #include "protocols/link_ddc.h"
38 #include "protocols/link_hpd.h"
39 #include "protocols/link_dpcd.h"
40 #include "protocols/link_dp_capability.h"
41 #include "protocols/link_dp_dpia.h"
42 #include "protocols/link_dp_phy.h"
43 #include "protocols/link_dp_training.h"
44 #include "protocols/link_dp_dpia_bw.h"
45 #include "accessories/link_dp_trace.h"
46 
47 #include "link_enc_cfg.h"
48 #include "dm_helpers.h"
49 #include "clk_mgr.h"
50 
51  // Offset DPCD 050Eh == 0x5A
52 #define MST_HUB_ID_0x5A  0x5A
53 
54 #define DC_LOGGER \
55 	link->ctx->logger
56 #define DC_LOGGER_INIT(logger)
57 
58 #define LINK_INFO(...) \
59 	DC_LOG_HW_HOTPLUG(  \
60 		__VA_ARGS__)
61 /*
62  * Some receivers fail to train on first try and are good
63  * on subsequent tries. 2 retries should be plenty. If we
64  * don't have a successful training then we don't expect to
65  * ever get one.
66  */
67 #define LINK_TRAINING_MAX_VERIFY_RETRY 2
68 
69 static const u8 DP_SINK_BRANCH_DEV_NAME_7580[] = "7580\x80u";
70 
71 static const u8 dp_hdmi_dongle_signature_str[] = "DP-HDMI ADAPTOR";
72 
73 static enum ddc_transaction_type get_ddc_transaction_type(enum signal_type sink_signal)
74 {
75 	enum ddc_transaction_type transaction_type = DDC_TRANSACTION_TYPE_NONE;
76 
77 	switch (sink_signal) {
78 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
79 	case SIGNAL_TYPE_DVI_DUAL_LINK:
80 	case SIGNAL_TYPE_HDMI_TYPE_A:
81 	case SIGNAL_TYPE_LVDS:
82 	case SIGNAL_TYPE_RGB:
83 		transaction_type = DDC_TRANSACTION_TYPE_I2C;
84 		break;
85 
86 	case SIGNAL_TYPE_DISPLAY_PORT:
87 	case SIGNAL_TYPE_EDP:
88 		transaction_type = DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
89 		break;
90 
91 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
92 		/* MST does not use I2COverAux, but there is the
93 		 * SPECIAL use case for "immediate dwnstrm device
94 		 * access" (EPR#370830).
95 		 */
96 		transaction_type = DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
97 		break;
98 
99 	default:
100 		break;
101 	}
102 
103 	return transaction_type;
104 }
105 
106 static enum signal_type get_basic_signal_type(struct graphics_object_id encoder,
107 					      struct graphics_object_id downstream)
108 {
109 	if (downstream.type == OBJECT_TYPE_CONNECTOR) {
110 		switch (downstream.id) {
111 		case CONNECTOR_ID_SINGLE_LINK_DVII:
112 			switch (encoder.id) {
113 			case ENCODER_ID_INTERNAL_DAC1:
114 			case ENCODER_ID_INTERNAL_KLDSCP_DAC1:
115 			case ENCODER_ID_INTERNAL_DAC2:
116 			case ENCODER_ID_INTERNAL_KLDSCP_DAC2:
117 				return SIGNAL_TYPE_RGB;
118 			default:
119 				return SIGNAL_TYPE_DVI_SINGLE_LINK;
120 			}
121 		break;
122 		case CONNECTOR_ID_DUAL_LINK_DVII:
123 		{
124 			switch (encoder.id) {
125 			case ENCODER_ID_INTERNAL_DAC1:
126 			case ENCODER_ID_INTERNAL_KLDSCP_DAC1:
127 			case ENCODER_ID_INTERNAL_DAC2:
128 			case ENCODER_ID_INTERNAL_KLDSCP_DAC2:
129 				return SIGNAL_TYPE_RGB;
130 			default:
131 				return SIGNAL_TYPE_DVI_DUAL_LINK;
132 			}
133 		}
134 		break;
135 		case CONNECTOR_ID_SINGLE_LINK_DVID:
136 			return SIGNAL_TYPE_DVI_SINGLE_LINK;
137 		case CONNECTOR_ID_DUAL_LINK_DVID:
138 			return SIGNAL_TYPE_DVI_DUAL_LINK;
139 		case CONNECTOR_ID_VGA:
140 			return SIGNAL_TYPE_RGB;
141 		case CONNECTOR_ID_HDMI_TYPE_A:
142 			return SIGNAL_TYPE_HDMI_TYPE_A;
143 		case CONNECTOR_ID_LVDS:
144 			return SIGNAL_TYPE_LVDS;
145 		case CONNECTOR_ID_DISPLAY_PORT:
146 		case CONNECTOR_ID_USBC:
147 			return SIGNAL_TYPE_DISPLAY_PORT;
148 		case CONNECTOR_ID_EDP:
149 			return SIGNAL_TYPE_EDP;
150 		default:
151 			return SIGNAL_TYPE_NONE;
152 		}
153 	} else if (downstream.type == OBJECT_TYPE_ENCODER) {
154 		switch (downstream.id) {
155 		case ENCODER_ID_EXTERNAL_NUTMEG:
156 		case ENCODER_ID_EXTERNAL_TRAVIS:
157 			return SIGNAL_TYPE_DISPLAY_PORT;
158 		default:
159 			return SIGNAL_TYPE_NONE;
160 		}
161 	}
162 
163 	return SIGNAL_TYPE_NONE;
164 }
165 
166 /*
167  * @brief
168  * Detect output sink type
169  */
170 static enum signal_type link_detect_sink_signal_type(struct dc_link *link,
171 					 enum dc_detect_reason reason)
172 {
173 	enum signal_type result;
174 	struct audio_support *aud_support;
175 	struct graphics_object_id enc_id;
176 
177 	if (link->is_dig_mapping_flexible)
178 		enc_id = (struct graphics_object_id){.id = ENCODER_ID_UNKNOWN};
179 	else
180 		enc_id = link->link_enc->id;
181 	result = get_basic_signal_type(enc_id, link->link_id);
182 
183 	/* Use basic signal type for link without physical connector. */
184 	if (link->ep_type != DISPLAY_ENDPOINT_PHY)
185 		return result;
186 
187 	/*
188 	 * Internal digital encoder will detect only dongles
189 	 * that require digital signal
190 	 */
191 
192 	/*
193 	 * Detection mechanism is different
194 	 * for different native connectors.
195 	 * LVDS connector supports only LVDS signal;
196 	 * PCIE is a bus slot, the actual connector needs to be detected first;
197 	 * eDP connector supports only eDP signal;
198 	 * HDMI should check straps for audio
199 	 */
200 	switch (link->link_id.id) {
201 	case CONNECTOR_ID_HDMI_TYPE_A:
202 		/*
203 		 * check audio support:
204 		 * if native HDMI is not supported, switch to DVI
205 		 */
206 		aud_support = &link->dc->res_pool->audio_support;
207 
208 		if (!aud_support->hdmi_audio_native)
209 			result = SIGNAL_TYPE_DVI_SINGLE_LINK;
210 		break;
211 	case CONNECTOR_ID_DISPLAY_PORT:
212 	case CONNECTOR_ID_USBC:
213 		/*
214 		 * DP HPD short pulse. Passive DP dongle will not
215 		 * have short pulse
216 		 */
217 		if (reason != DETECT_REASON_HPDRX) {
218 			/*
219 			 * Check whether DP signal detected: if not -
220 			 * we assume signal is DVI; it could be corrected
221 			 * to HDMI after dongle detection
222 			 */
223 			if (!dm_helpers_is_dp_sink_present(link))
224 				result = SIGNAL_TYPE_DVI_SINGLE_LINK;
225 		}
226 		break;
227 	case CONNECTOR_ID_PCIE:
228 		/* ZAZTODO implement PCIE add-on card detection */
229 		break;
230 	default:
231 		break;
232 	}
233 
234 	return result;
235 }
236 
237 static enum signal_type decide_signal_from_strap_and_dongle_type(enum display_dongle_type dongle_type,
238 								 struct audio_support *audio_support)
239 {
240 	enum signal_type signal = SIGNAL_TYPE_NONE;
241 
242 	switch (dongle_type) {
243 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
244 		if (audio_support->hdmi_audio_on_dongle)
245 			signal = SIGNAL_TYPE_HDMI_TYPE_A;
246 		else
247 			signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
248 		break;
249 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
250 		signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
251 		break;
252 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
253 		if (audio_support->hdmi_audio_native)
254 			signal =  SIGNAL_TYPE_HDMI_TYPE_A;
255 		else
256 			signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
257 		break;
258 	default:
259 		signal = SIGNAL_TYPE_NONE;
260 		break;
261 	}
262 
263 	return signal;
264 }
265 
266 static void read_scdc_caps(struct ddc_service *ddc_service,
267 		struct dc_sink *sink)
268 {
269 	uint8_t slave_address = HDMI_SCDC_ADDRESS;
270 	uint8_t offset = HDMI_SCDC_MANUFACTURER_OUI;
271 
272 	if (ddc_service->link->local_sink &&
273 		!ddc_service->link->local_sink->edid_caps.scdc_present)
274 		return;
275 
276 	link_query_ddc_data(ddc_service, slave_address, &offset,
277 			sizeof(offset), sink->scdc_caps.manufacturer_OUI.byte,
278 			sizeof(sink->scdc_caps.manufacturer_OUI.byte));
279 
280 	offset = HDMI_SCDC_DEVICE_ID;
281 
282 	link_query_ddc_data(ddc_service, slave_address, &offset,
283 			sizeof(offset), &(sink->scdc_caps.device_id.byte),
284 			sizeof(sink->scdc_caps.device_id.byte));
285 }
286 
287 static bool i2c_read(
288 	struct ddc_service *ddc,
289 	uint32_t address,
290 	uint8_t *buffer,
291 	uint32_t len)
292 {
293 	uint8_t offs_data = 0;
294 	struct i2c_payload payloads[2] = {
295 		{
296 		.write = true,
297 		.address = address,
298 		.length = 1,
299 		.data = &offs_data },
300 		{
301 		.write = false,
302 		.address = address,
303 		.length = len,
304 		.data = buffer } };
305 
306 	struct i2c_command command = {
307 		.payloads = payloads,
308 		.number_of_payloads = 2,
309 		.engine = DDC_I2C_COMMAND_ENGINE,
310 		.speed = ddc->ctx->dc->caps.i2c_speed_in_khz };
311 
312 	return dm_helpers_submit_i2c(
313 			ddc->ctx,
314 			ddc->link,
315 			&command);
316 }
317 
318 enum {
319 	DP_SINK_CAP_SIZE =
320 		DP_EDP_CONFIGURATION_CAP - DP_DPCD_REV + 1
321 };
322 
323 static void query_dp_dual_mode_adaptor(
324 	struct ddc_service *ddc,
325 	struct display_sink_capability *sink_cap)
326 {
327 	uint8_t i;
328 	bool is_valid_hdmi_signature;
329 	enum display_dongle_type *dongle = &sink_cap->dongle_type;
330 	uint8_t type2_dongle_buf[DP_ADAPTOR_TYPE2_SIZE];
331 	bool is_type2_dongle = false;
332 	int retry_count = 2;
333 	struct dp_hdmi_dongle_signature_data *dongle_signature;
334 	struct dc_link *link = ddc->link;
335 
336 	/* Assume we have no valid DP passive dongle connected */
337 	*dongle = DISPLAY_DONGLE_NONE;
338 	sink_cap->max_hdmi_pixel_clock = DP_ADAPTOR_HDMI_SAFE_MAX_TMDS_CLK;
339 
340 	/* Read DP-HDMI dongle I2c (no response interpreted as DP-DVI dongle)*/
341 	if (!i2c_read(
342 		ddc,
343 		DP_HDMI_DONGLE_ADDRESS,
344 		type2_dongle_buf,
345 		sizeof(type2_dongle_buf))) {
346 		/* Passive HDMI dongles can sometimes fail here without retrying*/
347 		while (retry_count > 0) {
348 			if (i2c_read(ddc,
349 				DP_HDMI_DONGLE_ADDRESS,
350 				type2_dongle_buf,
351 				sizeof(type2_dongle_buf)))
352 				break;
353 			retry_count--;
354 		}
355 		if (retry_count == 0) {
356 			*dongle = DISPLAY_DONGLE_DP_DVI_DONGLE;
357 			sink_cap->max_hdmi_pixel_clock = DP_ADAPTOR_DVI_MAX_TMDS_CLK;
358 
359 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf, sizeof(type2_dongle_buf),
360 					"DP-DVI passive dongle %dMhz: ",
361 					DP_ADAPTOR_DVI_MAX_TMDS_CLK / 1000);
362 			return;
363 		}
364 	}
365 
366 	/* Check if Type 2 dongle.*/
367 	if (type2_dongle_buf[DP_ADAPTOR_TYPE2_REG_ID] == DP_ADAPTOR_TYPE2_ID)
368 		is_type2_dongle = true;
369 
370 	dongle_signature =
371 		(struct dp_hdmi_dongle_signature_data *)type2_dongle_buf;
372 
373 	is_valid_hdmi_signature = true;
374 
375 	/* Check EOT */
376 	if (dongle_signature->eot != DP_HDMI_DONGLE_SIGNATURE_EOT) {
377 		is_valid_hdmi_signature = false;
378 	}
379 
380 	/* Check signature */
381 	for (i = 0; i < sizeof(dongle_signature->id); ++i) {
382 		/* If its not the right signature,
383 		 * skip mismatch in subversion byte.*/
384 		if (dongle_signature->id[i] !=
385 			dp_hdmi_dongle_signature_str[i] && i != 3) {
386 
387 			if (is_type2_dongle) {
388 				is_valid_hdmi_signature = false;
389 				break;
390 			}
391 
392 		}
393 	}
394 
395 	if (is_type2_dongle) {
396 		uint32_t max_tmds_clk =
397 			type2_dongle_buf[DP_ADAPTOR_TYPE2_REG_MAX_TMDS_CLK];
398 
399 		max_tmds_clk = max_tmds_clk * 2 + max_tmds_clk / 2;
400 
401 		if (0 == max_tmds_clk ||
402 				max_tmds_clk < DP_ADAPTOR_TYPE2_MIN_TMDS_CLK ||
403 				max_tmds_clk > DP_ADAPTOR_TYPE2_MAX_TMDS_CLK) {
404 			*dongle = DISPLAY_DONGLE_DP_DVI_DONGLE;
405 
406 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
407 					sizeof(type2_dongle_buf),
408 					"DP-DVI passive dongle %dMhz: ",
409 					DP_ADAPTOR_DVI_MAX_TMDS_CLK / 1000);
410 		} else {
411 			if (is_valid_hdmi_signature == true) {
412 				*dongle = DISPLAY_DONGLE_DP_HDMI_DONGLE;
413 
414 				CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
415 						sizeof(type2_dongle_buf),
416 						"Type 2 DP-HDMI passive dongle %dMhz: ",
417 						max_tmds_clk);
418 			} else {
419 				*dongle = DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE;
420 
421 				CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
422 						sizeof(type2_dongle_buf),
423 						"Type 2 DP-HDMI passive dongle (no signature) %dMhz: ",
424 						max_tmds_clk);
425 
426 			}
427 
428 			/* Multiply by 1000 to convert to kHz. */
429 			sink_cap->max_hdmi_pixel_clock =
430 				max_tmds_clk * 1000;
431 		}
432 		sink_cap->is_dongle_type_one = false;
433 
434 	} else {
435 		if (is_valid_hdmi_signature == true) {
436 			*dongle = DISPLAY_DONGLE_DP_HDMI_DONGLE;
437 
438 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
439 					sizeof(type2_dongle_buf),
440 					"Type 1 DP-HDMI passive dongle %dMhz: ",
441 					sink_cap->max_hdmi_pixel_clock / 1000);
442 		} else {
443 			*dongle = DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE;
444 
445 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
446 					sizeof(type2_dongle_buf),
447 					"Type 1 DP-HDMI passive dongle (no signature) %dMhz: ",
448 					sink_cap->max_hdmi_pixel_clock / 1000);
449 		}
450 		sink_cap->is_dongle_type_one = true;
451 	}
452 
453 	return;
454 }
455 
456 static enum signal_type dp_passive_dongle_detection(struct ddc_service *ddc,
457 						    struct display_sink_capability *sink_cap,
458 						    struct audio_support *audio_support)
459 {
460 	query_dp_dual_mode_adaptor(ddc, sink_cap);
461 
462 	return decide_signal_from_strap_and_dongle_type(sink_cap->dongle_type,
463 							audio_support);
464 }
465 
466 static void link_disconnect_sink(struct dc_link *link)
467 {
468 	if (link->local_sink) {
469 		dc_sink_release(link->local_sink);
470 		link->local_sink = NULL;
471 	}
472 
473 	link->dpcd_sink_count = 0;
474 	//link->dpcd_caps.dpcd_rev.raw = 0;
475 }
476 
477 static void link_disconnect_remap(struct dc_sink *prev_sink, struct dc_link *link)
478 {
479 	dc_sink_release(link->local_sink);
480 	link->local_sink = prev_sink;
481 }
482 
483 static void query_hdcp_capability(enum signal_type signal, struct dc_link *link)
484 {
485 	struct hdcp_protection_message msg22;
486 	struct hdcp_protection_message msg14;
487 
488 	memset(&msg22, 0, sizeof(struct hdcp_protection_message));
489 	memset(&msg14, 0, sizeof(struct hdcp_protection_message));
490 	memset(link->hdcp_caps.rx_caps.raw, 0,
491 		sizeof(link->hdcp_caps.rx_caps.raw));
492 
493 	if ((link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT &&
494 			link->ddc->transaction_type ==
495 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX) ||
496 			link->connector_signal == SIGNAL_TYPE_EDP) {
497 		msg22.data = link->hdcp_caps.rx_caps.raw;
498 		msg22.length = sizeof(link->hdcp_caps.rx_caps.raw);
499 		msg22.msg_id = HDCP_MESSAGE_ID_RX_CAPS;
500 	} else {
501 		msg22.data = &link->hdcp_caps.rx_caps.fields.version;
502 		msg22.length = sizeof(link->hdcp_caps.rx_caps.fields.version);
503 		msg22.msg_id = HDCP_MESSAGE_ID_HDCP2VERSION;
504 	}
505 	msg22.version = HDCP_VERSION_22;
506 	msg22.link = HDCP_LINK_PRIMARY;
507 	msg22.max_retries = 5;
508 	dc_process_hdcp_msg(signal, link, &msg22);
509 
510 	if (signal == SIGNAL_TYPE_DISPLAY_PORT || signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
511 		msg14.data = &link->hdcp_caps.bcaps.raw;
512 		msg14.length = sizeof(link->hdcp_caps.bcaps.raw);
513 		msg14.msg_id = HDCP_MESSAGE_ID_READ_BCAPS;
514 		msg14.version = HDCP_VERSION_14;
515 		msg14.link = HDCP_LINK_PRIMARY;
516 		msg14.max_retries = 5;
517 
518 		dc_process_hdcp_msg(signal, link, &msg14);
519 	}
520 
521 }
522 static void read_current_link_settings_on_detect(struct dc_link *link)
523 {
524 	union lane_count_set lane_count_set = {0};
525 	uint8_t link_bw_set = 0;
526 	uint8_t link_rate_set = 0;
527 	uint32_t read_dpcd_retry_cnt = 10;
528 	enum dc_status status = DC_ERROR_UNEXPECTED;
529 	int i;
530 	union max_down_spread max_down_spread = {0};
531 
532 	// Read DPCD 00101h to find out the number of lanes currently set
533 	for (i = 0; i < read_dpcd_retry_cnt; i++) {
534 		status = core_link_read_dpcd(link,
535 					     DP_LANE_COUNT_SET,
536 					     &lane_count_set.raw,
537 					     sizeof(lane_count_set));
538 		/* First DPCD read after VDD ON can fail if the particular board
539 		 * does not have HPD pin wired correctly. So if DPCD read fails,
540 		 * which it should never happen, retry a few times. Target worst
541 		 * case scenario of 80 ms.
542 		 */
543 		if (status == DC_OK) {
544 			link->cur_link_settings.lane_count =
545 					lane_count_set.bits.LANE_COUNT_SET;
546 			break;
547 		}
548 
549 		msleep(8);
550 	}
551 
552 	// Read DPCD 00100h to find if standard link rates are set
553 	core_link_read_dpcd(link, DP_LINK_BW_SET,
554 			    &link_bw_set, sizeof(link_bw_set));
555 
556 	if (link_bw_set == 0) {
557 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
558 			/* If standard link rates are not being used,
559 			 * Read DPCD 00115h to find the edp link rate set used
560 			 */
561 			core_link_read_dpcd(link, DP_LINK_RATE_SET,
562 					    &link_rate_set, sizeof(link_rate_set));
563 
564 			// edp_supported_link_rates_count = 0 for DP
565 			if (link_rate_set < link->dpcd_caps.edp_supported_link_rates_count) {
566 				link->cur_link_settings.link_rate =
567 					link->dpcd_caps.edp_supported_link_rates[link_rate_set];
568 				link->cur_link_settings.link_rate_set = link_rate_set;
569 				link->cur_link_settings.use_link_rate_set = true;
570 			}
571 		} else {
572 			// Link Rate not found. Seamless boot may not work.
573 			ASSERT(false);
574 		}
575 	} else {
576 		link->cur_link_settings.link_rate = link_bw_set;
577 		link->cur_link_settings.use_link_rate_set = false;
578 	}
579 	// Read DPCD 00003h to find the max down spread.
580 	core_link_read_dpcd(link, DP_MAX_DOWNSPREAD,
581 			    &max_down_spread.raw, sizeof(max_down_spread));
582 	link->cur_link_settings.link_spread =
583 		max_down_spread.bits.MAX_DOWN_SPREAD ?
584 		LINK_SPREAD_05_DOWNSPREAD_30KHZ : LINK_SPREAD_DISABLED;
585 }
586 
587 static bool detect_dp(struct dc_link *link,
588 		      struct display_sink_capability *sink_caps,
589 		      enum dc_detect_reason reason)
590 {
591 	struct audio_support *audio_support = &link->dc->res_pool->audio_support;
592 
593 	sink_caps->signal = link_detect_sink_signal_type(link, reason);
594 	sink_caps->transaction_type =
595 		get_ddc_transaction_type(sink_caps->signal);
596 
597 	if (sink_caps->transaction_type == DDC_TRANSACTION_TYPE_I2C_OVER_AUX) {
598 		sink_caps->signal = SIGNAL_TYPE_DISPLAY_PORT;
599 		if (!detect_dp_sink_caps(link)) {
600 			return false;
601 		}
602 
603 		if (is_dp_branch_device(link))
604 			/* DP SST branch */
605 			link->type = dc_connection_sst_branch;
606 	} else {
607 		if (link->dc->debug.disable_dp_plus_plus_wa &&
608 				link->link_enc->features.flags.bits.IS_UHBR20_CAPABLE)
609 			return false;
610 
611 		/* DP passive dongles */
612 		sink_caps->signal = dp_passive_dongle_detection(link->ddc,
613 								sink_caps,
614 								audio_support);
615 		link->dpcd_caps.dongle_type = sink_caps->dongle_type;
616 		link->dpcd_caps.is_dongle_type_one = sink_caps->is_dongle_type_one;
617 		link->dpcd_caps.dpcd_rev.raw = 0;
618 		link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.raw = 0;
619 	}
620 
621 	return true;
622 }
623 
624 static bool is_same_edid(struct dc_edid *old_edid, struct dc_edid *new_edid)
625 {
626 	if (old_edid->length != new_edid->length)
627 		return false;
628 
629 	if (new_edid->length == 0)
630 		return false;
631 
632 	return (memcmp(old_edid->raw_edid,
633 		       new_edid->raw_edid, new_edid->length) == 0);
634 }
635 
636 static bool wait_for_entering_dp_alt_mode(struct dc_link *link)
637 {
638 
639 	/**
640 	 * something is terribly wrong if time out is > 200ms. (5Hz)
641 	 * 500 microseconds * 400 tries us 200 ms
642 	 **/
643 	unsigned int sleep_time_in_microseconds = 500;
644 	unsigned int tries_allowed = 400;
645 	bool is_in_alt_mode;
646 	unsigned long long enter_timestamp;
647 	unsigned long long finish_timestamp;
648 	unsigned long long time_taken_in_ns;
649 	int tries_taken;
650 
651 	DC_LOGGER_INIT(link->ctx->logger);
652 
653 	/**
654 	 * this function will only exist if we are on dcn21 (is_in_alt_mode is a
655 	 *  function pointer, so checking to see if it is equal to 0 is the same
656 	 *  as checking to see if it is null
657 	 **/
658 	if (!link->link_enc->funcs->is_in_alt_mode)
659 		return true;
660 
661 	is_in_alt_mode = link->link_enc->funcs->is_in_alt_mode(link->link_enc);
662 	DC_LOG_DC("DP Alt mode state on HPD: %d  Link=%d\n", is_in_alt_mode, link->link_index);
663 
664 	if (is_in_alt_mode)
665 		return true;
666 
667 	enter_timestamp = dm_get_timestamp(link->ctx);
668 
669 	for (tries_taken = 0; tries_taken < tries_allowed; tries_taken++) {
670 		udelay(sleep_time_in_microseconds);
671 		/* ask the link if alt mode is enabled, if so return ok */
672 		if (link->link_enc->funcs->is_in_alt_mode(link->link_enc)) {
673 			finish_timestamp = dm_get_timestamp(link->ctx);
674 			time_taken_in_ns =
675 				dm_get_elapse_time_in_ns(link->ctx,
676 							 finish_timestamp,
677 							 enter_timestamp);
678 			DC_LOG_WARNING("Alt mode entered finished after %llu ms\n",
679 				       div_u64(time_taken_in_ns, 1000000));
680 			return true;
681 		}
682 	}
683 	finish_timestamp = dm_get_timestamp(link->ctx);
684 	time_taken_in_ns = dm_get_elapse_time_in_ns(link->ctx, finish_timestamp,
685 						    enter_timestamp);
686 	DC_LOG_WARNING("Alt mode has timed out after %llu ms\n",
687 			div_u64(time_taken_in_ns, 1000000));
688 	return false;
689 }
690 
691 static void apply_dpia_mst_dsc_always_on_wa(struct dc_link *link)
692 {
693 	/* Apply work around for tunneled MST on certain USB4 docks. Always use DSC if dock
694 	 * reports DSC support.
695 	 */
696 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
697 			link->type == dc_connection_mst_branch &&
698 			link->dpcd_caps.branch_dev_id == DP_BRANCH_DEVICE_ID_90CC24 &&
699 			link->dpcd_caps.branch_hw_revision == DP_BRANCH_HW_REV_20 &&
700 			link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_SUPPORT &&
701 			!link->dc->debug.dpia_debug.bits.disable_mst_dsc_work_around)
702 		link->wa_flags.dpia_mst_dsc_always_on = true;
703 
704 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
705 		link->type == dc_connection_mst_branch &&
706 		link->dpcd_caps.branch_dev_id == DP_BRANCH_DEVICE_ID_90CC24 &&
707 		link->dpcd_caps.branch_vendor_specific_data[2] == MST_HUB_ID_0x5A &&
708 		link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_SUPPORT &&
709 		!link->dc->debug.dpia_debug.bits.disable_mst_dsc_work_around) {
710 			link->wa_flags.dpia_mst_dsc_always_on = true;
711 	}
712 }
713 
714 static void revert_dpia_mst_dsc_always_on_wa(struct dc_link *link)
715 {
716 	/* Disable work around which keeps DSC on for tunneled MST on certain USB4 docks. */
717 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA)
718 		link->wa_flags.dpia_mst_dsc_always_on = false;
719 }
720 
721 static bool discover_dp_mst_topology(struct dc_link *link, enum dc_detect_reason reason)
722 {
723 	DC_LOGGER_INIT(link->ctx->logger);
724 
725 	LINK_INFO("link=%d, mst branch is now Connected\n",
726 		  link->link_index);
727 
728 	link->type = dc_connection_mst_branch;
729 	apply_dpia_mst_dsc_always_on_wa(link);
730 
731 	dm_helpers_dp_update_branch_info(link->ctx, link);
732 	if (dm_helpers_dp_mst_start_top_mgr(link->ctx,
733 			link, (reason == DETECT_REASON_BOOT || reason == DETECT_REASON_RESUMEFROMS3S4))) {
734 		link_disconnect_sink(link);
735 	} else {
736 		link->type = dc_connection_sst_branch;
737 	}
738 
739 	return link->type == dc_connection_mst_branch;
740 }
741 
742 bool link_reset_cur_dp_mst_topology(struct dc_link *link)
743 {
744 	DC_LOGGER_INIT(link->ctx->logger);
745 
746 	LINK_INFO("link=%d, mst branch is now Disconnected\n",
747 		  link->link_index);
748 
749 	revert_dpia_mst_dsc_always_on_wa(link);
750 	return dm_helpers_dp_mst_stop_top_mgr(link->ctx, link);
751 }
752 
753 static bool should_prepare_phy_clocks_for_link_verification(const struct dc *dc,
754 		enum dc_detect_reason reason)
755 {
756 	int i;
757 	bool can_apply_seamless_boot = false;
758 
759 	for (i = 0; i < dc->current_state->stream_count; i++) {
760 		if (dc->current_state->streams[i]->apply_seamless_boot_optimization) {
761 			can_apply_seamless_boot = true;
762 			break;
763 		}
764 	}
765 
766 	return !can_apply_seamless_boot && reason != DETECT_REASON_BOOT;
767 }
768 
769 static void prepare_phy_clocks_for_destructive_link_verification(const struct dc *dc)
770 {
771 	dc_z10_restore(dc);
772 	clk_mgr_exit_optimized_pwr_state(dc, dc->clk_mgr);
773 }
774 
775 static void restore_phy_clocks_for_destructive_link_verification(const struct dc *dc)
776 {
777 	clk_mgr_optimize_pwr_state(dc, dc->clk_mgr);
778 }
779 
780 static void verify_link_capability_destructive(struct dc_link *link,
781 		struct dc_sink *sink,
782 		enum dc_detect_reason reason)
783 {
784 	bool should_prepare_phy_clocks =
785 			should_prepare_phy_clocks_for_link_verification(link->dc, reason);
786 
787 	if (should_prepare_phy_clocks)
788 		prepare_phy_clocks_for_destructive_link_verification(link->dc);
789 
790 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
791 		struct dc_link_settings known_limit_link_setting =
792 				dp_get_max_link_cap(link);
793 		link_set_all_streams_dpms_off_for_link(link);
794 		dp_verify_link_cap_with_retries(
795 				link, &known_limit_link_setting,
796 				LINK_TRAINING_MAX_VERIFY_RETRY);
797 	} else {
798 		ASSERT(0);
799 	}
800 
801 	if (should_prepare_phy_clocks)
802 		restore_phy_clocks_for_destructive_link_verification(link->dc);
803 }
804 
805 static void verify_link_capability_non_destructive(struct dc_link *link)
806 {
807 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
808 		if (dc_is_embedded_signal(link->local_sink->sink_signal) ||
809 				link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA)
810 			/* TODO - should we check link encoder's max link caps here?
811 			 * How do we know which link encoder to check from?
812 			 */
813 			link->verified_link_cap = link->reported_link_cap;
814 		else
815 			link->verified_link_cap = dp_get_max_link_cap(link);
816 	}
817 }
818 
819 static bool should_verify_link_capability_destructively(struct dc_link *link,
820 		enum dc_detect_reason reason)
821 {
822 	bool destrictive = false;
823 	struct dc_link_settings max_link_cap;
824 	bool is_link_enc_unavailable = false;
825 
826 	if (!link->dc->config.unify_link_enc_assignment)
827 		is_link_enc_unavailable = link->link_enc &&
828 			link->dc->res_pool->funcs->link_encs_assign &&
829 			!link_enc_cfg_is_link_enc_avail(
830 					link->ctx->dc,
831 					link->link_enc->preferred_engine,
832 					link);
833 
834 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
835 		max_link_cap = dp_get_max_link_cap(link);
836 		destrictive = true;
837 
838 		if (link->dc->debug.skip_detection_link_training ||
839 				dc_is_embedded_signal(link->local_sink->sink_signal) ||
840 				(link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
841 				!link->dc->config.enable_dpia_pre_training)) {
842 			destrictive = false;
843 		} else if (link_dp_get_encoding_format(&max_link_cap) ==
844 				DP_8b_10b_ENCODING) {
845 			if (link->dpcd_caps.is_mst_capable ||
846 					is_link_enc_unavailable) {
847 				destrictive = false;
848 			}
849 		}
850 	}
851 
852 	return destrictive;
853 }
854 
855 static void verify_link_capability(struct dc_link *link, struct dc_sink *sink,
856 		enum dc_detect_reason reason)
857 {
858 	if (should_verify_link_capability_destructively(link, reason))
859 		verify_link_capability_destructive(link, sink, reason);
860 	else
861 		verify_link_capability_non_destructive(link);
862 }
863 
864 /**
865  * link_detect_evaluate_edid_header() - Evaluate if an EDID header is acceptable.
866  *
867  * Evaluates an 8-byte EDID header to check if it's good enough
868  * for the purpose of determining whether a display is connected
869  * without reading the full EDID.
870  *
871  * @edid_header: The first 8 bytes of the EDID read from DDC.
872  *
873  * Return: true if the header looks valid (>= 6 of 8 bytes match the
874  *         expected 00/FF pattern), false otherwise.
875  */
876 static bool link_detect_evaluate_edid_header(uint8_t edid_header[8])
877 {
878 	int edid_header_score = 0;
879 	int i;
880 
881 	for (i = 0; i < 8; ++i)
882 		edid_header_score += edid_header[i] == ((i == 0 || i == 7) ? 0x00 : 0xff);
883 
884 	return edid_header_score >= 6;
885 }
886 
887 /**
888  * link_detect_ddc_probe() - Probe the DDC to see if a display is connected.
889  *
890  * Detect whether a display is connected to DDC without reading full EDID.
891  * Reads only the EDID header (the first 8 bytes of EDID) from DDC and
892  * evaluates whether that matches.
893  *
894  * @link: DC link whose DDC/I2C is probed for the EDID header.
895  *
896  * Return: true if the EDID header was read and passes validation,
897  *         false otherwise.
898  */
899 static bool link_detect_ddc_probe(struct dc_link *link)
900 {
901 	if (!link->ddc)
902 		return false;
903 
904 	uint8_t edid_header[8] = {0};
905 	bool ddc_probed = i2c_read(link->ddc, 0x50, edid_header, sizeof(edid_header));
906 
907 	if (!ddc_probed)
908 		return false;
909 
910 	if (!link_detect_evaluate_edid_header(edid_header))
911 		return false;
912 
913 	return true;
914 }
915 
916 /**
917  * link_detect_dac_load_detect() - Performs DAC load detection.
918  *
919  * Load detection can be used to detect the presence of an
920  * analog display when we can't read DDC. This causes a visible
921  * visual glitch so it should be used sparingly.
922  *
923  * @link: DC link to test using the DAC load-detect path.
924  *
925  * Return: true if the VBIOS load-detect call reports OK, false
926  *         otherwise.
927  */
928 static bool link_detect_dac_load_detect(struct dc_link *link)
929 {
930 	struct dc_bios *bios = link->ctx->dc_bios;
931 	struct link_encoder *link_enc = link->link_enc;
932 	enum engine_id engine_id = link_enc->preferred_engine;
933 	enum dal_device_type device_type = DEVICE_TYPE_CRT;
934 	enum bp_result bp_result;
935 	uint32_t enum_id;
936 
937 	switch (engine_id) {
938 	case ENGINE_ID_DACB:
939 		enum_id = 2;
940 		break;
941 	case ENGINE_ID_DACA:
942 	default:
943 		engine_id = ENGINE_ID_DACA;
944 		enum_id = 1;
945 		break;
946 	}
947 
948 	bp_result = bios->funcs->dac_load_detection(bios, engine_id, device_type, enum_id);
949 	return bp_result == BP_RESULT_OK;
950 }
951 
952 /*
953  * detect_link_and_local_sink() - Detect if a sink is attached to a given link
954  *
955  * link->local_sink is created or destroyed as needed.
956  *
957  * This does not create remote sinks.
958  */
959 static bool detect_link_and_local_sink(struct dc_link *link,
960 				  enum dc_detect_reason reason)
961 {
962 	struct dc_sink_init_data sink_init_data = { 0 };
963 	struct display_sink_capability sink_caps = { 0 };
964 	uint32_t i;
965 	bool converter_disable_audio = false;
966 	struct audio_support *aud_support = &link->dc->res_pool->audio_support;
967 	bool same_edid = false;
968 	enum dc_edid_status edid_status;
969 	struct dc_context *dc_ctx = link->ctx;
970 	struct dc *dc = dc_ctx->dc;
971 	struct dc_sink *sink = NULL;
972 	struct dc_sink *prev_sink = NULL;
973 	struct dpcd_caps prev_dpcd_caps;
974 	enum dc_connection_type new_connection_type = dc_connection_none;
975 	const uint32_t post_oui_delay = 30; // 30ms
976 
977 	DC_LOGGER_INIT(link->ctx->logger);
978 
979 	if (dc_is_virtual_signal(link->connector_signal))
980 		return false;
981 
982 	if (((link->connector_signal == SIGNAL_TYPE_LVDS ||
983 		link->connector_signal == SIGNAL_TYPE_EDP) &&
984 		(!link->dc->config.allow_edp_hotplug_detection)) &&
985 		link->local_sink) {
986 		// need to re-write OUI and brightness in resume case
987 		if (link->connector_signal == SIGNAL_TYPE_EDP &&
988 			(link->dpcd_sink_ext_caps.bits.oled == 1)) {
989 			dpcd_set_source_specific_data(link);
990 			msleep(post_oui_delay);
991 			set_default_brightness(link);
992 		}
993 
994 		return true;
995 	}
996 
997 	if (!link_detect_connection_type(link, &new_connection_type)) {
998 		BREAK_TO_DEBUGGER();
999 		return false;
1000 	}
1001 
1002 	prev_sink = link->local_sink;
1003 	if (prev_sink) {
1004 		dc_sink_retain(prev_sink);
1005 		memcpy(&prev_dpcd_caps, &link->dpcd_caps, sizeof(struct dpcd_caps));
1006 	}
1007 
1008 	link_disconnect_sink(link);
1009 	if (new_connection_type != dc_connection_none) {
1010 		link->type = new_connection_type;
1011 		link->link_state_valid = false;
1012 
1013 		/* From Disconnected-to-Connected. */
1014 		switch (link->connector_signal) {
1015 		case SIGNAL_TYPE_HDMI_TYPE_A: {
1016 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1017 			if (aud_support->hdmi_audio_native)
1018 				sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1019 			else
1020 				sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1021 			break;
1022 		}
1023 
1024 		case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1025 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1026 			sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1027 			break;
1028 		}
1029 
1030 		case SIGNAL_TYPE_DVI_DUAL_LINK: {
1031 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1032 			sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1033 			break;
1034 		}
1035 
1036 		case SIGNAL_TYPE_RGB: {
1037 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1038 			sink_caps.signal = SIGNAL_TYPE_RGB;
1039 			break;
1040 		}
1041 
1042 		case SIGNAL_TYPE_LVDS: {
1043 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1044 			sink_caps.signal = SIGNAL_TYPE_LVDS;
1045 			break;
1046 		}
1047 
1048 		case SIGNAL_TYPE_EDP: {
1049 			detect_edp_sink_caps(link);
1050 			read_current_link_settings_on_detect(link);
1051 
1052 			/* Disable power sequence on MIPI panel + converter
1053 			 */
1054 			if (dc->config.enable_mipi_converter_optimization &&
1055 				dc_ctx->dce_version == DCN_VERSION_3_01 &&
1056 				link->dpcd_caps.sink_dev_id == DP_BRANCH_DEVICE_ID_0022B9 &&
1057 				memcmp(&link->dpcd_caps.branch_dev_name, DP_SINK_BRANCH_DEV_NAME_7580,
1058 					sizeof(link->dpcd_caps.branch_dev_name)) == 0) {
1059 				dc->config.edp_no_power_sequencing = true;
1060 
1061 				if (!link->dpcd_caps.set_power_state_capable_edp)
1062 					link->wa_flags.dp_keep_receiver_powered = true;
1063 			}
1064 
1065 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1066 			sink_caps.signal = SIGNAL_TYPE_EDP;
1067 			break;
1068 		}
1069 
1070 		case SIGNAL_TYPE_DISPLAY_PORT: {
1071 
1072 			/* wa HPD high coming too early*/
1073 			if (link->ep_type == DISPLAY_ENDPOINT_PHY &&
1074 			    link->link_enc->features.flags.bits.DP_IS_USB_C == 1) {
1075 
1076 				/* if alt mode times out, return false */
1077 				if (!wait_for_entering_dp_alt_mode(link))
1078 					return false;
1079 			}
1080 
1081 			if (!detect_dp(link, &sink_caps, reason)) {
1082 
1083 				if (prev_sink)
1084 					dc_sink_release(prev_sink);
1085 				return false;
1086 			}
1087 
1088 			/* Active SST downstream branch device unplug*/
1089 			if (link->type == dc_connection_sst_branch &&
1090 			    link->dpcd_caps.sink_count.bits.SINK_COUNT == 0) {
1091 				if (prev_sink)
1092 					/* Downstream unplug */
1093 					dc_sink_release(prev_sink);
1094 				return true;
1095 			}
1096 
1097 			/* disable audio for non DP to HDMI active sst converter */
1098 			if (link->type == dc_connection_sst_branch &&
1099 					is_dp_active_dongle(link) &&
1100 					(link->dpcd_caps.dongle_type !=
1101 							DISPLAY_DONGLE_DP_HDMI_CONVERTER))
1102 				converter_disable_audio = true;
1103 
1104 			/* limited link rate to HBR3 for DPIA until we implement USB4 V2 */
1105 			if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
1106 					link->reported_link_cap.link_rate > LINK_RATE_HIGH3)
1107 				link->reported_link_cap.link_rate = LINK_RATE_HIGH3;
1108 
1109 			if (link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dp_tunneling
1110 					&& link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dpia_bw_alloc
1111 					&& link->dpcd_caps.usb4_dp_tun_info.driver_bw_cap.bits.driver_bw_alloc_support) {
1112 				if (link_dpia_enable_usb4_dp_bw_alloc_mode(link) == false)
1113 					link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dpia_bw_alloc = false;
1114 			}
1115 			break;
1116 		}
1117 
1118 		default:
1119 			DC_ERROR("Invalid connector type! signal:%d\n",
1120 				 link->connector_signal);
1121 			if (prev_sink)
1122 				dc_sink_release(prev_sink);
1123 			return false;
1124 		} /* switch() */
1125 
1126 		if (link->dpcd_caps.sink_count.bits.SINK_COUNT)
1127 			link->dpcd_sink_count =
1128 				link->dpcd_caps.sink_count.bits.SINK_COUNT;
1129 		else
1130 			link->dpcd_sink_count = 1;
1131 
1132 		set_ddc_transaction_type(link->ddc,
1133 						     sink_caps.transaction_type);
1134 
1135 		link->aux_mode =
1136 			link_is_in_aux_transaction_mode(link->ddc);
1137 
1138 		sink_init_data.link = link;
1139 		sink_init_data.sink_signal = sink_caps.signal;
1140 
1141 		sink = dc_sink_create(&sink_init_data);
1142 		if (!sink) {
1143 			DC_ERROR("Failed to create sink!\n");
1144 			if (prev_sink)
1145 				dc_sink_release(prev_sink);
1146 			return false;
1147 		}
1148 
1149 		sink->link->dongle_max_pix_clk = sink_caps.max_hdmi_pixel_clock;
1150 		sink->converter_disable_audio = converter_disable_audio;
1151 
1152 		/* dc_sink_create returns a new reference */
1153 		link->local_sink = sink;
1154 
1155 		edid_status = dm_helpers_read_local_edid(link->ctx,
1156 							 link, sink);
1157 
1158 		switch (edid_status) {
1159 		case EDID_BAD_CHECKSUM:
1160 			DC_LOG_ERROR("EDID checksum invalid.\n");
1161 			break;
1162 		case EDID_PARTIAL_VALID:
1163 			DC_LOG_ERROR("Partial EDID valid, abandon invalid blocks.\n");
1164 			break;
1165 		case EDID_NO_RESPONSE:
1166 			/* Analog connectors without EDID:
1167 			 * - old monitor that actually doesn't have EDID
1168 			 * - cheap DVI-A cable or adapter that doesn't connect DDC
1169 			 */
1170 			if (dc_connector_supports_analog(link->link_id.id)) {
1171 				/* If we didn't do DAC load detection yet, do it now
1172 				 * to verify there really is a display connected.
1173 				 */
1174 				if (link->type != dc_connection_dac_load &&
1175 					!link_detect_dac_load_detect(link)) {
1176 					if (prev_sink)
1177 						dc_sink_release(prev_sink);
1178 					link_disconnect_sink(link);
1179 					return false;
1180 				}
1181 
1182 				DC_LOG_INFO("%s detected analog display without EDID\n", __func__);
1183 				link->type = dc_connection_dac_load;
1184 				sink->edid_caps.analog = true;
1185 				break;
1186 			}
1187 
1188 			DC_LOG_ERROR("No EDID read.\n");
1189 
1190 			/*
1191 			 * Abort detection for non-DP connectors if we have
1192 			 * no EDID
1193 			 *
1194 			 * DP needs to report as connected if HDP is high
1195 			 * even if we have no EDID in order to go to
1196 			 * fail-safe mode
1197 			 */
1198 			if (dc_is_hdmi_signal(link->connector_signal) ||
1199 			    dc_is_dvi_signal(link->connector_signal)) {
1200 				if (prev_sink)
1201 					dc_sink_release(prev_sink);
1202 
1203 				return false;
1204 			}
1205 
1206 			if (link->type == dc_connection_sst_branch &&
1207 					link->dpcd_caps.dongle_type ==
1208 						DISPLAY_DONGLE_DP_VGA_CONVERTER &&
1209 					reason == DETECT_REASON_HPDRX) {
1210 				/* Abort detection for DP-VGA adapters when EDID
1211 				 * can't be read and detection reason is VGA-side
1212 				 * hotplug
1213 				 */
1214 				if (prev_sink)
1215 					dc_sink_release(prev_sink);
1216 				link_disconnect_sink(link);
1217 
1218 				return true;
1219 			}
1220 
1221 			break;
1222 		default:
1223 			break;
1224 		}
1225 
1226 		// Check if edid is the same
1227 		if ((prev_sink) &&
1228 		    (edid_status == EDID_THE_SAME || edid_status == EDID_OK))
1229 			same_edid = is_same_edid(&prev_sink->dc_edid,
1230 						 &sink->dc_edid);
1231 
1232 		if (sink->edid_caps.panel_patch.skip_scdc_overwrite)
1233 			link->ctx->dc->debug.hdmi20_disable = true;
1234 
1235 		if (sink->edid_caps.panel_patch.remove_sink_ext_caps)
1236 			link->dpcd_sink_ext_caps.raw = 0;
1237 
1238 		if (dc_is_hdmi_signal(link->connector_signal))
1239 			read_scdc_caps(link->ddc, link->local_sink);
1240 
1241 		if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT &&
1242 		    sink_caps.transaction_type ==
1243 		    DDC_TRANSACTION_TYPE_I2C_OVER_AUX) {
1244 			/*
1245 			 * TODO debug why certain monitors don't like
1246 			 *  two link trainings
1247 			 */
1248 			query_hdcp_capability(sink->sink_signal, link);
1249 		} else {
1250 			// If edid is the same, then discard new sink and revert back to original sink
1251 			if (same_edid) {
1252 				link_disconnect_remap(prev_sink, link);
1253 				sink = prev_sink;
1254 				prev_sink = NULL;
1255 			}
1256 
1257 			if (!sink->edid_caps.analog)
1258 				query_hdcp_capability(sink->sink_signal, link);
1259 		}
1260 
1261 		/* DVI-I connector connected to analog display. */
1262 		if ((link->link_id.id == CONNECTOR_ID_DUAL_LINK_DVII ||
1263 		     link->link_id.id == CONNECTOR_ID_SINGLE_LINK_DVII) &&
1264 			sink->edid_caps.analog)
1265 			sink->sink_signal = SIGNAL_TYPE_RGB;
1266 
1267 		/* HDMI-DVI Dongle */
1268 		if (sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A &&
1269 		    !sink->edid_caps.edid_hdmi)
1270 			sink->sink_signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1271 		else if (dc_is_dvi_signal(sink->sink_signal) &&
1272 			 dc_is_dvi_signal(link->connector_signal) &&
1273 			 aud_support->hdmi_audio_native &&
1274 			 sink->edid_caps.edid_hdmi)
1275 			sink->sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
1276 
1277 		if (link->local_sink && dc_is_dp_signal(sink_caps.signal))
1278 			dp_trace_init(link);
1279 
1280 		/* Connectivity log: detection */
1281 		for (i = 0; i < sink->dc_edid.length / DC_EDID_BLOCK_SIZE; i++) {
1282 			CONN_DATA_DETECT(link,
1283 					 &sink->dc_edid.raw_edid[i * DC_EDID_BLOCK_SIZE],
1284 					 DC_EDID_BLOCK_SIZE,
1285 					 "%s: [Block %d] ", sink->edid_caps.display_name, i);
1286 		}
1287 
1288 		DC_LOG_DETECTION_EDID_PARSER("%s: "
1289 			"manufacturer_id = %X, "
1290 			"product_id = %X, "
1291 			"serial_number = %X, "
1292 			"manufacture_week = %d, "
1293 			"manufacture_year = %d, "
1294 			"display_name = %s, "
1295 			"speaker_flag = %d, "
1296 			"audio_mode_count = %d\n",
1297 			__func__,
1298 			sink->edid_caps.manufacturer_id,
1299 			sink->edid_caps.product_id,
1300 			sink->edid_caps.serial_number,
1301 			sink->edid_caps.manufacture_week,
1302 			sink->edid_caps.manufacture_year,
1303 			sink->edid_caps.display_name,
1304 			sink->edid_caps.speaker_flags,
1305 			sink->edid_caps.audio_mode_count);
1306 
1307 		for (i = 0; i < sink->edid_caps.audio_mode_count; i++) {
1308 			DC_LOG_DETECTION_EDID_PARSER("%s: mode number = %d, "
1309 				"format_code = %d, "
1310 				"channel_count = %d, "
1311 				"sample_rate = %d, "
1312 				"sample_size = %d\n",
1313 				__func__,
1314 				i,
1315 				sink->edid_caps.audio_modes[i].format_code,
1316 				sink->edid_caps.audio_modes[i].channel_count,
1317 				sink->edid_caps.audio_modes[i].sample_rate,
1318 				sink->edid_caps.audio_modes[i].sample_size);
1319 		}
1320 
1321 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
1322 			// Init dc_panel_config by HW config
1323 			if (dc_ctx->dc->res_pool->funcs->get_panel_config_defaults)
1324 				dc_ctx->dc->res_pool->funcs->get_panel_config_defaults(&link->panel_config);
1325 			// Pickup base DM settings
1326 			dm_helpers_init_panel_settings(dc_ctx, &link->panel_config, sink);
1327 			// Override dc_panel_config if system has specific settings
1328 			dm_helpers_override_panel_settings(dc_ctx, &link->panel_config);
1329 
1330 			//sink only can use supported link rate table, we are foreced to enable it
1331 			if (link->reported_link_cap.link_rate == LINK_RATE_UNKNOWN)
1332 				link->panel_config.ilr.optimize_edp_link_rate = true;
1333 			link->reported_link_cap.link_rate = get_max_edp_link_rate(link);
1334 		}
1335 
1336 	} else {
1337 		/* From Connected-to-Disconnected. */
1338 		link->type = dc_connection_none;
1339 		sink_caps.signal = SIGNAL_TYPE_NONE;
1340 		memset(&link->hdcp_caps, 0, sizeof(struct hdcp_caps));
1341 		/* When we unplug a passive DP-HDMI dongle connection, dongle_max_pix_clk
1342 		 *  is not cleared. If we emulate a DP signal on this connection, it thinks
1343 		 *  the dongle is still there and limits the number of modes we can emulate.
1344 		 *  Clear dongle_max_pix_clk on disconnect to fix this
1345 		 */
1346 		link->dongle_max_pix_clk = 0;
1347 
1348 		dc_link_clear_dprx_states(link);
1349 		dp_trace_reset(link);
1350 	}
1351 
1352 	LINK_INFO("link=%d, dc_sink_in=%p is now %s prev_sink=%p edid same=%d\n",
1353 		  link->link_index, sink,
1354 		  (sink_caps.signal ==
1355 		   SIGNAL_TYPE_NONE ? "Disconnected" : "Connected"),
1356 		  prev_sink, same_edid);
1357 
1358 	if (prev_sink)
1359 		dc_sink_release(prev_sink);
1360 
1361 	return true;
1362 }
1363 
1364 /**
1365  * link_detect_analog() - Determines if an analog sink is connected.
1366  *
1367  * @link: DC link to evaluate (must support analog signalling).
1368  * @type: Updated with the detected connection type:
1369  *        dc_connection_single (analog via DDC),
1370  *        dc_connection_dac_load (via load-detect),
1371  *        or dc_connection_none.
1372  *
1373  * Return: true if detection completed.
1374  */
1375 static bool link_detect_analog(struct dc_link *link, enum dc_connection_type *type)
1376 {
1377 	/* Don't care about connectors that don't support an analog signal. */
1378 	ASSERT(dc_connector_supports_analog(link->link_id.id));
1379 
1380 	if (link_detect_ddc_probe(link)) {
1381 		*type = dc_connection_single;
1382 		return true;
1383 	}
1384 
1385 	if (link_detect_dac_load_detect(link)) {
1386 		*type = dc_connection_dac_load;
1387 		return true;
1388 	}
1389 
1390 	*type = dc_connection_none;
1391 	return true;
1392 }
1393 
1394 /*
1395  * link_detect_connection_type() - Determine if there is a sink connected
1396  *
1397  * @type: Returned connection type
1398  * Does not detect downstream devices, such as MST sinks
1399  * or display connected through active dongles
1400  */
1401 bool link_detect_connection_type(struct dc_link *link, enum dc_connection_type *type)
1402 {
1403 	if (link->connector_signal == SIGNAL_TYPE_LVDS) {
1404 		*type = dc_connection_single;
1405 		return true;
1406 	}
1407 
1408 	/* Ignore the HPD pin (if any) for analog connectors.
1409 	 * Instead rely on DDC and DAC.
1410 	 *
1411 	 * - VGA connectors don't have any HPD at all.
1412 	 * - Some DVI-A cables don't connect the HPD pin.
1413 	 * - Some DVI-A cables pull up the HPD pin.
1414 	 *   (So it's high even when no display is connected.)
1415 	 */
1416 	if (dc_connector_supports_analog(link->link_id.id))
1417 		return link_detect_analog(link, type);
1418 
1419 	if (link->connector_signal == SIGNAL_TYPE_EDP) {
1420 		/*in case it is not on*/
1421 		if (!link->dc->config.edp_no_power_sequencing)
1422 			link->dc->hwss.edp_power_control(link, true);
1423 		link->dc->hwss.edp_wait_for_hpd_ready(link, true);
1424 	}
1425 
1426 	/* Link may not have physical HPD pin. */
1427 	if (link->ep_type != DISPLAY_ENDPOINT_PHY) {
1428 		if (link->is_hpd_pending || !dpia_query_hpd_status(link))
1429 			*type = dc_connection_none;
1430 		else
1431 			*type = dc_connection_single;
1432 
1433 		return true;
1434 	}
1435 
1436 
1437 	if (link_get_hpd_state(link)) {
1438 		*type = dc_connection_single;
1439 		/* TODO: need to do the actual detection */
1440 	} else {
1441 		*type = dc_connection_none;
1442 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
1443 			/* eDP is not connected, power down it */
1444 			if (!link->dc->config.edp_no_power_sequencing)
1445 				link->dc->hwss.edp_power_control(link, false);
1446 		}
1447 	}
1448 
1449 	return true;
1450 }
1451 
1452 bool link_detect(struct dc_link *link, enum dc_detect_reason reason)
1453 {
1454 	bool is_local_sink_detect_success;
1455 	bool is_delegated_to_mst_top_mgr = false;
1456 	enum dc_connection_type pre_link_type = link->type;
1457 
1458 	DC_LOGGER_INIT(link->ctx->logger);
1459 
1460 	is_local_sink_detect_success = detect_link_and_local_sink(link, reason);
1461 
1462 	if (is_local_sink_detect_success && link->local_sink)
1463 		verify_link_capability(link, link->local_sink, reason);
1464 
1465 	DC_LOG_DC("%s: link_index=%d is_local_sink_detect_success=%d pre_link_type=%d link_type=%d\n", __func__,
1466 				link->link_index, is_local_sink_detect_success, pre_link_type, link->type);
1467 
1468 	if (is_local_sink_detect_success && link->local_sink &&
1469 			dc_is_dp_signal(link->local_sink->sink_signal) &&
1470 			link->dpcd_caps.is_mst_capable)
1471 		is_delegated_to_mst_top_mgr = discover_dp_mst_topology(link, reason);
1472 
1473 	if (pre_link_type == dc_connection_mst_branch &&
1474 			link->type != dc_connection_mst_branch)
1475 		is_delegated_to_mst_top_mgr = link_reset_cur_dp_mst_topology(link);
1476 
1477 	return is_local_sink_detect_success && !is_delegated_to_mst_top_mgr;
1478 }
1479 
1480 void link_clear_dprx_states(struct dc_link *link)
1481 {
1482 	memset(&link->dprx_states, 0, sizeof(link->dprx_states));
1483 }
1484 
1485 bool link_is_hdcp14(struct dc_link *link, enum signal_type signal)
1486 {
1487 	bool ret = false;
1488 
1489 	switch (signal)	{
1490 	case SIGNAL_TYPE_DISPLAY_PORT:
1491 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
1492 		ret = link->hdcp_caps.bcaps.bits.HDCP_CAPABLE;
1493 		break;
1494 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
1495 	case SIGNAL_TYPE_DVI_DUAL_LINK:
1496 	case SIGNAL_TYPE_HDMI_TYPE_A:
1497 	/* HDMI doesn't tell us its HDCP(1.4) capability, so assume to always be capable,
1498 	 * we can poll for bksv but some displays have an issue with this. Since its so rare
1499 	 * for a display to not be 1.4 capable, this assumtion is ok
1500 	 */
1501 		ret = true;
1502 		break;
1503 	default:
1504 		break;
1505 	}
1506 	return ret;
1507 }
1508 
1509 bool link_is_hdcp22(struct dc_link *link, enum signal_type signal)
1510 {
1511 	bool ret = false;
1512 
1513 	switch (signal)	{
1514 	case SIGNAL_TYPE_DISPLAY_PORT:
1515 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
1516 		ret = (link->hdcp_caps.bcaps.bits.HDCP_CAPABLE &&
1517 				link->hdcp_caps.rx_caps.fields.byte0.hdcp_capable &&
1518 				(link->hdcp_caps.rx_caps.fields.version == 0x2)) ? 1 : 0;
1519 		break;
1520 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
1521 	case SIGNAL_TYPE_DVI_DUAL_LINK:
1522 	case SIGNAL_TYPE_HDMI_TYPE_A:
1523 		ret = (link->hdcp_caps.rx_caps.fields.version == 0x4) ? 1:0;
1524 		break;
1525 	default:
1526 		break;
1527 	}
1528 
1529 	return ret;
1530 }
1531 
1532 const struct dc_link_status *link_get_status(const struct dc_link *link)
1533 {
1534 	return &link->link_status;
1535 }
1536 
1537 
1538 static bool link_add_remote_sink_helper(struct dc_link *dc_link, struct dc_sink *sink)
1539 {
1540 	if (dc_link->sink_count >= MAX_SINKS_PER_LINK) {
1541 		BREAK_TO_DEBUGGER();
1542 		return false;
1543 	}
1544 
1545 	dc_sink_retain(sink);
1546 
1547 	dc_link->remote_sinks[dc_link->sink_count] = sink;
1548 	dc_link->sink_count++;
1549 
1550 	return true;
1551 }
1552 
1553 struct dc_sink *link_add_remote_sink(
1554 		struct dc_link *link,
1555 		const uint8_t *edid,
1556 		int len,
1557 		struct dc_sink_init_data *init_data)
1558 {
1559 	struct dc_sink *dc_sink;
1560 	enum dc_edid_status edid_status;
1561 
1562 	if (len > DC_MAX_EDID_BUFFER_SIZE) {
1563 		dm_error("Max EDID buffer size breached!\n");
1564 		return NULL;
1565 	}
1566 
1567 	if (!init_data) {
1568 		BREAK_TO_DEBUGGER();
1569 		return NULL;
1570 	}
1571 
1572 	if (!init_data->link) {
1573 		BREAK_TO_DEBUGGER();
1574 		return NULL;
1575 	}
1576 
1577 	dc_sink = dc_sink_create(init_data);
1578 
1579 	if (!dc_sink)
1580 		return NULL;
1581 
1582 	memmove(dc_sink->dc_edid.raw_edid, edid, len);
1583 	dc_sink->dc_edid.length = len;
1584 
1585 	if (!link_add_remote_sink_helper(
1586 			link,
1587 			dc_sink))
1588 		goto fail_add_sink;
1589 
1590 	edid_status = dm_helpers_parse_edid_caps(
1591 			link,
1592 			&dc_sink->dc_edid,
1593 			&dc_sink->edid_caps);
1594 
1595 	/*
1596 	 * Treat device as no EDID device if EDID
1597 	 * parsing fails
1598 	 */
1599 	if (edid_status != EDID_OK && edid_status != EDID_PARTIAL_VALID) {
1600 		dc_sink->dc_edid.length = 0;
1601 		dm_error("Bad EDID, status%d!\n", edid_status);
1602 	}
1603 
1604 	return dc_sink;
1605 
1606 fail_add_sink:
1607 	dc_sink_release(dc_sink);
1608 	return NULL;
1609 }
1610 
1611 void link_remove_remote_sink(struct dc_link *link, struct dc_sink *sink)
1612 {
1613 	int i;
1614 
1615 	if (!link->sink_count) {
1616 		BREAK_TO_DEBUGGER();
1617 		return;
1618 	}
1619 
1620 	for (i = 0; i < link->sink_count; i++) {
1621 		if (link->remote_sinks[i] == sink) {
1622 			dc_sink_release(sink);
1623 			link->remote_sinks[i] = NULL;
1624 
1625 			/* shrink array to remove empty place */
1626 			while (i < link->sink_count - 1) {
1627 				link->remote_sinks[i] = link->remote_sinks[i+1];
1628 				i++;
1629 			}
1630 			link->remote_sinks[i] = NULL;
1631 			link->sink_count--;
1632 			return;
1633 		}
1634 	}
1635 }
1636