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