xref: /linux/drivers/gpu/drm/amd/display/dc/link/link_detection.c (revision 9156bf442ee56c0f883aa4c81af9c8471eef6846)
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_DVI_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 	if (is_valid_hdmi_signature)
395 		sink_cap->max_hdmi_pixel_clock = DP_ADAPTOR_HDMI_SAFE_MAX_TMDS_CLK;
396 
397 	if (is_type2_dongle) {
398 		uint32_t max_tmds_clk =
399 			type2_dongle_buf[DP_ADAPTOR_TYPE2_REG_MAX_TMDS_CLK];
400 
401 		max_tmds_clk = max_tmds_clk * 2 + max_tmds_clk / 2;
402 
403 		if (0 == max_tmds_clk ||
404 				max_tmds_clk < DP_ADAPTOR_TYPE2_MIN_TMDS_CLK ||
405 				max_tmds_clk > DP_ADAPTOR_TYPE2_MAX_TMDS_CLK) {
406 			*dongle = DISPLAY_DONGLE_DP_DVI_DONGLE;
407 
408 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
409 					sizeof(type2_dongle_buf),
410 					"DP-DVI passive dongle %dMhz: ",
411 					DP_ADAPTOR_DVI_MAX_TMDS_CLK / 1000);
412 		} else {
413 			if (is_valid_hdmi_signature == true) {
414 				*dongle = DISPLAY_DONGLE_DP_HDMI_DONGLE;
415 
416 				CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
417 						sizeof(type2_dongle_buf),
418 						"Type 2 DP-HDMI passive dongle %dMhz: ",
419 						max_tmds_clk);
420 			} else {
421 				*dongle = DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE;
422 
423 				CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
424 						sizeof(type2_dongle_buf),
425 						"Type 2 DP-HDMI passive dongle (no signature) %dMhz: ",
426 						max_tmds_clk);
427 
428 			}
429 
430 			/* Multiply by 1000 to convert to kHz. */
431 			sink_cap->max_hdmi_pixel_clock =
432 				max_tmds_clk * 1000;
433 		}
434 		sink_cap->is_dongle_type_one = false;
435 
436 	} else {
437 		if (is_valid_hdmi_signature == true) {
438 			*dongle = DISPLAY_DONGLE_DP_HDMI_DONGLE;
439 
440 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
441 					sizeof(type2_dongle_buf),
442 					"Type 1 DP-HDMI passive dongle %dMhz: ",
443 					sink_cap->max_hdmi_pixel_clock / 1000);
444 		} else {
445 			*dongle = DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE;
446 
447 			CONN_DATA_DETECT(ddc->link, type2_dongle_buf,
448 					sizeof(type2_dongle_buf),
449 					"Type 1 DP-HDMI passive dongle (no signature) %dMhz: ",
450 					sink_cap->max_hdmi_pixel_clock / 1000);
451 		}
452 		sink_cap->is_dongle_type_one = true;
453 	}
454 
455 	return;
456 }
457 
458 static enum signal_type dp_passive_dongle_detection(struct ddc_service *ddc,
459 						    struct display_sink_capability *sink_cap,
460 						    struct audio_support *audio_support)
461 {
462 	query_dp_dual_mode_adaptor(ddc, sink_cap);
463 
464 	return decide_signal_from_strap_and_dongle_type(sink_cap->dongle_type,
465 							audio_support);
466 }
467 
468 static void link_disconnect_sink(struct dc_link *link)
469 {
470 	if (link->local_sink) {
471 		dc_sink_release(link->local_sink);
472 		link->local_sink = NULL;
473 	}
474 
475 	link->dpcd_sink_count = 0;
476 	//link->dpcd_caps.dpcd_rev.raw = 0;
477 }
478 
479 static void link_disconnect_remap(struct dc_sink *prev_sink, struct dc_link *link)
480 {
481 	dc_sink_release(link->local_sink);
482 	link->local_sink = prev_sink;
483 }
484 
485 static void query_hdcp_capability(enum signal_type signal, struct dc_link *link)
486 {
487 	struct hdcp_protection_message msg22;
488 	struct hdcp_protection_message msg14;
489 
490 	memset(&msg22, 0, sizeof(struct hdcp_protection_message));
491 	memset(&msg14, 0, sizeof(struct hdcp_protection_message));
492 	memset(link->hdcp_caps.rx_caps.raw, 0,
493 		sizeof(link->hdcp_caps.rx_caps.raw));
494 
495 	if ((link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT &&
496 			link->ddc->transaction_type ==
497 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX) ||
498 			link->connector_signal == SIGNAL_TYPE_EDP) {
499 		msg22.data = link->hdcp_caps.rx_caps.raw;
500 		msg22.length = sizeof(link->hdcp_caps.rx_caps.raw);
501 		msg22.msg_id = HDCP_MESSAGE_ID_RX_CAPS;
502 	} else {
503 		msg22.data = &link->hdcp_caps.rx_caps.fields.version;
504 		msg22.length = sizeof(link->hdcp_caps.rx_caps.fields.version);
505 		msg22.msg_id = HDCP_MESSAGE_ID_HDCP2VERSION;
506 	}
507 	msg22.version = HDCP_VERSION_22;
508 	msg22.link = HDCP_LINK_PRIMARY;
509 	msg22.max_retries = 5;
510 	dc_process_hdcp_msg(signal, link, &msg22);
511 
512 	if (signal == SIGNAL_TYPE_DISPLAY_PORT || signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
513 		msg14.data = &link->hdcp_caps.bcaps.raw;
514 		msg14.length = sizeof(link->hdcp_caps.bcaps.raw);
515 		msg14.msg_id = HDCP_MESSAGE_ID_READ_BCAPS;
516 		msg14.version = HDCP_VERSION_14;
517 		msg14.link = HDCP_LINK_PRIMARY;
518 		msg14.max_retries = 5;
519 
520 		dc_process_hdcp_msg(signal, link, &msg14);
521 	}
522 
523 }
524 static void read_current_link_settings_on_detect(struct dc_link *link)
525 {
526 	union lane_count_set lane_count_set = {0};
527 	uint8_t link_bw_set = 0;
528 	uint8_t link_rate_set = 0;
529 	uint32_t read_dpcd_retry_cnt = 10;
530 	enum dc_status status = DC_ERROR_UNEXPECTED;
531 	int i;
532 	union max_down_spread max_down_spread = {0};
533 
534 	// Read DPCD 00101h to find out the number of lanes currently set
535 	for (i = 0; i < read_dpcd_retry_cnt; i++) {
536 		status = core_link_read_dpcd(link,
537 					     DP_LANE_COUNT_SET,
538 					     &lane_count_set.raw,
539 					     sizeof(lane_count_set));
540 		/* First DPCD read after VDD ON can fail if the particular board
541 		 * does not have HPD pin wired correctly. So if DPCD read fails,
542 		 * which it should never happen, retry a few times. Target worst
543 		 * case scenario of 80 ms.
544 		 */
545 		if (status == DC_OK) {
546 			link->cur_link_settings.lane_count =
547 					lane_count_set.bits.LANE_COUNT_SET;
548 			break;
549 		}
550 
551 		msleep(8);
552 	}
553 
554 	// Read DPCD 00100h to find if standard link rates are set
555 	core_link_read_dpcd(link, DP_LINK_BW_SET,
556 			    &link_bw_set, sizeof(link_bw_set));
557 
558 	if (link_bw_set == 0) {
559 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
560 			/* If standard link rates are not being used,
561 			 * Read DPCD 00115h to find the edp link rate set used
562 			 */
563 			core_link_read_dpcd(link, DP_LINK_RATE_SET,
564 					    &link_rate_set, sizeof(link_rate_set));
565 
566 			// edp_supported_link_rates_count = 0 for DP
567 			if (link_rate_set < link->dpcd_caps.edp_supported_link_rates_count) {
568 				link->cur_link_settings.link_rate =
569 					link->dpcd_caps.edp_supported_link_rates[link_rate_set];
570 				link->cur_link_settings.link_rate_set = link_rate_set;
571 				link->cur_link_settings.use_link_rate_set = true;
572 			}
573 		} else {
574 			// Link Rate not found. Seamless boot may not work.
575 			ASSERT(false);
576 		}
577 	} else {
578 		link->cur_link_settings.link_rate = link_bw_set;
579 		link->cur_link_settings.use_link_rate_set = false;
580 	}
581 	// Read DPCD 00003h to find the max down spread.
582 	core_link_read_dpcd(link, DP_MAX_DOWNSPREAD,
583 			    &max_down_spread.raw, sizeof(max_down_spread));
584 	link->cur_link_settings.link_spread =
585 		max_down_spread.bits.MAX_DOWN_SPREAD ?
586 		LINK_SPREAD_05_DOWNSPREAD_30KHZ : LINK_SPREAD_DISABLED;
587 }
588 
589 static bool detect_dp(struct dc_link *link,
590 		      struct display_sink_capability *sink_caps,
591 		      enum dc_detect_reason reason)
592 {
593 	struct audio_support *audio_support = &link->dc->res_pool->audio_support;
594 
595 	sink_caps->signal = link_detect_sink_signal_type(link, reason);
596 	sink_caps->transaction_type =
597 		get_ddc_transaction_type(sink_caps->signal);
598 
599 	if (sink_caps->transaction_type == DDC_TRANSACTION_TYPE_I2C_OVER_AUX) {
600 		sink_caps->signal = SIGNAL_TYPE_DISPLAY_PORT;
601 		if (!detect_dp_sink_caps(link)) {
602 			return false;
603 		}
604 
605 		if (is_dp_branch_device(link))
606 			/* DP SST branch */
607 			link->type = dc_connection_sst_branch;
608 	} else {
609 		if (link->dc->debug.disable_dp_plus_plus_wa &&
610 				link->link_enc->features.flags.bits.IS_UHBR20_CAPABLE)
611 			return false;
612 
613 		/* DP passive dongles */
614 		sink_caps->signal = dp_passive_dongle_detection(link->ddc,
615 								sink_caps,
616 								audio_support);
617 		link->dpcd_caps.dongle_type = sink_caps->dongle_type;
618 		link->dpcd_caps.is_dongle_type_one = sink_caps->is_dongle_type_one;
619 		link->dpcd_caps.dpcd_rev.raw = 0;
620 		link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.raw = 0;
621 	}
622 
623 	return true;
624 }
625 
626 static bool is_same_edid(struct dc_edid *old_edid, struct dc_edid *new_edid)
627 {
628 	if (old_edid == NULL || new_edid == NULL)
629 		return false;
630 
631 	if (old_edid->length != new_edid->length)
632 		return false;
633 
634 	if (new_edid->length == 0)
635 		return false;
636 
637 	return (memcmp(old_edid->raw_edid,
638 		       new_edid->raw_edid, new_edid->length) == 0);
639 }
640 
641 static bool wait_for_entering_dp_alt_mode(struct dc_link *link)
642 {
643 
644 	/**
645 	 * something is terribly wrong if time out is > 200ms. (5Hz)
646 	 * 500 microseconds * 400 tries us 200 ms
647 	 **/
648 	unsigned int sleep_time_in_microseconds = 500;
649 	unsigned int tries_allowed = 400;
650 	bool is_in_alt_mode;
651 	unsigned long long enter_timestamp;
652 	unsigned long long finish_timestamp;
653 	unsigned long long time_taken_in_ns;
654 	int tries_taken;
655 
656 	DC_LOGGER_INIT(link->ctx->logger);
657 
658 	/**
659 	 * this function will only exist if we are on dcn21 (is_in_alt_mode is a
660 	 *  function pointer, so checking to see if it is equal to 0 is the same
661 	 *  as checking to see if it is null
662 	 **/
663 	if (!link->link_enc->funcs->is_in_alt_mode)
664 		return true;
665 
666 	is_in_alt_mode = link->link_enc->funcs->is_in_alt_mode(link->link_enc);
667 	DC_LOG_DC("DP Alt mode state on HPD: %d  Link=%d\n", is_in_alt_mode, link->link_index);
668 
669 	if (is_in_alt_mode)
670 		return true;
671 
672 	enter_timestamp = dm_get_timestamp(link->ctx);
673 
674 	for (tries_taken = 0; tries_taken < tries_allowed; tries_taken++) {
675 		udelay(sleep_time_in_microseconds);
676 		/* ask the link if alt mode is enabled, if so return ok */
677 		if (link->link_enc->funcs->is_in_alt_mode(link->link_enc)) {
678 			finish_timestamp = dm_get_timestamp(link->ctx);
679 			time_taken_in_ns =
680 				dm_get_elapse_time_in_ns(link->ctx,
681 							 finish_timestamp,
682 							 enter_timestamp);
683 			DC_LOG_WARNING("Alt mode entered finished after %llu ms\n",
684 				       div_u64(time_taken_in_ns, 1000000));
685 			return true;
686 		}
687 	}
688 	finish_timestamp = dm_get_timestamp(link->ctx);
689 	time_taken_in_ns = dm_get_elapse_time_in_ns(link->ctx, finish_timestamp,
690 						    enter_timestamp);
691 	DC_LOG_WARNING("Alt mode has timed out after %llu ms\n",
692 			div_u64(time_taken_in_ns, 1000000));
693 	return false;
694 }
695 
696 static void apply_dpia_mst_dsc_always_on_wa(struct dc_link *link)
697 {
698 	/* Apply work around for tunneled MST on certain USB4 docks. Always use DSC if dock
699 	 * reports DSC support.
700 	 */
701 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
702 			link->type == dc_connection_mst_branch &&
703 			link->dpcd_caps.branch_dev_id == DP_BRANCH_DEVICE_ID_90CC24 &&
704 			link->dpcd_caps.branch_hw_revision == DP_BRANCH_HW_REV_20 &&
705 			link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_SUPPORT &&
706 			!link->dc->debug.dpia_debug.bits.disable_mst_dsc_work_around)
707 		link->wa_flags.dpia_mst_dsc_always_on = true;
708 
709 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
710 		link->type == dc_connection_mst_branch &&
711 		link->dpcd_caps.branch_dev_id == DP_BRANCH_DEVICE_ID_90CC24 &&
712 		link->dpcd_caps.branch_vendor_specific_data[2] == MST_HUB_ID_0x5A &&
713 		link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_SUPPORT &&
714 		!link->dc->debug.dpia_debug.bits.disable_mst_dsc_work_around) {
715 			link->wa_flags.dpia_mst_dsc_always_on = true;
716 	}
717 }
718 
719 static void revert_dpia_mst_dsc_always_on_wa(struct dc_link *link)
720 {
721 	/* Disable work around which keeps DSC on for tunneled MST on certain USB4 docks. */
722 	if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA)
723 		link->wa_flags.dpia_mst_dsc_always_on = false;
724 }
725 
726 static bool discover_dp_mst_topology(struct dc_link *link, enum dc_detect_reason reason)
727 {
728 	DC_LOGGER_INIT(link->ctx->logger);
729 
730 	LINK_INFO("link=%d, mst branch is now Connected\n",
731 		  link->link_index);
732 
733 	link->type = dc_connection_mst_branch;
734 	apply_dpia_mst_dsc_always_on_wa(link);
735 
736 	dm_helpers_dp_update_branch_info(link->ctx, link);
737 	if (dm_helpers_dp_mst_start_top_mgr(link->ctx,
738 			link, (reason == DETECT_REASON_BOOT || reason == DETECT_REASON_RESUMEFROMS3S4))) {
739 		link_disconnect_sink(link);
740 	} else {
741 		link->type = dc_connection_sst_branch;
742 	}
743 
744 	return link->type == dc_connection_mst_branch;
745 }
746 
747 bool link_reset_cur_dp_mst_topology(struct dc_link *link)
748 {
749 	DC_LOGGER_INIT(link->ctx->logger);
750 
751 	LINK_INFO("link=%d, mst branch is now Disconnected\n",
752 		  link->link_index);
753 
754 	revert_dpia_mst_dsc_always_on_wa(link);
755 	return dm_helpers_dp_mst_stop_top_mgr(link->ctx, link);
756 }
757 
758 static bool should_prepare_phy_clocks_for_link_verification(const struct dc *dc,
759 		enum dc_detect_reason reason)
760 {
761 	int i;
762 	bool can_apply_seamless_boot = false;
763 
764 	for (i = 0; i < dc->current_state->stream_count; i++) {
765 		if (dc->current_state->streams[i]->apply_seamless_boot_optimization) {
766 			can_apply_seamless_boot = true;
767 			break;
768 		}
769 	}
770 
771 	return !can_apply_seamless_boot && reason != DETECT_REASON_BOOT;
772 }
773 
774 static void prepare_phy_clocks_for_destructive_link_verification(const struct dc *dc)
775 {
776 	dc_z10_restore(dc);
777 	clk_mgr_exit_optimized_pwr_state(dc, dc->clk_mgr);
778 }
779 
780 static void restore_phy_clocks_for_destructive_link_verification(const struct dc *dc)
781 {
782 	clk_mgr_optimize_pwr_state(dc, dc->clk_mgr);
783 }
784 
785 static void verify_link_capability_destructive(struct dc_link *link,
786 		struct dc_sink *sink,
787 		enum dc_detect_reason reason)
788 {
789 	bool should_prepare_phy_clocks =
790 			should_prepare_phy_clocks_for_link_verification(link->dc, reason);
791 
792 	if (should_prepare_phy_clocks)
793 		prepare_phy_clocks_for_destructive_link_verification(link->dc);
794 
795 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
796 		struct dc_link_settings known_limit_link_setting =
797 				dp_get_max_link_cap(link);
798 		link_set_all_streams_dpms_off_for_link(link);
799 		dp_verify_link_cap_with_retries(
800 				link, &known_limit_link_setting,
801 				LINK_TRAINING_MAX_VERIFY_RETRY);
802 	} else {
803 		ASSERT(0);
804 	}
805 
806 	if (should_prepare_phy_clocks)
807 		restore_phy_clocks_for_destructive_link_verification(link->dc);
808 }
809 
810 static void verify_link_capability_non_destructive(struct dc_link *link)
811 {
812 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
813 		if (dc_is_embedded_signal(link->local_sink->sink_signal) ||
814 				link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA)
815 			/* TODO - should we check link encoder's max link caps here?
816 			 * How do we know which link encoder to check from?
817 			 */
818 			link->verified_link_cap = link->reported_link_cap;
819 		else
820 			link->verified_link_cap = dp_get_max_link_cap(link);
821 	}
822 }
823 
824 static bool should_verify_link_capability_destructively(struct dc_link *link,
825 		enum dc_detect_reason reason)
826 {
827 	bool destrictive = false;
828 	struct dc_link_settings max_link_cap;
829 	bool is_link_enc_unavailable = false;
830 
831 	if (!link->dc->config.unify_link_enc_assignment)
832 		is_link_enc_unavailable = link->link_enc &&
833 			link->dc->res_pool->funcs->link_encs_assign &&
834 			!link_enc_cfg_is_link_enc_avail(
835 					link->ctx->dc,
836 					link->link_enc->preferred_engine,
837 					link);
838 
839 	if (dc_is_dp_signal(link->local_sink->sink_signal)) {
840 		max_link_cap = dp_get_max_link_cap(link);
841 		destrictive = true;
842 
843 		if (link->dc->debug.skip_detection_link_training ||
844 				dc_is_embedded_signal(link->local_sink->sink_signal) ||
845 				(link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
846 				!link->dc->config.enable_dpia_pre_training)) {
847 			destrictive = false;
848 		} else if (link_dp_get_encoding_format(&max_link_cap) ==
849 				DP_8b_10b_ENCODING) {
850 			if (link->dpcd_caps.is_mst_capable ||
851 					is_link_enc_unavailable) {
852 				destrictive = false;
853 			}
854 		}
855 	}
856 
857 	return destrictive;
858 }
859 
860 static void verify_link_capability(struct dc_link *link, struct dc_sink *sink,
861 		enum dc_detect_reason reason)
862 {
863 	if (should_verify_link_capability_destructively(link, reason))
864 		verify_link_capability_destructive(link, sink, reason);
865 	else
866 		verify_link_capability_non_destructive(link);
867 }
868 
869 /**
870  * link_detect_evaluate_edid_header() - Evaluate if an EDID header is acceptable.
871  *
872  * Evaluates an 8-byte EDID header to check if it's good enough
873  * for the purpose of determining whether a display is connected
874  * without reading the full EDID.
875  *
876  * @edid_header: The first 8 bytes of the EDID read from DDC.
877  *
878  * Return: true if the header looks valid (>= 6 of 8 bytes match the
879  *         expected 00/FF pattern), false otherwise.
880  */
881 static bool link_detect_evaluate_edid_header(uint8_t edid_header[8])
882 {
883 	int edid_header_score = 0;
884 	int i;
885 
886 	for (i = 0; i < 8; ++i)
887 		edid_header_score += edid_header[i] == ((i == 0 || i == 7) ? 0x00 : 0xff);
888 
889 	return edid_header_score >= 6;
890 }
891 
892 /**
893  * link_detect_ddc_probe() - Probe the DDC to see if a display is connected.
894  *
895  * Detect whether a display is connected to DDC without reading full EDID.
896  * Reads only the EDID header (the first 8 bytes of EDID) from DDC and
897  * evaluates whether that matches.
898  *
899  * @link: DC link whose DDC/I2C is probed for the EDID header.
900  *
901  * Return: true if the EDID header was read and passes validation,
902  *         false otherwise.
903  */
904 static bool link_detect_ddc_probe(struct dc_link *link)
905 {
906 	if (!link->ddc)
907 		return false;
908 
909 	uint8_t edid_header[8] = {0};
910 	bool ddc_probed = i2c_read(link->ddc, 0x50, edid_header, sizeof(edid_header));
911 
912 	if (!ddc_probed)
913 		return false;
914 
915 	if (!link_detect_evaluate_edid_header(edid_header))
916 		return false;
917 
918 	return true;
919 }
920 
921 /**
922  * link_detect_dac_load_detect() - Performs DAC load detection.
923  *
924  * Load detection can be used to detect the presence of an
925  * analog display when we can't read DDC. This causes a visible
926  * visual glitch so it should be used sparingly.
927  *
928  * @link: DC link to test using the DAC load-detect path.
929  *
930  * Return: true if the VBIOS load-detect call reports OK, false
931  *         otherwise.
932  */
933 static bool link_detect_dac_load_detect(struct dc_link *link)
934 {
935 	struct dc_bios *bios = link->ctx->dc_bios;
936 	struct link_encoder *link_enc = link->link_enc;
937 	enum engine_id engine_id = link_enc->preferred_engine;
938 	enum dal_device_type device_type = DEVICE_TYPE_CRT;
939 	enum bp_result bp_result = BP_RESULT_UNSUPPORTED;
940 	uint32_t enum_id;
941 
942 	switch (engine_id) {
943 	case ENGINE_ID_DACB:
944 		enum_id = 2;
945 		break;
946 	case ENGINE_ID_DACA:
947 	default:
948 		engine_id = ENGINE_ID_DACA;
949 		enum_id = 1;
950 		break;
951 	}
952 
953 	if (bios->funcs->dac_load_detection)
954 		bp_result = bios->funcs->dac_load_detection(bios, engine_id, device_type, enum_id);
955 
956 	return bp_result == BP_RESULT_OK;
957 }
958 
959 /*
960  * detect_link_and_local_sink() - Detect if a sink is attached to a given link
961  *
962  * link->local_sink is created or destroyed as needed.
963  *
964  * This does not create remote sinks.
965  */
966 static bool detect_link_and_local_sink(struct dc_link *link,
967 				  enum dc_detect_reason reason)
968 {
969 	struct dc_sink_init_data sink_init_data = { 0 };
970 	struct display_sink_capability sink_caps = { 0 };
971 	uint32_t i;
972 	bool converter_disable_audio = false;
973 	struct audio_support *aud_support = &link->dc->res_pool->audio_support;
974 	bool same_edid = false;
975 	enum dc_edid_status edid_status;
976 	struct dc_context *dc_ctx = link->ctx;
977 	struct dc *dc = dc_ctx->dc;
978 	struct dc_sink *sink = NULL;
979 	struct dc_sink *prev_sink = NULL;
980 	struct dpcd_caps prev_dpcd_caps;
981 	enum dc_connection_type new_connection_type = dc_connection_none;
982 	const uint32_t post_oui_delay = 30; // 30ms
983 
984 	DC_LOGGER_INIT(link->ctx->logger);
985 
986 	if (dc_is_virtual_signal(link->connector_signal))
987 		return false;
988 
989 	if (((link->connector_signal == SIGNAL_TYPE_LVDS ||
990 		link->connector_signal == SIGNAL_TYPE_EDP) &&
991 		(!link->dc->config.allow_edp_hotplug_detection)) &&
992 		link->local_sink) {
993 		// need to re-write OUI and brightness in resume case
994 		if (link->connector_signal == SIGNAL_TYPE_EDP &&
995 			(link->dpcd_sink_ext_caps.bits.oled == 1)) {
996 			dpcd_set_source_specific_data(link);
997 			msleep(post_oui_delay);
998 			set_default_brightness_aux(link);
999 		}
1000 
1001 		return true;
1002 	}
1003 
1004 	if (!link_detect_connection_type(link, &new_connection_type)) {
1005 		BREAK_TO_DEBUGGER();
1006 		return false;
1007 	}
1008 
1009 	prev_sink = link->local_sink;
1010 	if (prev_sink) {
1011 		dc_sink_retain(prev_sink);
1012 		memcpy(&prev_dpcd_caps, &link->dpcd_caps, sizeof(struct dpcd_caps));
1013 	}
1014 
1015 	link_disconnect_sink(link);
1016 	if (new_connection_type != dc_connection_none) {
1017 		link->type = new_connection_type;
1018 		link->link_state_valid = false;
1019 
1020 		/* From Disconnected-to-Connected. */
1021 		switch (link->connector_signal) {
1022 		case SIGNAL_TYPE_HDMI_TYPE_A: {
1023 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1024 			if (aud_support->hdmi_audio_native)
1025 				sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1026 			else
1027 				sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1028 			break;
1029 		}
1030 
1031 		case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1032 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1033 			sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1034 			break;
1035 		}
1036 
1037 		case SIGNAL_TYPE_DVI_DUAL_LINK: {
1038 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1039 			sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1040 			break;
1041 		}
1042 
1043 		case SIGNAL_TYPE_RGB: {
1044 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1045 			sink_caps.signal = SIGNAL_TYPE_RGB;
1046 			break;
1047 		}
1048 
1049 		case SIGNAL_TYPE_LVDS: {
1050 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1051 			sink_caps.signal = SIGNAL_TYPE_LVDS;
1052 			break;
1053 		}
1054 
1055 		case SIGNAL_TYPE_EDP: {
1056 			detect_edp_sink_caps(link);
1057 			read_current_link_settings_on_detect(link);
1058 
1059 			/* Disable power sequence on MIPI panel + converter
1060 			 */
1061 			if (dc->config.enable_mipi_converter_optimization &&
1062 				dc_ctx->dce_version == DCN_VERSION_3_01 &&
1063 				link->dpcd_caps.sink_dev_id == DP_BRANCH_DEVICE_ID_0022B9 &&
1064 				memcmp(&link->dpcd_caps.branch_dev_name, DP_SINK_BRANCH_DEV_NAME_7580,
1065 					sizeof(link->dpcd_caps.branch_dev_name)) == 0) {
1066 				dc->config.edp_no_power_sequencing = true;
1067 
1068 				if (!link->dpcd_caps.set_power_state_capable_edp)
1069 					link->wa_flags.dp_keep_receiver_powered = true;
1070 			}
1071 
1072 			sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1073 			sink_caps.signal = SIGNAL_TYPE_EDP;
1074 			break;
1075 		}
1076 
1077 		case SIGNAL_TYPE_DISPLAY_PORT: {
1078 
1079 			/* wa HPD high coming too early*/
1080 			if (link->ep_type == DISPLAY_ENDPOINT_PHY &&
1081 			    link->link_enc->features.flags.bits.DP_IS_USB_C == 1) {
1082 
1083 				/* if alt mode times out, return false */
1084 				if (!wait_for_entering_dp_alt_mode(link))
1085 					return false;
1086 			}
1087 
1088 			if (!detect_dp(link, &sink_caps, reason)) {
1089 
1090 				if (prev_sink)
1091 					dc_sink_release(prev_sink);
1092 				return false;
1093 			}
1094 
1095 			/* Active SST downstream branch device unplug*/
1096 			if (link->type == dc_connection_sst_branch &&
1097 			    link->dpcd_caps.sink_count.bits.SINK_COUNT == 0) {
1098 				if (prev_sink)
1099 					/* Downstream unplug */
1100 					dc_sink_release(prev_sink);
1101 				return true;
1102 			}
1103 
1104 			/* disable audio for non DP to HDMI active sst converter */
1105 			if (link->type == dc_connection_sst_branch &&
1106 					is_dp_active_dongle(link) &&
1107 					(link->dpcd_caps.dongle_type !=
1108 							DISPLAY_DONGLE_DP_HDMI_CONVERTER))
1109 				converter_disable_audio = true;
1110 
1111 			/* limited link rate to HBR3 for DPIA until we implement USB4 V2 */
1112 			if (link->ep_type == DISPLAY_ENDPOINT_USB4_DPIA &&
1113 					link->reported_link_cap.link_rate > LINK_RATE_HIGH3)
1114 				link->reported_link_cap.link_rate = LINK_RATE_HIGH3;
1115 
1116 			if (link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dp_tunneling
1117 					&& link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dpia_bw_alloc
1118 					&& link->dpcd_caps.usb4_dp_tun_info.driver_bw_cap.bits.driver_bw_alloc_support) {
1119 				if (link_dpia_enable_usb4_dp_bw_alloc_mode(link) == false)
1120 					link->dpcd_caps.usb4_dp_tun_info.dp_tun_cap.bits.dpia_bw_alloc = false;
1121 			}
1122 			break;
1123 		}
1124 
1125 		default:
1126 			DC_ERROR("Invalid connector type! signal:%d\n",
1127 				 link->connector_signal);
1128 			if (prev_sink)
1129 				dc_sink_release(prev_sink);
1130 			return false;
1131 		} /* switch() */
1132 
1133 		if (link->dpcd_caps.sink_count.bits.SINK_COUNT)
1134 			link->dpcd_sink_count =
1135 				link->dpcd_caps.sink_count.bits.SINK_COUNT;
1136 		else
1137 			link->dpcd_sink_count = 1;
1138 
1139 		set_ddc_transaction_type(link->ddc,
1140 						     sink_caps.transaction_type);
1141 
1142 		link->aux_mode =
1143 			link_is_in_aux_transaction_mode(link->ddc);
1144 
1145 		sink_init_data.link = link;
1146 		sink_init_data.sink_signal = sink_caps.signal;
1147 
1148 		sink = dc_sink_create(&sink_init_data);
1149 		if (!sink) {
1150 			DC_ERROR("Failed to create sink!\n");
1151 			if (prev_sink)
1152 				dc_sink_release(prev_sink);
1153 			return false;
1154 		}
1155 
1156 		sink->link->dongle_max_pix_clk = sink_caps.max_hdmi_pixel_clock;
1157 		sink->converter_disable_audio = converter_disable_audio;
1158 
1159 		/* dc_sink_create returns a new reference */
1160 		link->local_sink = sink;
1161 
1162 		edid_status = dm_helpers_read_local_edid(link->ctx,
1163 							 link, sink);
1164 
1165 		switch (edid_status) {
1166 		case EDID_BAD_CHECKSUM:
1167 			DC_LOG_ERROR("EDID checksum invalid.\n");
1168 			break;
1169 		case EDID_PARTIAL_VALID:
1170 			DC_LOG_ERROR("Partial EDID valid, abandon invalid blocks.\n");
1171 			break;
1172 		case EDID_NO_RESPONSE:
1173 			/* Analog connectors without EDID:
1174 			 * - old monitor that actually doesn't have EDID
1175 			 * - cheap DVI-A cable or adapter that doesn't connect DDC
1176 			 */
1177 			if (dc_connector_supports_analog(link->link_id.id)) {
1178 				/* If we didn't already detect a display using
1179 				 * DAC load detection, we know it isn't connected.
1180 				 */
1181 				if (link->type != dc_connection_analog_load) {
1182 					if (prev_sink)
1183 						dc_sink_release(prev_sink);
1184 					link_disconnect_sink(link);
1185 					return false;
1186 				}
1187 
1188 				LINK_INFO("link=%d, analog display detected without EDID\n",
1189 					   link->link_index);
1190 
1191 				link->type = dc_connection_analog_load;
1192 				sink->edid_caps.analog = true;
1193 				break;
1194 			}
1195 
1196 			DC_LOG_ERROR("No EDID read.\n");
1197 
1198 			/*
1199 			 * Abort detection for non-DP connectors if we have
1200 			 * no EDID
1201 			 *
1202 			 * DP needs to report as connected if HDP is high
1203 			 * even if we have no EDID in order to go to
1204 			 * fail-safe mode
1205 			 */
1206 			if (dc_is_hdmi_signal(link->connector_signal) ||
1207 			    dc_is_dvi_signal(link->connector_signal)) {
1208 				if (prev_sink)
1209 					dc_sink_release(prev_sink);
1210 
1211 				return false;
1212 			}
1213 
1214 			if (link->type == dc_connection_sst_branch &&
1215 					link->dpcd_caps.dongle_type ==
1216 						DISPLAY_DONGLE_DP_VGA_CONVERTER &&
1217 					reason == DETECT_REASON_HPDRX) {
1218 				/* Abort detection for DP-VGA adapters when EDID
1219 				 * can't be read and detection reason is VGA-side
1220 				 * hotplug
1221 				 */
1222 				if (prev_sink)
1223 					dc_sink_release(prev_sink);
1224 				link_disconnect_sink(link);
1225 
1226 				return true;
1227 			}
1228 
1229 			break;
1230 		default:
1231 			break;
1232 		}
1233 
1234 		// Check if edid is the same
1235 		if ((prev_sink) &&
1236 		    (edid_status == EDID_THE_SAME || edid_status == EDID_OK))
1237 			same_edid = is_same_edid(&prev_sink->dc_edid,
1238 						 &sink->dc_edid);
1239 
1240 		if (sink->edid_caps.panel_patch.skip_scdc_overwrite)
1241 			link->ctx->dc->debug.hdmi20_disable = true;
1242 
1243 		if (sink->edid_caps.panel_patch.remove_sink_ext_caps)
1244 			link->dpcd_sink_ext_caps.raw = 0;
1245 
1246 		if (dc_is_hdmi_signal(link->connector_signal))
1247 			read_scdc_caps(link->ddc, link->local_sink);
1248 
1249 		if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT &&
1250 		    sink_caps.transaction_type ==
1251 		    DDC_TRANSACTION_TYPE_I2C_OVER_AUX) {
1252 			/*
1253 			 * TODO debug why certain monitors don't like
1254 			 *  two link trainings
1255 			 */
1256 			query_hdcp_capability(sink->sink_signal, link);
1257 		} else {
1258 			// If edid is the same, then discard new sink and revert back to original sink
1259 			if (same_edid) {
1260 				link_disconnect_remap(prev_sink, link);
1261 				sink = prev_sink;
1262 				prev_sink = NULL;
1263 			}
1264 
1265 			if (!sink->edid_caps.analog)
1266 				query_hdcp_capability(sink->sink_signal, link);
1267 		}
1268 
1269 		/* DVI-I connector connected to analog display. */
1270 		if ((link->link_id.id == CONNECTOR_ID_DUAL_LINK_DVII ||
1271 		     link->link_id.id == CONNECTOR_ID_SINGLE_LINK_DVII) &&
1272 			sink->edid_caps.analog)
1273 			sink->sink_signal = SIGNAL_TYPE_RGB;
1274 
1275 		/* HDMI-DVI Dongle */
1276 		if (sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A &&
1277 		    !sink->edid_caps.edid_hdmi)
1278 			sink->sink_signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1279 		else if (dc_is_dvi_signal(sink->sink_signal) &&
1280 			 dc_is_dvi_signal(link->connector_signal) &&
1281 			 aud_support->hdmi_audio_native &&
1282 			 sink->edid_caps.edid_hdmi)
1283 			sink->sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
1284 
1285 		if (link->local_sink && dc_is_dp_signal(sink_caps.signal))
1286 			dp_trace_init(link);
1287 
1288 		/* Connectivity log: detection */
1289 		for (i = 0; i < sink->dc_edid.length / DC_EDID_BLOCK_SIZE; i++) {
1290 			CONN_DATA_DETECT(link,
1291 					 &sink->dc_edid.raw_edid[i * DC_EDID_BLOCK_SIZE],
1292 					 DC_EDID_BLOCK_SIZE,
1293 					 "%s: [Block %d] ", sink->edid_caps.display_name, i);
1294 		}
1295 
1296 		DC_LOG_DETECTION_EDID_PARSER("%s: "
1297 			"manufacturer_id = %X, "
1298 			"product_id = %X, "
1299 			"serial_number = %X, "
1300 			"manufacture_week = %d, "
1301 			"manufacture_year = %d, "
1302 			"display_name = %s, "
1303 			"speaker_flag = %d, "
1304 			"audio_mode_count = %d\n",
1305 			__func__,
1306 			sink->edid_caps.manufacturer_id,
1307 			sink->edid_caps.product_id,
1308 			sink->edid_caps.serial_number,
1309 			sink->edid_caps.manufacture_week,
1310 			sink->edid_caps.manufacture_year,
1311 			sink->edid_caps.display_name,
1312 			sink->edid_caps.speaker_flags,
1313 			sink->edid_caps.audio_mode_count);
1314 
1315 		for (i = 0; i < sink->edid_caps.audio_mode_count; i++) {
1316 			DC_LOG_DETECTION_EDID_PARSER("%s: mode number = %d, "
1317 				"format_code = %d, "
1318 				"channel_count = %d, "
1319 				"sample_rate = %d, "
1320 				"sample_size = %d\n",
1321 				__func__,
1322 				i,
1323 				sink->edid_caps.audio_modes[i].format_code,
1324 				sink->edid_caps.audio_modes[i].channel_count,
1325 				sink->edid_caps.audio_modes[i].sample_rate,
1326 				sink->edid_caps.audio_modes[i].sample_size);
1327 		}
1328 
1329 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
1330 			// Init dc_panel_config by HW config
1331 			if (dc_ctx->dc->res_pool->funcs->get_panel_config_defaults)
1332 				dc_ctx->dc->res_pool->funcs->get_panel_config_defaults(&link->panel_config);
1333 			// Pickup base DM settings
1334 			dm_helpers_init_panel_settings(dc_ctx, &link->panel_config, sink);
1335 			// Override dc_panel_config if system has specific settings
1336 			dm_helpers_override_panel_settings(dc_ctx, &link->panel_config);
1337 
1338 			//sink only can use supported link rate table, we are foreced to enable it
1339 			if (link->reported_link_cap.link_rate == LINK_RATE_UNKNOWN)
1340 				link->panel_config.ilr.optimize_edp_link_rate = true;
1341 			link->reported_link_cap.link_rate = get_max_edp_link_rate(link);
1342 		}
1343 
1344 	} else {
1345 		/* From Connected-to-Disconnected. */
1346 		link->type = dc_connection_none;
1347 		sink_caps.signal = SIGNAL_TYPE_NONE;
1348 		memset(&link->hdcp_caps, 0, sizeof(struct hdcp_caps));
1349 		/* When we unplug a passive DP-HDMI dongle connection, dongle_max_pix_clk
1350 		 *  is not cleared. If we emulate a DP signal on this connection, it thinks
1351 		 *  the dongle is still there and limits the number of modes we can emulate.
1352 		 *  Clear dongle_max_pix_clk on disconnect to fix this
1353 		 */
1354 		link->dongle_max_pix_clk = 0;
1355 
1356 		dc_link_clear_dprx_states(link);
1357 		dp_trace_reset(link);
1358 	}
1359 
1360 	LINK_INFO("link=%d, dc_sink_in=%p is now %s prev_sink=%p edid same=%d\n",
1361 		  link->link_index, sink,
1362 		  (sink_caps.signal ==
1363 		   SIGNAL_TYPE_NONE ? "Disconnected" : "Connected"),
1364 		  prev_sink, same_edid);
1365 
1366 	if (prev_sink)
1367 		dc_sink_release(prev_sink);
1368 
1369 	return true;
1370 }
1371 
1372 /**
1373  * link_detect_connection_type_analog() - Determines if an analog sink is connected.
1374  *
1375  * @link: DC link to evaluate (must support analog signalling).
1376  * @type: Updated with the detected connection type:
1377  *        dc_connection_single (analog via DDC),
1378  *        dc_connection_analog_load (via load-detect),
1379  *        or dc_connection_none.
1380  *
1381  * Return: true if detection completed.
1382  */
1383 static bool link_detect_connection_type_analog(struct dc_link *link, enum dc_connection_type *type)
1384 {
1385 	/* Don't care about connectors that don't support an analog signal. */
1386 	ASSERT(dc_connector_supports_analog(link->link_id.id));
1387 
1388 	if (link_detect_ddc_probe(link)) {
1389 		*type = dc_connection_single;
1390 		return true;
1391 	}
1392 
1393 	if (link_detect_dac_load_detect(link)) {
1394 		*type = dc_connection_analog_load;
1395 		return true;
1396 	}
1397 
1398 	*type = dc_connection_none;
1399 	return true;
1400 }
1401 
1402 /*
1403  * link_detect_connection_type() - Determine if there is a sink connected
1404  *
1405  * @type: Returned connection type
1406  * Does not detect downstream devices, such as MST sinks
1407  * or display connected through active dongles
1408  */
1409 bool link_detect_connection_type(struct dc_link *link, enum dc_connection_type *type)
1410 {
1411 	if (link->connector_signal == SIGNAL_TYPE_LVDS) {
1412 		*type = dc_connection_single;
1413 		return true;
1414 	}
1415 
1416 	/* Ignore the HPD pin (if any) for analog connectors.
1417 	 * Instead rely on DDC and DAC.
1418 	 *
1419 	 * - VGA connectors don't have any HPD at all.
1420 	 * - Some DVI-A cables don't connect the HPD pin.
1421 	 * - Some DVI-A cables pull up the HPD pin.
1422 	 *   (So it's high even when no display is connected.)
1423 	 */
1424 	if (dc_connector_supports_analog(link->link_id.id))
1425 		return link_detect_connection_type_analog(link, type);
1426 
1427 	if (link->connector_signal == SIGNAL_TYPE_EDP) {
1428 		/*in case it is not on*/
1429 		if (!link->dc->config.edp_no_power_sequencing)
1430 			link->dc->hwss.edp_power_control(link, true);
1431 		link->dc->hwss.edp_wait_for_hpd_ready(link, true);
1432 	}
1433 
1434 	/* Link may not have physical HPD pin. */
1435 	if (link->ep_type != DISPLAY_ENDPOINT_PHY) {
1436 		if (link->is_hpd_pending || !dpia_query_hpd_status(link))
1437 			*type = dc_connection_none;
1438 		else
1439 			*type = dc_connection_single;
1440 
1441 		return true;
1442 	}
1443 
1444 
1445 	if (link_get_hpd_state(link)) {
1446 		*type = dc_connection_single;
1447 		/* TODO: need to do the actual detection */
1448 	} else {
1449 		*type = dc_connection_none;
1450 		if (link->connector_signal == SIGNAL_TYPE_EDP) {
1451 			/* eDP is not connected, power down it */
1452 			if (!link->dc->config.edp_no_power_sequencing)
1453 				link->dc->hwss.edp_power_control(link, false);
1454 		}
1455 	}
1456 
1457 	return true;
1458 }
1459 
1460 bool link_detect(struct dc_link *link, enum dc_detect_reason reason)
1461 {
1462 	bool is_local_sink_detect_success;
1463 	bool is_delegated_to_mst_top_mgr = false;
1464 	enum dc_connection_type pre_link_type = link->type;
1465 
1466 	DC_LOGGER_INIT(link->ctx->logger);
1467 
1468 	is_local_sink_detect_success = detect_link_and_local_sink(link, reason);
1469 
1470 	if (is_local_sink_detect_success && link->local_sink)
1471 		verify_link_capability(link, link->local_sink, reason);
1472 
1473 	DC_LOG_DC("%s: link_index=%d is_local_sink_detect_success=%d pre_link_type=%d link_type=%d\n", __func__,
1474 				link->link_index, is_local_sink_detect_success, pre_link_type, link->type);
1475 
1476 	if (is_local_sink_detect_success && link->local_sink &&
1477 			dc_is_dp_signal(link->local_sink->sink_signal) &&
1478 			link->dpcd_caps.is_mst_capable)
1479 		is_delegated_to_mst_top_mgr = discover_dp_mst_topology(link, reason);
1480 
1481 	if (pre_link_type == dc_connection_mst_branch &&
1482 			link->type != dc_connection_mst_branch)
1483 		is_delegated_to_mst_top_mgr = link_reset_cur_dp_mst_topology(link);
1484 
1485 	return is_local_sink_detect_success && !is_delegated_to_mst_top_mgr;
1486 }
1487 
1488 void link_clear_dprx_states(struct dc_link *link)
1489 {
1490 	memset(&link->dprx_states, 0, sizeof(link->dprx_states));
1491 }
1492 
1493 bool link_is_hdcp14(struct dc_link *link, enum signal_type signal)
1494 {
1495 	bool ret = false;
1496 
1497 	switch (signal)	{
1498 	case SIGNAL_TYPE_DISPLAY_PORT:
1499 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
1500 		ret = link->hdcp_caps.bcaps.bits.HDCP_CAPABLE;
1501 		break;
1502 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
1503 	case SIGNAL_TYPE_DVI_DUAL_LINK:
1504 	case SIGNAL_TYPE_HDMI_TYPE_A:
1505 	/* HDMI doesn't tell us its HDCP(1.4) capability, so assume to always be capable,
1506 	 * we can poll for bksv but some displays have an issue with this. Since its so rare
1507 	 * for a display to not be 1.4 capable, this assumtion is ok
1508 	 */
1509 		ret = true;
1510 		break;
1511 	default:
1512 		break;
1513 	}
1514 	return ret;
1515 }
1516 
1517 bool link_is_hdcp22(struct dc_link *link, enum signal_type signal)
1518 {
1519 	bool ret = false;
1520 
1521 	switch (signal)	{
1522 	case SIGNAL_TYPE_DISPLAY_PORT:
1523 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
1524 		ret = (link->hdcp_caps.bcaps.bits.HDCP_CAPABLE &&
1525 				link->hdcp_caps.rx_caps.fields.byte0.hdcp_capable &&
1526 				(link->hdcp_caps.rx_caps.fields.version == 0x2)) ? 1 : 0;
1527 		break;
1528 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
1529 	case SIGNAL_TYPE_DVI_DUAL_LINK:
1530 	case SIGNAL_TYPE_HDMI_TYPE_A:
1531 		ret = (link->hdcp_caps.rx_caps.fields.version == 0x4) ? 1:0;
1532 		break;
1533 	default:
1534 		break;
1535 	}
1536 
1537 	return ret;
1538 }
1539 
1540 const struct dc_link_status *link_get_status(const struct dc_link *link)
1541 {
1542 	return &link->link_status;
1543 }
1544 
1545 
1546 static bool link_add_remote_sink_helper(struct dc_link *dc_link, struct dc_sink *sink)
1547 {
1548 	if (dc_link->sink_count >= MAX_SINKS_PER_LINK) {
1549 		BREAK_TO_DEBUGGER();
1550 		return false;
1551 	}
1552 
1553 	dc_sink_retain(sink);
1554 
1555 	dc_link->remote_sinks[dc_link->sink_count] = sink;
1556 	dc_link->sink_count++;
1557 
1558 	return true;
1559 }
1560 
1561 struct dc_sink *link_add_remote_sink(
1562 		struct dc_link *link,
1563 		const uint8_t *edid,
1564 		int len,
1565 		struct dc_sink_init_data *init_data)
1566 {
1567 	struct dc_sink *dc_sink;
1568 	enum dc_edid_status edid_status;
1569 
1570 	if (len > DC_MAX_EDID_BUFFER_SIZE) {
1571 		dm_error("Max EDID buffer size breached!\n");
1572 		return NULL;
1573 	}
1574 
1575 	if (!init_data) {
1576 		BREAK_TO_DEBUGGER();
1577 		return NULL;
1578 	}
1579 
1580 	if (!init_data->link) {
1581 		BREAK_TO_DEBUGGER();
1582 		return NULL;
1583 	}
1584 
1585 	dc_sink = dc_sink_create(init_data);
1586 
1587 	if (!dc_sink)
1588 		return NULL;
1589 
1590 	memmove(dc_sink->dc_edid.raw_edid, edid, len);
1591 	dc_sink->dc_edid.length = len;
1592 
1593 	if (!link_add_remote_sink_helper(
1594 			link,
1595 			dc_sink))
1596 		goto fail_add_sink;
1597 
1598 	edid_status = dm_helpers_parse_edid_caps(
1599 			link,
1600 			&dc_sink->dc_edid,
1601 			&dc_sink->edid_caps);
1602 
1603 	/*
1604 	 * Treat device as no EDID device if EDID
1605 	 * parsing fails
1606 	 */
1607 	if (edid_status != EDID_OK && edid_status != EDID_PARTIAL_VALID) {
1608 		dc_sink->dc_edid.length = 0;
1609 		dm_error("Bad EDID, status%d!\n", edid_status);
1610 	}
1611 
1612 	return dc_sink;
1613 
1614 fail_add_sink:
1615 	dc_sink_release(dc_sink);
1616 	return NULL;
1617 }
1618 
1619 void link_remove_remote_sink(struct dc_link *link, struct dc_sink *sink)
1620 {
1621 	int i;
1622 
1623 	if (!link->sink_count) {
1624 		BREAK_TO_DEBUGGER();
1625 		return;
1626 	}
1627 
1628 	for (i = 0; i < link->sink_count; i++) {
1629 		if (link->remote_sinks[i] == sink) {
1630 			dc_sink_release(sink);
1631 			link->remote_sinks[i] = NULL;
1632 
1633 			/* shrink array to remove empty place */
1634 			while (i < link->sink_count - 1) {
1635 				link->remote_sinks[i] = link->remote_sinks[i+1];
1636 				i++;
1637 			}
1638 			link->remote_sinks[i] = NULL;
1639 			link->sink_count--;
1640 			return;
1641 		}
1642 	}
1643 }
1644