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