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