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