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