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