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 "dm_services_types.h"
27 #include "dc.h"
28 #include "dc/inc/core_types.h"
29 
30 #include "vid.h"
31 #include "amdgpu.h"
32 #include "amdgpu_display.h"
33 #include "amdgpu_ucode.h"
34 #include "atom.h"
35 #include "amdgpu_dm.h"
36 #include "amdgpu_pm.h"
37 
38 #include "amd_shared.h"
39 #include "amdgpu_dm_irq.h"
40 #include "dm_helpers.h"
41 #include "dm_services_types.h"
42 #include "amdgpu_dm_mst_types.h"
43 #if defined(CONFIG_DEBUG_FS)
44 #include "amdgpu_dm_debugfs.h"
45 #endif
46 
47 #include "ivsrcid/ivsrcid_vislands30.h"
48 
49 #include <linux/module.h>
50 #include <linux/moduleparam.h>
51 #include <linux/version.h>
52 #include <linux/types.h>
53 #include <linux/pm_runtime.h>
54 #include <linux/firmware.h>
55 
56 #include <drm/drmP.h>
57 #include <drm/drm_atomic.h>
58 #include <drm/drm_atomic_helper.h>
59 #include <drm/drm_dp_mst_helper.h>
60 #include <drm/drm_fb_helper.h>
61 #include <drm/drm_edid.h>
62 
63 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
64 #include "ivsrcid/irqsrcs_dcn_1_0.h"
65 
66 #include "dcn/dcn_1_0_offset.h"
67 #include "dcn/dcn_1_0_sh_mask.h"
68 #include "soc15_hw_ip.h"
69 #include "vega10_ip_offset.h"
70 
71 #include "soc15_common.h"
72 #endif
73 
74 #include "modules/inc/mod_freesync.h"
75 
76 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
77 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
78 
79 /**
80  * DOC: overview
81  *
82  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
83  * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
84  * requests into DC requests, and DC responses into DRM responses.
85  *
86  * The root control structure is &struct amdgpu_display_manager.
87  */
88 
89 /* basic init/fini API */
90 static int amdgpu_dm_init(struct amdgpu_device *adev);
91 static void amdgpu_dm_fini(struct amdgpu_device *adev);
92 
93 /*
94  * initializes drm_device display related structures, based on the information
95  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
96  * drm_encoder, drm_mode_config
97  *
98  * Returns 0 on success
99  */
100 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
101 /* removes and deallocates the drm structures, created by the above function */
102 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
103 
104 static void
105 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
106 
107 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
108 				struct drm_plane *plane,
109 				unsigned long possible_crtcs);
110 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
111 			       struct drm_plane *plane,
112 			       uint32_t link_index);
113 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
114 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
115 				    uint32_t link_index,
116 				    struct amdgpu_encoder *amdgpu_encoder);
117 static int amdgpu_dm_encoder_init(struct drm_device *dev,
118 				  struct amdgpu_encoder *aencoder,
119 				  uint32_t link_index);
120 
121 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
122 
123 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
124 				   struct drm_atomic_state *state,
125 				   bool nonblock);
126 
127 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
128 
129 static int amdgpu_dm_atomic_check(struct drm_device *dev,
130 				  struct drm_atomic_state *state);
131 
132 
133 
134 
135 static const enum drm_plane_type dm_plane_type_default[AMDGPU_MAX_PLANES] = {
136 	DRM_PLANE_TYPE_PRIMARY,
137 	DRM_PLANE_TYPE_PRIMARY,
138 	DRM_PLANE_TYPE_PRIMARY,
139 	DRM_PLANE_TYPE_PRIMARY,
140 	DRM_PLANE_TYPE_PRIMARY,
141 	DRM_PLANE_TYPE_PRIMARY,
142 };
143 
144 static const enum drm_plane_type dm_plane_type_carizzo[AMDGPU_MAX_PLANES] = {
145 	DRM_PLANE_TYPE_PRIMARY,
146 	DRM_PLANE_TYPE_PRIMARY,
147 	DRM_PLANE_TYPE_PRIMARY,
148 	DRM_PLANE_TYPE_OVERLAY,/* YUV Capable Underlay */
149 };
150 
151 static const enum drm_plane_type dm_plane_type_stoney[AMDGPU_MAX_PLANES] = {
152 	DRM_PLANE_TYPE_PRIMARY,
153 	DRM_PLANE_TYPE_PRIMARY,
154 	DRM_PLANE_TYPE_OVERLAY, /* YUV Capable Underlay */
155 };
156 
157 /*
158  * dm_vblank_get_counter
159  *
160  * @brief
161  * Get counter for number of vertical blanks
162  *
163  * @param
164  * struct amdgpu_device *adev - [in] desired amdgpu device
165  * int disp_idx - [in] which CRTC to get the counter from
166  *
167  * @return
168  * Counter for vertical blanks
169  */
170 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
171 {
172 	if (crtc >= adev->mode_info.num_crtc)
173 		return 0;
174 	else {
175 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
176 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
177 				acrtc->base.state);
178 
179 
180 		if (acrtc_state->stream == NULL) {
181 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
182 				  crtc);
183 			return 0;
184 		}
185 
186 		return dc_stream_get_vblank_counter(acrtc_state->stream);
187 	}
188 }
189 
190 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
191 				  u32 *vbl, u32 *position)
192 {
193 	uint32_t v_blank_start, v_blank_end, h_position, v_position;
194 
195 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
196 		return -EINVAL;
197 	else {
198 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
199 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
200 						acrtc->base.state);
201 
202 		if (acrtc_state->stream ==  NULL) {
203 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
204 				  crtc);
205 			return 0;
206 		}
207 
208 		/*
209 		 * TODO rework base driver to use values directly.
210 		 * for now parse it back into reg-format
211 		 */
212 		dc_stream_get_scanoutpos(acrtc_state->stream,
213 					 &v_blank_start,
214 					 &v_blank_end,
215 					 &h_position,
216 					 &v_position);
217 
218 		*position = v_position | (h_position << 16);
219 		*vbl = v_blank_start | (v_blank_end << 16);
220 	}
221 
222 	return 0;
223 }
224 
225 static bool dm_is_idle(void *handle)
226 {
227 	/* XXX todo */
228 	return true;
229 }
230 
231 static int dm_wait_for_idle(void *handle)
232 {
233 	/* XXX todo */
234 	return 0;
235 }
236 
237 static bool dm_check_soft_reset(void *handle)
238 {
239 	return false;
240 }
241 
242 static int dm_soft_reset(void *handle)
243 {
244 	/* XXX todo */
245 	return 0;
246 }
247 
248 static struct amdgpu_crtc *
249 get_crtc_by_otg_inst(struct amdgpu_device *adev,
250 		     int otg_inst)
251 {
252 	struct drm_device *dev = adev->ddev;
253 	struct drm_crtc *crtc;
254 	struct amdgpu_crtc *amdgpu_crtc;
255 
256 	if (otg_inst == -1) {
257 		WARN_ON(1);
258 		return adev->mode_info.crtcs[0];
259 	}
260 
261 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
262 		amdgpu_crtc = to_amdgpu_crtc(crtc);
263 
264 		if (amdgpu_crtc->otg_inst == otg_inst)
265 			return amdgpu_crtc;
266 	}
267 
268 	return NULL;
269 }
270 
271 static void dm_pflip_high_irq(void *interrupt_params)
272 {
273 	struct amdgpu_crtc *amdgpu_crtc;
274 	struct common_irq_params *irq_params = interrupt_params;
275 	struct amdgpu_device *adev = irq_params->adev;
276 	unsigned long flags;
277 
278 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
279 
280 	/* IRQ could occur when in initial stage */
281 	/* TODO work and BO cleanup */
282 	if (amdgpu_crtc == NULL) {
283 		DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
284 		return;
285 	}
286 
287 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
288 
289 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
290 		DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
291 						 amdgpu_crtc->pflip_status,
292 						 AMDGPU_FLIP_SUBMITTED,
293 						 amdgpu_crtc->crtc_id,
294 						 amdgpu_crtc);
295 		spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
296 		return;
297 	}
298 
299 
300 	/* wake up userspace */
301 	if (amdgpu_crtc->event) {
302 		/* Update to correct count(s) if racing with vblank irq */
303 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
304 
305 		drm_crtc_send_vblank_event(&amdgpu_crtc->base, amdgpu_crtc->event);
306 
307 		/* page flip completed. clean up */
308 		amdgpu_crtc->event = NULL;
309 
310 	} else
311 		WARN_ON(1);
312 
313 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
314 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
315 
316 	DRM_DEBUG_DRIVER("%s - crtc :%d[%p], pflip_stat:AMDGPU_FLIP_NONE\n",
317 					__func__, amdgpu_crtc->crtc_id, amdgpu_crtc);
318 
319 	drm_crtc_vblank_put(&amdgpu_crtc->base);
320 }
321 
322 static void dm_crtc_high_irq(void *interrupt_params)
323 {
324 	struct common_irq_params *irq_params = interrupt_params;
325 	struct amdgpu_device *adev = irq_params->adev;
326 	struct amdgpu_crtc *acrtc;
327 
328 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
329 
330 	if (acrtc) {
331 		drm_crtc_handle_vblank(&acrtc->base);
332 		amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
333 	}
334 }
335 
336 static int dm_set_clockgating_state(void *handle,
337 		  enum amd_clockgating_state state)
338 {
339 	return 0;
340 }
341 
342 static int dm_set_powergating_state(void *handle,
343 		  enum amd_powergating_state state)
344 {
345 	return 0;
346 }
347 
348 /* Prototypes of private functions */
349 static int dm_early_init(void* handle);
350 
351 /* Allocate memory for FBC compressed data  */
352 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
353 {
354 	struct drm_device *dev = connector->dev;
355 	struct amdgpu_device *adev = dev->dev_private;
356 	struct dm_comressor_info *compressor = &adev->dm.compressor;
357 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
358 	struct drm_display_mode *mode;
359 	unsigned long max_size = 0;
360 
361 	if (adev->dm.dc->fbc_compressor == NULL)
362 		return;
363 
364 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
365 		return;
366 
367 	if (compressor->bo_ptr)
368 		return;
369 
370 
371 	list_for_each_entry(mode, &connector->modes, head) {
372 		if (max_size < mode->htotal * mode->vtotal)
373 			max_size = mode->htotal * mode->vtotal;
374 	}
375 
376 	if (max_size) {
377 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
378 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
379 			    &compressor->gpu_addr, &compressor->cpu_addr);
380 
381 		if (r)
382 			DRM_ERROR("DM: Failed to initialize FBC\n");
383 		else {
384 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
385 			DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
386 		}
387 
388 	}
389 
390 }
391 
392 static int amdgpu_dm_init(struct amdgpu_device *adev)
393 {
394 	struct dc_init_data init_data;
395 	adev->dm.ddev = adev->ddev;
396 	adev->dm.adev = adev;
397 
398 	/* Zero all the fields */
399 	memset(&init_data, 0, sizeof(init_data));
400 
401 	if(amdgpu_dm_irq_init(adev)) {
402 		DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
403 		goto error;
404 	}
405 
406 	init_data.asic_id.chip_family = adev->family;
407 
408 	init_data.asic_id.pci_revision_id = adev->rev_id;
409 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
410 
411 	init_data.asic_id.vram_width = adev->gmc.vram_width;
412 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
413 	init_data.asic_id.atombios_base_address =
414 		adev->mode_info.atom_context->bios;
415 
416 	init_data.driver = adev;
417 
418 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
419 
420 	if (!adev->dm.cgs_device) {
421 		DRM_ERROR("amdgpu: failed to create cgs device.\n");
422 		goto error;
423 	}
424 
425 	init_data.cgs_device = adev->dm.cgs_device;
426 
427 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
428 
429 	/*
430 	 * TODO debug why this doesn't work on Raven
431 	 */
432 	if (adev->flags & AMD_IS_APU &&
433 	    adev->asic_type >= CHIP_CARRIZO &&
434 	    adev->asic_type < CHIP_RAVEN)
435 		init_data.flags.gpu_vm_support = true;
436 
437 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
438 		init_data.flags.fbc_support = true;
439 
440 	/* Display Core create. */
441 	adev->dm.dc = dc_create(&init_data);
442 
443 	if (adev->dm.dc) {
444 		DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
445 	} else {
446 		DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
447 		goto error;
448 	}
449 
450 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
451 	if (!adev->dm.freesync_module) {
452 		DRM_ERROR(
453 		"amdgpu: failed to initialize freesync_module.\n");
454 	} else
455 		DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
456 				adev->dm.freesync_module);
457 
458 	amdgpu_dm_init_color_mod();
459 
460 	if (amdgpu_dm_initialize_drm_device(adev)) {
461 		DRM_ERROR(
462 		"amdgpu: failed to initialize sw for display support.\n");
463 		goto error;
464 	}
465 
466 	/* Update the actual used number of crtc */
467 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
468 
469 	/* TODO: Add_display_info? */
470 
471 	/* TODO use dynamic cursor width */
472 	adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
473 	adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
474 
475 	if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
476 		DRM_ERROR(
477 		"amdgpu: failed to initialize sw for display support.\n");
478 		goto error;
479 	}
480 
481 #if defined(CONFIG_DEBUG_FS)
482 	if (dtn_debugfs_init(adev))
483 		DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
484 #endif
485 
486 	DRM_DEBUG_DRIVER("KMS initialized.\n");
487 
488 	return 0;
489 error:
490 	amdgpu_dm_fini(adev);
491 
492 	return -EINVAL;
493 }
494 
495 static void amdgpu_dm_fini(struct amdgpu_device *adev)
496 {
497 	amdgpu_dm_destroy_drm_device(&adev->dm);
498 	/*
499 	 * TODO: pageflip, vlank interrupt
500 	 *
501 	 * amdgpu_dm_irq_fini(adev);
502 	 */
503 
504 	if (adev->dm.cgs_device) {
505 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
506 		adev->dm.cgs_device = NULL;
507 	}
508 	if (adev->dm.freesync_module) {
509 		mod_freesync_destroy(adev->dm.freesync_module);
510 		adev->dm.freesync_module = NULL;
511 	}
512 	/* DC Destroy TODO: Replace destroy DAL */
513 	if (adev->dm.dc)
514 		dc_destroy(&adev->dm.dc);
515 	return;
516 }
517 
518 static int load_dmcu_fw(struct amdgpu_device *adev)
519 {
520 	const char *fw_name_dmcu;
521 	int r;
522 	const struct dmcu_firmware_header_v1_0 *hdr;
523 
524 	switch(adev->asic_type) {
525 	case CHIP_BONAIRE:
526 	case CHIP_HAWAII:
527 	case CHIP_KAVERI:
528 	case CHIP_KABINI:
529 	case CHIP_MULLINS:
530 	case CHIP_TONGA:
531 	case CHIP_FIJI:
532 	case CHIP_CARRIZO:
533 	case CHIP_STONEY:
534 	case CHIP_POLARIS11:
535 	case CHIP_POLARIS10:
536 	case CHIP_POLARIS12:
537 	case CHIP_VEGAM:
538 	case CHIP_VEGA10:
539 	case CHIP_VEGA12:
540 	case CHIP_VEGA20:
541 		return 0;
542 	case CHIP_RAVEN:
543 		fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
544 		break;
545 	default:
546 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
547 		return -EINVAL;
548 	}
549 
550 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
551 		DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
552 		return 0;
553 	}
554 
555 	r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
556 	if (r == -ENOENT) {
557 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
558 		DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
559 		adev->dm.fw_dmcu = NULL;
560 		return 0;
561 	}
562 	if (r) {
563 		dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
564 			fw_name_dmcu);
565 		return r;
566 	}
567 
568 	r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
569 	if (r) {
570 		dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
571 			fw_name_dmcu);
572 		release_firmware(adev->dm.fw_dmcu);
573 		adev->dm.fw_dmcu = NULL;
574 		return r;
575 	}
576 
577 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
578 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
579 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
580 	adev->firmware.fw_size +=
581 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
582 
583 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
584 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
585 	adev->firmware.fw_size +=
586 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
587 
588 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
589 
590 	DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
591 
592 	return 0;
593 }
594 
595 static int dm_sw_init(void *handle)
596 {
597 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
598 
599 	return load_dmcu_fw(adev);
600 }
601 
602 static int dm_sw_fini(void *handle)
603 {
604 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
605 
606 	if(adev->dm.fw_dmcu) {
607 		release_firmware(adev->dm.fw_dmcu);
608 		adev->dm.fw_dmcu = NULL;
609 	}
610 
611 	return 0;
612 }
613 
614 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
615 {
616 	struct amdgpu_dm_connector *aconnector;
617 	struct drm_connector *connector;
618 	int ret = 0;
619 
620 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
621 
622 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
623 		aconnector = to_amdgpu_dm_connector(connector);
624 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
625 		    aconnector->mst_mgr.aux) {
626 			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
627 					aconnector, aconnector->base.base.id);
628 
629 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
630 			if (ret < 0) {
631 				DRM_ERROR("DM_MST: Failed to start MST\n");
632 				((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
633 				return ret;
634 				}
635 			}
636 	}
637 
638 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
639 	return ret;
640 }
641 
642 static int dm_late_init(void *handle)
643 {
644 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
645 
646 	return detect_mst_link_for_all_connectors(adev->ddev);
647 }
648 
649 static void s3_handle_mst(struct drm_device *dev, bool suspend)
650 {
651 	struct amdgpu_dm_connector *aconnector;
652 	struct drm_connector *connector;
653 
654 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
655 
656 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
657 		   aconnector = to_amdgpu_dm_connector(connector);
658 		   if (aconnector->dc_link->type == dc_connection_mst_branch &&
659 				   !aconnector->mst_port) {
660 
661 			   if (suspend)
662 				   drm_dp_mst_topology_mgr_suspend(&aconnector->mst_mgr);
663 			   else
664 				   drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr);
665 		   }
666 	}
667 
668 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
669 }
670 
671 /**
672  * dm_hw_init() - Initialize DC device
673  * @handle: The base driver device containing the amdpgu_dm device.
674  *
675  * Initialize the &struct amdgpu_display_manager device. This involves calling
676  * the initializers of each DM component, then populating the struct with them.
677  *
678  * Although the function implies hardware initialization, both hardware and
679  * software are initialized here. Splitting them out to their relevant init
680  * hooks is a future TODO item.
681  *
682  * Some notable things that are initialized here:
683  *
684  * - Display Core, both software and hardware
685  * - DC modules that we need (freesync and color management)
686  * - DRM software states
687  * - Interrupt sources and handlers
688  * - Vblank support
689  * - Debug FS entries, if enabled
690  */
691 static int dm_hw_init(void *handle)
692 {
693 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
694 	/* Create DAL display manager */
695 	amdgpu_dm_init(adev);
696 	amdgpu_dm_hpd_init(adev);
697 
698 	return 0;
699 }
700 
701 /**
702  * dm_hw_fini() - Teardown DC device
703  * @handle: The base driver device containing the amdpgu_dm device.
704  *
705  * Teardown components within &struct amdgpu_display_manager that require
706  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
707  * were loaded. Also flush IRQ workqueues and disable them.
708  */
709 static int dm_hw_fini(void *handle)
710 {
711 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
712 
713 	amdgpu_dm_hpd_fini(adev);
714 
715 	amdgpu_dm_irq_fini(adev);
716 	amdgpu_dm_fini(adev);
717 	return 0;
718 }
719 
720 static int dm_suspend(void *handle)
721 {
722 	struct amdgpu_device *adev = handle;
723 	struct amdgpu_display_manager *dm = &adev->dm;
724 	int ret = 0;
725 
726 	s3_handle_mst(adev->ddev, true);
727 
728 	amdgpu_dm_irq_suspend(adev);
729 
730 	WARN_ON(adev->dm.cached_state);
731 	adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
732 
733 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
734 
735 	return ret;
736 }
737 
738 static struct amdgpu_dm_connector *
739 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
740 					     struct drm_crtc *crtc)
741 {
742 	uint32_t i;
743 	struct drm_connector_state *new_con_state;
744 	struct drm_connector *connector;
745 	struct drm_crtc *crtc_from_state;
746 
747 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
748 		crtc_from_state = new_con_state->crtc;
749 
750 		if (crtc_from_state == crtc)
751 			return to_amdgpu_dm_connector(connector);
752 	}
753 
754 	return NULL;
755 }
756 
757 static void emulated_link_detect(struct dc_link *link)
758 {
759 	struct dc_sink_init_data sink_init_data = { 0 };
760 	struct display_sink_capability sink_caps = { 0 };
761 	enum dc_edid_status edid_status;
762 	struct dc_context *dc_ctx = link->ctx;
763 	struct dc_sink *sink = NULL;
764 	struct dc_sink *prev_sink = NULL;
765 
766 	link->type = dc_connection_none;
767 	prev_sink = link->local_sink;
768 
769 	if (prev_sink != NULL)
770 		dc_sink_retain(prev_sink);
771 
772 	switch (link->connector_signal) {
773 	case SIGNAL_TYPE_HDMI_TYPE_A: {
774 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
775 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
776 		break;
777 	}
778 
779 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
780 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
781 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
782 		break;
783 	}
784 
785 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
786 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
787 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
788 		break;
789 	}
790 
791 	case SIGNAL_TYPE_LVDS: {
792 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
793 		sink_caps.signal = SIGNAL_TYPE_LVDS;
794 		break;
795 	}
796 
797 	case SIGNAL_TYPE_EDP: {
798 		sink_caps.transaction_type =
799 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
800 		sink_caps.signal = SIGNAL_TYPE_EDP;
801 		break;
802 	}
803 
804 	case SIGNAL_TYPE_DISPLAY_PORT: {
805 		sink_caps.transaction_type =
806 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
807 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
808 		break;
809 	}
810 
811 	default:
812 		DC_ERROR("Invalid connector type! signal:%d\n",
813 			link->connector_signal);
814 		return;
815 	}
816 
817 	sink_init_data.link = link;
818 	sink_init_data.sink_signal = sink_caps.signal;
819 
820 	sink = dc_sink_create(&sink_init_data);
821 	if (!sink) {
822 		DC_ERROR("Failed to create sink!\n");
823 		return;
824 	}
825 
826 	link->local_sink = sink;
827 
828 	edid_status = dm_helpers_read_local_edid(
829 			link->ctx,
830 			link,
831 			sink);
832 
833 	if (edid_status != EDID_OK)
834 		DC_ERROR("Failed to read EDID");
835 
836 }
837 
838 static int dm_resume(void *handle)
839 {
840 	struct amdgpu_device *adev = handle;
841 	struct drm_device *ddev = adev->ddev;
842 	struct amdgpu_display_manager *dm = &adev->dm;
843 	struct amdgpu_dm_connector *aconnector;
844 	struct drm_connector *connector;
845 	struct drm_crtc *crtc;
846 	struct drm_crtc_state *new_crtc_state;
847 	struct dm_crtc_state *dm_new_crtc_state;
848 	struct drm_plane *plane;
849 	struct drm_plane_state *new_plane_state;
850 	struct dm_plane_state *dm_new_plane_state;
851 	enum dc_connection_type new_connection_type = dc_connection_none;
852 	int ret;
853 	int i;
854 
855 	/* power on hardware */
856 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
857 
858 	/* program HPD filter */
859 	dc_resume(dm->dc);
860 
861 	/* On resume we need to  rewrite the MSTM control bits to enamble MST*/
862 	s3_handle_mst(ddev, false);
863 
864 	/*
865 	 * early enable HPD Rx IRQ, should be done before set mode as short
866 	 * pulse interrupts are used for MST
867 	 */
868 	amdgpu_dm_irq_resume_early(adev);
869 
870 	/* Do detection*/
871 	list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
872 		aconnector = to_amdgpu_dm_connector(connector);
873 
874 		/*
875 		 * this is the case when traversing through already created
876 		 * MST connectors, should be skipped
877 		 */
878 		if (aconnector->mst_port)
879 			continue;
880 
881 		mutex_lock(&aconnector->hpd_lock);
882 		if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
883 			DRM_ERROR("KMS: Failed to detect connector\n");
884 
885 		if (aconnector->base.force && new_connection_type == dc_connection_none)
886 			emulated_link_detect(aconnector->dc_link);
887 		else
888 			dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
889 
890 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
891 			aconnector->fake_enable = false;
892 
893 		aconnector->dc_sink = NULL;
894 		amdgpu_dm_update_connector_after_detect(aconnector);
895 		mutex_unlock(&aconnector->hpd_lock);
896 	}
897 
898 	/* Force mode set in atomic commit */
899 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
900 		new_crtc_state->active_changed = true;
901 
902 	/*
903 	 * atomic_check is expected to create the dc states. We need to release
904 	 * them here, since they were duplicated as part of the suspend
905 	 * procedure.
906 	 */
907 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
908 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
909 		if (dm_new_crtc_state->stream) {
910 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
911 			dc_stream_release(dm_new_crtc_state->stream);
912 			dm_new_crtc_state->stream = NULL;
913 		}
914 	}
915 
916 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
917 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
918 		if (dm_new_plane_state->dc_state) {
919 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
920 			dc_plane_state_release(dm_new_plane_state->dc_state);
921 			dm_new_plane_state->dc_state = NULL;
922 		}
923 	}
924 
925 	ret = drm_atomic_helper_resume(ddev, dm->cached_state);
926 
927 	dm->cached_state = NULL;
928 
929 	amdgpu_dm_irq_resume_late(adev);
930 
931 	return ret;
932 }
933 
934 /**
935  * DOC: DM Lifecycle
936  *
937  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
938  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
939  * the base driver's device list to be initialized and torn down accordingly.
940  *
941  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
942  */
943 
944 static const struct amd_ip_funcs amdgpu_dm_funcs = {
945 	.name = "dm",
946 	.early_init = dm_early_init,
947 	.late_init = dm_late_init,
948 	.sw_init = dm_sw_init,
949 	.sw_fini = dm_sw_fini,
950 	.hw_init = dm_hw_init,
951 	.hw_fini = dm_hw_fini,
952 	.suspend = dm_suspend,
953 	.resume = dm_resume,
954 	.is_idle = dm_is_idle,
955 	.wait_for_idle = dm_wait_for_idle,
956 	.check_soft_reset = dm_check_soft_reset,
957 	.soft_reset = dm_soft_reset,
958 	.set_clockgating_state = dm_set_clockgating_state,
959 	.set_powergating_state = dm_set_powergating_state,
960 };
961 
962 const struct amdgpu_ip_block_version dm_ip_block =
963 {
964 	.type = AMD_IP_BLOCK_TYPE_DCE,
965 	.major = 1,
966 	.minor = 0,
967 	.rev = 0,
968 	.funcs = &amdgpu_dm_funcs,
969 };
970 
971 
972 static struct drm_atomic_state *
973 dm_atomic_state_alloc(struct drm_device *dev)
974 {
975 	struct dm_atomic_state *state = kzalloc(sizeof(*state), GFP_KERNEL);
976 
977 	if (!state)
978 		return NULL;
979 
980 	if (drm_atomic_state_init(dev, &state->base) < 0)
981 		goto fail;
982 
983 	return &state->base;
984 
985 fail:
986 	kfree(state);
987 	return NULL;
988 }
989 
990 static void
991 dm_atomic_state_clear(struct drm_atomic_state *state)
992 {
993 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
994 
995 	if (dm_state->context) {
996 		dc_release_state(dm_state->context);
997 		dm_state->context = NULL;
998 	}
999 
1000 	drm_atomic_state_default_clear(state);
1001 }
1002 
1003 static void
1004 dm_atomic_state_alloc_free(struct drm_atomic_state *state)
1005 {
1006 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1007 	drm_atomic_state_default_release(state);
1008 	kfree(dm_state);
1009 }
1010 
1011 /**
1012  * DOC: atomic
1013  *
1014  * *WIP*
1015  */
1016 
1017 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1018 	.fb_create = amdgpu_display_user_framebuffer_create,
1019 	.output_poll_changed = drm_fb_helper_output_poll_changed,
1020 	.atomic_check = amdgpu_dm_atomic_check,
1021 	.atomic_commit = amdgpu_dm_atomic_commit,
1022 	.atomic_state_alloc = dm_atomic_state_alloc,
1023 	.atomic_state_clear = dm_atomic_state_clear,
1024 	.atomic_state_free = dm_atomic_state_alloc_free
1025 };
1026 
1027 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1028 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1029 };
1030 
1031 static void
1032 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1033 {
1034 	struct drm_connector *connector = &aconnector->base;
1035 	struct drm_device *dev = connector->dev;
1036 	struct dc_sink *sink;
1037 
1038 	/* MST handled by drm_mst framework */
1039 	if (aconnector->mst_mgr.mst_state == true)
1040 		return;
1041 
1042 
1043 	sink = aconnector->dc_link->local_sink;
1044 
1045 	/*
1046 	 * Edid mgmt connector gets first update only in mode_valid hook and then
1047 	 * the connector sink is set to either fake or physical sink depends on link status.
1048 	 * Skip if already done during boot.
1049 	 */
1050 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1051 			&& aconnector->dc_em_sink) {
1052 
1053 		/*
1054 		 * For S3 resume with headless use eml_sink to fake stream
1055 		 * because on resume connector->sink is set to NULL
1056 		 */
1057 		mutex_lock(&dev->mode_config.mutex);
1058 
1059 		if (sink) {
1060 			if (aconnector->dc_sink) {
1061 				amdgpu_dm_update_freesync_caps(connector, NULL);
1062 				/*
1063 				 * retain and release below are used to
1064 				 * bump up refcount for sink because the link doesn't point
1065 				 * to it anymore after disconnect, so on next crtc to connector
1066 				 * reshuffle by UMD we will get into unwanted dc_sink release
1067 				 */
1068 				if (aconnector->dc_sink != aconnector->dc_em_sink)
1069 					dc_sink_release(aconnector->dc_sink);
1070 			}
1071 			aconnector->dc_sink = sink;
1072 			amdgpu_dm_update_freesync_caps(connector,
1073 					aconnector->edid);
1074 		} else {
1075 			amdgpu_dm_update_freesync_caps(connector, NULL);
1076 			if (!aconnector->dc_sink)
1077 				aconnector->dc_sink = aconnector->dc_em_sink;
1078 			else if (aconnector->dc_sink != aconnector->dc_em_sink)
1079 				dc_sink_retain(aconnector->dc_sink);
1080 		}
1081 
1082 		mutex_unlock(&dev->mode_config.mutex);
1083 		return;
1084 	}
1085 
1086 	/*
1087 	 * TODO: temporary guard to look for proper fix
1088 	 * if this sink is MST sink, we should not do anything
1089 	 */
1090 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
1091 		return;
1092 
1093 	if (aconnector->dc_sink == sink) {
1094 		/*
1095 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
1096 		 * Do nothing!!
1097 		 */
1098 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1099 				aconnector->connector_id);
1100 		return;
1101 	}
1102 
1103 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1104 		aconnector->connector_id, aconnector->dc_sink, sink);
1105 
1106 	mutex_lock(&dev->mode_config.mutex);
1107 
1108 	/*
1109 	 * 1. Update status of the drm connector
1110 	 * 2. Send an event and let userspace tell us what to do
1111 	 */
1112 	if (sink) {
1113 		/*
1114 		 * TODO: check if we still need the S3 mode update workaround.
1115 		 * If yes, put it here.
1116 		 */
1117 		if (aconnector->dc_sink)
1118 			amdgpu_dm_update_freesync_caps(connector, NULL);
1119 
1120 		aconnector->dc_sink = sink;
1121 		if (sink->dc_edid.length == 0) {
1122 			aconnector->edid = NULL;
1123 			drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1124 		} else {
1125 			aconnector->edid =
1126 				(struct edid *) sink->dc_edid.raw_edid;
1127 
1128 
1129 			drm_connector_update_edid_property(connector,
1130 					aconnector->edid);
1131 			drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1132 					    aconnector->edid);
1133 		}
1134 		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1135 
1136 	} else {
1137 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1138 		amdgpu_dm_update_freesync_caps(connector, NULL);
1139 		drm_connector_update_edid_property(connector, NULL);
1140 		aconnector->num_modes = 0;
1141 		aconnector->dc_sink = NULL;
1142 		aconnector->edid = NULL;
1143 	}
1144 
1145 	mutex_unlock(&dev->mode_config.mutex);
1146 }
1147 
1148 static void handle_hpd_irq(void *param)
1149 {
1150 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1151 	struct drm_connector *connector = &aconnector->base;
1152 	struct drm_device *dev = connector->dev;
1153 	enum dc_connection_type new_connection_type = dc_connection_none;
1154 
1155 	/*
1156 	 * In case of failure or MST no need to update connector status or notify the OS
1157 	 * since (for MST case) MST does this in its own context.
1158 	 */
1159 	mutex_lock(&aconnector->hpd_lock);
1160 
1161 	if (aconnector->fake_enable)
1162 		aconnector->fake_enable = false;
1163 
1164 	if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1165 		DRM_ERROR("KMS: Failed to detect connector\n");
1166 
1167 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
1168 		emulated_link_detect(aconnector->dc_link);
1169 
1170 
1171 		drm_modeset_lock_all(dev);
1172 		dm_restore_drm_connector_state(dev, connector);
1173 		drm_modeset_unlock_all(dev);
1174 
1175 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1176 			drm_kms_helper_hotplug_event(dev);
1177 
1178 	} else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1179 		amdgpu_dm_update_connector_after_detect(aconnector);
1180 
1181 
1182 		drm_modeset_lock_all(dev);
1183 		dm_restore_drm_connector_state(dev, connector);
1184 		drm_modeset_unlock_all(dev);
1185 
1186 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1187 			drm_kms_helper_hotplug_event(dev);
1188 	}
1189 	mutex_unlock(&aconnector->hpd_lock);
1190 
1191 }
1192 
1193 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1194 {
1195 	uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1196 	uint8_t dret;
1197 	bool new_irq_handled = false;
1198 	int dpcd_addr;
1199 	int dpcd_bytes_to_read;
1200 
1201 	const int max_process_count = 30;
1202 	int process_count = 0;
1203 
1204 	const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1205 
1206 	if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1207 		dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1208 		/* DPCD 0x200 - 0x201 for downstream IRQ */
1209 		dpcd_addr = DP_SINK_COUNT;
1210 	} else {
1211 		dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1212 		/* DPCD 0x2002 - 0x2005 for downstream IRQ */
1213 		dpcd_addr = DP_SINK_COUNT_ESI;
1214 	}
1215 
1216 	dret = drm_dp_dpcd_read(
1217 		&aconnector->dm_dp_aux.aux,
1218 		dpcd_addr,
1219 		esi,
1220 		dpcd_bytes_to_read);
1221 
1222 	while (dret == dpcd_bytes_to_read &&
1223 		process_count < max_process_count) {
1224 		uint8_t retry;
1225 		dret = 0;
1226 
1227 		process_count++;
1228 
1229 		DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1230 		/* handle HPD short pulse irq */
1231 		if (aconnector->mst_mgr.mst_state)
1232 			drm_dp_mst_hpd_irq(
1233 				&aconnector->mst_mgr,
1234 				esi,
1235 				&new_irq_handled);
1236 
1237 		if (new_irq_handled) {
1238 			/* ACK at DPCD to notify down stream */
1239 			const int ack_dpcd_bytes_to_write =
1240 				dpcd_bytes_to_read - 1;
1241 
1242 			for (retry = 0; retry < 3; retry++) {
1243 				uint8_t wret;
1244 
1245 				wret = drm_dp_dpcd_write(
1246 					&aconnector->dm_dp_aux.aux,
1247 					dpcd_addr + 1,
1248 					&esi[1],
1249 					ack_dpcd_bytes_to_write);
1250 				if (wret == ack_dpcd_bytes_to_write)
1251 					break;
1252 			}
1253 
1254 			/* check if there is new irq to be handled */
1255 			dret = drm_dp_dpcd_read(
1256 				&aconnector->dm_dp_aux.aux,
1257 				dpcd_addr,
1258 				esi,
1259 				dpcd_bytes_to_read);
1260 
1261 			new_irq_handled = false;
1262 		} else {
1263 			break;
1264 		}
1265 	}
1266 
1267 	if (process_count == max_process_count)
1268 		DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1269 }
1270 
1271 static void handle_hpd_rx_irq(void *param)
1272 {
1273 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1274 	struct drm_connector *connector = &aconnector->base;
1275 	struct drm_device *dev = connector->dev;
1276 	struct dc_link *dc_link = aconnector->dc_link;
1277 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1278 	enum dc_connection_type new_connection_type = dc_connection_none;
1279 
1280 	/*
1281 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1282 	 * conflict, after implement i2c helper, this mutex should be
1283 	 * retired.
1284 	 */
1285 	if (dc_link->type != dc_connection_mst_branch)
1286 		mutex_lock(&aconnector->hpd_lock);
1287 
1288 	if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1289 			!is_mst_root_connector) {
1290 		/* Downstream Port status changed. */
1291 		if (!dc_link_detect_sink(dc_link, &new_connection_type))
1292 			DRM_ERROR("KMS: Failed to detect connector\n");
1293 
1294 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
1295 			emulated_link_detect(dc_link);
1296 
1297 			if (aconnector->fake_enable)
1298 				aconnector->fake_enable = false;
1299 
1300 			amdgpu_dm_update_connector_after_detect(aconnector);
1301 
1302 
1303 			drm_modeset_lock_all(dev);
1304 			dm_restore_drm_connector_state(dev, connector);
1305 			drm_modeset_unlock_all(dev);
1306 
1307 			drm_kms_helper_hotplug_event(dev);
1308 		} else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1309 
1310 			if (aconnector->fake_enable)
1311 				aconnector->fake_enable = false;
1312 
1313 			amdgpu_dm_update_connector_after_detect(aconnector);
1314 
1315 
1316 			drm_modeset_lock_all(dev);
1317 			dm_restore_drm_connector_state(dev, connector);
1318 			drm_modeset_unlock_all(dev);
1319 
1320 			drm_kms_helper_hotplug_event(dev);
1321 		}
1322 	}
1323 	if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1324 	    (dc_link->type == dc_connection_mst_branch))
1325 		dm_handle_hpd_rx_irq(aconnector);
1326 
1327 	if (dc_link->type != dc_connection_mst_branch) {
1328 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1329 		mutex_unlock(&aconnector->hpd_lock);
1330 	}
1331 }
1332 
1333 static void register_hpd_handlers(struct amdgpu_device *adev)
1334 {
1335 	struct drm_device *dev = adev->ddev;
1336 	struct drm_connector *connector;
1337 	struct amdgpu_dm_connector *aconnector;
1338 	const struct dc_link *dc_link;
1339 	struct dc_interrupt_params int_params = {0};
1340 
1341 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1342 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1343 
1344 	list_for_each_entry(connector,
1345 			&dev->mode_config.connector_list, head)	{
1346 
1347 		aconnector = to_amdgpu_dm_connector(connector);
1348 		dc_link = aconnector->dc_link;
1349 
1350 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1351 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1352 			int_params.irq_source = dc_link->irq_source_hpd;
1353 
1354 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1355 					handle_hpd_irq,
1356 					(void *) aconnector);
1357 		}
1358 
1359 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1360 
1361 			/* Also register for DP short pulse (hpd_rx). */
1362 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1363 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
1364 
1365 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1366 					handle_hpd_rx_irq,
1367 					(void *) aconnector);
1368 		}
1369 	}
1370 }
1371 
1372 /* Register IRQ sources and initialize IRQ callbacks */
1373 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1374 {
1375 	struct dc *dc = adev->dm.dc;
1376 	struct common_irq_params *c_irq_params;
1377 	struct dc_interrupt_params int_params = {0};
1378 	int r;
1379 	int i;
1380 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1381 
1382 	if (adev->asic_type == CHIP_VEGA10 ||
1383 	    adev->asic_type == CHIP_VEGA12 ||
1384 	    adev->asic_type == CHIP_VEGA20 ||
1385 	    adev->asic_type == CHIP_RAVEN)
1386 		client_id = SOC15_IH_CLIENTID_DCE;
1387 
1388 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1389 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1390 
1391 	/*
1392 	 * Actions of amdgpu_irq_add_id():
1393 	 * 1. Register a set() function with base driver.
1394 	 *    Base driver will call set() function to enable/disable an
1395 	 *    interrupt in DC hardware.
1396 	 * 2. Register amdgpu_dm_irq_handler().
1397 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1398 	 *    coming from DC hardware.
1399 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1400 	 *    for acknowledging and handling. */
1401 
1402 	/* Use VBLANK interrupt */
1403 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1404 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1405 		if (r) {
1406 			DRM_ERROR("Failed to add crtc irq id!\n");
1407 			return r;
1408 		}
1409 
1410 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1411 		int_params.irq_source =
1412 			dc_interrupt_to_irq_source(dc, i, 0);
1413 
1414 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1415 
1416 		c_irq_params->adev = adev;
1417 		c_irq_params->irq_src = int_params.irq_source;
1418 
1419 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1420 				dm_crtc_high_irq, c_irq_params);
1421 	}
1422 
1423 	/* Use GRPH_PFLIP interrupt */
1424 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1425 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1426 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1427 		if (r) {
1428 			DRM_ERROR("Failed to add page flip irq id!\n");
1429 			return r;
1430 		}
1431 
1432 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1433 		int_params.irq_source =
1434 			dc_interrupt_to_irq_source(dc, i, 0);
1435 
1436 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1437 
1438 		c_irq_params->adev = adev;
1439 		c_irq_params->irq_src = int_params.irq_source;
1440 
1441 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1442 				dm_pflip_high_irq, c_irq_params);
1443 
1444 	}
1445 
1446 	/* HPD */
1447 	r = amdgpu_irq_add_id(adev, client_id,
1448 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1449 	if (r) {
1450 		DRM_ERROR("Failed to add hpd irq id!\n");
1451 		return r;
1452 	}
1453 
1454 	register_hpd_handlers(adev);
1455 
1456 	return 0;
1457 }
1458 
1459 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1460 /* Register IRQ sources and initialize IRQ callbacks */
1461 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1462 {
1463 	struct dc *dc = adev->dm.dc;
1464 	struct common_irq_params *c_irq_params;
1465 	struct dc_interrupt_params int_params = {0};
1466 	int r;
1467 	int i;
1468 
1469 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1470 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1471 
1472 	/*
1473 	 * Actions of amdgpu_irq_add_id():
1474 	 * 1. Register a set() function with base driver.
1475 	 *    Base driver will call set() function to enable/disable an
1476 	 *    interrupt in DC hardware.
1477 	 * 2. Register amdgpu_dm_irq_handler().
1478 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1479 	 *    coming from DC hardware.
1480 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1481 	 *    for acknowledging and handling.
1482 	 */
1483 
1484 	/* Use VSTARTUP interrupt */
1485 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1486 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1487 			i++) {
1488 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1489 
1490 		if (r) {
1491 			DRM_ERROR("Failed to add crtc irq id!\n");
1492 			return r;
1493 		}
1494 
1495 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1496 		int_params.irq_source =
1497 			dc_interrupt_to_irq_source(dc, i, 0);
1498 
1499 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1500 
1501 		c_irq_params->adev = adev;
1502 		c_irq_params->irq_src = int_params.irq_source;
1503 
1504 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1505 				dm_crtc_high_irq, c_irq_params);
1506 	}
1507 
1508 	/* Use GRPH_PFLIP interrupt */
1509 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1510 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1511 			i++) {
1512 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1513 		if (r) {
1514 			DRM_ERROR("Failed to add page flip irq id!\n");
1515 			return r;
1516 		}
1517 
1518 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1519 		int_params.irq_source =
1520 			dc_interrupt_to_irq_source(dc, i, 0);
1521 
1522 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1523 
1524 		c_irq_params->adev = adev;
1525 		c_irq_params->irq_src = int_params.irq_source;
1526 
1527 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1528 				dm_pflip_high_irq, c_irq_params);
1529 
1530 	}
1531 
1532 	/* HPD */
1533 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1534 			&adev->hpd_irq);
1535 	if (r) {
1536 		DRM_ERROR("Failed to add hpd irq id!\n");
1537 		return r;
1538 	}
1539 
1540 	register_hpd_handlers(adev);
1541 
1542 	return 0;
1543 }
1544 #endif
1545 
1546 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1547 {
1548 	int r;
1549 
1550 	adev->mode_info.mode_config_initialized = true;
1551 
1552 	adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1553 	adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1554 
1555 	adev->ddev->mode_config.max_width = 16384;
1556 	adev->ddev->mode_config.max_height = 16384;
1557 
1558 	adev->ddev->mode_config.preferred_depth = 24;
1559 	adev->ddev->mode_config.prefer_shadow = 1;
1560 	/* indicates support for immediate flip */
1561 	adev->ddev->mode_config.async_page_flip = true;
1562 
1563 	adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1564 
1565 	r = amdgpu_display_modeset_create_props(adev);
1566 	if (r)
1567 		return r;
1568 
1569 	return 0;
1570 }
1571 
1572 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1573 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1574 
1575 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1576 {
1577 	struct amdgpu_display_manager *dm = bl_get_data(bd);
1578 
1579 	/* backlight_pwm_u16_16 parameter is in unsigned 32 bit, 16 bit integer
1580 	 * and 16 bit fractional, where 1.0 is max backlight value.
1581 	 * bd->props.brightness is 8 bit format and needs to be converted by
1582 	 * scaling via copy lower byte to upper byte of 16 bit value.
1583 	 */
1584 	uint32_t brightness = bd->props.brightness * 0x101;
1585 
1586 	/*
1587 	 * PWM interperts 0 as 100% rather than 0% because of HW
1588 	 * limitation for level 0.  So limiting minimum brightness level
1589 	 * to 1.
1590 	 */
1591 	if (bd->props.brightness < 1)
1592 		brightness = 0x101;
1593 
1594 	if (dc_link_set_backlight_level(dm->backlight_link,
1595 			brightness, 0, 0))
1596 		return 0;
1597 	else
1598 		return 1;
1599 }
1600 
1601 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1602 {
1603 	struct amdgpu_display_manager *dm = bl_get_data(bd);
1604 	int ret = dc_link_get_backlight_level(dm->backlight_link);
1605 
1606 	if (ret == DC_ERROR_UNEXPECTED)
1607 		return bd->props.brightness;
1608 	return ret;
1609 }
1610 
1611 static const struct backlight_ops amdgpu_dm_backlight_ops = {
1612 	.get_brightness = amdgpu_dm_backlight_get_brightness,
1613 	.update_status	= amdgpu_dm_backlight_update_status,
1614 };
1615 
1616 static void
1617 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1618 {
1619 	char bl_name[16];
1620 	struct backlight_properties props = { 0 };
1621 
1622 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1623 	props.brightness = AMDGPU_MAX_BL_LEVEL;
1624 	props.type = BACKLIGHT_RAW;
1625 
1626 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1627 			dm->adev->ddev->primary->index);
1628 
1629 	dm->backlight_dev = backlight_device_register(bl_name,
1630 			dm->adev->ddev->dev,
1631 			dm,
1632 			&amdgpu_dm_backlight_ops,
1633 			&props);
1634 
1635 	if (IS_ERR(dm->backlight_dev))
1636 		DRM_ERROR("DM: Backlight registration failed!\n");
1637 	else
1638 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1639 }
1640 
1641 #endif
1642 
1643 static int initialize_plane(struct amdgpu_display_manager *dm,
1644 			     struct amdgpu_mode_info *mode_info,
1645 			     int plane_id)
1646 {
1647 	struct drm_plane *plane;
1648 	unsigned long possible_crtcs;
1649 	int ret = 0;
1650 
1651 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
1652 	mode_info->planes[plane_id] = plane;
1653 
1654 	if (!plane) {
1655 		DRM_ERROR("KMS: Failed to allocate plane\n");
1656 		return -ENOMEM;
1657 	}
1658 	plane->type = mode_info->plane_type[plane_id];
1659 
1660 	/*
1661 	 * HACK: IGT tests expect that each plane can only have
1662 	 * one possible CRTC. For now, set one CRTC for each
1663 	 * plane that is not an underlay, but still allow multiple
1664 	 * CRTCs for underlay planes.
1665 	 */
1666 	possible_crtcs = 1 << plane_id;
1667 	if (plane_id >= dm->dc->caps.max_streams)
1668 		possible_crtcs = 0xff;
1669 
1670 	ret = amdgpu_dm_plane_init(dm, mode_info->planes[plane_id], possible_crtcs);
1671 
1672 	if (ret) {
1673 		DRM_ERROR("KMS: Failed to initialize plane\n");
1674 		return ret;
1675 	}
1676 
1677 	return ret;
1678 }
1679 
1680 
1681 static void register_backlight_device(struct amdgpu_display_manager *dm,
1682 				      struct dc_link *link)
1683 {
1684 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1685 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1686 
1687 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
1688 	    link->type != dc_connection_none) {
1689 		/*
1690 		 * Event if registration failed, we should continue with
1691 		 * DM initialization because not having a backlight control
1692 		 * is better then a black screen.
1693 		 */
1694 		amdgpu_dm_register_backlight_device(dm);
1695 
1696 		if (dm->backlight_dev)
1697 			dm->backlight_link = link;
1698 	}
1699 #endif
1700 }
1701 
1702 
1703 /*
1704  * In this architecture, the association
1705  * connector -> encoder -> crtc
1706  * id not really requried. The crtc and connector will hold the
1707  * display_index as an abstraction to use with DAL component
1708  *
1709  * Returns 0 on success
1710  */
1711 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
1712 {
1713 	struct amdgpu_display_manager *dm = &adev->dm;
1714 	int32_t i;
1715 	struct amdgpu_dm_connector *aconnector = NULL;
1716 	struct amdgpu_encoder *aencoder = NULL;
1717 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
1718 	uint32_t link_cnt;
1719 	int32_t total_overlay_planes, total_primary_planes;
1720 	enum dc_connection_type new_connection_type = dc_connection_none;
1721 
1722 	link_cnt = dm->dc->caps.max_links;
1723 	if (amdgpu_dm_mode_config_init(dm->adev)) {
1724 		DRM_ERROR("DM: Failed to initialize mode config\n");
1725 		return -EINVAL;
1726 	}
1727 
1728 	/* Identify the number of planes to be initialized */
1729 	total_overlay_planes = dm->dc->caps.max_slave_planes;
1730 	total_primary_planes = dm->dc->caps.max_planes - dm->dc->caps.max_slave_planes;
1731 
1732 	/* First initialize overlay planes, index starting after primary planes */
1733 	for (i = (total_overlay_planes - 1); i >= 0; i--) {
1734 		if (initialize_plane(dm, mode_info, (total_primary_planes + i))) {
1735 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
1736 			goto fail;
1737 		}
1738 	}
1739 
1740 	/* Initialize primary planes */
1741 	for (i = (total_primary_planes - 1); i >= 0; i--) {
1742 		if (initialize_plane(dm, mode_info, i)) {
1743 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
1744 			goto fail;
1745 		}
1746 	}
1747 
1748 	for (i = 0; i < dm->dc->caps.max_streams; i++)
1749 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
1750 			DRM_ERROR("KMS: Failed to initialize crtc\n");
1751 			goto fail;
1752 		}
1753 
1754 	dm->display_indexes_num = dm->dc->caps.max_streams;
1755 
1756 	/* loops over all connectors on the board */
1757 	for (i = 0; i < link_cnt; i++) {
1758 		struct dc_link *link = NULL;
1759 
1760 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
1761 			DRM_ERROR(
1762 				"KMS: Cannot support more than %d display indexes\n",
1763 					AMDGPU_DM_MAX_DISPLAY_INDEX);
1764 			continue;
1765 		}
1766 
1767 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
1768 		if (!aconnector)
1769 			goto fail;
1770 
1771 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
1772 		if (!aencoder)
1773 			goto fail;
1774 
1775 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
1776 			DRM_ERROR("KMS: Failed to initialize encoder\n");
1777 			goto fail;
1778 		}
1779 
1780 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
1781 			DRM_ERROR("KMS: Failed to initialize connector\n");
1782 			goto fail;
1783 		}
1784 
1785 		link = dc_get_link_at_index(dm->dc, i);
1786 
1787 		if (!dc_link_detect_sink(link, &new_connection_type))
1788 			DRM_ERROR("KMS: Failed to detect connector\n");
1789 
1790 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
1791 			emulated_link_detect(link);
1792 			amdgpu_dm_update_connector_after_detect(aconnector);
1793 
1794 		} else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
1795 			amdgpu_dm_update_connector_after_detect(aconnector);
1796 			register_backlight_device(dm, link);
1797 		}
1798 
1799 
1800 	}
1801 
1802 	/* Software is initialized. Now we can register interrupt handlers. */
1803 	switch (adev->asic_type) {
1804 	case CHIP_BONAIRE:
1805 	case CHIP_HAWAII:
1806 	case CHIP_KAVERI:
1807 	case CHIP_KABINI:
1808 	case CHIP_MULLINS:
1809 	case CHIP_TONGA:
1810 	case CHIP_FIJI:
1811 	case CHIP_CARRIZO:
1812 	case CHIP_STONEY:
1813 	case CHIP_POLARIS11:
1814 	case CHIP_POLARIS10:
1815 	case CHIP_POLARIS12:
1816 	case CHIP_VEGAM:
1817 	case CHIP_VEGA10:
1818 	case CHIP_VEGA12:
1819 	case CHIP_VEGA20:
1820 		if (dce110_register_irq_handlers(dm->adev)) {
1821 			DRM_ERROR("DM: Failed to initialize IRQ\n");
1822 			goto fail;
1823 		}
1824 		break;
1825 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1826 	case CHIP_RAVEN:
1827 		if (dcn10_register_irq_handlers(dm->adev)) {
1828 			DRM_ERROR("DM: Failed to initialize IRQ\n");
1829 			goto fail;
1830 		}
1831 		break;
1832 #endif
1833 	default:
1834 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1835 		goto fail;
1836 	}
1837 
1838 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
1839 		dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
1840 
1841 	return 0;
1842 fail:
1843 	kfree(aencoder);
1844 	kfree(aconnector);
1845 	for (i = 0; i < dm->dc->caps.max_planes; i++)
1846 		kfree(mode_info->planes[i]);
1847 	return -EINVAL;
1848 }
1849 
1850 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
1851 {
1852 	drm_mode_config_cleanup(dm->ddev);
1853 	return;
1854 }
1855 
1856 /******************************************************************************
1857  * amdgpu_display_funcs functions
1858  *****************************************************************************/
1859 
1860 /*
1861  * dm_bandwidth_update - program display watermarks
1862  *
1863  * @adev: amdgpu_device pointer
1864  *
1865  * Calculate and program the display watermarks and line buffer allocation.
1866  */
1867 static void dm_bandwidth_update(struct amdgpu_device *adev)
1868 {
1869 	/* TODO: implement later */
1870 }
1871 
1872 static int amdgpu_notify_freesync(struct drm_device *dev, void *data,
1873 				struct drm_file *filp)
1874 {
1875 	struct drm_atomic_state *state;
1876 	struct drm_modeset_acquire_ctx ctx;
1877 	struct drm_crtc *crtc;
1878 	struct drm_connector *connector;
1879 	struct drm_connector_state *old_con_state, *new_con_state;
1880 	int ret = 0;
1881 	uint8_t i;
1882 	bool enable = false;
1883 
1884 	drm_modeset_acquire_init(&ctx, 0);
1885 
1886 	state = drm_atomic_state_alloc(dev);
1887 	if (!state) {
1888 		ret = -ENOMEM;
1889 		goto out;
1890 	}
1891 	state->acquire_ctx = &ctx;
1892 
1893 retry:
1894 	drm_for_each_crtc(crtc, dev) {
1895 		ret = drm_atomic_add_affected_connectors(state, crtc);
1896 		if (ret)
1897 			goto fail;
1898 
1899 		/* TODO rework amdgpu_dm_commit_planes so we don't need this */
1900 		ret = drm_atomic_add_affected_planes(state, crtc);
1901 		if (ret)
1902 			goto fail;
1903 	}
1904 
1905 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
1906 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
1907 		struct drm_crtc_state *new_crtc_state;
1908 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
1909 		struct dm_crtc_state *dm_new_crtc_state;
1910 
1911 		if (!acrtc) {
1912 			ASSERT(0);
1913 			continue;
1914 		}
1915 
1916 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
1917 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1918 
1919 		dm_new_crtc_state->freesync_enabled = enable;
1920 	}
1921 
1922 	ret = drm_atomic_commit(state);
1923 
1924 fail:
1925 	if (ret == -EDEADLK) {
1926 		drm_atomic_state_clear(state);
1927 		drm_modeset_backoff(&ctx);
1928 		goto retry;
1929 	}
1930 
1931 	drm_atomic_state_put(state);
1932 
1933 out:
1934 	drm_modeset_drop_locks(&ctx);
1935 	drm_modeset_acquire_fini(&ctx);
1936 	return ret;
1937 }
1938 
1939 static const struct amdgpu_display_funcs dm_display_funcs = {
1940 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
1941 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
1942 	.backlight_set_level = NULL, /* never called for DC */
1943 	.backlight_get_level = NULL, /* never called for DC */
1944 	.hpd_sense = NULL,/* called unconditionally */
1945 	.hpd_set_polarity = NULL, /* called unconditionally */
1946 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
1947 	.page_flip_get_scanoutpos =
1948 		dm_crtc_get_scanoutpos,/* called unconditionally */
1949 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
1950 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
1951 	.notify_freesync = amdgpu_notify_freesync,
1952 
1953 };
1954 
1955 #if defined(CONFIG_DEBUG_KERNEL_DC)
1956 
1957 static ssize_t s3_debug_store(struct device *device,
1958 			      struct device_attribute *attr,
1959 			      const char *buf,
1960 			      size_t count)
1961 {
1962 	int ret;
1963 	int s3_state;
1964 	struct pci_dev *pdev = to_pci_dev(device);
1965 	struct drm_device *drm_dev = pci_get_drvdata(pdev);
1966 	struct amdgpu_device *adev = drm_dev->dev_private;
1967 
1968 	ret = kstrtoint(buf, 0, &s3_state);
1969 
1970 	if (ret == 0) {
1971 		if (s3_state) {
1972 			dm_resume(adev);
1973 			drm_kms_helper_hotplug_event(adev->ddev);
1974 		} else
1975 			dm_suspend(adev);
1976 	}
1977 
1978 	return ret == 0 ? count : 0;
1979 }
1980 
1981 DEVICE_ATTR_WO(s3_debug);
1982 
1983 #endif
1984 
1985 static int dm_early_init(void *handle)
1986 {
1987 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1988 
1989 	switch (adev->asic_type) {
1990 	case CHIP_BONAIRE:
1991 	case CHIP_HAWAII:
1992 		adev->mode_info.num_crtc = 6;
1993 		adev->mode_info.num_hpd = 6;
1994 		adev->mode_info.num_dig = 6;
1995 		adev->mode_info.plane_type = dm_plane_type_default;
1996 		break;
1997 	case CHIP_KAVERI:
1998 		adev->mode_info.num_crtc = 4;
1999 		adev->mode_info.num_hpd = 6;
2000 		adev->mode_info.num_dig = 7;
2001 		adev->mode_info.plane_type = dm_plane_type_default;
2002 		break;
2003 	case CHIP_KABINI:
2004 	case CHIP_MULLINS:
2005 		adev->mode_info.num_crtc = 2;
2006 		adev->mode_info.num_hpd = 6;
2007 		adev->mode_info.num_dig = 6;
2008 		adev->mode_info.plane_type = dm_plane_type_default;
2009 		break;
2010 	case CHIP_FIJI:
2011 	case CHIP_TONGA:
2012 		adev->mode_info.num_crtc = 6;
2013 		adev->mode_info.num_hpd = 6;
2014 		adev->mode_info.num_dig = 7;
2015 		adev->mode_info.plane_type = dm_plane_type_default;
2016 		break;
2017 	case CHIP_CARRIZO:
2018 		adev->mode_info.num_crtc = 3;
2019 		adev->mode_info.num_hpd = 6;
2020 		adev->mode_info.num_dig = 9;
2021 		adev->mode_info.plane_type = dm_plane_type_carizzo;
2022 		break;
2023 	case CHIP_STONEY:
2024 		adev->mode_info.num_crtc = 2;
2025 		adev->mode_info.num_hpd = 6;
2026 		adev->mode_info.num_dig = 9;
2027 		adev->mode_info.plane_type = dm_plane_type_stoney;
2028 		break;
2029 	case CHIP_POLARIS11:
2030 	case CHIP_POLARIS12:
2031 		adev->mode_info.num_crtc = 5;
2032 		adev->mode_info.num_hpd = 5;
2033 		adev->mode_info.num_dig = 5;
2034 		adev->mode_info.plane_type = dm_plane_type_default;
2035 		break;
2036 	case CHIP_POLARIS10:
2037 	case CHIP_VEGAM:
2038 		adev->mode_info.num_crtc = 6;
2039 		adev->mode_info.num_hpd = 6;
2040 		adev->mode_info.num_dig = 6;
2041 		adev->mode_info.plane_type = dm_plane_type_default;
2042 		break;
2043 	case CHIP_VEGA10:
2044 	case CHIP_VEGA12:
2045 	case CHIP_VEGA20:
2046 		adev->mode_info.num_crtc = 6;
2047 		adev->mode_info.num_hpd = 6;
2048 		adev->mode_info.num_dig = 6;
2049 		adev->mode_info.plane_type = dm_plane_type_default;
2050 		break;
2051 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2052 	case CHIP_RAVEN:
2053 		adev->mode_info.num_crtc = 4;
2054 		adev->mode_info.num_hpd = 4;
2055 		adev->mode_info.num_dig = 4;
2056 		adev->mode_info.plane_type = dm_plane_type_default;
2057 		break;
2058 #endif
2059 	default:
2060 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2061 		return -EINVAL;
2062 	}
2063 
2064 	amdgpu_dm_set_irq_funcs(adev);
2065 
2066 	if (adev->mode_info.funcs == NULL)
2067 		adev->mode_info.funcs = &dm_display_funcs;
2068 
2069 	/*
2070 	 * Note: Do NOT change adev->audio_endpt_rreg and
2071 	 * adev->audio_endpt_wreg because they are initialised in
2072 	 * amdgpu_device_init()
2073 	 */
2074 #if defined(CONFIG_DEBUG_KERNEL_DC)
2075 	device_create_file(
2076 		adev->ddev->dev,
2077 		&dev_attr_s3_debug);
2078 #endif
2079 
2080 	return 0;
2081 }
2082 
2083 static bool modeset_required(struct drm_crtc_state *crtc_state,
2084 			     struct dc_stream_state *new_stream,
2085 			     struct dc_stream_state *old_stream)
2086 {
2087 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
2088 		return false;
2089 
2090 	if (!crtc_state->enable)
2091 		return false;
2092 
2093 	return crtc_state->active;
2094 }
2095 
2096 static bool modereset_required(struct drm_crtc_state *crtc_state)
2097 {
2098 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
2099 		return false;
2100 
2101 	return !crtc_state->enable || !crtc_state->active;
2102 }
2103 
2104 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2105 {
2106 	drm_encoder_cleanup(encoder);
2107 	kfree(encoder);
2108 }
2109 
2110 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2111 	.destroy = amdgpu_dm_encoder_destroy,
2112 };
2113 
2114 static bool fill_rects_from_plane_state(const struct drm_plane_state *state,
2115 					struct dc_plane_state *plane_state)
2116 {
2117 	plane_state->src_rect.x = state->src_x >> 16;
2118 	plane_state->src_rect.y = state->src_y >> 16;
2119 	/* we ignore the mantissa for now and do not deal with floating pixels :( */
2120 	plane_state->src_rect.width = state->src_w >> 16;
2121 
2122 	if (plane_state->src_rect.width == 0)
2123 		return false;
2124 
2125 	plane_state->src_rect.height = state->src_h >> 16;
2126 	if (plane_state->src_rect.height == 0)
2127 		return false;
2128 
2129 	plane_state->dst_rect.x = state->crtc_x;
2130 	plane_state->dst_rect.y = state->crtc_y;
2131 
2132 	if (state->crtc_w == 0)
2133 		return false;
2134 
2135 	plane_state->dst_rect.width = state->crtc_w;
2136 
2137 	if (state->crtc_h == 0)
2138 		return false;
2139 
2140 	plane_state->dst_rect.height = state->crtc_h;
2141 
2142 	plane_state->clip_rect = plane_state->dst_rect;
2143 
2144 	switch (state->rotation & DRM_MODE_ROTATE_MASK) {
2145 	case DRM_MODE_ROTATE_0:
2146 		plane_state->rotation = ROTATION_ANGLE_0;
2147 		break;
2148 	case DRM_MODE_ROTATE_90:
2149 		plane_state->rotation = ROTATION_ANGLE_90;
2150 		break;
2151 	case DRM_MODE_ROTATE_180:
2152 		plane_state->rotation = ROTATION_ANGLE_180;
2153 		break;
2154 	case DRM_MODE_ROTATE_270:
2155 		plane_state->rotation = ROTATION_ANGLE_270;
2156 		break;
2157 	default:
2158 		plane_state->rotation = ROTATION_ANGLE_0;
2159 		break;
2160 	}
2161 
2162 	return true;
2163 }
2164 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2165 		       uint64_t *tiling_flags)
2166 {
2167 	struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2168 	int r = amdgpu_bo_reserve(rbo, false);
2169 
2170 	if (unlikely(r)) {
2171 		/* Don't show error message when returning -ERESTARTSYS */
2172 		if (r != -ERESTARTSYS)
2173 			DRM_ERROR("Unable to reserve buffer: %d\n", r);
2174 		return r;
2175 	}
2176 
2177 	if (tiling_flags)
2178 		amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2179 
2180 	amdgpu_bo_unreserve(rbo);
2181 
2182 	return r;
2183 }
2184 
2185 static int fill_plane_attributes_from_fb(struct amdgpu_device *adev,
2186 					 struct dc_plane_state *plane_state,
2187 					 const struct amdgpu_framebuffer *amdgpu_fb)
2188 {
2189 	uint64_t tiling_flags;
2190 	unsigned int awidth;
2191 	const struct drm_framebuffer *fb = &amdgpu_fb->base;
2192 	int ret = 0;
2193 	struct drm_format_name_buf format_name;
2194 
2195 	ret = get_fb_info(
2196 		amdgpu_fb,
2197 		&tiling_flags);
2198 
2199 	if (ret)
2200 		return ret;
2201 
2202 	switch (fb->format->format) {
2203 	case DRM_FORMAT_C8:
2204 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2205 		break;
2206 	case DRM_FORMAT_RGB565:
2207 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2208 		break;
2209 	case DRM_FORMAT_XRGB8888:
2210 	case DRM_FORMAT_ARGB8888:
2211 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2212 		break;
2213 	case DRM_FORMAT_XRGB2101010:
2214 	case DRM_FORMAT_ARGB2101010:
2215 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2216 		break;
2217 	case DRM_FORMAT_XBGR2101010:
2218 	case DRM_FORMAT_ABGR2101010:
2219 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2220 		break;
2221 	case DRM_FORMAT_XBGR8888:
2222 	case DRM_FORMAT_ABGR8888:
2223 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2224 		break;
2225 	case DRM_FORMAT_NV21:
2226 		plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2227 		break;
2228 	case DRM_FORMAT_NV12:
2229 		plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2230 		break;
2231 	default:
2232 		DRM_ERROR("Unsupported screen format %s\n",
2233 			  drm_get_format_name(fb->format->format, &format_name));
2234 		return -EINVAL;
2235 	}
2236 
2237 	if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2238 		plane_state->address.type = PLN_ADDR_TYPE_GRAPHICS;
2239 		plane_state->plane_size.grph.surface_size.x = 0;
2240 		plane_state->plane_size.grph.surface_size.y = 0;
2241 		plane_state->plane_size.grph.surface_size.width = fb->width;
2242 		plane_state->plane_size.grph.surface_size.height = fb->height;
2243 		plane_state->plane_size.grph.surface_pitch =
2244 				fb->pitches[0] / fb->format->cpp[0];
2245 		/* TODO: unhardcode */
2246 		plane_state->color_space = COLOR_SPACE_SRGB;
2247 
2248 	} else {
2249 		awidth = ALIGN(fb->width, 64);
2250 		plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2251 		plane_state->plane_size.video.luma_size.x = 0;
2252 		plane_state->plane_size.video.luma_size.y = 0;
2253 		plane_state->plane_size.video.luma_size.width = awidth;
2254 		plane_state->plane_size.video.luma_size.height = fb->height;
2255 		/* TODO: unhardcode */
2256 		plane_state->plane_size.video.luma_pitch = awidth;
2257 
2258 		plane_state->plane_size.video.chroma_size.x = 0;
2259 		plane_state->plane_size.video.chroma_size.y = 0;
2260 		plane_state->plane_size.video.chroma_size.width = awidth;
2261 		plane_state->plane_size.video.chroma_size.height = fb->height;
2262 		plane_state->plane_size.video.chroma_pitch = awidth / 2;
2263 
2264 		/* TODO: unhardcode */
2265 		plane_state->color_space = COLOR_SPACE_YCBCR709;
2266 	}
2267 
2268 	memset(&plane_state->tiling_info, 0, sizeof(plane_state->tiling_info));
2269 
2270 	/* Fill GFX8 params */
2271 	if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2272 		unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2273 
2274 		bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2275 		bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2276 		mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2277 		tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2278 		num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2279 
2280 		/* XXX fix me for VI */
2281 		plane_state->tiling_info.gfx8.num_banks = num_banks;
2282 		plane_state->tiling_info.gfx8.array_mode =
2283 				DC_ARRAY_2D_TILED_THIN1;
2284 		plane_state->tiling_info.gfx8.tile_split = tile_split;
2285 		plane_state->tiling_info.gfx8.bank_width = bankw;
2286 		plane_state->tiling_info.gfx8.bank_height = bankh;
2287 		plane_state->tiling_info.gfx8.tile_aspect = mtaspect;
2288 		plane_state->tiling_info.gfx8.tile_mode =
2289 				DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2290 	} else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2291 			== DC_ARRAY_1D_TILED_THIN1) {
2292 		plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2293 	}
2294 
2295 	plane_state->tiling_info.gfx8.pipe_config =
2296 			AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2297 
2298 	if (adev->asic_type == CHIP_VEGA10 ||
2299 	    adev->asic_type == CHIP_VEGA12 ||
2300 	    adev->asic_type == CHIP_VEGA20 ||
2301 	    adev->asic_type == CHIP_RAVEN) {
2302 		/* Fill GFX9 params */
2303 		plane_state->tiling_info.gfx9.num_pipes =
2304 			adev->gfx.config.gb_addr_config_fields.num_pipes;
2305 		plane_state->tiling_info.gfx9.num_banks =
2306 			adev->gfx.config.gb_addr_config_fields.num_banks;
2307 		plane_state->tiling_info.gfx9.pipe_interleave =
2308 			adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2309 		plane_state->tiling_info.gfx9.num_shader_engines =
2310 			adev->gfx.config.gb_addr_config_fields.num_se;
2311 		plane_state->tiling_info.gfx9.max_compressed_frags =
2312 			adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2313 		plane_state->tiling_info.gfx9.num_rb_per_se =
2314 			adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2315 		plane_state->tiling_info.gfx9.swizzle =
2316 			AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2317 		plane_state->tiling_info.gfx9.shaderEnable = 1;
2318 	}
2319 
2320 	plane_state->visible = true;
2321 	plane_state->scaling_quality.h_taps_c = 0;
2322 	plane_state->scaling_quality.v_taps_c = 0;
2323 
2324 	/* is this needed? is plane_state zeroed at allocation? */
2325 	plane_state->scaling_quality.h_taps = 0;
2326 	plane_state->scaling_quality.v_taps = 0;
2327 	plane_state->stereo_format = PLANE_STEREO_FORMAT_NONE;
2328 
2329 	return ret;
2330 
2331 }
2332 
2333 static int fill_plane_attributes(struct amdgpu_device *adev,
2334 				 struct dc_plane_state *dc_plane_state,
2335 				 struct drm_plane_state *plane_state,
2336 				 struct drm_crtc_state *crtc_state)
2337 {
2338 	const struct amdgpu_framebuffer *amdgpu_fb =
2339 		to_amdgpu_framebuffer(plane_state->fb);
2340 	const struct drm_crtc *crtc = plane_state->crtc;
2341 	int ret = 0;
2342 
2343 	if (!fill_rects_from_plane_state(plane_state, dc_plane_state))
2344 		return -EINVAL;
2345 
2346 	ret = fill_plane_attributes_from_fb(
2347 		crtc->dev->dev_private,
2348 		dc_plane_state,
2349 		amdgpu_fb);
2350 
2351 	if (ret)
2352 		return ret;
2353 
2354 	/*
2355 	 * Always set input transfer function, since plane state is refreshed
2356 	 * every time.
2357 	 */
2358 	ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2359 	if (ret) {
2360 		dc_transfer_func_release(dc_plane_state->in_transfer_func);
2361 		dc_plane_state->in_transfer_func = NULL;
2362 	}
2363 
2364 	return ret;
2365 }
2366 
2367 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2368 					   const struct dm_connector_state *dm_state,
2369 					   struct dc_stream_state *stream)
2370 {
2371 	enum amdgpu_rmx_type rmx_type;
2372 
2373 	struct rect src = { 0 }; /* viewport in composition space*/
2374 	struct rect dst = { 0 }; /* stream addressable area */
2375 
2376 	/* no mode. nothing to be done */
2377 	if (!mode)
2378 		return;
2379 
2380 	/* Full screen scaling by default */
2381 	src.width = mode->hdisplay;
2382 	src.height = mode->vdisplay;
2383 	dst.width = stream->timing.h_addressable;
2384 	dst.height = stream->timing.v_addressable;
2385 
2386 	if (dm_state) {
2387 		rmx_type = dm_state->scaling;
2388 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2389 			if (src.width * dst.height <
2390 					src.height * dst.width) {
2391 				/* height needs less upscaling/more downscaling */
2392 				dst.width = src.width *
2393 						dst.height / src.height;
2394 			} else {
2395 				/* width needs less upscaling/more downscaling */
2396 				dst.height = src.height *
2397 						dst.width / src.width;
2398 			}
2399 		} else if (rmx_type == RMX_CENTER) {
2400 			dst = src;
2401 		}
2402 
2403 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
2404 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
2405 
2406 		if (dm_state->underscan_enable) {
2407 			dst.x += dm_state->underscan_hborder / 2;
2408 			dst.y += dm_state->underscan_vborder / 2;
2409 			dst.width -= dm_state->underscan_hborder;
2410 			dst.height -= dm_state->underscan_vborder;
2411 		}
2412 	}
2413 
2414 	stream->src = src;
2415 	stream->dst = dst;
2416 
2417 	DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2418 			dst.x, dst.y, dst.width, dst.height);
2419 
2420 }
2421 
2422 static enum dc_color_depth
2423 convert_color_depth_from_display_info(const struct drm_connector *connector)
2424 {
2425 	uint32_t bpc = connector->display_info.bpc;
2426 
2427 	switch (bpc) {
2428 	case 0:
2429 		/*
2430 		 * Temporary Work around, DRM doesn't parse color depth for
2431 		 * EDID revision before 1.4
2432 		 * TODO: Fix edid parsing
2433 		 */
2434 		return COLOR_DEPTH_888;
2435 	case 6:
2436 		return COLOR_DEPTH_666;
2437 	case 8:
2438 		return COLOR_DEPTH_888;
2439 	case 10:
2440 		return COLOR_DEPTH_101010;
2441 	case 12:
2442 		return COLOR_DEPTH_121212;
2443 	case 14:
2444 		return COLOR_DEPTH_141414;
2445 	case 16:
2446 		return COLOR_DEPTH_161616;
2447 	default:
2448 		return COLOR_DEPTH_UNDEFINED;
2449 	}
2450 }
2451 
2452 static enum dc_aspect_ratio
2453 get_aspect_ratio(const struct drm_display_mode *mode_in)
2454 {
2455 	/* 1-1 mapping, since both enums follow the HDMI spec. */
2456 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
2457 }
2458 
2459 static enum dc_color_space
2460 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
2461 {
2462 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
2463 
2464 	switch (dc_crtc_timing->pixel_encoding)	{
2465 	case PIXEL_ENCODING_YCBCR422:
2466 	case PIXEL_ENCODING_YCBCR444:
2467 	case PIXEL_ENCODING_YCBCR420:
2468 	{
2469 		/*
2470 		 * 27030khz is the separation point between HDTV and SDTV
2471 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
2472 		 * respectively
2473 		 */
2474 		if (dc_crtc_timing->pix_clk_khz > 27030) {
2475 			if (dc_crtc_timing->flags.Y_ONLY)
2476 				color_space =
2477 					COLOR_SPACE_YCBCR709_LIMITED;
2478 			else
2479 				color_space = COLOR_SPACE_YCBCR709;
2480 		} else {
2481 			if (dc_crtc_timing->flags.Y_ONLY)
2482 				color_space =
2483 					COLOR_SPACE_YCBCR601_LIMITED;
2484 			else
2485 				color_space = COLOR_SPACE_YCBCR601;
2486 		}
2487 
2488 	}
2489 	break;
2490 	case PIXEL_ENCODING_RGB:
2491 		color_space = COLOR_SPACE_SRGB;
2492 		break;
2493 
2494 	default:
2495 		WARN_ON(1);
2496 		break;
2497 	}
2498 
2499 	return color_space;
2500 }
2501 
2502 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
2503 {
2504 	if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2505 		return;
2506 
2507 	timing_out->display_color_depth--;
2508 }
2509 
2510 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
2511 						const struct drm_display_info *info)
2512 {
2513 	int normalized_clk;
2514 	if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2515 		return;
2516 	do {
2517 		normalized_clk = timing_out->pix_clk_khz;
2518 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
2519 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
2520 			normalized_clk /= 2;
2521 		/* Adjusting pix clock following on HDMI spec based on colour depth */
2522 		switch (timing_out->display_color_depth) {
2523 		case COLOR_DEPTH_101010:
2524 			normalized_clk = (normalized_clk * 30) / 24;
2525 			break;
2526 		case COLOR_DEPTH_121212:
2527 			normalized_clk = (normalized_clk * 36) / 24;
2528 			break;
2529 		case COLOR_DEPTH_161616:
2530 			normalized_clk = (normalized_clk * 48) / 24;
2531 			break;
2532 		default:
2533 			return;
2534 		}
2535 		if (normalized_clk <= info->max_tmds_clock)
2536 			return;
2537 		reduce_mode_colour_depth(timing_out);
2538 
2539 	} while (timing_out->display_color_depth > COLOR_DEPTH_888);
2540 
2541 }
2542 
2543 static void
2544 fill_stream_properties_from_drm_display_mode(struct dc_stream_state *stream,
2545 					     const struct drm_display_mode *mode_in,
2546 					     const struct drm_connector *connector)
2547 {
2548 	struct dc_crtc_timing *timing_out = &stream->timing;
2549 	const struct drm_display_info *info = &connector->display_info;
2550 
2551 	memset(timing_out, 0, sizeof(struct dc_crtc_timing));
2552 
2553 	timing_out->h_border_left = 0;
2554 	timing_out->h_border_right = 0;
2555 	timing_out->v_border_top = 0;
2556 	timing_out->v_border_bottom = 0;
2557 	/* TODO: un-hardcode */
2558 	if (drm_mode_is_420_only(info, mode_in)
2559 			&& stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2560 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
2561 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
2562 			&& stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2563 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
2564 	else
2565 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
2566 
2567 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
2568 	timing_out->display_color_depth = convert_color_depth_from_display_info(
2569 			connector);
2570 	timing_out->scan_type = SCANNING_TYPE_NODATA;
2571 	timing_out->hdmi_vic = 0;
2572 	timing_out->vic = drm_match_cea_mode(mode_in);
2573 
2574 	timing_out->h_addressable = mode_in->crtc_hdisplay;
2575 	timing_out->h_total = mode_in->crtc_htotal;
2576 	timing_out->h_sync_width =
2577 		mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
2578 	timing_out->h_front_porch =
2579 		mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
2580 	timing_out->v_total = mode_in->crtc_vtotal;
2581 	timing_out->v_addressable = mode_in->crtc_vdisplay;
2582 	timing_out->v_front_porch =
2583 		mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
2584 	timing_out->v_sync_width =
2585 		mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
2586 	timing_out->pix_clk_khz = mode_in->crtc_clock;
2587 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
2588 	if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
2589 		timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
2590 	if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
2591 		timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
2592 
2593 	stream->output_color_space = get_output_color_space(timing_out);
2594 
2595 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
2596 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
2597 	if (stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2598 		adjust_colour_depth_from_display_info(timing_out, info);
2599 }
2600 
2601 static void fill_audio_info(struct audio_info *audio_info,
2602 			    const struct drm_connector *drm_connector,
2603 			    const struct dc_sink *dc_sink)
2604 {
2605 	int i = 0;
2606 	int cea_revision = 0;
2607 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
2608 
2609 	audio_info->manufacture_id = edid_caps->manufacturer_id;
2610 	audio_info->product_id = edid_caps->product_id;
2611 
2612 	cea_revision = drm_connector->display_info.cea_rev;
2613 
2614 	strncpy(audio_info->display_name,
2615 		edid_caps->display_name,
2616 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS - 1);
2617 
2618 	if (cea_revision >= 3) {
2619 		audio_info->mode_count = edid_caps->audio_mode_count;
2620 
2621 		for (i = 0; i < audio_info->mode_count; ++i) {
2622 			audio_info->modes[i].format_code =
2623 					(enum audio_format_code)
2624 					(edid_caps->audio_modes[i].format_code);
2625 			audio_info->modes[i].channel_count =
2626 					edid_caps->audio_modes[i].channel_count;
2627 			audio_info->modes[i].sample_rates.all =
2628 					edid_caps->audio_modes[i].sample_rate;
2629 			audio_info->modes[i].sample_size =
2630 					edid_caps->audio_modes[i].sample_size;
2631 		}
2632 	}
2633 
2634 	audio_info->flags.all = edid_caps->speaker_flags;
2635 
2636 	/* TODO: We only check for the progressive mode, check for interlace mode too */
2637 	if (drm_connector->latency_present[0]) {
2638 		audio_info->video_latency = drm_connector->video_latency[0];
2639 		audio_info->audio_latency = drm_connector->audio_latency[0];
2640 	}
2641 
2642 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
2643 
2644 }
2645 
2646 static void
2647 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
2648 				      struct drm_display_mode *dst_mode)
2649 {
2650 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
2651 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
2652 	dst_mode->crtc_clock = src_mode->crtc_clock;
2653 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
2654 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
2655 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
2656 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
2657 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
2658 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
2659 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
2660 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
2661 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
2662 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
2663 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
2664 }
2665 
2666 static void
2667 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
2668 					const struct drm_display_mode *native_mode,
2669 					bool scale_enabled)
2670 {
2671 	if (scale_enabled) {
2672 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2673 	} else if (native_mode->clock == drm_mode->clock &&
2674 			native_mode->htotal == drm_mode->htotal &&
2675 			native_mode->vtotal == drm_mode->vtotal) {
2676 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2677 	} else {
2678 		/* no scaling nor amdgpu inserted, no need to patch */
2679 	}
2680 }
2681 
2682 static struct dc_sink *
2683 create_fake_sink(struct amdgpu_dm_connector *aconnector)
2684 {
2685 	struct dc_sink_init_data sink_init_data = { 0 };
2686 	struct dc_sink *sink = NULL;
2687 	sink_init_data.link = aconnector->dc_link;
2688 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
2689 
2690 	sink = dc_sink_create(&sink_init_data);
2691 	if (!sink) {
2692 		DRM_ERROR("Failed to create sink!\n");
2693 		return NULL;
2694 	}
2695 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
2696 
2697 	return sink;
2698 }
2699 
2700 static void set_multisync_trigger_params(
2701 		struct dc_stream_state *stream)
2702 {
2703 	if (stream->triggered_crtc_reset.enabled) {
2704 		stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
2705 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
2706 	}
2707 }
2708 
2709 static void set_master_stream(struct dc_stream_state *stream_set[],
2710 			      int stream_count)
2711 {
2712 	int j, highest_rfr = 0, master_stream = 0;
2713 
2714 	for (j = 0;  j < stream_count; j++) {
2715 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
2716 			int refresh_rate = 0;
2717 
2718 			refresh_rate = (stream_set[j]->timing.pix_clk_khz*1000)/
2719 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
2720 			if (refresh_rate > highest_rfr) {
2721 				highest_rfr = refresh_rate;
2722 				master_stream = j;
2723 			}
2724 		}
2725 	}
2726 	for (j = 0;  j < stream_count; j++) {
2727 		if (stream_set[j])
2728 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
2729 	}
2730 }
2731 
2732 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
2733 {
2734 	int i = 0;
2735 
2736 	if (context->stream_count < 2)
2737 		return;
2738 	for (i = 0; i < context->stream_count ; i++) {
2739 		if (!context->streams[i])
2740 			continue;
2741 		/*
2742 		 * TODO: add a function to read AMD VSDB bits and set
2743 		 * crtc_sync_master.multi_sync_enabled flag
2744 		 * For now it's set to false
2745 		 */
2746 		set_multisync_trigger_params(context->streams[i]);
2747 	}
2748 	set_master_stream(context->streams, context->stream_count);
2749 }
2750 
2751 static struct dc_stream_state *
2752 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
2753 		       const struct drm_display_mode *drm_mode,
2754 		       const struct dm_connector_state *dm_state)
2755 {
2756 	struct drm_display_mode *preferred_mode = NULL;
2757 	struct drm_connector *drm_connector;
2758 	struct dc_stream_state *stream = NULL;
2759 	struct drm_display_mode mode = *drm_mode;
2760 	bool native_mode_found = false;
2761 	struct dc_sink *sink = NULL;
2762 	if (aconnector == NULL) {
2763 		DRM_ERROR("aconnector is NULL!\n");
2764 		return stream;
2765 	}
2766 
2767 	drm_connector = &aconnector->base;
2768 
2769 	if (!aconnector->dc_sink) {
2770 		if (!aconnector->mst_port) {
2771 			sink = create_fake_sink(aconnector);
2772 			if (!sink)
2773 				return stream;
2774 		}
2775 	} else {
2776 		sink = aconnector->dc_sink;
2777 	}
2778 
2779 	stream = dc_create_stream_for_sink(sink);
2780 
2781 	if (stream == NULL) {
2782 		DRM_ERROR("Failed to create stream for sink!\n");
2783 		goto finish;
2784 	}
2785 
2786 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
2787 		/* Search for preferred mode */
2788 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
2789 			native_mode_found = true;
2790 			break;
2791 		}
2792 	}
2793 	if (!native_mode_found)
2794 		preferred_mode = list_first_entry_or_null(
2795 				&aconnector->base.modes,
2796 				struct drm_display_mode,
2797 				head);
2798 
2799 	if (preferred_mode == NULL) {
2800 		/*
2801 		 * This may not be an error, the use case is when we have no
2802 		 * usermode calls to reset and set mode upon hotplug. In this
2803 		 * case, we call set mode ourselves to restore the previous mode
2804 		 * and the modelist may not be filled in in time.
2805 		 */
2806 		DRM_DEBUG_DRIVER("No preferred mode found\n");
2807 	} else {
2808 		decide_crtc_timing_for_drm_display_mode(
2809 				&mode, preferred_mode,
2810 				dm_state ? (dm_state->scaling != RMX_OFF) : false);
2811 	}
2812 
2813 	if (!dm_state)
2814 		drm_mode_set_crtcinfo(&mode, 0);
2815 
2816 	fill_stream_properties_from_drm_display_mode(stream,
2817 			&mode, &aconnector->base);
2818 	update_stream_scaling_settings(&mode, dm_state, stream);
2819 
2820 	fill_audio_info(
2821 		&stream->audio_info,
2822 		drm_connector,
2823 		sink);
2824 
2825 	update_stream_signal(stream);
2826 
2827 	if (dm_state && dm_state->freesync_capable)
2828 		stream->ignore_msa_timing_param = true;
2829 finish:
2830 	if (sink && sink->sink_signal == SIGNAL_TYPE_VIRTUAL && aconnector->base.force != DRM_FORCE_ON)
2831 		dc_sink_release(sink);
2832 
2833 	return stream;
2834 }
2835 
2836 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
2837 {
2838 	drm_crtc_cleanup(crtc);
2839 	kfree(crtc);
2840 }
2841 
2842 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
2843 				  struct drm_crtc_state *state)
2844 {
2845 	struct dm_crtc_state *cur = to_dm_crtc_state(state);
2846 
2847 	/* TODO Destroy dc_stream objects are stream object is flattened */
2848 	if (cur->stream)
2849 		dc_stream_release(cur->stream);
2850 
2851 
2852 	__drm_atomic_helper_crtc_destroy_state(state);
2853 
2854 
2855 	kfree(state);
2856 }
2857 
2858 static void dm_crtc_reset_state(struct drm_crtc *crtc)
2859 {
2860 	struct dm_crtc_state *state;
2861 
2862 	if (crtc->state)
2863 		dm_crtc_destroy_state(crtc, crtc->state);
2864 
2865 	state = kzalloc(sizeof(*state), GFP_KERNEL);
2866 	if (WARN_ON(!state))
2867 		return;
2868 
2869 	crtc->state = &state->base;
2870 	crtc->state->crtc = crtc;
2871 
2872 }
2873 
2874 static struct drm_crtc_state *
2875 dm_crtc_duplicate_state(struct drm_crtc *crtc)
2876 {
2877 	struct dm_crtc_state *state, *cur;
2878 
2879 	cur = to_dm_crtc_state(crtc->state);
2880 
2881 	if (WARN_ON(!crtc->state))
2882 		return NULL;
2883 
2884 	state = kzalloc(sizeof(*state), GFP_KERNEL);
2885 	if (!state)
2886 		return NULL;
2887 
2888 	__drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
2889 
2890 	if (cur->stream) {
2891 		state->stream = cur->stream;
2892 		dc_stream_retain(state->stream);
2893 	}
2894 
2895 	state->adjust = cur->adjust;
2896 	state->vrr_infopacket = cur->vrr_infopacket;
2897 	state->freesync_enabled = cur->freesync_enabled;
2898 
2899 	/* TODO Duplicate dc_stream after objects are stream object is flattened */
2900 
2901 	return &state->base;
2902 }
2903 
2904 
2905 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
2906 {
2907 	enum dc_irq_source irq_source;
2908 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
2909 	struct amdgpu_device *adev = crtc->dev->dev_private;
2910 
2911 	irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
2912 	return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2913 }
2914 
2915 static int dm_enable_vblank(struct drm_crtc *crtc)
2916 {
2917 	return dm_set_vblank(crtc, true);
2918 }
2919 
2920 static void dm_disable_vblank(struct drm_crtc *crtc)
2921 {
2922 	dm_set_vblank(crtc, false);
2923 }
2924 
2925 /* Implemented only the options currently availible for the driver */
2926 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
2927 	.reset = dm_crtc_reset_state,
2928 	.destroy = amdgpu_dm_crtc_destroy,
2929 	.gamma_set = drm_atomic_helper_legacy_gamma_set,
2930 	.set_config = drm_atomic_helper_set_config,
2931 	.page_flip = drm_atomic_helper_page_flip,
2932 	.atomic_duplicate_state = dm_crtc_duplicate_state,
2933 	.atomic_destroy_state = dm_crtc_destroy_state,
2934 	.set_crc_source = amdgpu_dm_crtc_set_crc_source,
2935 	.verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
2936 	.enable_vblank = dm_enable_vblank,
2937 	.disable_vblank = dm_disable_vblank,
2938 };
2939 
2940 static enum drm_connector_status
2941 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
2942 {
2943 	bool connected;
2944 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2945 
2946 	/*
2947 	 * Notes:
2948 	 * 1. This interface is NOT called in context of HPD irq.
2949 	 * 2. This interface *is called* in context of user-mode ioctl. Which
2950 	 * makes it a bad place for *any* MST-related activity.
2951 	 */
2952 
2953 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
2954 	    !aconnector->fake_enable)
2955 		connected = (aconnector->dc_sink != NULL);
2956 	else
2957 		connected = (aconnector->base.force == DRM_FORCE_ON);
2958 
2959 	return (connected ? connector_status_connected :
2960 			connector_status_disconnected);
2961 }
2962 
2963 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
2964 					    struct drm_connector_state *connector_state,
2965 					    struct drm_property *property,
2966 					    uint64_t val)
2967 {
2968 	struct drm_device *dev = connector->dev;
2969 	struct amdgpu_device *adev = dev->dev_private;
2970 	struct dm_connector_state *dm_old_state =
2971 		to_dm_connector_state(connector->state);
2972 	struct dm_connector_state *dm_new_state =
2973 		to_dm_connector_state(connector_state);
2974 
2975 	int ret = -EINVAL;
2976 
2977 	if (property == dev->mode_config.scaling_mode_property) {
2978 		enum amdgpu_rmx_type rmx_type;
2979 
2980 		switch (val) {
2981 		case DRM_MODE_SCALE_CENTER:
2982 			rmx_type = RMX_CENTER;
2983 			break;
2984 		case DRM_MODE_SCALE_ASPECT:
2985 			rmx_type = RMX_ASPECT;
2986 			break;
2987 		case DRM_MODE_SCALE_FULLSCREEN:
2988 			rmx_type = RMX_FULL;
2989 			break;
2990 		case DRM_MODE_SCALE_NONE:
2991 		default:
2992 			rmx_type = RMX_OFF;
2993 			break;
2994 		}
2995 
2996 		if (dm_old_state->scaling == rmx_type)
2997 			return 0;
2998 
2999 		dm_new_state->scaling = rmx_type;
3000 		ret = 0;
3001 	} else if (property == adev->mode_info.underscan_hborder_property) {
3002 		dm_new_state->underscan_hborder = val;
3003 		ret = 0;
3004 	} else if (property == adev->mode_info.underscan_vborder_property) {
3005 		dm_new_state->underscan_vborder = val;
3006 		ret = 0;
3007 	} else if (property == adev->mode_info.underscan_property) {
3008 		dm_new_state->underscan_enable = val;
3009 		ret = 0;
3010 	}
3011 
3012 	return ret;
3013 }
3014 
3015 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3016 					    const struct drm_connector_state *state,
3017 					    struct drm_property *property,
3018 					    uint64_t *val)
3019 {
3020 	struct drm_device *dev = connector->dev;
3021 	struct amdgpu_device *adev = dev->dev_private;
3022 	struct dm_connector_state *dm_state =
3023 		to_dm_connector_state(state);
3024 	int ret = -EINVAL;
3025 
3026 	if (property == dev->mode_config.scaling_mode_property) {
3027 		switch (dm_state->scaling) {
3028 		case RMX_CENTER:
3029 			*val = DRM_MODE_SCALE_CENTER;
3030 			break;
3031 		case RMX_ASPECT:
3032 			*val = DRM_MODE_SCALE_ASPECT;
3033 			break;
3034 		case RMX_FULL:
3035 			*val = DRM_MODE_SCALE_FULLSCREEN;
3036 			break;
3037 		case RMX_OFF:
3038 		default:
3039 			*val = DRM_MODE_SCALE_NONE;
3040 			break;
3041 		}
3042 		ret = 0;
3043 	} else if (property == adev->mode_info.underscan_hborder_property) {
3044 		*val = dm_state->underscan_hborder;
3045 		ret = 0;
3046 	} else if (property == adev->mode_info.underscan_vborder_property) {
3047 		*val = dm_state->underscan_vborder;
3048 		ret = 0;
3049 	} else if (property == adev->mode_info.underscan_property) {
3050 		*val = dm_state->underscan_enable;
3051 		ret = 0;
3052 	}
3053 	return ret;
3054 }
3055 
3056 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
3057 {
3058 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3059 	const struct dc_link *link = aconnector->dc_link;
3060 	struct amdgpu_device *adev = connector->dev->dev_private;
3061 	struct amdgpu_display_manager *dm = &adev->dm;
3062 
3063 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3064 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3065 
3066 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
3067 	    link->type != dc_connection_none &&
3068 	    dm->backlight_dev) {
3069 		backlight_device_unregister(dm->backlight_dev);
3070 		dm->backlight_dev = NULL;
3071 	}
3072 #endif
3073 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
3074 	drm_connector_unregister(connector);
3075 	drm_connector_cleanup(connector);
3076 	kfree(connector);
3077 }
3078 
3079 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
3080 {
3081 	struct dm_connector_state *state =
3082 		to_dm_connector_state(connector->state);
3083 
3084 	if (connector->state)
3085 		__drm_atomic_helper_connector_destroy_state(connector->state);
3086 
3087 	kfree(state);
3088 
3089 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3090 
3091 	if (state) {
3092 		state->scaling = RMX_OFF;
3093 		state->underscan_enable = false;
3094 		state->underscan_hborder = 0;
3095 		state->underscan_vborder = 0;
3096 
3097 		__drm_atomic_helper_connector_reset(connector, &state->base);
3098 	}
3099 }
3100 
3101 struct drm_connector_state *
3102 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
3103 {
3104 	struct dm_connector_state *state =
3105 		to_dm_connector_state(connector->state);
3106 
3107 	struct dm_connector_state *new_state =
3108 			kmemdup(state, sizeof(*state), GFP_KERNEL);
3109 
3110 	if (!new_state)
3111 		return NULL;
3112 
3113 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
3114 
3115 	new_state->freesync_capable = state->freesync_capable;
3116 	new_state->freesync_enable = state->freesync_enable;
3117 
3118 	return &new_state->base;
3119 }
3120 
3121 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
3122 	.reset = amdgpu_dm_connector_funcs_reset,
3123 	.detect = amdgpu_dm_connector_detect,
3124 	.fill_modes = drm_helper_probe_single_connector_modes,
3125 	.destroy = amdgpu_dm_connector_destroy,
3126 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
3127 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
3128 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
3129 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property
3130 };
3131 
3132 static int get_modes(struct drm_connector *connector)
3133 {
3134 	return amdgpu_dm_connector_get_modes(connector);
3135 }
3136 
3137 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
3138 {
3139 	struct dc_sink_init_data init_params = {
3140 			.link = aconnector->dc_link,
3141 			.sink_signal = SIGNAL_TYPE_VIRTUAL
3142 	};
3143 	struct edid *edid;
3144 
3145 	if (!aconnector->base.edid_blob_ptr) {
3146 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
3147 				aconnector->base.name);
3148 
3149 		aconnector->base.force = DRM_FORCE_OFF;
3150 		aconnector->base.override_edid = false;
3151 		return;
3152 	}
3153 
3154 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
3155 
3156 	aconnector->edid = edid;
3157 
3158 	aconnector->dc_em_sink = dc_link_add_remote_sink(
3159 		aconnector->dc_link,
3160 		(uint8_t *)edid,
3161 		(edid->extensions + 1) * EDID_LENGTH,
3162 		&init_params);
3163 
3164 	if (aconnector->base.force == DRM_FORCE_ON)
3165 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
3166 		aconnector->dc_link->local_sink :
3167 		aconnector->dc_em_sink;
3168 }
3169 
3170 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
3171 {
3172 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
3173 
3174 	/*
3175 	 * In case of headless boot with force on for DP managed connector
3176 	 * Those settings have to be != 0 to get initial modeset
3177 	 */
3178 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
3179 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
3180 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
3181 	}
3182 
3183 
3184 	aconnector->base.override_edid = true;
3185 	create_eml_sink(aconnector);
3186 }
3187 
3188 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
3189 				   struct drm_display_mode *mode)
3190 {
3191 	int result = MODE_ERROR;
3192 	struct dc_sink *dc_sink;
3193 	struct amdgpu_device *adev = connector->dev->dev_private;
3194 	/* TODO: Unhardcode stream count */
3195 	struct dc_stream_state *stream;
3196 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3197 	enum dc_status dc_result = DC_OK;
3198 
3199 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
3200 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
3201 		return result;
3202 
3203 	/*
3204 	 * Only run this the first time mode_valid is called to initilialize
3205 	 * EDID mgmt
3206 	 */
3207 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
3208 		!aconnector->dc_em_sink)
3209 		handle_edid_mgmt(aconnector);
3210 
3211 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
3212 
3213 	if (dc_sink == NULL) {
3214 		DRM_ERROR("dc_sink is NULL!\n");
3215 		goto fail;
3216 	}
3217 
3218 	stream = create_stream_for_sink(aconnector, mode, NULL);
3219 	if (stream == NULL) {
3220 		DRM_ERROR("Failed to create stream for sink!\n");
3221 		goto fail;
3222 	}
3223 
3224 	dc_result = dc_validate_stream(adev->dm.dc, stream);
3225 
3226 	if (dc_result == DC_OK)
3227 		result = MODE_OK;
3228 	else
3229 		DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
3230 			      mode->vdisplay,
3231 			      mode->hdisplay,
3232 			      mode->clock,
3233 			      dc_result);
3234 
3235 	dc_stream_release(stream);
3236 
3237 fail:
3238 	/* TODO: error handling*/
3239 	return result;
3240 }
3241 
3242 static const struct drm_connector_helper_funcs
3243 amdgpu_dm_connector_helper_funcs = {
3244 	/*
3245 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
3246 	 * modes will be filtered by drm_mode_validate_size(), and those modes
3247 	 * are missing after user start lightdm. So we need to renew modes list.
3248 	 * in get_modes call back, not just return the modes count
3249 	 */
3250 	.get_modes = get_modes,
3251 	.mode_valid = amdgpu_dm_connector_mode_valid,
3252 };
3253 
3254 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
3255 {
3256 }
3257 
3258 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
3259 				       struct drm_crtc_state *state)
3260 {
3261 	struct amdgpu_device *adev = crtc->dev->dev_private;
3262 	struct dc *dc = adev->dm.dc;
3263 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
3264 	int ret = -EINVAL;
3265 
3266 	if (unlikely(!dm_crtc_state->stream &&
3267 		     modeset_required(state, NULL, dm_crtc_state->stream))) {
3268 		WARN_ON(1);
3269 		return ret;
3270 	}
3271 
3272 	/* In some use cases, like reset, no stream is attached */
3273 	if (!dm_crtc_state->stream)
3274 		return 0;
3275 
3276 	if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
3277 		return 0;
3278 
3279 	return ret;
3280 }
3281 
3282 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
3283 				      const struct drm_display_mode *mode,
3284 				      struct drm_display_mode *adjusted_mode)
3285 {
3286 	return true;
3287 }
3288 
3289 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
3290 	.disable = dm_crtc_helper_disable,
3291 	.atomic_check = dm_crtc_helper_atomic_check,
3292 	.mode_fixup = dm_crtc_helper_mode_fixup
3293 };
3294 
3295 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
3296 {
3297 
3298 }
3299 
3300 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
3301 					  struct drm_crtc_state *crtc_state,
3302 					  struct drm_connector_state *conn_state)
3303 {
3304 	return 0;
3305 }
3306 
3307 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
3308 	.disable = dm_encoder_helper_disable,
3309 	.atomic_check = dm_encoder_helper_atomic_check
3310 };
3311 
3312 static void dm_drm_plane_reset(struct drm_plane *plane)
3313 {
3314 	struct dm_plane_state *amdgpu_state = NULL;
3315 
3316 	if (plane->state)
3317 		plane->funcs->atomic_destroy_state(plane, plane->state);
3318 
3319 	amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
3320 	WARN_ON(amdgpu_state == NULL);
3321 
3322 	if (amdgpu_state) {
3323 		plane->state = &amdgpu_state->base;
3324 		plane->state->plane = plane;
3325 		plane->state->rotation = DRM_MODE_ROTATE_0;
3326 	}
3327 }
3328 
3329 static struct drm_plane_state *
3330 dm_drm_plane_duplicate_state(struct drm_plane *plane)
3331 {
3332 	struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
3333 
3334 	old_dm_plane_state = to_dm_plane_state(plane->state);
3335 	dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
3336 	if (!dm_plane_state)
3337 		return NULL;
3338 
3339 	__drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
3340 
3341 	if (old_dm_plane_state->dc_state) {
3342 		dm_plane_state->dc_state = old_dm_plane_state->dc_state;
3343 		dc_plane_state_retain(dm_plane_state->dc_state);
3344 	}
3345 
3346 	return &dm_plane_state->base;
3347 }
3348 
3349 void dm_drm_plane_destroy_state(struct drm_plane *plane,
3350 				struct drm_plane_state *state)
3351 {
3352 	struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3353 
3354 	if (dm_plane_state->dc_state)
3355 		dc_plane_state_release(dm_plane_state->dc_state);
3356 
3357 	drm_atomic_helper_plane_destroy_state(plane, state);
3358 }
3359 
3360 static const struct drm_plane_funcs dm_plane_funcs = {
3361 	.update_plane	= drm_atomic_helper_update_plane,
3362 	.disable_plane	= drm_atomic_helper_disable_plane,
3363 	.destroy	= drm_primary_helper_destroy,
3364 	.reset = dm_drm_plane_reset,
3365 	.atomic_duplicate_state = dm_drm_plane_duplicate_state,
3366 	.atomic_destroy_state = dm_drm_plane_destroy_state,
3367 };
3368 
3369 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
3370 				      struct drm_plane_state *new_state)
3371 {
3372 	struct amdgpu_framebuffer *afb;
3373 	struct drm_gem_object *obj;
3374 	struct amdgpu_device *adev;
3375 	struct amdgpu_bo *rbo;
3376 	uint64_t chroma_addr = 0;
3377 	struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
3378 	unsigned int awidth;
3379 	uint32_t domain;
3380 	int r;
3381 
3382 	dm_plane_state_old = to_dm_plane_state(plane->state);
3383 	dm_plane_state_new = to_dm_plane_state(new_state);
3384 
3385 	if (!new_state->fb) {
3386 		DRM_DEBUG_DRIVER("No FB bound\n");
3387 		return 0;
3388 	}
3389 
3390 	afb = to_amdgpu_framebuffer(new_state->fb);
3391 	obj = new_state->fb->obj[0];
3392 	rbo = gem_to_amdgpu_bo(obj);
3393 	adev = amdgpu_ttm_adev(rbo->tbo.bdev);
3394 	r = amdgpu_bo_reserve(rbo, false);
3395 	if (unlikely(r != 0))
3396 		return r;
3397 
3398 	if (plane->type != DRM_PLANE_TYPE_CURSOR)
3399 		domain = amdgpu_display_supported_domains(adev);
3400 	else
3401 		domain = AMDGPU_GEM_DOMAIN_VRAM;
3402 
3403 	r = amdgpu_bo_pin(rbo, domain);
3404 	if (unlikely(r != 0)) {
3405 		if (r != -ERESTARTSYS)
3406 			DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
3407 		amdgpu_bo_unreserve(rbo);
3408 		return r;
3409 	}
3410 
3411 	r = amdgpu_ttm_alloc_gart(&rbo->tbo);
3412 	if (unlikely(r != 0)) {
3413 		amdgpu_bo_unpin(rbo);
3414 		amdgpu_bo_unreserve(rbo);
3415 		DRM_ERROR("%p bind failed\n", rbo);
3416 		return r;
3417 	}
3418 	amdgpu_bo_unreserve(rbo);
3419 
3420 	afb->address = amdgpu_bo_gpu_offset(rbo);
3421 
3422 	amdgpu_bo_ref(rbo);
3423 
3424 	if (dm_plane_state_new->dc_state &&
3425 			dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
3426 		struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
3427 
3428 		if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
3429 			plane_state->address.grph.addr.low_part = lower_32_bits(afb->address);
3430 			plane_state->address.grph.addr.high_part = upper_32_bits(afb->address);
3431 		} else {
3432 			awidth = ALIGN(new_state->fb->width, 64);
3433 			plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
3434 			plane_state->address.video_progressive.luma_addr.low_part
3435 							= lower_32_bits(afb->address);
3436 			plane_state->address.video_progressive.luma_addr.high_part
3437 							= upper_32_bits(afb->address);
3438 			chroma_addr = afb->address + (u64)awidth * new_state->fb->height;
3439 			plane_state->address.video_progressive.chroma_addr.low_part
3440 							= lower_32_bits(chroma_addr);
3441 			plane_state->address.video_progressive.chroma_addr.high_part
3442 							= upper_32_bits(chroma_addr);
3443 		}
3444 	}
3445 
3446 	return 0;
3447 }
3448 
3449 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
3450 				       struct drm_plane_state *old_state)
3451 {
3452 	struct amdgpu_bo *rbo;
3453 	int r;
3454 
3455 	if (!old_state->fb)
3456 		return;
3457 
3458 	rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
3459 	r = amdgpu_bo_reserve(rbo, false);
3460 	if (unlikely(r)) {
3461 		DRM_ERROR("failed to reserve rbo before unpin\n");
3462 		return;
3463 	}
3464 
3465 	amdgpu_bo_unpin(rbo);
3466 	amdgpu_bo_unreserve(rbo);
3467 	amdgpu_bo_unref(&rbo);
3468 }
3469 
3470 static int dm_plane_atomic_check(struct drm_plane *plane,
3471 				 struct drm_plane_state *state)
3472 {
3473 	struct amdgpu_device *adev = plane->dev->dev_private;
3474 	struct dc *dc = adev->dm.dc;
3475 	struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3476 
3477 	if (!dm_plane_state->dc_state)
3478 		return 0;
3479 
3480 	if (!fill_rects_from_plane_state(state, dm_plane_state->dc_state))
3481 		return -EINVAL;
3482 
3483 	if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
3484 		return 0;
3485 
3486 	return -EINVAL;
3487 }
3488 
3489 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
3490 	.prepare_fb = dm_plane_helper_prepare_fb,
3491 	.cleanup_fb = dm_plane_helper_cleanup_fb,
3492 	.atomic_check = dm_plane_atomic_check,
3493 };
3494 
3495 /*
3496  * TODO: these are currently initialized to rgb formats only.
3497  * For future use cases we should either initialize them dynamically based on
3498  * plane capabilities, or initialize this array to all formats, so internal drm
3499  * check will succeed, and let DC implement proper check
3500  */
3501 static const uint32_t rgb_formats[] = {
3502 	DRM_FORMAT_RGB888,
3503 	DRM_FORMAT_XRGB8888,
3504 	DRM_FORMAT_ARGB8888,
3505 	DRM_FORMAT_RGBA8888,
3506 	DRM_FORMAT_XRGB2101010,
3507 	DRM_FORMAT_XBGR2101010,
3508 	DRM_FORMAT_ARGB2101010,
3509 	DRM_FORMAT_ABGR2101010,
3510 	DRM_FORMAT_XBGR8888,
3511 	DRM_FORMAT_ABGR8888,
3512 };
3513 
3514 static const uint32_t yuv_formats[] = {
3515 	DRM_FORMAT_NV12,
3516 	DRM_FORMAT_NV21,
3517 };
3518 
3519 static const u32 cursor_formats[] = {
3520 	DRM_FORMAT_ARGB8888
3521 };
3522 
3523 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
3524 				struct drm_plane *plane,
3525 				unsigned long possible_crtcs)
3526 {
3527 	int res = -EPERM;
3528 
3529 	switch (plane->type) {
3530 	case DRM_PLANE_TYPE_PRIMARY:
3531 		res = drm_universal_plane_init(
3532 				dm->adev->ddev,
3533 				plane,
3534 				possible_crtcs,
3535 				&dm_plane_funcs,
3536 				rgb_formats,
3537 				ARRAY_SIZE(rgb_formats),
3538 				NULL, plane->type, NULL);
3539 		break;
3540 	case DRM_PLANE_TYPE_OVERLAY:
3541 		res = drm_universal_plane_init(
3542 				dm->adev->ddev,
3543 				plane,
3544 				possible_crtcs,
3545 				&dm_plane_funcs,
3546 				yuv_formats,
3547 				ARRAY_SIZE(yuv_formats),
3548 				NULL, plane->type, NULL);
3549 		break;
3550 	case DRM_PLANE_TYPE_CURSOR:
3551 		res = drm_universal_plane_init(
3552 				dm->adev->ddev,
3553 				plane,
3554 				possible_crtcs,
3555 				&dm_plane_funcs,
3556 				cursor_formats,
3557 				ARRAY_SIZE(cursor_formats),
3558 				NULL, plane->type, NULL);
3559 		break;
3560 	}
3561 
3562 	drm_plane_helper_add(plane, &dm_plane_helper_funcs);
3563 
3564 	/* Create (reset) the plane state */
3565 	if (plane->funcs->reset)
3566 		plane->funcs->reset(plane);
3567 
3568 
3569 	return res;
3570 }
3571 
3572 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
3573 			       struct drm_plane *plane,
3574 			       uint32_t crtc_index)
3575 {
3576 	struct amdgpu_crtc *acrtc = NULL;
3577 	struct drm_plane *cursor_plane;
3578 
3579 	int res = -ENOMEM;
3580 
3581 	cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
3582 	if (!cursor_plane)
3583 		goto fail;
3584 
3585 	cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
3586 	res = amdgpu_dm_plane_init(dm, cursor_plane, 0);
3587 
3588 	acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
3589 	if (!acrtc)
3590 		goto fail;
3591 
3592 	res = drm_crtc_init_with_planes(
3593 			dm->ddev,
3594 			&acrtc->base,
3595 			plane,
3596 			cursor_plane,
3597 			&amdgpu_dm_crtc_funcs, NULL);
3598 
3599 	if (res)
3600 		goto fail;
3601 
3602 	drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
3603 
3604 	/* Create (reset) the plane state */
3605 	if (acrtc->base.funcs->reset)
3606 		acrtc->base.funcs->reset(&acrtc->base);
3607 
3608 	acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
3609 	acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
3610 
3611 	acrtc->crtc_id = crtc_index;
3612 	acrtc->base.enabled = false;
3613 	acrtc->otg_inst = -1;
3614 
3615 	dm->adev->mode_info.crtcs[crtc_index] = acrtc;
3616 	drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
3617 				   true, MAX_COLOR_LUT_ENTRIES);
3618 	drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
3619 
3620 	return 0;
3621 
3622 fail:
3623 	kfree(acrtc);
3624 	kfree(cursor_plane);
3625 	return res;
3626 }
3627 
3628 
3629 static int to_drm_connector_type(enum signal_type st)
3630 {
3631 	switch (st) {
3632 	case SIGNAL_TYPE_HDMI_TYPE_A:
3633 		return DRM_MODE_CONNECTOR_HDMIA;
3634 	case SIGNAL_TYPE_EDP:
3635 		return DRM_MODE_CONNECTOR_eDP;
3636 	case SIGNAL_TYPE_LVDS:
3637 		return DRM_MODE_CONNECTOR_LVDS;
3638 	case SIGNAL_TYPE_RGB:
3639 		return DRM_MODE_CONNECTOR_VGA;
3640 	case SIGNAL_TYPE_DISPLAY_PORT:
3641 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
3642 		return DRM_MODE_CONNECTOR_DisplayPort;
3643 	case SIGNAL_TYPE_DVI_DUAL_LINK:
3644 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
3645 		return DRM_MODE_CONNECTOR_DVID;
3646 	case SIGNAL_TYPE_VIRTUAL:
3647 		return DRM_MODE_CONNECTOR_VIRTUAL;
3648 
3649 	default:
3650 		return DRM_MODE_CONNECTOR_Unknown;
3651 	}
3652 }
3653 
3654 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
3655 {
3656 	return drm_encoder_find(connector->dev, NULL, connector->encoder_ids[0]);
3657 }
3658 
3659 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
3660 {
3661 	struct drm_encoder *encoder;
3662 	struct amdgpu_encoder *amdgpu_encoder;
3663 
3664 	encoder = amdgpu_dm_connector_to_encoder(connector);
3665 
3666 	if (encoder == NULL)
3667 		return;
3668 
3669 	amdgpu_encoder = to_amdgpu_encoder(encoder);
3670 
3671 	amdgpu_encoder->native_mode.clock = 0;
3672 
3673 	if (!list_empty(&connector->probed_modes)) {
3674 		struct drm_display_mode *preferred_mode = NULL;
3675 
3676 		list_for_each_entry(preferred_mode,
3677 				    &connector->probed_modes,
3678 				    head) {
3679 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
3680 				amdgpu_encoder->native_mode = *preferred_mode;
3681 
3682 			break;
3683 		}
3684 
3685 	}
3686 }
3687 
3688 static struct drm_display_mode *
3689 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
3690 			     char *name,
3691 			     int hdisplay, int vdisplay)
3692 {
3693 	struct drm_device *dev = encoder->dev;
3694 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3695 	struct drm_display_mode *mode = NULL;
3696 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3697 
3698 	mode = drm_mode_duplicate(dev, native_mode);
3699 
3700 	if (mode == NULL)
3701 		return NULL;
3702 
3703 	mode->hdisplay = hdisplay;
3704 	mode->vdisplay = vdisplay;
3705 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
3706 	strncpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
3707 
3708 	return mode;
3709 
3710 }
3711 
3712 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
3713 						 struct drm_connector *connector)
3714 {
3715 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3716 	struct drm_display_mode *mode = NULL;
3717 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3718 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3719 				to_amdgpu_dm_connector(connector);
3720 	int i;
3721 	int n;
3722 	struct mode_size {
3723 		char name[DRM_DISPLAY_MODE_LEN];
3724 		int w;
3725 		int h;
3726 	} common_modes[] = {
3727 		{  "640x480",  640,  480},
3728 		{  "800x600",  800,  600},
3729 		{ "1024x768", 1024,  768},
3730 		{ "1280x720", 1280,  720},
3731 		{ "1280x800", 1280,  800},
3732 		{"1280x1024", 1280, 1024},
3733 		{ "1440x900", 1440,  900},
3734 		{"1680x1050", 1680, 1050},
3735 		{"1600x1200", 1600, 1200},
3736 		{"1920x1080", 1920, 1080},
3737 		{"1920x1200", 1920, 1200}
3738 	};
3739 
3740 	n = ARRAY_SIZE(common_modes);
3741 
3742 	for (i = 0; i < n; i++) {
3743 		struct drm_display_mode *curmode = NULL;
3744 		bool mode_existed = false;
3745 
3746 		if (common_modes[i].w > native_mode->hdisplay ||
3747 		    common_modes[i].h > native_mode->vdisplay ||
3748 		   (common_modes[i].w == native_mode->hdisplay &&
3749 		    common_modes[i].h == native_mode->vdisplay))
3750 			continue;
3751 
3752 		list_for_each_entry(curmode, &connector->probed_modes, head) {
3753 			if (common_modes[i].w == curmode->hdisplay &&
3754 			    common_modes[i].h == curmode->vdisplay) {
3755 				mode_existed = true;
3756 				break;
3757 			}
3758 		}
3759 
3760 		if (mode_existed)
3761 			continue;
3762 
3763 		mode = amdgpu_dm_create_common_mode(encoder,
3764 				common_modes[i].name, common_modes[i].w,
3765 				common_modes[i].h);
3766 		drm_mode_probed_add(connector, mode);
3767 		amdgpu_dm_connector->num_modes++;
3768 	}
3769 }
3770 
3771 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
3772 					      struct edid *edid)
3773 {
3774 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3775 			to_amdgpu_dm_connector(connector);
3776 
3777 	if (edid) {
3778 		/* empty probed_modes */
3779 		INIT_LIST_HEAD(&connector->probed_modes);
3780 		amdgpu_dm_connector->num_modes =
3781 				drm_add_edid_modes(connector, edid);
3782 
3783 		amdgpu_dm_get_native_mode(connector);
3784 	} else {
3785 		amdgpu_dm_connector->num_modes = 0;
3786 	}
3787 }
3788 
3789 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
3790 {
3791 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3792 			to_amdgpu_dm_connector(connector);
3793 	struct drm_encoder *encoder;
3794 	struct edid *edid = amdgpu_dm_connector->edid;
3795 
3796 	encoder = amdgpu_dm_connector_to_encoder(connector);
3797 
3798 	if (!edid || !drm_edid_is_valid(edid)) {
3799 		amdgpu_dm_connector->num_modes =
3800 				drm_add_modes_noedid(connector, 640, 480);
3801 	} else {
3802 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
3803 		amdgpu_dm_connector_add_common_modes(encoder, connector);
3804 	}
3805 	amdgpu_dm_fbc_init(connector);
3806 
3807 	return amdgpu_dm_connector->num_modes;
3808 }
3809 
3810 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
3811 				     struct amdgpu_dm_connector *aconnector,
3812 				     int connector_type,
3813 				     struct dc_link *link,
3814 				     int link_index)
3815 {
3816 	struct amdgpu_device *adev = dm->ddev->dev_private;
3817 
3818 	aconnector->connector_id = link_index;
3819 	aconnector->dc_link = link;
3820 	aconnector->base.interlace_allowed = false;
3821 	aconnector->base.doublescan_allowed = false;
3822 	aconnector->base.stereo_allowed = false;
3823 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
3824 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
3825 	mutex_init(&aconnector->hpd_lock);
3826 
3827 	/*
3828 	 * configure support HPD hot plug connector_>polled default value is 0
3829 	 * which means HPD hot plug not supported
3830 	 */
3831 	switch (connector_type) {
3832 	case DRM_MODE_CONNECTOR_HDMIA:
3833 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3834 		aconnector->base.ycbcr_420_allowed =
3835 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
3836 		break;
3837 	case DRM_MODE_CONNECTOR_DisplayPort:
3838 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3839 		aconnector->base.ycbcr_420_allowed =
3840 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
3841 		break;
3842 	case DRM_MODE_CONNECTOR_DVID:
3843 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3844 		break;
3845 	default:
3846 		break;
3847 	}
3848 
3849 	drm_object_attach_property(&aconnector->base.base,
3850 				dm->ddev->mode_config.scaling_mode_property,
3851 				DRM_MODE_SCALE_NONE);
3852 
3853 	drm_object_attach_property(&aconnector->base.base,
3854 				adev->mode_info.underscan_property,
3855 				UNDERSCAN_OFF);
3856 	drm_object_attach_property(&aconnector->base.base,
3857 				adev->mode_info.underscan_hborder_property,
3858 				0);
3859 	drm_object_attach_property(&aconnector->base.base,
3860 				adev->mode_info.underscan_vborder_property,
3861 				0);
3862 
3863 }
3864 
3865 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
3866 			      struct i2c_msg *msgs, int num)
3867 {
3868 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
3869 	struct ddc_service *ddc_service = i2c->ddc_service;
3870 	struct i2c_command cmd;
3871 	int i;
3872 	int result = -EIO;
3873 
3874 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
3875 
3876 	if (!cmd.payloads)
3877 		return result;
3878 
3879 	cmd.number_of_payloads = num;
3880 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
3881 	cmd.speed = 100;
3882 
3883 	for (i = 0; i < num; i++) {
3884 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
3885 		cmd.payloads[i].address = msgs[i].addr;
3886 		cmd.payloads[i].length = msgs[i].len;
3887 		cmd.payloads[i].data = msgs[i].buf;
3888 	}
3889 
3890 	if (dc_submit_i2c(
3891 			ddc_service->ctx->dc,
3892 			ddc_service->ddc_pin->hw_info.ddc_channel,
3893 			&cmd))
3894 		result = num;
3895 
3896 	kfree(cmd.payloads);
3897 	return result;
3898 }
3899 
3900 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
3901 {
3902 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
3903 }
3904 
3905 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
3906 	.master_xfer = amdgpu_dm_i2c_xfer,
3907 	.functionality = amdgpu_dm_i2c_func,
3908 };
3909 
3910 static struct amdgpu_i2c_adapter *
3911 create_i2c(struct ddc_service *ddc_service,
3912 	   int link_index,
3913 	   int *res)
3914 {
3915 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
3916 	struct amdgpu_i2c_adapter *i2c;
3917 
3918 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
3919 	if (!i2c)
3920 		return NULL;
3921 	i2c->base.owner = THIS_MODULE;
3922 	i2c->base.class = I2C_CLASS_DDC;
3923 	i2c->base.dev.parent = &adev->pdev->dev;
3924 	i2c->base.algo = &amdgpu_dm_i2c_algo;
3925 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
3926 	i2c_set_adapdata(&i2c->base, i2c);
3927 	i2c->ddc_service = ddc_service;
3928 	i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
3929 
3930 	return i2c;
3931 }
3932 
3933 
3934 /*
3935  * Note: this function assumes that dc_link_detect() was called for the
3936  * dc_link which will be represented by this aconnector.
3937  */
3938 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
3939 				    struct amdgpu_dm_connector *aconnector,
3940 				    uint32_t link_index,
3941 				    struct amdgpu_encoder *aencoder)
3942 {
3943 	int res = 0;
3944 	int connector_type;
3945 	struct dc *dc = dm->dc;
3946 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
3947 	struct amdgpu_i2c_adapter *i2c;
3948 
3949 	link->priv = aconnector;
3950 
3951 	DRM_DEBUG_DRIVER("%s()\n", __func__);
3952 
3953 	i2c = create_i2c(link->ddc, link->link_index, &res);
3954 	if (!i2c) {
3955 		DRM_ERROR("Failed to create i2c adapter data\n");
3956 		return -ENOMEM;
3957 	}
3958 
3959 	aconnector->i2c = i2c;
3960 	res = i2c_add_adapter(&i2c->base);
3961 
3962 	if (res) {
3963 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
3964 		goto out_free;
3965 	}
3966 
3967 	connector_type = to_drm_connector_type(link->connector_signal);
3968 
3969 	res = drm_connector_init(
3970 			dm->ddev,
3971 			&aconnector->base,
3972 			&amdgpu_dm_connector_funcs,
3973 			connector_type);
3974 
3975 	if (res) {
3976 		DRM_ERROR("connector_init failed\n");
3977 		aconnector->connector_id = -1;
3978 		goto out_free;
3979 	}
3980 
3981 	drm_connector_helper_add(
3982 			&aconnector->base,
3983 			&amdgpu_dm_connector_helper_funcs);
3984 
3985 	if (aconnector->base.funcs->reset)
3986 		aconnector->base.funcs->reset(&aconnector->base);
3987 
3988 	amdgpu_dm_connector_init_helper(
3989 		dm,
3990 		aconnector,
3991 		connector_type,
3992 		link,
3993 		link_index);
3994 
3995 	drm_connector_attach_encoder(
3996 		&aconnector->base, &aencoder->base);
3997 
3998 	drm_connector_register(&aconnector->base);
3999 #if defined(CONFIG_DEBUG_FS)
4000 	res = connector_debugfs_init(aconnector);
4001 	if (res) {
4002 		DRM_ERROR("Failed to create debugfs for connector");
4003 		goto out_free;
4004 	}
4005 #endif
4006 
4007 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
4008 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
4009 		amdgpu_dm_initialize_dp_connector(dm, aconnector);
4010 
4011 out_free:
4012 	if (res) {
4013 		kfree(i2c);
4014 		aconnector->i2c = NULL;
4015 	}
4016 	return res;
4017 }
4018 
4019 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
4020 {
4021 	switch (adev->mode_info.num_crtc) {
4022 	case 1:
4023 		return 0x1;
4024 	case 2:
4025 		return 0x3;
4026 	case 3:
4027 		return 0x7;
4028 	case 4:
4029 		return 0xf;
4030 	case 5:
4031 		return 0x1f;
4032 	case 6:
4033 	default:
4034 		return 0x3f;
4035 	}
4036 }
4037 
4038 static int amdgpu_dm_encoder_init(struct drm_device *dev,
4039 				  struct amdgpu_encoder *aencoder,
4040 				  uint32_t link_index)
4041 {
4042 	struct amdgpu_device *adev = dev->dev_private;
4043 
4044 	int res = drm_encoder_init(dev,
4045 				   &aencoder->base,
4046 				   &amdgpu_dm_encoder_funcs,
4047 				   DRM_MODE_ENCODER_TMDS,
4048 				   NULL);
4049 
4050 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
4051 
4052 	if (!res)
4053 		aencoder->encoder_id = link_index;
4054 	else
4055 		aencoder->encoder_id = -1;
4056 
4057 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
4058 
4059 	return res;
4060 }
4061 
4062 static void manage_dm_interrupts(struct amdgpu_device *adev,
4063 				 struct amdgpu_crtc *acrtc,
4064 				 bool enable)
4065 {
4066 	/*
4067 	 * this is not correct translation but will work as soon as VBLANK
4068 	 * constant is the same as PFLIP
4069 	 */
4070 	int irq_type =
4071 		amdgpu_display_crtc_idx_to_irq_type(
4072 			adev,
4073 			acrtc->crtc_id);
4074 
4075 	if (enable) {
4076 		drm_crtc_vblank_on(&acrtc->base);
4077 		amdgpu_irq_get(
4078 			adev,
4079 			&adev->pageflip_irq,
4080 			irq_type);
4081 	} else {
4082 
4083 		amdgpu_irq_put(
4084 			adev,
4085 			&adev->pageflip_irq,
4086 			irq_type);
4087 		drm_crtc_vblank_off(&acrtc->base);
4088 	}
4089 }
4090 
4091 static bool
4092 is_scaling_state_different(const struct dm_connector_state *dm_state,
4093 			   const struct dm_connector_state *old_dm_state)
4094 {
4095 	if (dm_state->scaling != old_dm_state->scaling)
4096 		return true;
4097 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
4098 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
4099 			return true;
4100 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
4101 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
4102 			return true;
4103 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
4104 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
4105 		return true;
4106 	return false;
4107 }
4108 
4109 static void remove_stream(struct amdgpu_device *adev,
4110 			  struct amdgpu_crtc *acrtc,
4111 			  struct dc_stream_state *stream)
4112 {
4113 	/* this is the update mode case */
4114 
4115 	acrtc->otg_inst = -1;
4116 	acrtc->enabled = false;
4117 }
4118 
4119 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
4120 			       struct dc_cursor_position *position)
4121 {
4122 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
4123 	int x, y;
4124 	int xorigin = 0, yorigin = 0;
4125 
4126 	if (!crtc || !plane->state->fb) {
4127 		position->enable = false;
4128 		position->x = 0;
4129 		position->y = 0;
4130 		return 0;
4131 	}
4132 
4133 	if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
4134 	    (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
4135 		DRM_ERROR("%s: bad cursor width or height %d x %d\n",
4136 			  __func__,
4137 			  plane->state->crtc_w,
4138 			  plane->state->crtc_h);
4139 		return -EINVAL;
4140 	}
4141 
4142 	x = plane->state->crtc_x;
4143 	y = plane->state->crtc_y;
4144 	/* avivo cursor are offset into the total surface */
4145 	x += crtc->primary->state->src_x >> 16;
4146 	y += crtc->primary->state->src_y >> 16;
4147 	if (x < 0) {
4148 		xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
4149 		x = 0;
4150 	}
4151 	if (y < 0) {
4152 		yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
4153 		y = 0;
4154 	}
4155 	position->enable = true;
4156 	position->x = x;
4157 	position->y = y;
4158 	position->x_hotspot = xorigin;
4159 	position->y_hotspot = yorigin;
4160 
4161 	return 0;
4162 }
4163 
4164 static void handle_cursor_update(struct drm_plane *plane,
4165 				 struct drm_plane_state *old_plane_state)
4166 {
4167 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
4168 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
4169 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
4170 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
4171 	uint64_t address = afb ? afb->address : 0;
4172 	struct dc_cursor_position position;
4173 	struct dc_cursor_attributes attributes;
4174 	int ret;
4175 
4176 	if (!plane->state->fb && !old_plane_state->fb)
4177 		return;
4178 
4179 	DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
4180 			 __func__,
4181 			 amdgpu_crtc->crtc_id,
4182 			 plane->state->crtc_w,
4183 			 plane->state->crtc_h);
4184 
4185 	ret = get_cursor_position(plane, crtc, &position);
4186 	if (ret)
4187 		return;
4188 
4189 	if (!position.enable) {
4190 		/* turn off cursor */
4191 		if (crtc_state && crtc_state->stream)
4192 			dc_stream_set_cursor_position(crtc_state->stream,
4193 						      &position);
4194 		return;
4195 	}
4196 
4197 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
4198 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
4199 
4200 	attributes.address.high_part = upper_32_bits(address);
4201 	attributes.address.low_part  = lower_32_bits(address);
4202 	attributes.width             = plane->state->crtc_w;
4203 	attributes.height            = plane->state->crtc_h;
4204 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
4205 	attributes.rotation_angle    = 0;
4206 	attributes.attribute_flags.value = 0;
4207 
4208 	attributes.pitch = attributes.width;
4209 
4210 	if (crtc_state->stream) {
4211 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
4212 							 &attributes))
4213 			DRM_ERROR("DC failed to set cursor attributes\n");
4214 
4215 		if (!dc_stream_set_cursor_position(crtc_state->stream,
4216 						   &position))
4217 			DRM_ERROR("DC failed to set cursor position\n");
4218 	}
4219 }
4220 
4221 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
4222 {
4223 
4224 	assert_spin_locked(&acrtc->base.dev->event_lock);
4225 	WARN_ON(acrtc->event);
4226 
4227 	acrtc->event = acrtc->base.state->event;
4228 
4229 	/* Set the flip status */
4230 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
4231 
4232 	/* Mark this event as consumed */
4233 	acrtc->base.state->event = NULL;
4234 
4235 	DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
4236 						 acrtc->crtc_id);
4237 }
4238 
4239 /*
4240  * Executes flip
4241  *
4242  * Waits on all BO's fences and for proper vblank count
4243  */
4244 static void amdgpu_dm_do_flip(struct drm_crtc *crtc,
4245 			      struct drm_framebuffer *fb,
4246 			      uint32_t target,
4247 			      struct dc_state *state)
4248 {
4249 	unsigned long flags;
4250 	uint32_t target_vblank;
4251 	int r, vpos, hpos;
4252 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4253 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
4254 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
4255 	struct amdgpu_device *adev = crtc->dev->dev_private;
4256 	bool async_flip = (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
4257 	struct dc_flip_addrs addr = { {0} };
4258 	/* TODO eliminate or rename surface_update */
4259 	struct dc_surface_update surface_updates[1] = { {0} };
4260 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
4261 	struct dc_stream_status *stream_status;
4262 
4263 
4264 	/* Prepare wait for target vblank early - before the fence-waits */
4265 	target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
4266 			amdgpu_get_vblank_counter_kms(crtc->dev, acrtc->crtc_id);
4267 
4268 	/*
4269 	 * TODO This might fail and hence better not used, wait
4270 	 * explicitly on fences instead
4271 	 * and in general should be called for
4272 	 * blocking commit to as per framework helpers
4273 	 */
4274 	r = amdgpu_bo_reserve(abo, true);
4275 	if (unlikely(r != 0)) {
4276 		DRM_ERROR("failed to reserve buffer before flip\n");
4277 		WARN_ON(1);
4278 	}
4279 
4280 	/* Wait for all fences on this FB */
4281 	WARN_ON(reservation_object_wait_timeout_rcu(abo->tbo.resv, true, false,
4282 								    MAX_SCHEDULE_TIMEOUT) < 0);
4283 
4284 	amdgpu_bo_unreserve(abo);
4285 
4286 	/*
4287 	 * Wait until we're out of the vertical blank period before the one
4288 	 * targeted by the flip
4289 	 */
4290 	while ((acrtc->enabled &&
4291 		(amdgpu_display_get_crtc_scanoutpos(adev->ddev, acrtc->crtc_id,
4292 						    0, &vpos, &hpos, NULL,
4293 						    NULL, &crtc->hwmode)
4294 		 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
4295 		(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
4296 		(int)(target_vblank -
4297 		  amdgpu_get_vblank_counter_kms(adev->ddev, acrtc->crtc_id)) > 0)) {
4298 		usleep_range(1000, 1100);
4299 	}
4300 
4301 	/* Flip */
4302 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
4303 
4304 	WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
4305 	WARN_ON(!acrtc_state->stream);
4306 
4307 	addr.address.grph.addr.low_part = lower_32_bits(afb->address);
4308 	addr.address.grph.addr.high_part = upper_32_bits(afb->address);
4309 	addr.flip_immediate = async_flip;
4310 
4311 
4312 	if (acrtc->base.state->event)
4313 		prepare_flip_isr(acrtc);
4314 
4315 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4316 
4317 	stream_status = dc_stream_get_status(acrtc_state->stream);
4318 	if (!stream_status) {
4319 		DRM_ERROR("No stream status for CRTC: id=%d\n",
4320 			acrtc->crtc_id);
4321 		return;
4322 	}
4323 
4324 	surface_updates->surface = stream_status->plane_states[0];
4325 	if (!surface_updates->surface) {
4326 		DRM_ERROR("No surface for CRTC: id=%d\n",
4327 			acrtc->crtc_id);
4328 		return;
4329 	}
4330 	surface_updates->flip_addr = &addr;
4331 
4332 	dc_commit_updates_for_stream(adev->dm.dc,
4333 					     surface_updates,
4334 					     1,
4335 					     acrtc_state->stream,
4336 					     NULL,
4337 					     &surface_updates->surface,
4338 					     state);
4339 
4340 	DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x \n",
4341 			 __func__,
4342 			 addr.address.grph.addr.high_part,
4343 			 addr.address.grph.addr.low_part);
4344 }
4345 
4346 /*
4347  * TODO this whole function needs to go
4348  *
4349  * dc_surface_update is needlessly complex. See if we can just replace this
4350  * with a dc_plane_state and follow the atomic model a bit more closely here.
4351  */
4352 static bool commit_planes_to_stream(
4353 		struct dc *dc,
4354 		struct dc_plane_state **plane_states,
4355 		uint8_t new_plane_count,
4356 		struct dm_crtc_state *dm_new_crtc_state,
4357 		struct dm_crtc_state *dm_old_crtc_state,
4358 		struct dc_state *state)
4359 {
4360 	/* no need to dynamically allocate this. it's pretty small */
4361 	struct dc_surface_update updates[MAX_SURFACES];
4362 	struct dc_flip_addrs *flip_addr;
4363 	struct dc_plane_info *plane_info;
4364 	struct dc_scaling_info *scaling_info;
4365 	int i;
4366 	struct dc_stream_state *dc_stream = dm_new_crtc_state->stream;
4367 	struct dc_stream_update *stream_update =
4368 			kzalloc(sizeof(struct dc_stream_update), GFP_KERNEL);
4369 
4370 	if (!stream_update) {
4371 		BREAK_TO_DEBUGGER();
4372 		return false;
4373 	}
4374 
4375 	flip_addr = kcalloc(MAX_SURFACES, sizeof(struct dc_flip_addrs),
4376 			    GFP_KERNEL);
4377 	plane_info = kcalloc(MAX_SURFACES, sizeof(struct dc_plane_info),
4378 			     GFP_KERNEL);
4379 	scaling_info = kcalloc(MAX_SURFACES, sizeof(struct dc_scaling_info),
4380 			       GFP_KERNEL);
4381 
4382 	if (!flip_addr || !plane_info || !scaling_info) {
4383 		kfree(flip_addr);
4384 		kfree(plane_info);
4385 		kfree(scaling_info);
4386 		kfree(stream_update);
4387 		return false;
4388 	}
4389 
4390 	memset(updates, 0, sizeof(updates));
4391 
4392 	stream_update->src = dc_stream->src;
4393 	stream_update->dst = dc_stream->dst;
4394 	stream_update->out_transfer_func = dc_stream->out_transfer_func;
4395 
4396 	if (dm_new_crtc_state->freesync_enabled != dm_old_crtc_state->freesync_enabled) {
4397 		stream_update->vrr_infopacket = &dc_stream->vrr_infopacket;
4398 		stream_update->adjust = &dc_stream->adjust;
4399 	}
4400 
4401 	for (i = 0; i < new_plane_count; i++) {
4402 		updates[i].surface = plane_states[i];
4403 		updates[i].gamma =
4404 			(struct dc_gamma *)plane_states[i]->gamma_correction;
4405 		updates[i].in_transfer_func = plane_states[i]->in_transfer_func;
4406 		flip_addr[i].address = plane_states[i]->address;
4407 		flip_addr[i].flip_immediate = plane_states[i]->flip_immediate;
4408 		plane_info[i].color_space = plane_states[i]->color_space;
4409 		plane_info[i].format = plane_states[i]->format;
4410 		plane_info[i].plane_size = plane_states[i]->plane_size;
4411 		plane_info[i].rotation = plane_states[i]->rotation;
4412 		plane_info[i].horizontal_mirror = plane_states[i]->horizontal_mirror;
4413 		plane_info[i].stereo_format = plane_states[i]->stereo_format;
4414 		plane_info[i].tiling_info = plane_states[i]->tiling_info;
4415 		plane_info[i].visible = plane_states[i]->visible;
4416 		plane_info[i].per_pixel_alpha = plane_states[i]->per_pixel_alpha;
4417 		plane_info[i].dcc = plane_states[i]->dcc;
4418 		scaling_info[i].scaling_quality = plane_states[i]->scaling_quality;
4419 		scaling_info[i].src_rect = plane_states[i]->src_rect;
4420 		scaling_info[i].dst_rect = plane_states[i]->dst_rect;
4421 		scaling_info[i].clip_rect = plane_states[i]->clip_rect;
4422 
4423 		updates[i].flip_addr = &flip_addr[i];
4424 		updates[i].plane_info = &plane_info[i];
4425 		updates[i].scaling_info = &scaling_info[i];
4426 	}
4427 
4428 	dc_commit_updates_for_stream(
4429 			dc,
4430 			updates,
4431 			new_plane_count,
4432 			dc_stream, stream_update, plane_states, state);
4433 
4434 	kfree(flip_addr);
4435 	kfree(plane_info);
4436 	kfree(scaling_info);
4437 	kfree(stream_update);
4438 	return true;
4439 }
4440 
4441 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
4442 				    struct drm_device *dev,
4443 				    struct amdgpu_display_manager *dm,
4444 				    struct drm_crtc *pcrtc,
4445 				    bool *wait_for_vblank)
4446 {
4447 	uint32_t i;
4448 	struct drm_plane *plane;
4449 	struct drm_plane_state *old_plane_state, *new_plane_state;
4450 	struct dc_stream_state *dc_stream_attach;
4451 	struct dc_plane_state *plane_states_constructed[MAX_SURFACES];
4452 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
4453 	struct drm_crtc_state *new_pcrtc_state =
4454 			drm_atomic_get_new_crtc_state(state, pcrtc);
4455 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
4456 	struct dm_crtc_state *dm_old_crtc_state =
4457 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
4458 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4459 	int planes_count = 0;
4460 	unsigned long flags;
4461 
4462 	/* update planes when needed */
4463 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
4464 		struct drm_crtc *crtc = new_plane_state->crtc;
4465 		struct drm_crtc_state *new_crtc_state;
4466 		struct drm_framebuffer *fb = new_plane_state->fb;
4467 		bool pflip_needed;
4468 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
4469 
4470 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
4471 			handle_cursor_update(plane, old_plane_state);
4472 			continue;
4473 		}
4474 
4475 		if (!fb || !crtc || pcrtc != crtc)
4476 			continue;
4477 
4478 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
4479 		if (!new_crtc_state->active)
4480 			continue;
4481 
4482 		pflip_needed = !state->allow_modeset;
4483 
4484 		spin_lock_irqsave(&crtc->dev->event_lock, flags);
4485 		if (acrtc_attach->pflip_status != AMDGPU_FLIP_NONE) {
4486 			DRM_ERROR("%s: acrtc %d, already busy\n",
4487 				  __func__,
4488 				  acrtc_attach->crtc_id);
4489 			/* In commit tail framework this cannot happen */
4490 			WARN_ON(1);
4491 		}
4492 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4493 
4494 		if (!pflip_needed || plane->type == DRM_PLANE_TYPE_OVERLAY) {
4495 			WARN_ON(!dm_new_plane_state->dc_state);
4496 
4497 			plane_states_constructed[planes_count] = dm_new_plane_state->dc_state;
4498 
4499 			dc_stream_attach = acrtc_state->stream;
4500 			planes_count++;
4501 
4502 		} else if (new_crtc_state->planes_changed) {
4503 			/* Assume even ONE crtc with immediate flip means
4504 			 * entire can't wait for VBLANK
4505 			 * TODO Check if it's correct
4506 			 */
4507 			*wait_for_vblank =
4508 					new_pcrtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC ?
4509 				false : true;
4510 
4511 			/* TODO: Needs rework for multiplane flip */
4512 			if (plane->type == DRM_PLANE_TYPE_PRIMARY)
4513 				drm_crtc_vblank_get(crtc);
4514 
4515 			amdgpu_dm_do_flip(
4516 				crtc,
4517 				fb,
4518 				(uint32_t)drm_crtc_vblank_count(crtc) + *wait_for_vblank,
4519 				dm_state->context);
4520 		}
4521 
4522 	}
4523 
4524 	if (planes_count) {
4525 		unsigned long flags;
4526 
4527 		if (new_pcrtc_state->event) {
4528 
4529 			drm_crtc_vblank_get(pcrtc);
4530 
4531 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4532 			prepare_flip_isr(acrtc_attach);
4533 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4534 		}
4535 
4536 		dc_stream_attach->adjust = acrtc_state->adjust;
4537 		dc_stream_attach->vrr_infopacket = acrtc_state->vrr_infopacket;
4538 
4539 		if (false == commit_planes_to_stream(dm->dc,
4540 							plane_states_constructed,
4541 							planes_count,
4542 							acrtc_state,
4543 							dm_old_crtc_state,
4544 							dm_state->context))
4545 			dm_error("%s: Failed to attach plane!\n", __func__);
4546 	} else {
4547 		/*TODO BUG Here should go disable planes on CRTC. */
4548 	}
4549 }
4550 
4551 /*
4552  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4553  * @crtc_state: the DRM CRTC state
4554  * @stream_state: the DC stream state.
4555  *
4556  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4557  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4558  */
4559 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4560 						struct dc_stream_state *stream_state)
4561 {
4562 	stream_state->mode_changed = crtc_state->mode_changed;
4563 }
4564 
4565 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
4566 				   struct drm_atomic_state *state,
4567 				   bool nonblock)
4568 {
4569 	struct drm_crtc *crtc;
4570 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4571 	struct amdgpu_device *adev = dev->dev_private;
4572 	int i;
4573 
4574 	/*
4575 	 * We evade vblanks and pflips on crtc that
4576 	 * should be changed. We do it here to flush & disable
4577 	 * interrupts before drm_swap_state is called in drm_atomic_helper_commit
4578 	 * it will update crtc->dm_crtc_state->stream pointer which is used in
4579 	 * the ISRs.
4580 	 */
4581 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4582 		struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4583 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4584 
4585 		if (drm_atomic_crtc_needs_modeset(new_crtc_state) && dm_old_crtc_state->stream)
4586 			manage_dm_interrupts(adev, acrtc, false);
4587 	}
4588 	/*
4589 	 * Add check here for SoC's that support hardware cursor plane, to
4590 	 * unset legacy_cursor_update
4591 	 */
4592 
4593 	return drm_atomic_helper_commit(dev, state, nonblock);
4594 
4595 	/*TODO Handle EINTR, reenable IRQ*/
4596 }
4597 
4598 /**
4599  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
4600  * @state: The atomic state to commit
4601  *
4602  * This will tell DC to commit the constructed DC state from atomic_check,
4603  * programming the hardware. Any failures here implies a hardware failure, since
4604  * atomic check should have filtered anything non-kosher.
4605  */
4606 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
4607 {
4608 	struct drm_device *dev = state->dev;
4609 	struct amdgpu_device *adev = dev->dev_private;
4610 	struct amdgpu_display_manager *dm = &adev->dm;
4611 	struct dm_atomic_state *dm_state;
4612 	uint32_t i, j;
4613 	struct drm_crtc *crtc;
4614 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4615 	unsigned long flags;
4616 	bool wait_for_vblank = true;
4617 	struct drm_connector *connector;
4618 	struct drm_connector_state *old_con_state, *new_con_state;
4619 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4620 	int crtc_disable_count = 0;
4621 
4622 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
4623 
4624 	dm_state = to_dm_atomic_state(state);
4625 
4626 	/* update changed items */
4627 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4628 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4629 
4630 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4631 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4632 
4633 		DRM_DEBUG_DRIVER(
4634 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4635 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
4636 			"connectors_changed:%d\n",
4637 			acrtc->crtc_id,
4638 			new_crtc_state->enable,
4639 			new_crtc_state->active,
4640 			new_crtc_state->planes_changed,
4641 			new_crtc_state->mode_changed,
4642 			new_crtc_state->active_changed,
4643 			new_crtc_state->connectors_changed);
4644 
4645 		/* Copy all transient state flags into dc state */
4646 		if (dm_new_crtc_state->stream) {
4647 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4648 							    dm_new_crtc_state->stream);
4649 		}
4650 
4651 		/* handles headless hotplug case, updating new_state and
4652 		 * aconnector as needed
4653 		 */
4654 
4655 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4656 
4657 			DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
4658 
4659 			if (!dm_new_crtc_state->stream) {
4660 				/*
4661 				 * this could happen because of issues with
4662 				 * userspace notifications delivery.
4663 				 * In this case userspace tries to set mode on
4664 				 * display which is disconnected in fact.
4665 				 * dc_sink is NULL in this case on aconnector.
4666 				 * We expect reset mode will come soon.
4667 				 *
4668 				 * This can also happen when unplug is done
4669 				 * during resume sequence ended
4670 				 *
4671 				 * In this case, we want to pretend we still
4672 				 * have a sink to keep the pipe running so that
4673 				 * hw state is consistent with the sw state
4674 				 */
4675 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4676 						__func__, acrtc->base.base.id);
4677 				continue;
4678 			}
4679 
4680 			if (dm_old_crtc_state->stream)
4681 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4682 
4683 			pm_runtime_get_noresume(dev->dev);
4684 
4685 			acrtc->enabled = true;
4686 			acrtc->hw_mode = new_crtc_state->mode;
4687 			crtc->hwmode = new_crtc_state->mode;
4688 		} else if (modereset_required(new_crtc_state)) {
4689 			DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
4690 
4691 			/* i.e. reset mode */
4692 			if (dm_old_crtc_state->stream)
4693 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4694 		}
4695 	} /* for_each_crtc_in_state() */
4696 
4697 	if (dm_state->context) {
4698 		dm_enable_per_frame_crtc_master_sync(dm_state->context);
4699 		WARN_ON(!dc_commit_state(dm->dc, dm_state->context));
4700 	}
4701 
4702 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4703 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4704 
4705 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4706 
4707 		if (dm_new_crtc_state->stream != NULL) {
4708 			const struct dc_stream_status *status =
4709 					dc_stream_get_status(dm_new_crtc_state->stream);
4710 
4711 			if (!status)
4712 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
4713 			else
4714 				acrtc->otg_inst = status->primary_otg_inst;
4715 		}
4716 	}
4717 
4718 	/* Handle scaling and underscan changes*/
4719 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4720 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4721 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
4722 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4723 		struct dc_stream_status *status = NULL;
4724 
4725 		if (acrtc) {
4726 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
4727 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4728 		}
4729 
4730 		/* Skip any modesets/resets */
4731 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
4732 			continue;
4733 
4734 		/* Skip anything that is not scaling or underscan changes */
4735 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
4736 			continue;
4737 
4738 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4739 
4740 		update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
4741 				dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
4742 
4743 		if (!dm_new_crtc_state->stream)
4744 			continue;
4745 
4746 		status = dc_stream_get_status(dm_new_crtc_state->stream);
4747 		WARN_ON(!status);
4748 		WARN_ON(!status->plane_count);
4749 
4750 		dm_new_crtc_state->stream->adjust = dm_new_crtc_state->adjust;
4751 		dm_new_crtc_state->stream->vrr_infopacket = dm_new_crtc_state->vrr_infopacket;
4752 
4753 		/*TODO How it works with MPO ?*/
4754 		if (!commit_planes_to_stream(
4755 				dm->dc,
4756 				status->plane_states,
4757 				status->plane_count,
4758 				dm_new_crtc_state,
4759 				to_dm_crtc_state(old_crtc_state),
4760 				dm_state->context))
4761 			dm_error("%s: Failed to update stream scaling!\n", __func__);
4762 	}
4763 
4764 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4765 			new_crtc_state, i) {
4766 		/*
4767 		 * loop to enable interrupts on newly arrived crtc
4768 		 */
4769 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4770 		bool modeset_needed;
4771 
4772 		if (old_crtc_state->active && !new_crtc_state->active)
4773 			crtc_disable_count++;
4774 
4775 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4776 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4777 		modeset_needed = modeset_required(
4778 				new_crtc_state,
4779 				dm_new_crtc_state->stream,
4780 				dm_old_crtc_state->stream);
4781 
4782 		if (dm_new_crtc_state->stream == NULL || !modeset_needed)
4783 			continue;
4784 
4785 		manage_dm_interrupts(adev, acrtc, true);
4786 	}
4787 
4788 	/* update planes when needed per crtc*/
4789 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
4790 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4791 
4792 		if (dm_new_crtc_state->stream)
4793 			amdgpu_dm_commit_planes(state, dev, dm, crtc, &wait_for_vblank);
4794 	}
4795 
4796 
4797 	/*
4798 	 * send vblank event on all events not handled in flip and
4799 	 * mark consumed event for drm_atomic_helper_commit_hw_done
4800 	 */
4801 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
4802 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4803 
4804 		if (new_crtc_state->event)
4805 			drm_send_event_locked(dev, &new_crtc_state->event->base);
4806 
4807 		new_crtc_state->event = NULL;
4808 	}
4809 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
4810 
4811 
4812 	if (wait_for_vblank)
4813 		drm_atomic_helper_wait_for_flip_done(dev, state);
4814 
4815 	/*
4816 	 * FIXME:
4817 	 * Delay hw_done() until flip_done() is signaled. This is to block
4818 	 * another commit from freeing the CRTC state while we're still
4819 	 * waiting on flip_done.
4820 	 */
4821 	drm_atomic_helper_commit_hw_done(state);
4822 
4823 	drm_atomic_helper_cleanup_planes(dev, state);
4824 
4825 	/*
4826 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
4827 	 * so we can put the GPU into runtime suspend if we're not driving any
4828 	 * displays anymore
4829 	 */
4830 	for (i = 0; i < crtc_disable_count; i++)
4831 		pm_runtime_put_autosuspend(dev->dev);
4832 	pm_runtime_mark_last_busy(dev->dev);
4833 }
4834 
4835 
4836 static int dm_force_atomic_commit(struct drm_connector *connector)
4837 {
4838 	int ret = 0;
4839 	struct drm_device *ddev = connector->dev;
4840 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
4841 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4842 	struct drm_plane *plane = disconnected_acrtc->base.primary;
4843 	struct drm_connector_state *conn_state;
4844 	struct drm_crtc_state *crtc_state;
4845 	struct drm_plane_state *plane_state;
4846 
4847 	if (!state)
4848 		return -ENOMEM;
4849 
4850 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
4851 
4852 	/* Construct an atomic state to restore previous display setting */
4853 
4854 	/*
4855 	 * Attach connectors to drm_atomic_state
4856 	 */
4857 	conn_state = drm_atomic_get_connector_state(state, connector);
4858 
4859 	ret = PTR_ERR_OR_ZERO(conn_state);
4860 	if (ret)
4861 		goto err;
4862 
4863 	/* Attach crtc to drm_atomic_state*/
4864 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
4865 
4866 	ret = PTR_ERR_OR_ZERO(crtc_state);
4867 	if (ret)
4868 		goto err;
4869 
4870 	/* force a restore */
4871 	crtc_state->mode_changed = true;
4872 
4873 	/* Attach plane to drm_atomic_state */
4874 	plane_state = drm_atomic_get_plane_state(state, plane);
4875 
4876 	ret = PTR_ERR_OR_ZERO(plane_state);
4877 	if (ret)
4878 		goto err;
4879 
4880 
4881 	/* Call commit internally with the state we just constructed */
4882 	ret = drm_atomic_commit(state);
4883 	if (!ret)
4884 		return 0;
4885 
4886 err:
4887 	DRM_ERROR("Restoring old state failed with %i\n", ret);
4888 	drm_atomic_state_put(state);
4889 
4890 	return ret;
4891 }
4892 
4893 /*
4894  * This function handles all cases when set mode does not come upon hotplug.
4895  * This includes when a display is unplugged then plugged back into the
4896  * same port and when running without usermode desktop manager supprot
4897  */
4898 void dm_restore_drm_connector_state(struct drm_device *dev,
4899 				    struct drm_connector *connector)
4900 {
4901 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4902 	struct amdgpu_crtc *disconnected_acrtc;
4903 	struct dm_crtc_state *acrtc_state;
4904 
4905 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
4906 		return;
4907 
4908 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4909 	if (!disconnected_acrtc)
4910 		return;
4911 
4912 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
4913 	if (!acrtc_state->stream)
4914 		return;
4915 
4916 	/*
4917 	 * If the previous sink is not released and different from the current,
4918 	 * we deduce we are in a state where we can not rely on usermode call
4919 	 * to turn on the display, so we do it here
4920 	 */
4921 	if (acrtc_state->stream->sink != aconnector->dc_sink)
4922 		dm_force_atomic_commit(&aconnector->base);
4923 }
4924 
4925 /*
4926  * Grabs all modesetting locks to serialize against any blocking commits,
4927  * Waits for completion of all non blocking commits.
4928  */
4929 static int do_aquire_global_lock(struct drm_device *dev,
4930 				 struct drm_atomic_state *state)
4931 {
4932 	struct drm_crtc *crtc;
4933 	struct drm_crtc_commit *commit;
4934 	long ret;
4935 
4936 	/*
4937 	 * Adding all modeset locks to aquire_ctx will
4938 	 * ensure that when the framework release it the
4939 	 * extra locks we are locking here will get released to
4940 	 */
4941 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
4942 	if (ret)
4943 		return ret;
4944 
4945 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
4946 		spin_lock(&crtc->commit_lock);
4947 		commit = list_first_entry_or_null(&crtc->commit_list,
4948 				struct drm_crtc_commit, commit_entry);
4949 		if (commit)
4950 			drm_crtc_commit_get(commit);
4951 		spin_unlock(&crtc->commit_lock);
4952 
4953 		if (!commit)
4954 			continue;
4955 
4956 		/*
4957 		 * Make sure all pending HW programming completed and
4958 		 * page flips done
4959 		 */
4960 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
4961 
4962 		if (ret > 0)
4963 			ret = wait_for_completion_interruptible_timeout(
4964 					&commit->flip_done, 10*HZ);
4965 
4966 		if (ret == 0)
4967 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
4968 				  "timed out\n", crtc->base.id, crtc->name);
4969 
4970 		drm_crtc_commit_put(commit);
4971 	}
4972 
4973 	return ret < 0 ? ret : 0;
4974 }
4975 
4976 void set_freesync_on_stream(struct amdgpu_display_manager *dm,
4977 			    struct dm_crtc_state *new_crtc_state,
4978 			    struct dm_connector_state *new_con_state,
4979 			    struct dc_stream_state *new_stream)
4980 {
4981 	struct mod_freesync_config config = {0};
4982 	struct mod_vrr_params vrr = {0};
4983 	struct dc_info_packet vrr_infopacket = {0};
4984 	struct amdgpu_dm_connector *aconnector =
4985 			to_amdgpu_dm_connector(new_con_state->base.connector);
4986 
4987 	if (new_con_state->freesync_capable &&
4988 	    new_con_state->freesync_enable) {
4989 		config.state = new_crtc_state->freesync_enabled ?
4990 				VRR_STATE_ACTIVE_VARIABLE :
4991 				VRR_STATE_INACTIVE;
4992 		config.min_refresh_in_uhz =
4993 				aconnector->min_vfreq * 1000000;
4994 		config.max_refresh_in_uhz =
4995 				aconnector->max_vfreq * 1000000;
4996 		config.vsif_supported = true;
4997 	}
4998 
4999 	mod_freesync_build_vrr_params(dm->freesync_module,
5000 				      new_stream,
5001 				      &config, &vrr);
5002 
5003 	mod_freesync_build_vrr_infopacket(dm->freesync_module,
5004 					  new_stream,
5005 					  &vrr,
5006 					  packet_type_fs1,
5007 					  NULL,
5008 					  &vrr_infopacket);
5009 
5010 	new_crtc_state->adjust = vrr.adjust;
5011 	new_crtc_state->vrr_infopacket = vrr_infopacket;
5012 }
5013 
5014 static int dm_update_crtcs_state(struct amdgpu_display_manager *dm,
5015 				 struct drm_atomic_state *state,
5016 				 bool enable,
5017 				 bool *lock_and_validation_needed)
5018 {
5019 	struct drm_crtc *crtc;
5020 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5021 	int i;
5022 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5023 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5024 	struct dc_stream_state *new_stream;
5025 	int ret = 0;
5026 
5027 	/*
5028 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
5029 	 * update changed items
5030 	 */
5031 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5032 		struct amdgpu_crtc *acrtc = NULL;
5033 		struct amdgpu_dm_connector *aconnector = NULL;
5034 		struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
5035 		struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
5036 		struct drm_plane_state *new_plane_state = NULL;
5037 
5038 		new_stream = NULL;
5039 
5040 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5041 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5042 		acrtc = to_amdgpu_crtc(crtc);
5043 
5044 		new_plane_state = drm_atomic_get_new_plane_state(state, new_crtc_state->crtc->primary);
5045 
5046 		if (new_crtc_state->enable && new_plane_state && !new_plane_state->fb) {
5047 			ret = -EINVAL;
5048 			goto fail;
5049 		}
5050 
5051 		aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
5052 
5053 		/* TODO This hack should go away */
5054 		if (aconnector && enable) {
5055 			/* Make sure fake sink is created in plug-in scenario */
5056 			drm_new_conn_state = drm_atomic_get_new_connector_state(state,
5057  								    &aconnector->base);
5058 			drm_old_conn_state = drm_atomic_get_old_connector_state(state,
5059 								    &aconnector->base);
5060 
5061 			if (IS_ERR(drm_new_conn_state)) {
5062 				ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
5063 				break;
5064 			}
5065 
5066 			dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
5067 			dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
5068 
5069 			new_stream = create_stream_for_sink(aconnector,
5070 							     &new_crtc_state->mode,
5071 							    dm_new_conn_state);
5072 
5073 			/*
5074 			 * we can have no stream on ACTION_SET if a display
5075 			 * was disconnected during S3, in this case it is not an
5076 			 * error, the OS will be updated after detection, and
5077 			 * will do the right thing on next atomic commit
5078 			 */
5079 
5080 			if (!new_stream) {
5081 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
5082 						__func__, acrtc->base.base.id);
5083 				break;
5084 			}
5085 
5086 			set_freesync_on_stream(dm, dm_new_crtc_state,
5087 					       dm_new_conn_state, new_stream);
5088 
5089 			if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5090 			    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
5091 				new_crtc_state->mode_changed = false;
5092 				DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
5093 						 new_crtc_state->mode_changed);
5094 			}
5095 		}
5096 
5097 		if (dm_old_crtc_state->freesync_enabled != dm_new_crtc_state->freesync_enabled)
5098 			new_crtc_state->mode_changed = true;
5099 
5100 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5101 			goto next_crtc;
5102 
5103 		DRM_DEBUG_DRIVER(
5104 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
5105 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
5106 			"connectors_changed:%d\n",
5107 			acrtc->crtc_id,
5108 			new_crtc_state->enable,
5109 			new_crtc_state->active,
5110 			new_crtc_state->planes_changed,
5111 			new_crtc_state->mode_changed,
5112 			new_crtc_state->active_changed,
5113 			new_crtc_state->connectors_changed);
5114 
5115 		/* Remove stream for any changed/disabled CRTC */
5116 		if (!enable) {
5117 
5118 			if (!dm_old_crtc_state->stream)
5119 				goto next_crtc;
5120 
5121 			DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
5122 					crtc->base.id);
5123 
5124 			/* i.e. reset mode */
5125 			if (dc_remove_stream_from_ctx(
5126 					dm->dc,
5127 					dm_state->context,
5128 					dm_old_crtc_state->stream) != DC_OK) {
5129 				ret = -EINVAL;
5130 				goto fail;
5131 			}
5132 
5133 			dc_stream_release(dm_old_crtc_state->stream);
5134 			dm_new_crtc_state->stream = NULL;
5135 
5136 			*lock_and_validation_needed = true;
5137 
5138 		} else {/* Add stream for any updated/enabled CRTC */
5139 			/*
5140 			 * Quick fix to prevent NULL pointer on new_stream when
5141 			 * added MST connectors not found in existing crtc_state in the chained mode
5142 			 * TODO: need to dig out the root cause of that
5143 			 */
5144 			if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
5145 				goto next_crtc;
5146 
5147 			if (modereset_required(new_crtc_state))
5148 				goto next_crtc;
5149 
5150 			if (modeset_required(new_crtc_state, new_stream,
5151 					     dm_old_crtc_state->stream)) {
5152 
5153 				WARN_ON(dm_new_crtc_state->stream);
5154 
5155 				dm_new_crtc_state->stream = new_stream;
5156 
5157 				dc_stream_retain(new_stream);
5158 
5159 				DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
5160 							crtc->base.id);
5161 
5162 				if (dc_add_stream_to_ctx(
5163 						dm->dc,
5164 						dm_state->context,
5165 						dm_new_crtc_state->stream) != DC_OK) {
5166 					ret = -EINVAL;
5167 					goto fail;
5168 				}
5169 
5170 				*lock_and_validation_needed = true;
5171 			}
5172 		}
5173 
5174 next_crtc:
5175 		/* Release extra reference */
5176 		if (new_stream)
5177 			 dc_stream_release(new_stream);
5178 
5179 		/*
5180 		 * We want to do dc stream updates that do not require a
5181 		 * full modeset below.
5182 		 */
5183 		if (!(enable && aconnector && new_crtc_state->enable &&
5184 		      new_crtc_state->active))
5185 			continue;
5186 		/*
5187 		 * Given above conditions, the dc state cannot be NULL because:
5188 		 * 1. We're in the process of enabling CRTCs (just been added
5189 		 *    to the dc context, or already is on the context)
5190 		 * 2. Has a valid connector attached, and
5191 		 * 3. Is currently active and enabled.
5192 		 * => The dc stream state currently exists.
5193 		 */
5194 		BUG_ON(dm_new_crtc_state->stream == NULL);
5195 
5196 		/* Scaling or underscan settings */
5197 		if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
5198 			update_stream_scaling_settings(
5199 				&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
5200 
5201 		/*
5202 		 * Color management settings. We also update color properties
5203 		 * when a modeset is needed, to ensure it gets reprogrammed.
5204 		 */
5205 		if (dm_new_crtc_state->base.color_mgmt_changed ||
5206 		    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
5207 			ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
5208 			if (ret)
5209 				goto fail;
5210 			amdgpu_dm_set_ctm(dm_new_crtc_state);
5211 		}
5212 
5213 
5214 	}
5215 
5216 	return ret;
5217 
5218 fail:
5219 	if (new_stream)
5220 		dc_stream_release(new_stream);
5221 	return ret;
5222 }
5223 
5224 static int dm_update_planes_state(struct dc *dc,
5225 				  struct drm_atomic_state *state,
5226 				  bool enable,
5227 				  bool *lock_and_validation_needed)
5228 {
5229 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
5230 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5231 	struct drm_plane *plane;
5232 	struct drm_plane_state *old_plane_state, *new_plane_state;
5233 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
5234 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5235 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
5236 	int i ;
5237 	/* TODO return page_flip_needed() function */
5238 	bool pflip_needed  = !state->allow_modeset;
5239 	int ret = 0;
5240 
5241 
5242 	/* Add new planes, in reverse order as DC expectation */
5243 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
5244 		new_plane_crtc = new_plane_state->crtc;
5245 		old_plane_crtc = old_plane_state->crtc;
5246 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
5247 		dm_old_plane_state = to_dm_plane_state(old_plane_state);
5248 
5249 		/*TODO Implement atomic check for cursor plane */
5250 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
5251 			continue;
5252 
5253 		/* Remove any changed/removed planes */
5254 		if (!enable) {
5255 			if (pflip_needed &&
5256 			    plane->type != DRM_PLANE_TYPE_OVERLAY)
5257 				continue;
5258 
5259 			if (!old_plane_crtc)
5260 				continue;
5261 
5262 			old_crtc_state = drm_atomic_get_old_crtc_state(
5263 					state, old_plane_crtc);
5264 			dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5265 
5266 			if (!dm_old_crtc_state->stream)
5267 				continue;
5268 
5269 			DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
5270 					plane->base.id, old_plane_crtc->base.id);
5271 
5272 			if (!dc_remove_plane_from_context(
5273 					dc,
5274 					dm_old_crtc_state->stream,
5275 					dm_old_plane_state->dc_state,
5276 					dm_state->context)) {
5277 
5278 				ret = EINVAL;
5279 				return ret;
5280 			}
5281 
5282 
5283 			dc_plane_state_release(dm_old_plane_state->dc_state);
5284 			dm_new_plane_state->dc_state = NULL;
5285 
5286 			*lock_and_validation_needed = true;
5287 
5288 		} else { /* Add new planes */
5289 			struct dc_plane_state *dc_new_plane_state;
5290 
5291 			if (drm_atomic_plane_disabling(plane->state, new_plane_state))
5292 				continue;
5293 
5294 			if (!new_plane_crtc)
5295 				continue;
5296 
5297 			new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
5298 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5299 
5300 			if (!dm_new_crtc_state->stream)
5301 				continue;
5302 
5303 			if (pflip_needed &&
5304 			    plane->type != DRM_PLANE_TYPE_OVERLAY)
5305 				continue;
5306 
5307 			WARN_ON(dm_new_plane_state->dc_state);
5308 
5309 			dc_new_plane_state = dc_create_plane_state(dc);
5310 			if (!dc_new_plane_state)
5311 				return -ENOMEM;
5312 
5313 			DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
5314 					plane->base.id, new_plane_crtc->base.id);
5315 
5316 			ret = fill_plane_attributes(
5317 				new_plane_crtc->dev->dev_private,
5318 				dc_new_plane_state,
5319 				new_plane_state,
5320 				new_crtc_state);
5321 			if (ret) {
5322 				dc_plane_state_release(dc_new_plane_state);
5323 				return ret;
5324 			}
5325 
5326 			/*
5327 			 * Any atomic check errors that occur after this will
5328 			 * not need a release. The plane state will be attached
5329 			 * to the stream, and therefore part of the atomic
5330 			 * state. It'll be released when the atomic state is
5331 			 * cleaned.
5332 			 */
5333 			if (!dc_add_plane_to_context(
5334 					dc,
5335 					dm_new_crtc_state->stream,
5336 					dc_new_plane_state,
5337 					dm_state->context)) {
5338 
5339 				dc_plane_state_release(dc_new_plane_state);
5340 				return -EINVAL;
5341 			}
5342 
5343 			dm_new_plane_state->dc_state = dc_new_plane_state;
5344 
5345 			/* Tell DC to do a full surface update every time there
5346 			 * is a plane change. Inefficient, but works for now.
5347 			 */
5348 			dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
5349 
5350 			*lock_and_validation_needed = true;
5351 		}
5352 	}
5353 
5354 
5355 	return ret;
5356 }
5357 enum surface_update_type dm_determine_update_type_for_commit(struct dc *dc, struct drm_atomic_state *state)
5358 {
5359 
5360 
5361 	int i, j, num_plane;
5362 	struct drm_plane_state *old_plane_state, *new_plane_state;
5363 	struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
5364 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
5365 	struct drm_plane *plane;
5366 
5367 	struct drm_crtc *crtc;
5368 	struct drm_crtc_state *new_crtc_state, *old_crtc_state;
5369 	struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
5370 	struct dc_stream_status *status = NULL;
5371 
5372 	struct dc_surface_update *updates = kzalloc(MAX_SURFACES * sizeof(struct dc_surface_update), GFP_KERNEL);
5373 	struct dc_plane_state *surface = kzalloc(MAX_SURFACES * sizeof(struct dc_plane_state), GFP_KERNEL);
5374 	struct dc_stream_update stream_update;
5375 	enum surface_update_type update_type = UPDATE_TYPE_FAST;
5376 
5377 	if (!updates || !surface) {
5378 		DRM_ERROR("Plane or surface update failed to allocate");
5379 		/* Set type to FULL to avoid crashing in DC*/
5380 		update_type = UPDATE_TYPE_FULL;
5381 		goto ret;
5382 	}
5383 
5384 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5385 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
5386 		old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
5387 		num_plane = 0;
5388 
5389 		if (new_dm_crtc_state->stream) {
5390 
5391 			for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
5392 				new_plane_crtc = new_plane_state->crtc;
5393 				old_plane_crtc = old_plane_state->crtc;
5394 				new_dm_plane_state = to_dm_plane_state(new_plane_state);
5395 				old_dm_plane_state = to_dm_plane_state(old_plane_state);
5396 
5397 				if (plane->type == DRM_PLANE_TYPE_CURSOR)
5398 					continue;
5399 
5400 				if (!state->allow_modeset)
5401 					continue;
5402 
5403 				if (crtc == new_plane_crtc) {
5404 					updates[num_plane].surface = &surface[num_plane];
5405 
5406 					if (new_crtc_state->mode_changed) {
5407 						updates[num_plane].surface->src_rect =
5408 									new_dm_plane_state->dc_state->src_rect;
5409 						updates[num_plane].surface->dst_rect =
5410 									new_dm_plane_state->dc_state->dst_rect;
5411 						updates[num_plane].surface->rotation =
5412 									new_dm_plane_state->dc_state->rotation;
5413 						updates[num_plane].surface->in_transfer_func =
5414 									new_dm_plane_state->dc_state->in_transfer_func;
5415 						stream_update.dst = new_dm_crtc_state->stream->dst;
5416 						stream_update.src = new_dm_crtc_state->stream->src;
5417 					}
5418 
5419 					if (new_crtc_state->color_mgmt_changed) {
5420 						updates[num_plane].gamma =
5421 								new_dm_plane_state->dc_state->gamma_correction;
5422 						updates[num_plane].in_transfer_func =
5423 								new_dm_plane_state->dc_state->in_transfer_func;
5424 						stream_update.gamut_remap =
5425 								&new_dm_crtc_state->stream->gamut_remap_matrix;
5426 						stream_update.out_transfer_func =
5427 								new_dm_crtc_state->stream->out_transfer_func;
5428 					}
5429 
5430 					num_plane++;
5431 				}
5432 			}
5433 
5434 			if (num_plane > 0) {
5435 				status = dc_stream_get_status(new_dm_crtc_state->stream);
5436 				update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
5437 										  &stream_update, status);
5438 
5439 				if (update_type > UPDATE_TYPE_MED) {
5440 					update_type = UPDATE_TYPE_FULL;
5441 					goto ret;
5442 				}
5443 			}
5444 
5445 		} else if (!new_dm_crtc_state->stream && old_dm_crtc_state->stream) {
5446 			update_type = UPDATE_TYPE_FULL;
5447 			goto ret;
5448 		}
5449 	}
5450 
5451 ret:
5452 	kfree(updates);
5453 	kfree(surface);
5454 
5455 	return update_type;
5456 }
5457 
5458 /**
5459  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
5460  * @dev: The DRM device
5461  * @state: The atomic state to commit
5462  *
5463  * Validate that the given atomic state is programmable by DC into hardware.
5464  * This involves constructing a &struct dc_state reflecting the new hardware
5465  * state we wish to commit, then querying DC to see if it is programmable. It's
5466  * important not to modify the existing DC state. Otherwise, atomic_check
5467  * may unexpectedly commit hardware changes.
5468  *
5469  * When validating the DC state, it's important that the right locks are
5470  * acquired. For full updates case which removes/adds/updates streams on one
5471  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
5472  * that any such full update commit will wait for completion of any outstanding
5473  * flip using DRMs synchronization events. See
5474  * dm_determine_update_type_for_commit()
5475  *
5476  * Note that DM adds the affected connectors for all CRTCs in state, when that
5477  * might not seem necessary. This is because DC stream creation requires the
5478  * DC sink, which is tied to the DRM connector state. Cleaning this up should
5479  * be possible but non-trivial - a possible TODO item.
5480  *
5481  * Return: -Error code if validation failed.
5482  */
5483 static int amdgpu_dm_atomic_check(struct drm_device *dev,
5484 				  struct drm_atomic_state *state)
5485 {
5486 	struct amdgpu_device *adev = dev->dev_private;
5487 	struct dc *dc = adev->dm.dc;
5488 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5489 	struct drm_connector *connector;
5490 	struct drm_connector_state *old_con_state, *new_con_state;
5491 	struct drm_crtc *crtc;
5492 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5493 	enum surface_update_type update_type = UPDATE_TYPE_FAST;
5494 	enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
5495 
5496 	int ret, i;
5497 
5498 	/*
5499 	 * This bool will be set for true for any modeset/reset
5500 	 * or plane update which implies non fast surface update.
5501 	 */
5502 	bool lock_and_validation_needed = false;
5503 
5504 	ret = drm_atomic_helper_check_modeset(dev, state);
5505 	if (ret)
5506 		goto fail;
5507 
5508 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5509 		struct dm_crtc_state *dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5510 		struct dm_crtc_state *dm_old_crtc_state  = to_dm_crtc_state(old_crtc_state);
5511 
5512 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
5513 		    !new_crtc_state->color_mgmt_changed &&
5514 		    (dm_old_crtc_state->freesync_enabled == dm_new_crtc_state->freesync_enabled))
5515 			continue;
5516 
5517 		if (!new_crtc_state->enable)
5518 			continue;
5519 
5520 		ret = drm_atomic_add_affected_connectors(state, crtc);
5521 		if (ret)
5522 			return ret;
5523 
5524 		ret = drm_atomic_add_affected_planes(state, crtc);
5525 		if (ret)
5526 			goto fail;
5527 	}
5528 
5529 	dm_state->context = dc_create_state();
5530 	ASSERT(dm_state->context);
5531 	dc_resource_state_copy_construct_current(dc, dm_state->context);
5532 
5533 	/* Remove exiting planes if they are modified */
5534 	ret = dm_update_planes_state(dc, state, false, &lock_and_validation_needed);
5535 	if (ret) {
5536 		goto fail;
5537 	}
5538 
5539 	/* Disable all crtcs which require disable */
5540 	ret = dm_update_crtcs_state(&adev->dm, state, false, &lock_and_validation_needed);
5541 	if (ret) {
5542 		goto fail;
5543 	}
5544 
5545 	/* Enable all crtcs which require enable */
5546 	ret = dm_update_crtcs_state(&adev->dm, state, true, &lock_and_validation_needed);
5547 	if (ret) {
5548 		goto fail;
5549 	}
5550 
5551 	/* Add new/modified planes */
5552 	ret = dm_update_planes_state(dc, state, true, &lock_and_validation_needed);
5553 	if (ret) {
5554 		goto fail;
5555 	}
5556 
5557 	/* Run this here since we want to validate the streams we created */
5558 	ret = drm_atomic_helper_check_planes(dev, state);
5559 	if (ret)
5560 		goto fail;
5561 
5562 	/* Check scaling and underscan changes*/
5563 	/* TODO Removed scaling changes validation due to inability to commit
5564 	 * new stream into context w\o causing full reset. Need to
5565 	 * decide how to handle.
5566 	 */
5567 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5568 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5569 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5570 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5571 
5572 		/* Skip any modesets/resets */
5573 		if (!acrtc || drm_atomic_crtc_needs_modeset(
5574 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
5575 			continue;
5576 
5577 		/* Skip any thing not scale or underscan changes */
5578 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
5579 			continue;
5580 
5581 		overall_update_type = UPDATE_TYPE_FULL;
5582 		lock_and_validation_needed = true;
5583 	}
5584 
5585 	update_type = dm_determine_update_type_for_commit(dc, state);
5586 
5587 	if (overall_update_type < update_type)
5588 		overall_update_type = update_type;
5589 
5590 	/*
5591 	 * lock_and_validation_needed was an old way to determine if we need to set
5592 	 * the global lock. Leaving it in to check if we broke any corner cases
5593 	 * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
5594 	 * lock_and_validation_needed false = UPDATE_TYPE_FAST
5595 	 */
5596 	if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
5597 		WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
5598 	else if (!lock_and_validation_needed && overall_update_type > UPDATE_TYPE_FAST)
5599 		WARN(1, "Global lock should NOT be set, overall_update_type should be UPDATE_TYPE_FAST");
5600 
5601 
5602 	if (overall_update_type > UPDATE_TYPE_FAST) {
5603 
5604 		ret = do_aquire_global_lock(dev, state);
5605 		if (ret)
5606 			goto fail;
5607 
5608 		if (dc_validate_global_state(dc, dm_state->context) != DC_OK) {
5609 			ret = -EINVAL;
5610 			goto fail;
5611 		}
5612 	}
5613 
5614 	/* Must be success */
5615 	WARN_ON(ret);
5616 	return ret;
5617 
5618 fail:
5619 	if (ret == -EDEADLK)
5620 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
5621 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
5622 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
5623 	else
5624 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
5625 
5626 	return ret;
5627 }
5628 
5629 static bool is_dp_capable_without_timing_msa(struct dc *dc,
5630 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
5631 {
5632 	uint8_t dpcd_data;
5633 	bool capable = false;
5634 
5635 	if (amdgpu_dm_connector->dc_link &&
5636 		dm_helpers_dp_read_dpcd(
5637 				NULL,
5638 				amdgpu_dm_connector->dc_link,
5639 				DP_DOWN_STREAM_PORT_COUNT,
5640 				&dpcd_data,
5641 				sizeof(dpcd_data))) {
5642 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
5643 	}
5644 
5645 	return capable;
5646 }
5647 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
5648 					struct edid *edid)
5649 {
5650 	int i;
5651 	bool edid_check_required;
5652 	struct detailed_timing *timing;
5653 	struct detailed_non_pixel *data;
5654 	struct detailed_data_monitor_range *range;
5655 	struct amdgpu_dm_connector *amdgpu_dm_connector =
5656 			to_amdgpu_dm_connector(connector);
5657 	struct dm_connector_state *dm_con_state;
5658 
5659 	struct drm_device *dev = connector->dev;
5660 	struct amdgpu_device *adev = dev->dev_private;
5661 
5662 	if (!connector->state) {
5663 		DRM_ERROR("%s - Connector has no state", __func__);
5664 		return;
5665 	}
5666 
5667 	if (!edid) {
5668 		dm_con_state = to_dm_connector_state(connector->state);
5669 
5670 		amdgpu_dm_connector->min_vfreq = 0;
5671 		amdgpu_dm_connector->max_vfreq = 0;
5672 		amdgpu_dm_connector->pixel_clock_mhz = 0;
5673 
5674 		dm_con_state->freesync_capable = false;
5675 		dm_con_state->freesync_enable = false;
5676 		return;
5677 	}
5678 
5679 	dm_con_state = to_dm_connector_state(connector->state);
5680 
5681 	edid_check_required = false;
5682 	if (!amdgpu_dm_connector->dc_sink) {
5683 		DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
5684 		return;
5685 	}
5686 	if (!adev->dm.freesync_module)
5687 		return;
5688 	/*
5689 	 * if edid non zero restrict freesync only for dp and edp
5690 	 */
5691 	if (edid) {
5692 		if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
5693 			|| amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
5694 			edid_check_required = is_dp_capable_without_timing_msa(
5695 						adev->dm.dc,
5696 						amdgpu_dm_connector);
5697 		}
5698 	}
5699 	dm_con_state->freesync_capable = false;
5700 	if (edid_check_required == true && (edid->version > 1 ||
5701 	   (edid->version == 1 && edid->revision > 1))) {
5702 		for (i = 0; i < 4; i++) {
5703 
5704 			timing	= &edid->detailed_timings[i];
5705 			data	= &timing->data.other_data;
5706 			range	= &data->data.range;
5707 			/*
5708 			 * Check if monitor has continuous frequency mode
5709 			 */
5710 			if (data->type != EDID_DETAIL_MONITOR_RANGE)
5711 				continue;
5712 			/*
5713 			 * Check for flag range limits only. If flag == 1 then
5714 			 * no additional timing information provided.
5715 			 * Default GTF, GTF Secondary curve and CVT are not
5716 			 * supported
5717 			 */
5718 			if (range->flags != 1)
5719 				continue;
5720 
5721 			amdgpu_dm_connector->min_vfreq = range->min_vfreq;
5722 			amdgpu_dm_connector->max_vfreq = range->max_vfreq;
5723 			amdgpu_dm_connector->pixel_clock_mhz =
5724 				range->pixel_clock_mhz * 10;
5725 			break;
5726 		}
5727 
5728 		if (amdgpu_dm_connector->max_vfreq -
5729 		    amdgpu_dm_connector->min_vfreq > 10) {
5730 
5731 			dm_con_state->freesync_capable = true;
5732 		}
5733 	}
5734 }
5735 
5736