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