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