1 /*
2  * Copyright 2015 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 #include <linux/string.h>
27 #include <linux/acpi.h>
28 #include <linux/i2c.h>
29 
30 #include <drm/drm_atomic.h>
31 #include <drm/drm_probe_helper.h>
32 #include <drm/amdgpu_drm.h>
33 #include <drm/drm_edid.h>
34 
35 #include "dm_services.h"
36 #include "amdgpu.h"
37 #include "dc.h"
38 #include "amdgpu_dm.h"
39 #include "amdgpu_dm_irq.h"
40 #include "amdgpu_dm_mst_types.h"
41 #include "dpcd_defs.h"
42 #include "dc/inc/core_types.h"
43 
44 #include "dm_helpers.h"
45 #include "ddc_service_types.h"
46 
47 /* MST Dock */
48 static const uint8_t SYNAPTICS_DEVICE_ID[] = "SYNA";
49 
50 /* dm_helpers_parse_edid_caps
51  *
52  * Parse edid caps
53  *
54  * @edid:	[in] pointer to edid
55  *  edid_caps:	[in] pointer to edid caps
56  * @return
57  *	void
58  * */
59 enum dc_edid_status dm_helpers_parse_edid_caps(
60 		struct dc_link *link,
61 		const struct dc_edid *edid,
62 		struct dc_edid_caps *edid_caps)
63 {
64 	struct amdgpu_dm_connector *aconnector = link->priv;
65 	struct drm_connector *connector = &aconnector->base;
66 	struct edid *edid_buf = edid ? (struct edid *) edid->raw_edid : NULL;
67 	struct cea_sad *sads;
68 	int sad_count = -1;
69 	int sadb_count = -1;
70 	int i = 0;
71 	uint8_t *sadb = NULL;
72 
73 	enum dc_edid_status result = EDID_OK;
74 
75 	if (!edid_caps || !edid)
76 		return EDID_BAD_INPUT;
77 
78 	if (!drm_edid_is_valid(edid_buf))
79 		result = EDID_BAD_CHECKSUM;
80 
81 	edid_caps->manufacturer_id = (uint16_t) edid_buf->mfg_id[0] |
82 					((uint16_t) edid_buf->mfg_id[1])<<8;
83 	edid_caps->product_id = (uint16_t) edid_buf->prod_code[0] |
84 					((uint16_t) edid_buf->prod_code[1])<<8;
85 	edid_caps->serial_number = edid_buf->serial;
86 	edid_caps->manufacture_week = edid_buf->mfg_week;
87 	edid_caps->manufacture_year = edid_buf->mfg_year;
88 
89 	drm_edid_get_monitor_name(edid_buf,
90 				  edid_caps->display_name,
91 				  AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
92 
93 	edid_caps->edid_hdmi = connector->display_info.is_hdmi;
94 
95 	sad_count = drm_edid_to_sad((struct edid *) edid->raw_edid, &sads);
96 	if (sad_count <= 0)
97 		return result;
98 
99 	edid_caps->audio_mode_count = sad_count < DC_MAX_AUDIO_DESC_COUNT ? sad_count : DC_MAX_AUDIO_DESC_COUNT;
100 	for (i = 0; i < edid_caps->audio_mode_count; ++i) {
101 		struct cea_sad *sad = &sads[i];
102 
103 		edid_caps->audio_modes[i].format_code = sad->format;
104 		edid_caps->audio_modes[i].channel_count = sad->channels + 1;
105 		edid_caps->audio_modes[i].sample_rate = sad->freq;
106 		edid_caps->audio_modes[i].sample_size = sad->byte2;
107 	}
108 
109 	sadb_count = drm_edid_to_speaker_allocation((struct edid *) edid->raw_edid, &sadb);
110 
111 	if (sadb_count < 0) {
112 		DRM_ERROR("Couldn't read Speaker Allocation Data Block: %d\n", sadb_count);
113 		sadb_count = 0;
114 	}
115 
116 	if (sadb_count)
117 		edid_caps->speaker_flags = sadb[0];
118 	else
119 		edid_caps->speaker_flags = DEFAULT_SPEAKER_LOCATION;
120 
121 	kfree(sads);
122 	kfree(sadb);
123 
124 	return result;
125 }
126 
127 static void
128 fill_dc_mst_payload_table_from_drm(struct dc_link *link,
129 				   bool enable,
130 				   struct drm_dp_mst_atomic_payload *target_payload,
131 				   struct dc_dp_mst_stream_allocation_table *table)
132 {
133 	struct dc_dp_mst_stream_allocation_table new_table = { 0 };
134 	struct dc_dp_mst_stream_allocation *sa;
135 	struct link_mst_stream_allocation_table copy_of_link_table =
136 										link->mst_stream_alloc_table;
137 
138 	int i;
139 	int current_hw_table_stream_cnt = copy_of_link_table.stream_count;
140 	struct link_mst_stream_allocation *dc_alloc;
141 
142 	/* TODO: refactor to set link->mst_stream_alloc_table directly if possible.*/
143 	if (enable) {
144 		dc_alloc =
145 		&copy_of_link_table.stream_allocations[current_hw_table_stream_cnt];
146 		dc_alloc->vcp_id = target_payload->vcpi;
147 		dc_alloc->slot_count = target_payload->time_slots;
148 	} else {
149 		for (i = 0; i < copy_of_link_table.stream_count; i++) {
150 			dc_alloc =
151 			&copy_of_link_table.stream_allocations[i];
152 
153 			if (dc_alloc->vcp_id == target_payload->vcpi) {
154 				dc_alloc->vcp_id = 0;
155 				dc_alloc->slot_count = 0;
156 				break;
157 			}
158 		}
159 		ASSERT(i != copy_of_link_table.stream_count);
160 	}
161 
162 	/* Fill payload info*/
163 	for (i = 0; i < MAX_CONTROLLER_NUM; i++) {
164 		dc_alloc =
165 			&copy_of_link_table.stream_allocations[i];
166 		if (dc_alloc->vcp_id > 0 && dc_alloc->slot_count > 0) {
167 			sa = &new_table.stream_allocations[new_table.stream_count];
168 			sa->slot_count = dc_alloc->slot_count;
169 			sa->vcp_id = dc_alloc->vcp_id;
170 			new_table.stream_count++;
171 		}
172 	}
173 
174 	/* Overwrite the old table */
175 	*table = new_table;
176 }
177 
178 void dm_helpers_dp_update_branch_info(
179 	struct dc_context *ctx,
180 	const struct dc_link *link)
181 {}
182 
183 static void dm_helpers_construct_old_payload(
184 			struct dc_link *link,
185 			int pbn_per_slot,
186 			struct drm_dp_mst_atomic_payload *new_payload,
187 			struct drm_dp_mst_atomic_payload *old_payload)
188 {
189 	struct link_mst_stream_allocation_table current_link_table =
190 									link->mst_stream_alloc_table;
191 	struct link_mst_stream_allocation *dc_alloc;
192 	int i;
193 
194 	*old_payload = *new_payload;
195 
196 	/* Set correct time_slots/PBN of old payload.
197 	 * other fields (delete & dsc_enabled) in
198 	 * struct drm_dp_mst_atomic_payload are don't care fields
199 	 * while calling drm_dp_remove_payload()
200 	 */
201 	for (i = 0; i < current_link_table.stream_count; i++) {
202 		dc_alloc =
203 			&current_link_table.stream_allocations[i];
204 
205 		if (dc_alloc->vcp_id == new_payload->vcpi) {
206 			old_payload->time_slots = dc_alloc->slot_count;
207 			old_payload->pbn = dc_alloc->slot_count * pbn_per_slot;
208 			break;
209 		}
210 	}
211 
212 	/* make sure there is an old payload*/
213 	ASSERT(i != current_link_table.stream_count);
214 
215 }
216 
217 /*
218  * Writes payload allocation table in immediate downstream device.
219  */
220 bool dm_helpers_dp_mst_write_payload_allocation_table(
221 		struct dc_context *ctx,
222 		const struct dc_stream_state *stream,
223 		struct dc_dp_mst_stream_allocation_table *proposed_table,
224 		bool enable)
225 {
226 	struct amdgpu_dm_connector *aconnector;
227 	struct drm_dp_mst_topology_state *mst_state;
228 	struct drm_dp_mst_atomic_payload *target_payload, *new_payload, old_payload;
229 	struct drm_dp_mst_topology_mgr *mst_mgr;
230 
231 	aconnector = (struct amdgpu_dm_connector *)stream->dm_stream_context;
232 	/* Accessing the connector state is required for vcpi_slots allocation
233 	 * and directly relies on behaviour in commit check
234 	 * that blocks before commit guaranteeing that the state
235 	 * is not gonna be swapped while still in use in commit tail */
236 
237 	if (!aconnector || !aconnector->mst_root)
238 		return false;
239 
240 	mst_mgr = &aconnector->mst_root->mst_mgr;
241 	mst_state = to_drm_dp_mst_topology_state(mst_mgr->base.state);
242 
243 	/* It's OK for this to fail */
244 	new_payload = drm_atomic_get_mst_payload_state(mst_state, aconnector->mst_output_port);
245 
246 	if (enable) {
247 		target_payload = new_payload;
248 
249 		drm_dp_add_payload_part1(mst_mgr, mst_state, new_payload);
250 	} else {
251 		/* construct old payload by VCPI*/
252 		dm_helpers_construct_old_payload(stream->link, mst_state->pbn_div,
253 						new_payload, &old_payload);
254 		target_payload = &old_payload;
255 
256 		drm_dp_remove_payload(mst_mgr, mst_state, &old_payload, new_payload);
257 	}
258 
259 	/* mst_mgr->->payloads are VC payload notify MST branch using DPCD or
260 	 * AUX message. The sequence is slot 1-63 allocated sequence for each
261 	 * stream. AMD ASIC stream slot allocation should follow the same
262 	 * sequence. copy DRM MST allocation to dc */
263 	fill_dc_mst_payload_table_from_drm(stream->link, enable, target_payload, proposed_table);
264 
265 	return true;
266 }
267 
268 /*
269  * poll pending down reply
270  */
271 void dm_helpers_dp_mst_poll_pending_down_reply(
272 	struct dc_context *ctx,
273 	const struct dc_link *link)
274 {}
275 
276 /*
277  * Clear payload allocation table before enable MST DP link.
278  */
279 void dm_helpers_dp_mst_clear_payload_allocation_table(
280 	struct dc_context *ctx,
281 	const struct dc_link *link)
282 {}
283 
284 /*
285  * Polls for ACT (allocation change trigger) handled and sends
286  * ALLOCATE_PAYLOAD message.
287  */
288 enum act_return_status dm_helpers_dp_mst_poll_for_allocation_change_trigger(
289 		struct dc_context *ctx,
290 		const struct dc_stream_state *stream)
291 {
292 	struct amdgpu_dm_connector *aconnector;
293 	struct drm_dp_mst_topology_mgr *mst_mgr;
294 	int ret;
295 
296 	aconnector = (struct amdgpu_dm_connector *)stream->dm_stream_context;
297 
298 	if (!aconnector || !aconnector->mst_root)
299 		return ACT_FAILED;
300 
301 	mst_mgr = &aconnector->mst_root->mst_mgr;
302 
303 	if (!mst_mgr->mst_state)
304 		return ACT_FAILED;
305 
306 	ret = drm_dp_check_act_status(mst_mgr);
307 
308 	if (ret)
309 		return ACT_FAILED;
310 
311 	return ACT_SUCCESS;
312 }
313 
314 bool dm_helpers_dp_mst_send_payload_allocation(
315 		struct dc_context *ctx,
316 		const struct dc_stream_state *stream,
317 		bool enable)
318 {
319 	struct amdgpu_dm_connector *aconnector;
320 	struct drm_dp_mst_topology_state *mst_state;
321 	struct drm_dp_mst_topology_mgr *mst_mgr;
322 	struct drm_dp_mst_atomic_payload *payload;
323 	enum mst_progress_status set_flag = MST_ALLOCATE_NEW_PAYLOAD;
324 	enum mst_progress_status clr_flag = MST_CLEAR_ALLOCATED_PAYLOAD;
325 	int ret = 0;
326 
327 	aconnector = (struct amdgpu_dm_connector *)stream->dm_stream_context;
328 
329 	if (!aconnector || !aconnector->mst_root)
330 		return false;
331 
332 	mst_mgr = &aconnector->mst_root->mst_mgr;
333 	mst_state = to_drm_dp_mst_topology_state(mst_mgr->base.state);
334 
335 	payload = drm_atomic_get_mst_payload_state(mst_state, aconnector->mst_output_port);
336 
337 	if (!enable) {
338 		set_flag = MST_CLEAR_ALLOCATED_PAYLOAD;
339 		clr_flag = MST_ALLOCATE_NEW_PAYLOAD;
340 	}
341 
342 	if (enable)
343 		ret = drm_dp_add_payload_part2(mst_mgr, mst_state->base.state, payload);
344 
345 	if (ret) {
346 		amdgpu_dm_set_mst_status(&aconnector->mst_status,
347 			set_flag, false);
348 	} else {
349 		amdgpu_dm_set_mst_status(&aconnector->mst_status,
350 			set_flag, true);
351 		amdgpu_dm_set_mst_status(&aconnector->mst_status,
352 			clr_flag, false);
353 	}
354 
355 	return true;
356 }
357 
358 void dm_dtn_log_begin(struct dc_context *ctx,
359 	struct dc_log_buffer_ctx *log_ctx)
360 {
361 	static const char msg[] = "[dtn begin]\n";
362 
363 	if (!log_ctx) {
364 		pr_info("%s", msg);
365 		return;
366 	}
367 
368 	dm_dtn_log_append_v(ctx, log_ctx, "%s", msg);
369 }
370 
371 __printf(3, 4)
372 void dm_dtn_log_append_v(struct dc_context *ctx,
373 	struct dc_log_buffer_ctx *log_ctx,
374 	const char *msg, ...)
375 {
376 	va_list args;
377 	size_t total;
378 	int n;
379 
380 	if (!log_ctx) {
381 		/* No context, redirect to dmesg. */
382 		struct va_format vaf;
383 
384 		vaf.fmt = msg;
385 		vaf.va = &args;
386 
387 		va_start(args, msg);
388 		pr_info("%pV", &vaf);
389 		va_end(args);
390 
391 		return;
392 	}
393 
394 	/* Measure the output. */
395 	va_start(args, msg);
396 	n = vsnprintf(NULL, 0, msg, args);
397 	va_end(args);
398 
399 	if (n <= 0)
400 		return;
401 
402 	/* Reallocate the string buffer as needed. */
403 	total = log_ctx->pos + n + 1;
404 
405 	if (total > log_ctx->size) {
406 		char *buf = (char *)kvcalloc(total, sizeof(char), GFP_KERNEL);
407 
408 		if (buf) {
409 			memcpy(buf, log_ctx->buf, log_ctx->pos);
410 			kfree(log_ctx->buf);
411 
412 			log_ctx->buf = buf;
413 			log_ctx->size = total;
414 		}
415 	}
416 
417 	if (!log_ctx->buf)
418 		return;
419 
420 	/* Write the formatted string to the log buffer. */
421 	va_start(args, msg);
422 	n = vscnprintf(
423 		log_ctx->buf + log_ctx->pos,
424 		log_ctx->size - log_ctx->pos,
425 		msg,
426 		args);
427 	va_end(args);
428 
429 	if (n > 0)
430 		log_ctx->pos += n;
431 }
432 
433 void dm_dtn_log_end(struct dc_context *ctx,
434 	struct dc_log_buffer_ctx *log_ctx)
435 {
436 	static const char msg[] = "[dtn end]\n";
437 
438 	if (!log_ctx) {
439 		pr_info("%s", msg);
440 		return;
441 	}
442 
443 	dm_dtn_log_append_v(ctx, log_ctx, "%s", msg);
444 }
445 
446 bool dm_helpers_dp_mst_start_top_mgr(
447 		struct dc_context *ctx,
448 		const struct dc_link *link,
449 		bool boot)
450 {
451 	struct amdgpu_dm_connector *aconnector = link->priv;
452 	int ret;
453 
454 	if (!aconnector) {
455 		DRM_ERROR("Failed to find connector for link!");
456 		return false;
457 	}
458 
459 	if (boot) {
460 		DRM_INFO("DM_MST: Differing MST start on aconnector: %p [id: %d]\n",
461 					aconnector, aconnector->base.base.id);
462 		return true;
463 	}
464 
465 	DRM_INFO("DM_MST: starting TM on aconnector: %p [id: %d]\n",
466 			aconnector, aconnector->base.base.id);
467 
468 	ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
469 	if (ret < 0) {
470 		DRM_ERROR("DM_MST: Failed to set the device into MST mode!");
471 		return false;
472 	}
473 
474 	DRM_INFO("DM_MST: DP%x, %d-lane link detected\n", aconnector->mst_mgr.dpcd[0],
475 		aconnector->mst_mgr.dpcd[2] & DP_MAX_LANE_COUNT_MASK);
476 
477 	return true;
478 }
479 
480 bool dm_helpers_dp_mst_stop_top_mgr(
481 		struct dc_context *ctx,
482 		struct dc_link *link)
483 {
484 	struct amdgpu_dm_connector *aconnector = link->priv;
485 
486 	if (!aconnector) {
487 		DRM_ERROR("Failed to find connector for link!");
488 		return false;
489 	}
490 
491 	DRM_INFO("DM_MST: stopping TM on aconnector: %p [id: %d]\n",
492 			aconnector, aconnector->base.base.id);
493 
494 	if (aconnector->mst_mgr.mst_state == true) {
495 		drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, false);
496 		link->cur_link_settings.lane_count = 0;
497 	}
498 
499 	return false;
500 }
501 
502 bool dm_helpers_dp_read_dpcd(
503 		struct dc_context *ctx,
504 		const struct dc_link *link,
505 		uint32_t address,
506 		uint8_t *data,
507 		uint32_t size)
508 {
509 
510 	struct amdgpu_dm_connector *aconnector = link->priv;
511 
512 	if (!aconnector) {
513 		DC_LOG_DC("Failed to find connector for link!\n");
514 		return false;
515 	}
516 
517 	return drm_dp_dpcd_read(&aconnector->dm_dp_aux.aux, address, data,
518 				size) == size;
519 }
520 
521 bool dm_helpers_dp_write_dpcd(
522 		struct dc_context *ctx,
523 		const struct dc_link *link,
524 		uint32_t address,
525 		const uint8_t *data,
526 		uint32_t size)
527 {
528 	struct amdgpu_dm_connector *aconnector = link->priv;
529 
530 	if (!aconnector) {
531 		DRM_ERROR("Failed to find connector for link!");
532 		return false;
533 	}
534 
535 	return drm_dp_dpcd_write(&aconnector->dm_dp_aux.aux,
536 			address, (uint8_t *)data, size) > 0;
537 }
538 
539 bool dm_helpers_submit_i2c(
540 		struct dc_context *ctx,
541 		const struct dc_link *link,
542 		struct i2c_command *cmd)
543 {
544 	struct amdgpu_dm_connector *aconnector = link->priv;
545 	struct i2c_msg *msgs;
546 	int i = 0;
547 	int num = cmd->number_of_payloads;
548 	bool result;
549 
550 	if (!aconnector) {
551 		DRM_ERROR("Failed to find connector for link!");
552 		return false;
553 	}
554 
555 	msgs = kcalloc(num, sizeof(struct i2c_msg), GFP_KERNEL);
556 
557 	if (!msgs)
558 		return false;
559 
560 	for (i = 0; i < num; i++) {
561 		msgs[i].flags = cmd->payloads[i].write ? 0 : I2C_M_RD;
562 		msgs[i].addr = cmd->payloads[i].address;
563 		msgs[i].len = cmd->payloads[i].length;
564 		msgs[i].buf = cmd->payloads[i].data;
565 	}
566 
567 	result = i2c_transfer(&aconnector->i2c->base, msgs, num) == num;
568 
569 	kfree(msgs);
570 
571 	return result;
572 }
573 
574 static bool execute_synaptics_rc_command(struct drm_dp_aux *aux,
575 		bool is_write_cmd,
576 		unsigned char cmd,
577 		unsigned int length,
578 		unsigned int offset,
579 		unsigned char *data)
580 {
581 	bool success = false;
582 	unsigned char rc_data[16] = {0};
583 	unsigned char rc_offset[4] = {0};
584 	unsigned char rc_length[2] = {0};
585 	unsigned char rc_cmd = 0;
586 	unsigned char rc_result = 0xFF;
587 	unsigned char i = 0;
588 	int ret;
589 
590 	if (is_write_cmd) {
591 		// write rc data
592 		memmove(rc_data, data, length);
593 		ret = drm_dp_dpcd_write(aux, SYNAPTICS_RC_DATA, rc_data, sizeof(rc_data));
594 	}
595 
596 	// write rc offset
597 	rc_offset[0] = (unsigned char) offset & 0xFF;
598 	rc_offset[1] = (unsigned char) (offset >> 8) & 0xFF;
599 	rc_offset[2] = (unsigned char) (offset >> 16) & 0xFF;
600 	rc_offset[3] = (unsigned char) (offset >> 24) & 0xFF;
601 	ret = drm_dp_dpcd_write(aux, SYNAPTICS_RC_OFFSET, rc_offset, sizeof(rc_offset));
602 
603 	// write rc length
604 	rc_length[0] = (unsigned char) length & 0xFF;
605 	rc_length[1] = (unsigned char) (length >> 8) & 0xFF;
606 	ret = drm_dp_dpcd_write(aux, SYNAPTICS_RC_LENGTH, rc_length, sizeof(rc_length));
607 
608 	// write rc cmd
609 	rc_cmd = cmd | 0x80;
610 	ret = drm_dp_dpcd_write(aux, SYNAPTICS_RC_COMMAND, &rc_cmd, sizeof(rc_cmd));
611 
612 	if (ret < 0) {
613 		DRM_ERROR("	execute_synaptics_rc_command - write cmd ..., err = %d\n", ret);
614 		return false;
615 	}
616 
617 	// poll until active is 0
618 	for (i = 0; i < 10; i++) {
619 		drm_dp_dpcd_read(aux, SYNAPTICS_RC_COMMAND, &rc_cmd, sizeof(rc_cmd));
620 		if (rc_cmd == cmd)
621 			// active is 0
622 			break;
623 		msleep(10);
624 	}
625 
626 	// read rc result
627 	drm_dp_dpcd_read(aux, SYNAPTICS_RC_RESULT, &rc_result, sizeof(rc_result));
628 	success = (rc_result == 0);
629 
630 	if (success && !is_write_cmd) {
631 		// read rc data
632 		drm_dp_dpcd_read(aux, SYNAPTICS_RC_DATA, data, length);
633 	}
634 
635 	DC_LOG_DC("	execute_synaptics_rc_command - success = %d\n", success);
636 
637 	return success;
638 }
639 
640 static void apply_synaptics_fifo_reset_wa(struct drm_dp_aux *aux)
641 {
642 	unsigned char data[16] = {0};
643 
644 	DC_LOG_DC("Start apply_synaptics_fifo_reset_wa\n");
645 
646 	// Step 2
647 	data[0] = 'P';
648 	data[1] = 'R';
649 	data[2] = 'I';
650 	data[3] = 'U';
651 	data[4] = 'S';
652 
653 	if (!execute_synaptics_rc_command(aux, true, 0x01, 5, 0, data))
654 		return;
655 
656 	// Step 3 and 4
657 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x220998, data))
658 		return;
659 
660 	data[0] &= (~(1 << 1)); // set bit 1 to 0
661 	if (!execute_synaptics_rc_command(aux, true, 0x21, 4, 0x220998, data))
662 		return;
663 
664 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x220D98, data))
665 		return;
666 
667 	data[0] &= (~(1 << 1)); // set bit 1 to 0
668 	if (!execute_synaptics_rc_command(aux, true, 0x21, 4, 0x220D98, data))
669 		return;
670 
671 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x221198, data))
672 		return;
673 
674 	data[0] &= (~(1 << 1)); // set bit 1 to 0
675 	if (!execute_synaptics_rc_command(aux, true, 0x21, 4, 0x221198, data))
676 		return;
677 
678 	// Step 3 and 5
679 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x220998, data))
680 		return;
681 
682 	data[0] |= (1 << 1); // set bit 1 to 1
683 	if (!execute_synaptics_rc_command(aux, true, 0x21, 4, 0x220998, data))
684 		return;
685 
686 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x220D98, data))
687 		return;
688 
689 	data[0] |= (1 << 1); // set bit 1 to 1
690 		return;
691 
692 	if (!execute_synaptics_rc_command(aux, false, 0x31, 4, 0x221198, data))
693 		return;
694 
695 	data[0] |= (1 << 1); // set bit 1 to 1
696 	if (!execute_synaptics_rc_command(aux, true, 0x21, 4, 0x221198, data))
697 		return;
698 
699 	// Step 6
700 	if (!execute_synaptics_rc_command(aux, true, 0x02, 0, 0, NULL))
701 		return;
702 
703 	DC_LOG_DC("Done apply_synaptics_fifo_reset_wa\n");
704 }
705 
706 static uint8_t write_dsc_enable_synaptics_non_virtual_dpcd_mst(
707 		struct drm_dp_aux *aux,
708 		const struct dc_stream_state *stream,
709 		bool enable)
710 {
711 	uint8_t ret = 0;
712 
713 	DC_LOG_DC("Configure DSC to non-virtual dpcd synaptics\n");
714 
715 	if (enable) {
716 		/* When DSC is enabled on previous boot and reboot with the hub,
717 		 * there is a chance that Synaptics hub gets stuck during reboot sequence.
718 		 * Applying a workaround to reset Synaptics SDP fifo before enabling the first stream
719 		 */
720 		if (!stream->link->link_status.link_active &&
721 			memcmp(stream->link->dpcd_caps.branch_dev_name,
722 				(int8_t *)SYNAPTICS_DEVICE_ID, 4) == 0)
723 			apply_synaptics_fifo_reset_wa(aux);
724 
725 		ret = drm_dp_dpcd_write(aux, DP_DSC_ENABLE, &enable, 1);
726 		DRM_INFO("Send DSC enable to synaptics\n");
727 
728 	} else {
729 		/* Synaptics hub not support virtual dpcd,
730 		 * external monitor occur garbage while disable DSC,
731 		 * Disable DSC only when entire link status turn to false,
732 		 */
733 		if (!stream->link->link_status.link_active) {
734 			ret = drm_dp_dpcd_write(aux, DP_DSC_ENABLE, &enable, 1);
735 			DRM_INFO("Send DSC disable to synaptics\n");
736 		}
737 	}
738 
739 	return ret;
740 }
741 
742 bool dm_helpers_dp_write_dsc_enable(
743 		struct dc_context *ctx,
744 		const struct dc_stream_state *stream,
745 		bool enable)
746 {
747 	static const uint8_t DSC_DISABLE;
748 	static const uint8_t DSC_DECODING = 0x01;
749 	static const uint8_t DSC_PASSTHROUGH = 0x02;
750 
751 	struct amdgpu_dm_connector *aconnector;
752 	struct drm_dp_mst_port *port;
753 	uint8_t enable_dsc = enable ? DSC_DECODING : DSC_DISABLE;
754 	uint8_t enable_passthrough = enable ? DSC_PASSTHROUGH : DSC_DISABLE;
755 	uint8_t ret = 0;
756 
757 	if (!stream)
758 		return false;
759 
760 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
761 		aconnector = (struct amdgpu_dm_connector *)stream->dm_stream_context;
762 
763 		if (!aconnector->dsc_aux)
764 			return false;
765 
766 		// apply w/a to synaptics
767 		if (needs_dsc_aux_workaround(aconnector->dc_link) &&
768 		    (aconnector->mst_downstream_port_present.byte & 0x7) != 0x3)
769 			return write_dsc_enable_synaptics_non_virtual_dpcd_mst(
770 				aconnector->dsc_aux, stream, enable_dsc);
771 
772 		port = aconnector->mst_output_port;
773 
774 		if (enable) {
775 			if (port->passthrough_aux) {
776 				ret = drm_dp_dpcd_write(port->passthrough_aux,
777 							DP_DSC_ENABLE,
778 							&enable_passthrough, 1);
779 				DC_LOG_DC("Sent DSC pass-through enable to virtual dpcd port, ret = %u\n",
780 					  ret);
781 			}
782 
783 			ret = drm_dp_dpcd_write(aconnector->dsc_aux,
784 						DP_DSC_ENABLE, &enable_dsc, 1);
785 			DC_LOG_DC("Sent DSC decoding enable to %s port, ret = %u\n",
786 				  (port->passthrough_aux) ? "remote RX" :
787 				  "virtual dpcd",
788 				  ret);
789 		} else {
790 			ret = drm_dp_dpcd_write(aconnector->dsc_aux,
791 						DP_DSC_ENABLE, &enable_dsc, 1);
792 			DC_LOG_DC("Sent DSC decoding disable to %s port, ret = %u\n",
793 				  (port->passthrough_aux) ? "remote RX" :
794 				  "virtual dpcd",
795 				  ret);
796 
797 			if (port->passthrough_aux) {
798 				ret = drm_dp_dpcd_write(port->passthrough_aux,
799 							DP_DSC_ENABLE,
800 							&enable_passthrough, 1);
801 				DC_LOG_DC("Sent DSC pass-through disable to virtual dpcd port, ret = %u\n",
802 					  ret);
803 			}
804 		}
805 	}
806 
807 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT || stream->signal == SIGNAL_TYPE_EDP) {
808 		if (stream->sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
809 			ret = dm_helpers_dp_write_dpcd(ctx, stream->link, DP_DSC_ENABLE, &enable_dsc, 1);
810 			DC_LOG_DC("Send DSC %s to SST RX\n", enable_dsc ? "enable" : "disable");
811 		} else if (stream->sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
812 			ret = dm_helpers_dp_write_dpcd(ctx, stream->link, DP_DSC_ENABLE, &enable_dsc, 1);
813 			DC_LOG_DC("Send DSC %s to DP-HDMI PCON\n", enable_dsc ? "enable" : "disable");
814 		}
815 	}
816 
817 	return ret;
818 }
819 
820 bool dm_helpers_is_dp_sink_present(struct dc_link *link)
821 {
822 	bool dp_sink_present;
823 	struct amdgpu_dm_connector *aconnector = link->priv;
824 
825 	if (!aconnector) {
826 		BUG_ON("Failed to find connector for link!");
827 		return true;
828 	}
829 
830 	mutex_lock(&aconnector->dm_dp_aux.aux.hw_mutex);
831 	dp_sink_present = dc_link_is_dp_sink_present(link);
832 	mutex_unlock(&aconnector->dm_dp_aux.aux.hw_mutex);
833 	return dp_sink_present;
834 }
835 
836 enum dc_edid_status dm_helpers_read_local_edid(
837 		struct dc_context *ctx,
838 		struct dc_link *link,
839 		struct dc_sink *sink)
840 {
841 	struct amdgpu_dm_connector *aconnector = link->priv;
842 	struct drm_connector *connector = &aconnector->base;
843 	struct i2c_adapter *ddc;
844 	int retry = 3;
845 	enum dc_edid_status edid_status;
846 	struct edid *edid;
847 
848 	if (link->aux_mode)
849 		ddc = &aconnector->dm_dp_aux.aux.ddc;
850 	else
851 		ddc = &aconnector->i2c->base;
852 
853 	/* some dongles read edid incorrectly the first time,
854 	 * do check sum and retry to make sure read correct edid.
855 	 */
856 	do {
857 
858 		edid = drm_get_edid(&aconnector->base, ddc);
859 
860 		/* DP Compliance Test 4.2.2.6 */
861 		if (link->aux_mode && connector->edid_corrupt)
862 			drm_dp_send_real_edid_checksum(&aconnector->dm_dp_aux.aux, connector->real_edid_checksum);
863 
864 		if (!edid && connector->edid_corrupt) {
865 			connector->edid_corrupt = false;
866 			return EDID_BAD_CHECKSUM;
867 		}
868 
869 		if (!edid)
870 			return EDID_NO_RESPONSE;
871 
872 		sink->dc_edid.length = EDID_LENGTH * (edid->extensions + 1);
873 		memmove(sink->dc_edid.raw_edid, (uint8_t *)edid, sink->dc_edid.length);
874 
875 		/* We don't need the original edid anymore */
876 		kfree(edid);
877 
878 		edid_status = dm_helpers_parse_edid_caps(
879 						link,
880 						&sink->dc_edid,
881 						&sink->edid_caps);
882 
883 	} while (edid_status == EDID_BAD_CHECKSUM && --retry > 0);
884 
885 	if (edid_status != EDID_OK)
886 		DRM_ERROR("EDID err: %d, on connector: %s",
887 				edid_status,
888 				aconnector->base.name);
889 
890 	/* DP Compliance Test 4.2.2.3 */
891 	if (link->aux_mode)
892 		drm_dp_send_real_edid_checksum(&aconnector->dm_dp_aux.aux, sink->dc_edid.raw_edid[sink->dc_edid.length-1]);
893 
894 	return edid_status;
895 }
896 int dm_helper_dmub_aux_transfer_sync(
897 		struct dc_context *ctx,
898 		const struct dc_link *link,
899 		struct aux_payload *payload,
900 		enum aux_return_code_type *operation_result)
901 {
902 	return amdgpu_dm_process_dmub_aux_transfer_sync(ctx, link->link_index, payload,
903 			operation_result);
904 }
905 
906 int dm_helpers_dmub_set_config_sync(struct dc_context *ctx,
907 		const struct dc_link *link,
908 		struct set_config_cmd_payload *payload,
909 		enum set_config_status *operation_result)
910 {
911 	return amdgpu_dm_process_dmub_set_config_sync(ctx, link->link_index, payload,
912 			operation_result);
913 }
914 
915 void dm_set_dcn_clocks(struct dc_context *ctx, struct dc_clocks *clks)
916 {
917 	/* TODO: something */
918 }
919 
920 void dm_helpers_smu_timeout(struct dc_context *ctx, unsigned int msg_id, unsigned int param, unsigned int timeout_us)
921 {
922 	// TODO:
923 	//amdgpu_device_gpu_recover(dc_context->driver-context, NULL);
924 }
925 
926 void dm_helpers_init_panel_settings(
927 	struct dc_context *ctx,
928 	struct dc_panel_config *panel_config,
929 	struct dc_sink *sink)
930 {
931 	// Extra Panel Power Sequence
932 	panel_config->pps.extra_t3_ms = sink->edid_caps.panel_patch.extra_t3_ms;
933 	panel_config->pps.extra_t7_ms = sink->edid_caps.panel_patch.extra_t7_ms;
934 	panel_config->pps.extra_delay_backlight_off = sink->edid_caps.panel_patch.extra_delay_backlight_off;
935 	panel_config->pps.extra_post_t7_ms = 0;
936 	panel_config->pps.extra_pre_t11_ms = 0;
937 	panel_config->pps.extra_t12_ms = sink->edid_caps.panel_patch.extra_t12_ms;
938 	panel_config->pps.extra_post_OUI_ms = 0;
939 	// Feature DSC
940 	panel_config->dsc.disable_dsc_edp = false;
941 	panel_config->dsc.force_dsc_edp_policy = 0;
942 }
943 
944 void dm_helpers_override_panel_settings(
945 	struct dc_context *ctx,
946 	struct dc_panel_config *panel_config)
947 {
948 	// Feature DSC
949 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC) {
950 		panel_config->dsc.disable_dsc_edp = true;
951 	}
952 }
953 
954 void *dm_helpers_allocate_gpu_mem(
955 		struct dc_context *ctx,
956 		enum dc_gpu_mem_alloc_type type,
957 		size_t size,
958 		long long *addr)
959 {
960 	struct amdgpu_device *adev = ctx->driver_context;
961 	struct dal_allocation *da;
962 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
963 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
964 	int ret;
965 
966 	da = kzalloc(sizeof(struct dal_allocation), GFP_KERNEL);
967 	if (!da)
968 		return NULL;
969 
970 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
971 				      domain, &da->bo,
972 				      &da->gpu_addr, &da->cpu_ptr);
973 
974 	*addr = da->gpu_addr;
975 
976 	if (ret) {
977 		kfree(da);
978 		return NULL;
979 	}
980 
981 	/* add da to list in dm */
982 	list_add(&da->list, &adev->dm.da_list);
983 
984 	return da->cpu_ptr;
985 }
986 
987 void dm_helpers_free_gpu_mem(
988 		struct dc_context *ctx,
989 		enum dc_gpu_mem_alloc_type type,
990 		void *pvMem)
991 {
992 	struct amdgpu_device *adev = ctx->driver_context;
993 	struct dal_allocation *da;
994 
995 	/* walk the da list in DM */
996 	list_for_each_entry(da, &adev->dm.da_list, list) {
997 		if (pvMem == da->cpu_ptr) {
998 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
999 			list_del(&da->list);
1000 			kfree(da);
1001 			break;
1002 		}
1003 	}
1004 }
1005 
1006 bool dm_helpers_dmub_outbox_interrupt_control(struct dc_context *ctx, bool enable)
1007 {
1008 	enum dc_irq_source irq_source;
1009 	bool ret;
1010 
1011 	irq_source = DC_IRQ_SOURCE_DMCUB_OUTBOX;
1012 
1013 	ret = dc_interrupt_set(ctx->dc, irq_source, enable);
1014 
1015 	DRM_DEBUG_DRIVER("Dmub trace irq %sabling: r=%d\n",
1016 			 enable ? "en" : "dis", ret);
1017 	return ret;
1018 }
1019 
1020 void dm_helpers_mst_enable_stream_features(const struct dc_stream_state *stream)
1021 {
1022 	/* TODO: virtual DPCD */
1023 	struct dc_link *link = stream->link;
1024 	union down_spread_ctrl old_downspread;
1025 	union down_spread_ctrl new_downspread;
1026 
1027 	if (link->aux_access_disabled)
1028 		return;
1029 
1030 	if (!dm_helpers_dp_read_dpcd(link->ctx, link, DP_DOWNSPREAD_CTRL,
1031 				     &old_downspread.raw,
1032 				     sizeof(old_downspread)))
1033 		return;
1034 
1035 	new_downspread.raw = old_downspread.raw;
1036 	new_downspread.bits.IGNORE_MSA_TIMING_PARAM =
1037 		(stream->ignore_msa_timing_param) ? 1 : 0;
1038 
1039 	if (new_downspread.raw != old_downspread.raw)
1040 		dm_helpers_dp_write_dpcd(link->ctx, link, DP_DOWNSPREAD_CTRL,
1041 					 &new_downspread.raw,
1042 					 sizeof(new_downspread));
1043 }
1044 
1045 bool dm_helpers_dp_handle_test_pattern_request(
1046 		struct dc_context *ctx,
1047 		const struct dc_link *link,
1048 		union link_test_pattern dpcd_test_pattern,
1049 		union test_misc dpcd_test_params)
1050 {
1051 	enum dp_test_pattern test_pattern;
1052 	enum dp_test_pattern_color_space test_pattern_color_space =
1053 			DP_TEST_PATTERN_COLOR_SPACE_UNDEFINED;
1054 	enum dc_color_depth requestColorDepth = COLOR_DEPTH_UNDEFINED;
1055 	enum dc_pixel_encoding requestPixelEncoding = PIXEL_ENCODING_UNDEFINED;
1056 	struct pipe_ctx *pipes = link->dc->current_state->res_ctx.pipe_ctx;
1057 	struct pipe_ctx *pipe_ctx = NULL;
1058 	struct amdgpu_dm_connector *aconnector = link->priv;
1059 	int i;
1060 
1061 	for (i = 0; i < MAX_PIPES; i++) {
1062 		if (pipes[i].stream == NULL)
1063 			continue;
1064 
1065 		if (pipes[i].stream->link == link && !pipes[i].top_pipe &&
1066 			!pipes[i].prev_odm_pipe) {
1067 			pipe_ctx = &pipes[i];
1068 			break;
1069 		}
1070 	}
1071 
1072 	if (pipe_ctx == NULL)
1073 		return false;
1074 
1075 	switch (dpcd_test_pattern.bits.PATTERN) {
1076 	case LINK_TEST_PATTERN_COLOR_RAMP:
1077 		test_pattern = DP_TEST_PATTERN_COLOR_RAMP;
1078 	break;
1079 	case LINK_TEST_PATTERN_VERTICAL_BARS:
1080 		test_pattern = DP_TEST_PATTERN_VERTICAL_BARS;
1081 	break; /* black and white */
1082 	case LINK_TEST_PATTERN_COLOR_SQUARES:
1083 		test_pattern = (dpcd_test_params.bits.DYN_RANGE ==
1084 				TEST_DYN_RANGE_VESA ?
1085 				DP_TEST_PATTERN_COLOR_SQUARES :
1086 				DP_TEST_PATTERN_COLOR_SQUARES_CEA);
1087 	break;
1088 	default:
1089 		test_pattern = DP_TEST_PATTERN_VIDEO_MODE;
1090 	break;
1091 	}
1092 
1093 	if (dpcd_test_params.bits.CLR_FORMAT == 0)
1094 		test_pattern_color_space = DP_TEST_PATTERN_COLOR_SPACE_RGB;
1095 	else
1096 		test_pattern_color_space = dpcd_test_params.bits.YCBCR_COEFS ?
1097 				DP_TEST_PATTERN_COLOR_SPACE_YCBCR709 :
1098 				DP_TEST_PATTERN_COLOR_SPACE_YCBCR601;
1099 
1100 	switch (dpcd_test_params.bits.BPC) {
1101 	case 0: // 6 bits
1102 		requestColorDepth = COLOR_DEPTH_666;
1103 		break;
1104 	case 1: // 8 bits
1105 		requestColorDepth = COLOR_DEPTH_888;
1106 		break;
1107 	case 2: // 10 bits
1108 		requestColorDepth = COLOR_DEPTH_101010;
1109 		break;
1110 	case 3: // 12 bits
1111 		requestColorDepth = COLOR_DEPTH_121212;
1112 		break;
1113 	default:
1114 		break;
1115 	}
1116 
1117 	switch (dpcd_test_params.bits.CLR_FORMAT) {
1118 	case 0:
1119 		requestPixelEncoding = PIXEL_ENCODING_RGB;
1120 		break;
1121 	case 1:
1122 		requestPixelEncoding = PIXEL_ENCODING_YCBCR422;
1123 		break;
1124 	case 2:
1125 		requestPixelEncoding = PIXEL_ENCODING_YCBCR444;
1126 		break;
1127 	default:
1128 		requestPixelEncoding = PIXEL_ENCODING_RGB;
1129 		break;
1130 	}
1131 
1132 	if ((requestColorDepth != COLOR_DEPTH_UNDEFINED
1133 		&& pipe_ctx->stream->timing.display_color_depth != requestColorDepth)
1134 		|| (requestPixelEncoding != PIXEL_ENCODING_UNDEFINED
1135 		&& pipe_ctx->stream->timing.pixel_encoding != requestPixelEncoding)) {
1136 		DC_LOG_DEBUG("%s: original bpc %d pix encoding %d, changing to %d  %d\n",
1137 				__func__,
1138 				pipe_ctx->stream->timing.display_color_depth,
1139 				pipe_ctx->stream->timing.pixel_encoding,
1140 				requestColorDepth,
1141 				requestPixelEncoding);
1142 		pipe_ctx->stream->timing.display_color_depth = requestColorDepth;
1143 		pipe_ctx->stream->timing.pixel_encoding = requestPixelEncoding;
1144 
1145 		dc_link_update_dsc_config(pipe_ctx);
1146 
1147 		aconnector->timing_changed = true;
1148 		/* store current timing */
1149 		if (aconnector->timing_requested)
1150 			*aconnector->timing_requested = pipe_ctx->stream->timing;
1151 		else
1152 			DC_LOG_ERROR("%s: timing storage failed\n", __func__);
1153 
1154 	}
1155 
1156 	dc_link_dp_set_test_pattern(
1157 		(struct dc_link *) link,
1158 		test_pattern,
1159 		test_pattern_color_space,
1160 		NULL,
1161 		NULL,
1162 		0);
1163 
1164 	return false;
1165 }
1166 
1167 void dm_set_phyd32clk(struct dc_context *ctx, int freq_khz)
1168 {
1169        // TODO
1170 }
1171 
1172 void dm_helpers_enable_periodic_detection(struct dc_context *ctx, bool enable)
1173 {
1174 	/* TODO: add periodic detection implementation */
1175 }
1176 
1177 void dm_helpers_dp_mst_update_branch_bandwidth(
1178 		struct dc_context *ctx,
1179 		struct dc_link *link)
1180 {
1181 	// TODO
1182 }
1183 
1184 static bool dm_is_freesync_pcon_whitelist(const uint32_t branch_dev_id)
1185 {
1186 	bool ret_val = false;
1187 
1188 	switch (branch_dev_id) {
1189 	case DP_BRANCH_DEVICE_ID_0060AD:
1190 	case DP_BRANCH_DEVICE_ID_00E04C:
1191 	case DP_BRANCH_DEVICE_ID_90CC24:
1192 		ret_val = true;
1193 		break;
1194 	default:
1195 		break;
1196 	}
1197 
1198 	return ret_val;
1199 }
1200 
1201 enum adaptive_sync_type dm_get_adaptive_sync_support_type(struct dc_link *link)
1202 {
1203 	struct dpcd_caps *dpcd_caps = &link->dpcd_caps;
1204 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
1205 
1206 	switch (dpcd_caps->dongle_type) {
1207 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
1208 		if (dpcd_caps->adaptive_sync_caps.dp_adap_sync_caps.bits.ADAPTIVE_SYNC_SDP_SUPPORT == true &&
1209 			dpcd_caps->allow_invalid_MSA_timing_param == true &&
1210 			dm_is_freesync_pcon_whitelist(dpcd_caps->branch_dev_id))
1211 			as_type = FREESYNC_TYPE_PCON_IN_WHITELIST;
1212 		break;
1213 	default:
1214 		break;
1215 	}
1216 
1217 	return as_type;
1218 }
1219