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