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