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