xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 #include "amdgpu_dm_backlight.h"
70 #include "amdgpu_dm_audio.h"
71 #include "amdgpu_dm_dmub.h"
72 #include "amdgpu_dm_connector.h"
73 #include "amdgpu_dm_pp_smu.h"
74 #include "amdgpu_dm_freesync.h"
75 #include "amdgpu_dm_cursor.h"
76 
77 #include "ivsrcid/ivsrcid_vislands30.h"
78 
79 #include <linux/backlight.h>
80 #include <linux/module.h>
81 #include <linux/moduleparam.h>
82 #include <linux/types.h>
83 #include <linux/pm_runtime.h>
84 #include <linux/pci.h>
85 #include <linux/power_supply.h>
86 #include <linux/firmware.h>
87 #include <linux/component.h>
88 #include <linux/sort.h>
89 
90 #include <drm/drm_privacy_screen_consumer.h>
91 #include <drm/display/drm_dp_mst_helper.h>
92 #include <drm/display/drm_hdmi_helper.h>
93 #include <drm/drm_atomic.h>
94 #include <drm/drm_atomic_uapi.h>
95 #include <drm/drm_atomic_helper.h>
96 #include <drm/drm_blend.h>
97 #include <drm/drm_fixed.h>
98 #include <drm/drm_fourcc.h>
99 #include <drm/drm_edid.h>
100 #include <drm/drm_eld.h>
101 #include <drm/drm_mode.h>
102 #include <drm/drm_utils.h>
103 #include <drm/drm_vblank.h>
104 #include <drm/drm_colorop.h>
105 #include <drm/drm_gem_atomic_helper.h>
106 
107 #include <media/cec-notifier.h>
108 #include <acpi/video.h>
109 
110 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
111 
112 #include "modules/inc/mod_freesync.h"
113 #include "modules/inc/mod_power.h"
114 #include "modules/power/power_helpers.h"
115 
116 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
117 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
118 
119 /**
120  * DOC: overview
121  *
122  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
123  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
124  * requests into DC requests, and DC responses into DRM responses.
125  *
126  * The root control structure is &struct amdgpu_display_manager.
127  */
128 
129 /* basic init/fini API */
130 static int amdgpu_dm_init(struct amdgpu_device *adev);
131 static void amdgpu_dm_fini(struct amdgpu_device *adev);
132 
133 /*
134  * initializes drm_device display related structures, based on the information
135  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
136  * drm_encoder, drm_mode_config
137  *
138  * Returns 0 on success
139  */
140 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
141 /* removes and deallocates the drm structures, created by the above function */
142 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
143 
144 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
145 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
146 STATIC_IFN_KUNIT void dm_enable_per_frame_crtc_master_sync(struct dc_state *context);
147 
148 static int amdgpu_dm_atomic_check(struct drm_device *dev,
149 				  struct drm_atomic_commit *state);
150 
151 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
152 {
153 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
154 		dc_exit_ips_for_hw_access(dc);
155 }
156 
157 /*
158  * dm_vblank_get_counter
159  *
160  * @brief
161  * Get counter for number of vertical blanks
162  *
163  * @param
164  * struct amdgpu_device *adev - [in] desired amdgpu device
165  * int disp_idx - [in] which CRTC to get the counter from
166  *
167  * @return
168  * Counter for vertical blanks
169  */
170 STATIC_IFN_KUNIT u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
171 {
172 	struct amdgpu_crtc *acrtc = NULL;
173 
174 	if (crtc >= adev->mode_info.num_crtc)
175 		return 0;
176 
177 	acrtc = adev->mode_info.crtcs[crtc];
178 
179 	if (!acrtc->dm_irq_params.stream) {
180 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
181 			  crtc);
182 		return 0;
183 	}
184 
185 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
186 }
187 EXPORT_IF_KUNIT(dm_vblank_get_counter);
188 
189 STATIC_IFN_KUNIT int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
190 					    u32 *vbl, u32 *position)
191 {
192 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
193 	struct amdgpu_crtc *acrtc = NULL;
194 	struct dc *dc = adev->dm.dc;
195 
196 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
197 		return -EINVAL;
198 
199 	acrtc = adev->mode_info.crtcs[crtc];
200 
201 	if (!acrtc->dm_irq_params.stream) {
202 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
203 			  crtc);
204 		return 0;
205 	}
206 
207 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
208 		dc_allow_idle_optimizations(dc, false);
209 
210 	/*
211 	 * TODO rework base driver to use values directly.
212 	 * for now parse it back into reg-format
213 	 */
214 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
215 				 &v_blank_start,
216 				 &v_blank_end,
217 				 &h_position,
218 				 &v_position);
219 
220 	*position = v_position | (h_position << 16);
221 	*vbl = v_blank_start | (v_blank_end << 16);
222 
223 	return 0;
224 }
225 EXPORT_IF_KUNIT(dm_crtc_get_scanoutpos);
226 
227 STATIC_IFN_KUNIT bool dm_is_idle(struct amdgpu_ip_block *ip_block)
228 {
229 	/* XXX todo */
230 	return true;
231 }
232 EXPORT_IF_KUNIT(dm_is_idle);
233 
234 STATIC_IFN_KUNIT int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
235 {
236 	/* XXX todo */
237 	return 0;
238 }
239 EXPORT_IF_KUNIT(dm_wait_for_idle);
240 
241 STATIC_IFN_KUNIT int dm_soft_reset(struct amdgpu_ip_block *ip_block)
242 {
243 	/* XXX todo */
244 	return 0;
245 }
246 EXPORT_IF_KUNIT(dm_soft_reset);
247 
248 /*
249  * DC will program planes with their z-order determined by their ordering
250  * in the dc_surface_updates array. This comparator is used to sort them
251  * by descending zpos.
252  */
253 STATIC_IFN_KUNIT int dm_plane_layer_index_cmp(const void *a, const void *b)
254 {
255 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
256 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
257 
258 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
259 	return sb->surface->layer_index - sa->surface->layer_index;
260 }
261 EXPORT_IF_KUNIT(dm_plane_layer_index_cmp);
262 
263 /**
264  * update_planes_and_stream_adapter() - Send planes to be updated in DC
265  *
266  * DC has a generic way to update planes and stream via
267  * dc_update_planes_and_stream function; however, DM might need some
268  * adjustments and preparation before calling it. This function is a wrapper
269  * for the dc_update_planes_and_stream that does any required configuration
270  * before passing control to DC.
271  *
272  * @dc: Display Core control structure
273  * @update_type: specify whether it is FULL/MEDIUM/FAST update
274  * @planes_count: planes count to update
275  * @stream: stream state
276  * @stream_update: stream update
277  * @array_of_surface_update: dc surface update pointer
278  *
279  */
280 static inline bool update_planes_and_stream_adapter(struct dc *dc,
281 						    int update_type,
282 						    int planes_count,
283 						    struct dc_stream_state *stream,
284 						    struct dc_stream_update *stream_update,
285 						    struct dc_surface_update *array_of_surface_update)
286 {
287 	sort(array_of_surface_update, planes_count,
288 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
289 
290 	/*
291 	 * Previous frame finished and HW is ready for optimization.
292 	 */
293 	dc_post_update_surfaces_to_stream(dc);
294 
295 	return dc_update_planes_and_stream(dc,
296 					   array_of_surface_update,
297 					   planes_count,
298 					   stream,
299 					   stream_update);
300 }
301 
302 STATIC_IFN_KUNIT int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
303 					      enum amd_clockgating_state state)
304 {
305 	return 0;
306 }
307 EXPORT_IF_KUNIT(dm_set_clockgating_state);
308 
309 STATIC_IFN_KUNIT int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
310 					      enum amd_powergating_state state)
311 {
312 	return 0;
313 }
314 EXPORT_IF_KUNIT(dm_set_powergating_state);
315 
316 /* Prototypes of private functions */
317 static int dm_early_init(struct amdgpu_ip_block *ip_block);
318 
319 /* Allocate memory for FBC compressed data  */
320 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
321 {
322 	u64 pt_base;
323 	u32 logical_addr_low;
324 	u32 logical_addr_high;
325 	u32 agp_base, agp_bot, agp_top;
326 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
327 
328 	memset(pa_config, 0, sizeof(*pa_config));
329 
330 	agp_base = 0;
331 	agp_bot = adev->gmc.agp_start >> 24;
332 	agp_top = adev->gmc.agp_end >> 24;
333 
334 	/* AGP aperture is disabled */
335 	if (agp_bot > agp_top) {
336 		logical_addr_low = adev->gmc.fb_start >> 18;
337 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
338 				       AMD_APU_IS_RENOIR |
339 				       AMD_APU_IS_GREEN_SARDINE))
340 			/*
341 			 * Raven2 has a HW issue that it is unable to use the vram which
342 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
343 			 * workaround that increase system aperture high address (add 1)
344 			 * to get rid of the VM fault and hardware hang.
345 			 */
346 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
347 		else
348 			logical_addr_high = adev->gmc.fb_end >> 18;
349 	} else {
350 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
351 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
352 				       AMD_APU_IS_RENOIR |
353 				       AMD_APU_IS_GREEN_SARDINE))
354 			/*
355 			 * Raven2 has a HW issue that it is unable to use the vram which
356 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
357 			 * workaround that increase system aperture high address (add 1)
358 			 * to get rid of the VM fault and hardware hang.
359 			 */
360 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
361 		else
362 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
363 	}
364 
365 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
366 
367 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
368 						   AMDGPU_GPU_PAGE_SHIFT);
369 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
370 						  AMDGPU_GPU_PAGE_SHIFT);
371 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
372 						 AMDGPU_GPU_PAGE_SHIFT);
373 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
374 						AMDGPU_GPU_PAGE_SHIFT);
375 	page_table_base.high_part = upper_32_bits(pt_base);
376 	page_table_base.low_part = lower_32_bits(pt_base);
377 
378 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
379 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
380 
381 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
382 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
383 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
384 
385 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
386 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
387 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
388 
389 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
390 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
391 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
392 
393 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
394 
395 }
396 
397 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
398 {
399 	struct mod_power_init_params init_data[MAX_NUM_EDP];
400 
401 	if (dm->num_of_edps == 0) {
402 		drm_dbg_driver(
403 			dm->ddev,
404 			"amdgpu: No eDP detected, skip initializing power module\n");
405 		return 0;
406 	}
407 
408 	/* Initialize all the power module parameters */
409 	for (int i = 0; i < dm->num_of_edps; i++) {
410 		init_data[i].allow_psr_smu_optimizations =
411 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
412 		init_data[i].allow_psr_multi_disp_optimizations =
413 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
414 		/* See dm_late_init */
415 		init_data[i].backlight_ramping_override = false;
416 		init_data[i].backlight_ramping_start = 0xCCCC;
417 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
418 		init_data[i].def_varibright_level = 0;
419 		init_data[i].abm_config_setting = 0;
420 		init_data[i].num_backlight_levels = 101;
421 		init_data[i].use_nits_based_brightness = false;
422 		init_data[i].panel_max_millinits = 0;
423 		init_data[i].panel_min_millinits = 0;
424 		init_data[i].disable_fractional_pwm =
425 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
426 		init_data[i].use_custom_backlight_caps = false;
427 		init_data[i].custom_backlight_caps_config_no = 0;
428 		init_data[i].use_linear_backlight_curve = false;
429 		init_data[i].def_varibright_enable = 0;
430 		init_data[i].varibright_level = 0;
431 		/*
432 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
433 		 * than 8-bit(0XFF max)
434 		 */
435 		init_data[i].min_backlight_pwm =
436 			dm->backlight_caps[i].min_input_signal * 0x101;
437 		init_data[i].max_backlight_pwm =
438 			dm->backlight_caps[i].max_input_signal * 0x101;
439 		init_data[i].min_abm_backlight =
440 			dm->backlight_caps[i].min_input_signal * 0x101;
441 
442 		/* Min backlight level after ABM reduction,  Don't allow below 1%
443 		 * 0xFFFF x 0.01 = 0x28F
444 		 */
445 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
446 			0x28F : init_data[i].min_abm_backlight;
447 	}
448 
449 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
450 	if (!dm->power_module) {
451 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
452 		return -ENOMEM;
453 	}
454 
455 	mod_power_hw_init(dm->power_module);
456 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
457 
458 	return 0;
459 }
460 
461 static int amdgpu_dm_init(struct amdgpu_device *adev)
462 {
463 	struct dc_init_data init_data;
464 	struct dc_callback_init init_params;
465 	int r;
466 
467 	adev->dm.ddev = adev_to_drm(adev);
468 	adev->dm.adev = adev;
469 
470 	/* Zero all the fields */
471 	memset(&init_data, 0, sizeof(init_data));
472 	memset(&init_params, 0, sizeof(init_params));
473 
474 	mutex_init(&adev->dm.dpia_aux_lock);
475 	mutex_init(&adev->dm.dc_lock);
476 	mutex_init(&adev->dm.audio_lock);
477 
478 	spin_lock_init(&adev->dm.dmub_lock);
479 
480 	if (amdgpu_dm_irq_init(adev)) {
481 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
482 		goto error;
483 	}
484 
485 	/* special handling for early revisions of GC 11.5.4 */
486 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
487 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
488 	else
489 		init_data.asic_id.chip_family = adev->family;
490 
491 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
492 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
493 	init_data.asic_id.chip_id = adev->pdev->device;
494 
495 	init_data.asic_id.vram_width = adev->gmc.vram_width;
496 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
497 	init_data.asic_id.atombios_base_address =
498 		adev->mode_info.atom_context->bios;
499 
500 	init_data.driver = adev;
501 
502 	/* cgs_device was created in dm_sw_init() */
503 	init_data.cgs_device = adev->dm.cgs_device;
504 
505 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
506 
507 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
508 	case IP_VERSION(2, 1, 0):
509 		switch (adev->dm.dmcub_fw_version) {
510 		case 0: /* development */
511 		case 0x1: /* linux-firmware.git hash 6d9f399 */
512 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
513 			init_data.flags.disable_dmcu = false;
514 			break;
515 		default:
516 			init_data.flags.disable_dmcu = true;
517 		}
518 		break;
519 	case IP_VERSION(2, 0, 3):
520 		init_data.flags.disable_dmcu = true;
521 		break;
522 	default:
523 		break;
524 	}
525 
526 	/* APU support S/G display by default except:
527 	 * ASICs before Carrizo,
528 	 * RAVEN1 (Users reported stability issue)
529 	 */
530 
531 	if (adev->asic_type < CHIP_CARRIZO) {
532 		init_data.flags.gpu_vm_support = false;
533 	} else if (adev->asic_type == CHIP_RAVEN) {
534 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
535 			init_data.flags.gpu_vm_support = false;
536 		else
537 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
538 	} else {
539 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
540 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
541 		else
542 			init_data.flags.gpu_vm_support =
543 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
544 	}
545 
546 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
547 
548 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
549 		init_data.flags.fbc_support = true;
550 
551 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
552 		init_data.flags.multi_mon_pp_mclk_switch = true;
553 
554 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
555 		init_data.flags.disable_fractional_pwm = true;
556 
557 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
558 		init_data.flags.edp_no_power_sequencing = true;
559 
560 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
561 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
562 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
563 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
564 
565 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
566 		init_data.flags.enable_frl = true;
567 
568 	init_data.flags.seamless_boot_edp_requested = false;
569 
570 	if (amdgpu_device_seamless_boot_supported(adev)) {
571 		init_data.flags.seamless_boot_edp_requested = true;
572 		init_data.flags.allow_seamless_boot_optimization = true;
573 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
574 	}
575 
576 	init_data.flags.enable_mipi_converter_optimization = true;
577 
578 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
579 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
580 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
581 
582 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
583 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
584 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
585 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
586 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
587 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
588 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
589 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
590 	else
591 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
592 
593 	init_data.flags.disable_ips_in_vpb = 0;
594 
595 	/* DCN35 and above supports dynamic DTBCLK switch */
596 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
597 		init_data.flags.allow_0_dtb_clk = true;
598 
599 	/* Enable DWB for tested platforms only */
600 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
601 		init_data.num_virtual_links = 1;
602 
603 	/* DCN42 and above dpia switch to unified link training path */
604 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
605 		init_data.flags.consolidated_dpia_dp_lt = true;
606 		init_data.flags.enable_dpia_pre_training = true;
607 		init_data.flags.unify_link_enc_assignment = true;
608 		init_data.flags.usb4_bw_alloc_support = true;
609 	}
610 
611 	/* DCN201 audio desyncs using DP SS */
612 	if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2)
613 		init_data.flags.ignore_dpref_ss = true;
614 
615 	retrieve_dmi_info(&adev->dm);
616 	if (adev->dm.edp0_on_dp1_quirk)
617 		init_data.flags.support_edp0_on_dp1 = true;
618 
619 	if (adev->dm.bb_from_dmub)
620 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
621 	else
622 		init_data.bb_from_dmub = NULL;
623 
624 	/* Display Core create. */
625 	adev->dm.dc = dc_create(&init_data);
626 
627 	if (adev->dm.dc) {
628 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
629 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
630 	} else {
631 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
632 		goto error;
633 	}
634 
635 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
636 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
637 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
638 	}
639 
640 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
641 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
642 	if (dm_should_disable_stutter(adev->pdev))
643 		adev->dm.dc->debug.disable_stutter = true;
644 
645 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
646 		adev->dm.dc->debug.disable_stutter = true;
647 
648 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
649 		adev->dm.dc->debug.disable_dsc = true;
650 
651 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
652 		adev->dm.dc->debug.disable_clock_gate = true;
653 
654 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
655 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
656 
657 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
658 		adev->dm.dc->debug.force_disable_subvp = true;
659 		adev->dm.dc->debug.fams2_config.bits.enable = false;
660 	}
661 
662 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
663 		adev->dm.dc->debug.using_dml2 = true;
664 		adev->dm.dc->debug.using_dml21 = true;
665 	}
666 
667 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
668 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
669 
670 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
671 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
672 
673 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
674 		adev->dm.dc->debug.skip_detection_link_training = true;
675 
676 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
677 
678 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
679 	adev->dm.dc->debug.ignore_cable_id = true;
680 
681 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
682 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
683 
684 	r = dm_dmub_hw_init(adev);
685 	if (r) {
686 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
687 		goto error;
688 	}
689 
690 	dc_hardware_init(adev->dm.dc);
691 
692 	/* GOP/vBIOS may leave an OPTC enabled for a display present at power-on
693 	 * but no longer driven (e.g. an external DP unplugged at boot). Such a
694 	 * dangling pipe keeps DCN out of idle and blocks s0i3. Power it down
695 	 * here when nothing needs to be preserved.
696 	 */
697 	if (adev->flags & AMD_IS_APU)
698 		dc_disable_dangling_timing_generators(adev->dm.dc);
699 
700 	adev->dm.hpd_rx_offload_wq = amdgpu_dm_hpd_rx_irq_create_workqueue(adev);
701 	if (!adev->dm.hpd_rx_offload_wq) {
702 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
703 		goto error;
704 	}
705 
706 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
707 		struct dc_phy_addr_space_config pa_config;
708 
709 		mmhub_read_system_context(adev, &pa_config);
710 
711 		// Call the DC init_memory func
712 		dc_setup_system_context(adev->dm.dc, &pa_config);
713 	}
714 
715 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
716 	if (!adev->dm.freesync_module) {
717 		drm_err(adev_to_drm(adev),
718 		"failed to initialize freesync_module.\n");
719 	} else
720 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
721 				adev->dm.freesync_module);
722 
723 	amdgpu_dm_init_color_mod();
724 
725 	if (adev->dm.dc->caps.max_links > 0) {
726 		adev->dm.vblank_control_workqueue =
727 			create_singlethread_workqueue("dm_vblank_control_workqueue");
728 		if (!adev->dm.vblank_control_workqueue)
729 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
730 	}
731 
732 	if (adev->dm.dc->caps.ips_support &&
733 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
734 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
735 
736 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
737 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
738 
739 		if (!adev->dm.hdcp_workqueue)
740 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
741 		else
742 			drm_dbg_driver(adev_to_drm(adev),
743 				       "hdcp_workqueue init done %p.\n",
744 				       adev->dm.hdcp_workqueue);
745 
746 		dc_init_callbacks(adev->dm.dc, &init_params);
747 	}
748 	if (adev->dm.dc->caps.max_links > 0) {
749 		adev->dm.hdmi_frl_status_polling_wq =
750 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
751 		if (!adev->dm.hdmi_frl_status_polling_wq)
752 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
753 	}
754 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
755 		init_completion(&adev->dm.dmub_aux_transfer_done);
756 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
757 		if (!adev->dm.dmub_notify) {
758 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
759 			goto error;
760 		}
761 
762 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
763 		if (!adev->dm.delayed_hpd_wq) {
764 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
765 			goto error;
766 		}
767 
768 		amdgpu_dm_outbox_init(adev);
769 		if (!dm_register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
770 			dm_dmub_aux_setconfig_callback, false)) {
771 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
772 			goto error;
773 		}
774 
775 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
776 			init_completion(&adev->dm.fused_io[i].replied);
777 
778 		if (!dm_register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
779 			dm_dmub_aux_fused_io_callback, false)) {
780 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
781 			goto error;
782 		}
783 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
784 		 * It is expected that DMUB will resend any pending notifications at this point. Note
785 		 * that hpd and hpd_irq handler registration are deferred to
786 		 * amdgpu_dm_register_hpd_handlers() to align legacy interface initialization
787 		 * sequence. Connection status will be proactivly detected once in the
788 		 * amdgpu_dm_initialize_drm_device.
789 		 */
790 		dc_enable_dmub_outbox(adev->dm.dc);
791 
792 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
793 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
794 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
795 	}
796 
797 	if (amdgpu_dm_initialize_drm_device(adev)) {
798 		drm_err(adev_to_drm(adev),
799 		"failed to initialize sw for display support.\n");
800 		goto error;
801 	}
802 
803 	if (amdgpu_dm_init_power_module(&adev->dm))
804 		goto error;
805 
806 	/* create fake encoders for MST */
807 	dm_dp_create_fake_mst_encoders(adev);
808 
809 	/* TODO: Add_display_info? */
810 
811 	/* TODO use dynamic cursor width */
812 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
813 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
814 
815 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
816 		drm_err(adev_to_drm(adev),
817 		"failed to initialize vblank for display support.\n");
818 		goto error;
819 	}
820 
821 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
822 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
823 	if (!adev->dm.secure_display_ctx.crtc_ctx)
824 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
825 
826 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
827 		adev->dm.secure_display_ctx.support_mul_roi = true;
828 
829 #endif
830 
831 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
832 
833 	return 0;
834 error:
835 	amdgpu_dm_fini(adev);
836 
837 	return -EINVAL;
838 }
839 
840 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
841 {
842 	struct amdgpu_device *adev = ip_block->adev;
843 
844 	amdgpu_dm_audio_fini(adev);
845 
846 	return 0;
847 }
848 
849 static void amdgpu_dm_fini(struct amdgpu_device *adev)
850 {
851 	int i;
852 
853 	if (adev->dm.vblank_control_workqueue) {
854 		destroy_workqueue(adev->dm.vblank_control_workqueue);
855 		adev->dm.vblank_control_workqueue = NULL;
856 	}
857 
858 	if (adev->dm.idle_workqueue) {
859 		if (adev->dm.idle_workqueue->running) {
860 			adev->dm.idle_workqueue->enable = false;
861 			flush_work(&adev->dm.idle_workqueue->work);
862 		}
863 
864 		kfree(adev->dm.idle_workqueue);
865 		adev->dm.idle_workqueue = NULL;
866 	}
867 
868 	/*
869 	 * Disable ISM before dc_destroy() invalidates dm->dc.
870 	 *
871 	 * Quiesce workers first without dc_lock (they take dc_lock
872 	 * themselves, so syncing under it would deadlock), then drive the
873 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
874 	 */
875 	amdgpu_dm_ism_disable(&adev->dm);
876 	scoped_guard(mutex, &adev->dm.dc_lock)
877 		amdgpu_dm_ism_force_full_power(&adev->dm);
878 
879 	amdgpu_dm_destroy_drm_device(&adev->dm);
880 
881 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
882 	if (adev->dm.secure_display_ctx.crtc_ctx) {
883 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
884 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
885 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
886 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
887 			}
888 		}
889 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
890 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
891 	}
892 #endif
893 	if (adev->dm.hdcp_workqueue) {
894 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
895 		adev->dm.hdcp_workqueue = NULL;
896 	}
897 
898 	if (adev->dm.dc) {
899 		dc_deinit_callbacks(adev->dm.dc);
900 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
901 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
902 			kfree(adev->dm.dmub_notify);
903 			adev->dm.dmub_notify = NULL;
904 			destroy_workqueue(adev->dm.delayed_hpd_wq);
905 			adev->dm.delayed_hpd_wq = NULL;
906 		}
907 	}
908 
909 	if (adev->dm.dmub_bo)
910 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
911 				      &adev->dm.dmub_bo_gpu_addr,
912 				      &adev->dm.dmub_bo_cpu_addr);
913 
914 	if (adev->dm.boot_time_crc_info.bo_ptr)
915 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
916 					&adev->dm.boot_time_crc_info.gpu_addr,
917 					&adev->dm.boot_time_crc_info.cpu_addr);
918 
919 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
920 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
921 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
922 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
923 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
924 			}
925 		}
926 
927 		kfree(adev->dm.hpd_rx_offload_wq);
928 		adev->dm.hpd_rx_offload_wq = NULL;
929 	}
930 
931 	amdgpu_dm_irq_fini(adev);
932 
933 	/* DC Destroy TODO: Replace destroy DAL */
934 	if (adev->dm.dc)
935 		dc_destroy(&adev->dm.dc);
936 
937 	if (adev->dm.cgs_device) {
938 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
939 		adev->dm.cgs_device = NULL;
940 	}
941 	if (adev->dm.freesync_module) {
942 		mod_freesync_destroy(adev->dm.freesync_module);
943 		adev->dm.freesync_module = NULL;
944 	}
945 
946 	if (adev->dm.power_module) {
947 		mod_power_destroy(adev->dm.power_module);
948 		adev->dm.power_module = NULL;
949 	}
950 	mutex_destroy(&adev->dm.audio_lock);
951 	mutex_destroy(&adev->dm.dc_lock);
952 	mutex_destroy(&adev->dm.dpia_aux_lock);
953 }
954 
955 static int load_dmcu_fw(struct amdgpu_device *adev)
956 {
957 	const char *fw_name_dmcu = NULL;
958 	int r;
959 	const struct dmcu_firmware_header_v1_0 *hdr;
960 
961 	switch (adev->asic_type) {
962 #if defined(CONFIG_DRM_AMD_DC_SI)
963 	case CHIP_TAHITI:
964 	case CHIP_PITCAIRN:
965 	case CHIP_VERDE:
966 	case CHIP_OLAND:
967 #endif
968 	case CHIP_BONAIRE:
969 	case CHIP_HAWAII:
970 	case CHIP_KAVERI:
971 	case CHIP_KABINI:
972 	case CHIP_MULLINS:
973 	case CHIP_TONGA:
974 	case CHIP_FIJI:
975 	case CHIP_CARRIZO:
976 	case CHIP_STONEY:
977 	case CHIP_POLARIS11:
978 	case CHIP_POLARIS10:
979 	case CHIP_POLARIS12:
980 	case CHIP_VEGAM:
981 	case CHIP_VEGA10:
982 	case CHIP_VEGA12:
983 	case CHIP_VEGA20:
984 		return 0;
985 	case CHIP_NAVI12:
986 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
987 		break;
988 	case CHIP_RAVEN:
989 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
990 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
991 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
992 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
993 		else
994 			return 0;
995 		break;
996 	default:
997 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
998 		case IP_VERSION(2, 0, 2):
999 		case IP_VERSION(2, 0, 3):
1000 		case IP_VERSION(2, 0, 0):
1001 		case IP_VERSION(2, 1, 0):
1002 		case IP_VERSION(3, 0, 0):
1003 		case IP_VERSION(3, 0, 2):
1004 		case IP_VERSION(3, 0, 3):
1005 		case IP_VERSION(3, 0, 1):
1006 		case IP_VERSION(3, 1, 2):
1007 		case IP_VERSION(3, 1, 3):
1008 		case IP_VERSION(3, 1, 4):
1009 		case IP_VERSION(3, 1, 5):
1010 		case IP_VERSION(3, 1, 6):
1011 		case IP_VERSION(3, 2, 0):
1012 		case IP_VERSION(3, 2, 1):
1013 		case IP_VERSION(3, 5, 0):
1014 		case IP_VERSION(3, 5, 1):
1015 		case IP_VERSION(3, 6, 0):
1016 		case IP_VERSION(4, 0, 1):
1017 		case IP_VERSION(4, 2, 0):
1018 		case IP_VERSION(4, 2, 1):
1019 		case IP_VERSION(6, 0, 0):
1020 			return 0;
1021 		default:
1022 			break;
1023 		}
1024 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
1025 		return -EINVAL;
1026 	}
1027 
1028 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1029 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
1030 		return 0;
1031 	}
1032 
1033 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
1034 				 "%s", fw_name_dmcu);
1035 	if (r == -ENODEV) {
1036 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
1037 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
1038 		adev->dm.fw_dmcu = NULL;
1039 		return 0;
1040 	}
1041 	if (r) {
1042 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
1043 			fw_name_dmcu);
1044 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
1045 		return r;
1046 	}
1047 
1048 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
1049 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
1050 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
1051 	adev->firmware.fw_size +=
1052 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1053 
1054 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
1055 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
1056 	adev->firmware.fw_size +=
1057 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1058 
1059 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
1060 
1061 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
1062 
1063 	return 0;
1064 }
1065 
1066 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
1067 {
1068 	struct amdgpu_device *adev = ip_block->adev;
1069 	int r;
1070 
1071 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
1072 
1073 	if (!adev->dm.cgs_device) {
1074 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
1075 		return -EINVAL;
1076 	}
1077 
1078 	/* Moved from dm init since we need to use allocations for storing bounding box data */
1079 	INIT_LIST_HEAD(&adev->dm.da_list);
1080 
1081 	r = dm_dmub_sw_init(adev);
1082 	if (r)
1083 		return r;
1084 
1085 	return load_dmcu_fw(adev);
1086 }
1087 
1088 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
1089 {
1090 	struct amdgpu_device *adev = ip_block->adev;
1091 	struct dal_allocation *da;
1092 
1093 	list_for_each_entry(da, &adev->dm.da_list, list) {
1094 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
1095 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1096 			list_del(&da->list);
1097 			kfree(da);
1098 			adev->dm.bb_from_dmub = NULL;
1099 			break;
1100 		}
1101 	}
1102 
1103 
1104 	kfree(adev->dm.dmub_fb_info);
1105 	adev->dm.dmub_fb_info = NULL;
1106 
1107 	if (adev->dm.dmub_srv) {
1108 		dmub_srv_destroy(adev->dm.dmub_srv);
1109 		kfree(adev->dm.dmub_srv);
1110 		adev->dm.dmub_srv = NULL;
1111 	}
1112 
1113 	amdgpu_ucode_release(&adev->dm.dmub_fw);
1114 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
1115 
1116 	return 0;
1117 }
1118 
1119 
1120 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
1121 {
1122 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
1123 	struct dmub_srv *dmub = NULL;
1124 	union dmub_fw_boot_options option = {0};
1125 	int ret = 0;
1126 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
1127 
1128 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
1129 		!adev->dm.dc->ctx->dmub_srv) {
1130 		return;
1131 	}
1132 
1133 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
1134 	bootcrc_info = &adev->dm.boot_time_crc_info;
1135 
1136 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
1137 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
1138 		return;
1139 	}
1140 
1141 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
1142 
1143 	/* Return if boot time CRC is not enabled */
1144 	if (option.bits.bootcrc_en_at_S0i3 == 0)
1145 		return;
1146 
1147 	/* Create a buffer for boot time CRC */
1148 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
1149 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
1150 		&bootcrc_info->bo_ptr,
1151 		&bootcrc_info->gpu_addr,
1152 		&bootcrc_info->cpu_addr);
1153 
1154 	if (ret) {
1155 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
1156 	} else {
1157 		bootcrc_info->size = fb_size;
1158 
1159 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
1160 			bootcrc_info->gpu_addr, bootcrc_info->size);
1161 
1162 		/* Send the buffer info to DMUB */
1163 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
1164 			bootcrc_info->gpu_addr, bootcrc_info->size);
1165 	}
1166 }
1167 
1168 static int dm_late_init(struct amdgpu_ip_block *ip_block)
1169 {
1170 	struct amdgpu_device *adev = ip_block->adev;
1171 
1172 	struct dmcu_iram_parameters params;
1173 	unsigned int linear_lut[16];
1174 	int i;
1175 	struct dmcu *dmcu = NULL;
1176 
1177 	dmcu = adev->dm.dc->res_pool->dmcu;
1178 
1179 	/* Init the boot time CRC (skip in resume) */
1180 	if ((adev->in_suspend == 0) &&
1181 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
1182 		amdgpu_dm_boot_time_crc_init(adev);
1183 
1184 	for (i = 0; i < 16; i++)
1185 		linear_lut[i] = 0xFFFF * i / 15;
1186 
1187 	params.set = 0;
1188 	params.backlight_ramping_override = false;
1189 	params.backlight_ramping_start = 0xCCCC;
1190 	params.backlight_ramping_reduction = 0xCCCCCCCC;
1191 	params.backlight_lut_array_size = 16;
1192 	params.backlight_lut_array = linear_lut;
1193 
1194 	/* Min backlight level after ABM reduction,  Don't allow below 1%
1195 	 * 0xFFFF x 0.01 = 0x28F
1196 	 */
1197 	params.min_abm_backlight = 0x28F;
1198 	/* In the case where abm is implemented on dmcub,
1199 	 * dmcu object will be null.
1200 	 * ABM 2.4 and up are implemented on dmcub.
1201 	 */
1202 	if (dmcu) {
1203 		if (!dmcu_load_iram(dmcu, params))
1204 			return -EINVAL;
1205 	} else if (adev->dm.dc->ctx->dmub_srv) {
1206 		struct dc_link *edp_links[MAX_NUM_EDP];
1207 		int edp_num;
1208 
1209 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
1210 		for (i = 0; i < edp_num; i++) {
1211 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
1212 				return -EINVAL;
1213 		}
1214 	}
1215 
1216 	return amdgpu_dm_detect_mst_link_for_all_connectors(adev_to_drm(adev));
1217 }
1218 
1219 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
1220 {
1221 	u8 buf[UUID_SIZE];
1222 	guid_t guid;
1223 	int ret;
1224 
1225 	mutex_lock(&mgr->lock);
1226 	if (!mgr->mst_primary)
1227 		goto out_fail;
1228 
1229 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
1230 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
1231 		goto out_fail;
1232 	}
1233 
1234 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
1235 				 DP_MST_EN |
1236 				 DP_UP_REQ_EN |
1237 				 DP_UPSTREAM_IS_SRC);
1238 	if (ret < 0) {
1239 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
1240 		goto out_fail;
1241 	}
1242 
1243 	/* Some hubs forget their guids after they resume */
1244 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
1245 	if (ret != sizeof(buf)) {
1246 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
1247 		goto out_fail;
1248 	}
1249 
1250 	import_guid(&guid, buf);
1251 
1252 	if (guid_is_null(&guid)) {
1253 		guid_gen(&guid);
1254 		export_guid(buf, &guid);
1255 
1256 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
1257 
1258 		if (ret != sizeof(buf)) {
1259 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
1260 			goto out_fail;
1261 		}
1262 	}
1263 
1264 	guid_copy(&mgr->mst_primary->guid, &guid);
1265 
1266 out_fail:
1267 	mutex_unlock(&mgr->lock);
1268 }
1269 
1270 static void s3_handle_mst(struct drm_device *dev, bool suspend)
1271 {
1272 	struct amdgpu_dm_connector *aconnector;
1273 	struct drm_connector *connector;
1274 	struct drm_connector_list_iter iter;
1275 	struct drm_dp_mst_topology_mgr *mgr;
1276 
1277 	drm_connector_list_iter_begin(dev, &iter);
1278 	drm_for_each_connector_iter(connector, &iter) {
1279 
1280 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1281 			continue;
1282 
1283 		aconnector = to_amdgpu_dm_connector(connector);
1284 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
1285 		    aconnector->mst_root)
1286 			continue;
1287 
1288 		mgr = &aconnector->mst_mgr;
1289 
1290 		if (suspend) {
1291 			drm_dp_mst_topology_mgr_suspend(mgr);
1292 		} else {
1293 			/* if extended timeout is supported in hardware,
1294 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
1295 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
1296 			 */
1297 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
1298 			if (!dp_is_lttpr_present(aconnector->dc_link))
1299 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
1300 
1301 			/* TODO: move resume_mst_branch_status() into drm mst resume again
1302 			 * once topology probing work is pulled out from mst resume into mst
1303 			 * resume 2nd step. mst resume 2nd step should be called after old
1304 			 * state getting restored (i.e. drm_atomic_helper_resume()).
1305 			 */
1306 			resume_mst_branch_status(mgr);
1307 		}
1308 	}
1309 	drm_connector_list_iter_end(&iter);
1310 }
1311 
1312 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
1313 {
1314 	struct amdgpu_display_manager *dm = &adev->dm;
1315 	struct amdgpu_i2c_adapter *oem_i2c;
1316 	struct ddc_service *oem_ddc_service;
1317 	int r;
1318 
1319 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
1320 	if (oem_ddc_service) {
1321 		oem_i2c = amdgpu_dm_create_i2c(oem_ddc_service, true);
1322 		if (!oem_i2c) {
1323 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
1324 			return -ENOMEM;
1325 		}
1326 
1327 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
1328 		if (r) {
1329 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
1330 			kfree(oem_i2c);
1331 			return r;
1332 		}
1333 		dm->oem_i2c = oem_i2c;
1334 	}
1335 
1336 	return 0;
1337 }
1338 
1339 /**
1340  * dm_hw_init() - Initialize DC device
1341  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
1342  *
1343  * Initialize the &struct amdgpu_display_manager device. This involves calling
1344  * the initializers of each DM component, then populating the struct with them.
1345  *
1346  * Although the function implies hardware initialization, both hardware and
1347  * software are initialized here. Splitting them out to their relevant init
1348  * hooks is a future TODO item.
1349  *
1350  * Some notable things that are initialized here:
1351  *
1352  * - Display Core, both software and hardware
1353  * - DC modules that we need (freesync and color management)
1354  * - DRM software states
1355  * - Interrupt sources and handlers
1356  * - Vblank support
1357  * - Debug FS entries, if enabled
1358  */
1359 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
1360 {
1361 	struct amdgpu_device *adev = ip_block->adev;
1362 	int r;
1363 
1364 	adev->dm.i2c_devres_group = devres_open_group(adev->dev, NULL, GFP_KERNEL);
1365 	if (!adev->dm.i2c_devres_group)
1366 		return -ENOMEM;
1367 
1368 	/* Create DAL display manager */
1369 	r = amdgpu_dm_init(adev);
1370 	if (r)
1371 		goto err_release_i2c;
1372 	amdgpu_dm_hpd_init(adev);
1373 
1374 	r = dm_oem_i2c_hw_init(adev);
1375 	if (r)
1376 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
1377 
1378 	devres_close_group(adev->dev, adev->dm.i2c_devres_group);
1379 	return 0;
1380 
1381 err_release_i2c:
1382 	devres_release_group(adev->dev, adev->dm.i2c_devres_group);
1383 	return r;
1384 }
1385 
1386 /**
1387  * dm_hw_fini() - Teardown DC device
1388  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
1389  *
1390  * Teardown components within &struct amdgpu_display_manager that require
1391  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
1392  * were loaded. Also flush IRQ workqueues and disable them.
1393  */
1394 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
1395 {
1396 	struct amdgpu_device *adev = ip_block->adev;
1397 
1398 	if (adev->dm.i2c_devres_group)
1399 		devres_release_group(adev->dev, adev->dm.i2c_devres_group);
1400 
1401 	amdgpu_dm_hpd_fini(adev);
1402 
1403 	amdgpu_dm_fini(adev);
1404 	return 0;
1405 }
1406 
1407 
1408 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
1409 				 struct dc_state *state, bool enable)
1410 {
1411 	enum dc_irq_source irq_source;
1412 	struct amdgpu_crtc *acrtc;
1413 	int rc = -EBUSY;
1414 	int i = 0;
1415 
1416 	for (i = 0; i < state->stream_count; i++) {
1417 		acrtc = amdgpu_dm_get_crtc_by_otg_inst(
1418 				adev, state->stream_status[i].primary_otg_inst);
1419 
1420 		if (acrtc && state->stream_status[i].plane_count != 0 &&
1421 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
1422 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
1423 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
1424 			if (rc)
1425 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
1426 					 enable ? "enable" : "disable");
1427 
1428 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
1429 				if (enable) {
1430 					if (amdgpu_dm_crtc_vrr_active(
1431 							to_dm_crtc_state(acrtc->base.state)))
1432 						rc = amdgpu_dm_crtc_set_vupdate_irq(
1433 							&acrtc->base, true);
1434 				} else
1435 					rc = amdgpu_dm_crtc_set_vupdate_irq(
1436 							&acrtc->base, false);
1437 
1438 				if (rc)
1439 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
1440 						enable ? "en" : "dis");
1441 			}
1442 
1443 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
1444 			/* During gpu-reset we disable and then enable vblank irq, so
1445 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
1446 			 */
1447 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
1448 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
1449 
1450 		} else if (acrtc && state->stream_status[i].plane_count != 0) {
1451 			/* DCN only needs to toggle VUPDATE_NO_LOCK */
1452 			rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, enable);
1453 			if (rc)
1454 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
1455 					 enable ? "en" : "dis");
1456 		}
1457 	}
1458 
1459 }
1460 
1461 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
1462 
1463 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
1464 {
1465 	struct dc_state *context __free(state_release) = NULL;
1466 	int i;
1467 	struct dc_stream_state *del_streams[MAX_PIPES];
1468 	int del_streams_count = 0;
1469 	struct dc_commit_streams_params params = {};
1470 
1471 	memset(del_streams, 0, sizeof(del_streams));
1472 
1473 	context = dc_state_create_current_copy(dc);
1474 	if (context == NULL)
1475 		return DC_ERROR_UNEXPECTED;
1476 
1477 	/* First remove from context all streams */
1478 	for (i = 0; i < context->stream_count; i++) {
1479 		struct dc_stream_state *stream = context->streams[i];
1480 
1481 		del_streams[del_streams_count++] = stream;
1482 	}
1483 
1484 	/* Remove all planes for removed streams and then remove the streams */
1485 	for (i = 0; i < del_streams_count; i++) {
1486 		enum dc_status res;
1487 
1488 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
1489 			return DC_FAIL_DETACH_SURFACES;
1490 
1491 		res = dc_state_remove_stream(dc, context, del_streams[i]);
1492 		if (res != DC_OK)
1493 			return res;
1494 	}
1495 
1496 	params.streams = context->streams;
1497 	params.stream_count = context->stream_count;
1498 
1499 	return dc_commit_streams(dc, &params);
1500 }
1501 
1502 static int dm_cache_state(struct amdgpu_device *adev)
1503 {
1504 	int r;
1505 
1506 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
1507 	if (IS_ERR(adev->dm.cached_state)) {
1508 		r = PTR_ERR(adev->dm.cached_state);
1509 		adev->dm.cached_state = NULL;
1510 	}
1511 
1512 	return adev->dm.cached_state ? 0 : r;
1513 }
1514 
1515 static void dm_destroy_cached_state(struct amdgpu_device *adev)
1516 {
1517 	struct amdgpu_display_manager *dm = &adev->dm;
1518 	struct drm_device *ddev = adev_to_drm(adev);
1519 	struct dm_plane_state *dm_new_plane_state;
1520 	struct drm_plane_state *new_plane_state;
1521 	struct dm_crtc_state *dm_new_crtc_state;
1522 	struct drm_crtc_state *new_crtc_state;
1523 	struct drm_plane *plane;
1524 	struct drm_crtc *crtc;
1525 	int i;
1526 
1527 	if (!dm->cached_state)
1528 		return;
1529 
1530 	/* Force mode set in atomic commit */
1531 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1532 		new_crtc_state->active_changed = true;
1533 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1534 		amdgpu_dm_reset_freesync_config_for_crtc(dm_new_crtc_state);
1535 	}
1536 
1537 	/*
1538 	 * atomic_check is expected to create the dc states. We need to release
1539 	 * them here, since they were duplicated as part of the suspend
1540 	 * procedure.
1541 	 */
1542 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1543 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1544 		if (dm_new_crtc_state->stream) {
1545 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1546 			dc_stream_release(dm_new_crtc_state->stream);
1547 			dm_new_crtc_state->stream = NULL;
1548 		}
1549 		dm_new_crtc_state->base.color_mgmt_changed = true;
1550 	}
1551 
1552 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1553 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
1554 		if (dm_new_plane_state->dc_state) {
1555 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1556 			dc_plane_state_release(dm_new_plane_state->dc_state);
1557 			dm_new_plane_state->dc_state = NULL;
1558 		}
1559 	}
1560 
1561 	drm_atomic_helper_resume(ddev, dm->cached_state);
1562 
1563 	dm->cached_state = NULL;
1564 }
1565 
1566 static int dm_suspend(struct amdgpu_ip_block *ip_block)
1567 {
1568 	struct amdgpu_device *adev = ip_block->adev;
1569 	struct amdgpu_display_manager *dm = &adev->dm;
1570 
1571 	if (amdgpu_in_reset(adev)) {
1572 		enum dc_status res;
1573 
1574 		/* Quiesce ISM workers before taking dc_lock (workers take
1575 		 * dc_lock themselves; syncing under it would deadlock).
1576 		 */
1577 		amdgpu_dm_ism_disable(dm);
1578 
1579 		mutex_lock(&dm->dc_lock);
1580 
1581 		amdgpu_dm_ism_force_full_power(dm);
1582 		dc_allow_idle_optimizations(adev->dm.dc, false);
1583 
1584 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
1585 
1586 		if (dm->cached_dc_state)
1587 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
1588 
1589 		res = amdgpu_dm_commit_zero_streams(dm->dc);
1590 		if (res != DC_OK) {
1591 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
1592 			dc_state_release(dm->cached_dc_state);
1593 			dm->cached_dc_state = NULL;
1594 			mutex_unlock(&dm->dc_lock);
1595 			return -EINVAL;
1596 		}
1597 
1598 		amdgpu_dm_irq_suspend(adev);
1599 
1600 		amdgpu_dm_hpd_rx_irq_work_suspend(dm);
1601 
1602 		return 0;
1603 	}
1604 
1605 	if (!adev->dm.cached_state) {
1606 		int r = dm_cache_state(adev);
1607 
1608 		if (r)
1609 			return r;
1610 	}
1611 
1612 	amdgpu_dm_s3_handle_hdmi_cec(adev_to_drm(adev), true);
1613 
1614 	s3_handle_mst(adev_to_drm(adev), true);
1615 
1616 	amdgpu_dm_irq_suspend(adev);
1617 
1618 	/*
1619 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
1620 	 * themselves; syncing under it would deadlock).
1621 	 */
1622 	amdgpu_dm_ism_disable(dm);
1623 	scoped_guard(mutex, &dm->dc_lock)
1624 		amdgpu_dm_ism_force_full_power(dm);
1625 
1626 	amdgpu_dm_hpd_rx_irq_work_suspend(dm);
1627 
1628 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
1629 
1630 	if (dm->dc->caps.ips_support && adev->in_s0ix)
1631 		dc_allow_idle_optimizations(dm->dc, true);
1632 
1633 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
1634 
1635 	return 0;
1636 }
1637 
1638 void amdgpu_dm_emulated_link_detect(struct dc_link *link)
1639 {
1640 	struct dc_sink_init_data sink_init_data = { 0 };
1641 	struct display_sink_capability sink_caps = { 0 };
1642 	enum dc_edid_status edid_status;
1643 	struct dc_context *dc_ctx = link->ctx;
1644 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
1645 	struct dc_sink *sink = NULL;
1646 	struct dc_sink *prev_sink = NULL;
1647 
1648 	link->type = dc_connection_none;
1649 	prev_sink = link->local_sink;
1650 
1651 	if (prev_sink)
1652 		dc_sink_release(prev_sink);
1653 
1654 	switch (link->connector_signal) {
1655 	case SIGNAL_TYPE_HDMI_TYPE_A: {
1656 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1657 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1658 		break;
1659 	}
1660 
1661 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1662 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1663 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1664 		break;
1665 	}
1666 
1667 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
1668 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1669 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1670 		break;
1671 	}
1672 
1673 	case SIGNAL_TYPE_LVDS: {
1674 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1675 		sink_caps.signal = SIGNAL_TYPE_LVDS;
1676 		break;
1677 	}
1678 
1679 	case SIGNAL_TYPE_EDP: {
1680 		sink_caps.transaction_type =
1681 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1682 		sink_caps.signal = SIGNAL_TYPE_EDP;
1683 		break;
1684 	}
1685 
1686 	case SIGNAL_TYPE_DISPLAY_PORT: {
1687 		sink_caps.transaction_type =
1688 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1689 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
1690 		break;
1691 	}
1692 
1693 	default:
1694 		drm_err(dev, "Invalid connector type! signal:%d\n",
1695 			link->connector_signal);
1696 		return;
1697 	}
1698 
1699 	sink_init_data.link = link;
1700 	sink_init_data.sink_signal = sink_caps.signal;
1701 
1702 	sink = dc_sink_create(&sink_init_data);
1703 	if (!sink) {
1704 		drm_err(dev, "Failed to create sink!\n");
1705 		return;
1706 	}
1707 
1708 	/* dc_sink_create returns a new reference */
1709 	link->local_sink = sink;
1710 
1711 	edid_status = dm_helpers_read_local_edid(
1712 			link->ctx,
1713 			link,
1714 			sink);
1715 
1716 	if (edid_status != EDID_OK)
1717 		drm_err(dev, "Failed to read EDID\n");
1718 
1719 }
1720 
1721 static void dm_gpureset_commit_state(struct dc_state *dc_state,
1722 				     struct amdgpu_display_manager *dm)
1723 {
1724 	struct {
1725 		struct dc_surface_update surface_updates[MAX_SURFACES];
1726 		struct dc_plane_info plane_infos[MAX_SURFACES];
1727 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
1728 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
1729 		struct dc_stream_update stream_update;
1730 	} *bundle __free(kfree);
1731 	int k, m;
1732 
1733 	bundle = kzalloc_obj(*bundle);
1734 
1735 	if (!bundle) {
1736 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
1737 		return;
1738 	}
1739 
1740 	for (k = 0; k < dc_state->stream_count; k++) {
1741 		bundle->stream_update.stream = dc_state->streams[k];
1742 
1743 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
1744 			bundle->surface_updates[m].surface =
1745 				dc_state->stream_status[k].plane_states[m];
1746 			bundle->surface_updates[m].surface->force_full_update =
1747 				true;
1748 		}
1749 
1750 		update_planes_and_stream_adapter(dm->dc,
1751 					 UPDATE_TYPE_FULL,
1752 					 dc_state->stream_status[k].plane_count,
1753 					 dc_state->streams[k],
1754 					 &bundle->stream_update,
1755 					 bundle->surface_updates);
1756 	}
1757 }
1758 
1759 void amdgpu_dm_apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
1760 											   struct dc_sink *sink)
1761 {
1762 	struct dc_panel_patch *ppatch = NULL;
1763 
1764 	if (!sink)
1765 		return;
1766 
1767 	ppatch = &sink->edid_caps.panel_patch;
1768 	if (ppatch->wait_after_dpcd_poweroff_ms) {
1769 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
1770 		drm_dbg_driver(adev_to_drm(adev),
1771 			       "%s: adding a %ds delay as w/a for panel\n",
1772 			       __func__,
1773 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
1774 	}
1775 }
1776 EXPORT_IF_KUNIT(amdgpu_dm_apply_delay_after_dpcd_poweroff);
1777 
1778 /**
1779  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
1780  * @adev: amdgpu device pointer
1781  *
1782  * Iterates through all DC links and dumps information about local and remote
1783  * (MST) sinks. Should be called after connector detection is complete to see
1784  * the final state of all links.
1785  */
1786 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
1787 {
1788 	struct dc *dc = adev->dm.dc;
1789 	struct drm_device *dev = adev_to_drm(adev);
1790 	int li;
1791 
1792 	if (!dc)
1793 		return;
1794 
1795 	for (li = 0; li < dc->link_count; li++) {
1796 		struct dc_link *l = dc->links[li];
1797 		const char *name = NULL;
1798 		int rs;
1799 
1800 		if (!l)
1801 			continue;
1802 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
1803 			name = l->local_sink->edid_caps.display_name;
1804 		else
1805 			name = "n/a";
1806 
1807 		drm_dbg_kms(dev,
1808 			"LINK_DUMP[%d]: local_sink=%p type=%d sink_signal=%d sink_count=%u edid_name=%s mst_capable=%d mst_alloc_streams=%d\n",
1809 			li,
1810 			l->local_sink,
1811 			l->type,
1812 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
1813 			l->sink_count,
1814 			name,
1815 			l->dpcd_caps.is_mst_capable,
1816 			l->mst_stream_alloc_table.stream_count);
1817 
1818 		/* Dump remote (MST) sinks if any */
1819 		for (rs = 0; rs < l->sink_count; rs++) {
1820 			struct dc_sink *rsink = l->remote_sinks[rs];
1821 			const char *rname = NULL;
1822 
1823 			if (!rsink)
1824 				continue;
1825 			if (rsink->edid_caps.display_name[0])
1826 				rname = rsink->edid_caps.display_name;
1827 			else
1828 				rname = "n/a";
1829 			drm_dbg_kms(dev,
1830 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
1831 				li, rs,
1832 				rsink,
1833 				rsink->sink_signal,
1834 				rname);
1835 		}
1836 	}
1837 }
1838 
1839 static int dm_resume(struct amdgpu_ip_block *ip_block)
1840 {
1841 	struct amdgpu_device *adev = ip_block->adev;
1842 	struct drm_device *ddev = adev_to_drm(adev);
1843 	struct amdgpu_display_manager *dm = &adev->dm;
1844 	struct amdgpu_dm_connector *aconnector;
1845 	struct drm_connector *connector;
1846 	struct drm_connector_list_iter iter;
1847 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1848 	enum dc_connection_type new_connection_type = dc_connection_none;
1849 	struct dc_state *dc_state;
1850 	int i, r, j;
1851 	struct dc_commit_streams_params commit_params = {};
1852 
1853 	if (dm->dc->caps.ips_support) {
1854 		if (!amdgpu_in_reset(adev))
1855 			mutex_lock(&dm->dc_lock);
1856 
1857 		/* Need to set POWER_STATE_D0 first or it will not execute
1858 		 * idle_power_optimizations command to DMUB.
1859 		 */
1860 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
1861 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
1862 
1863 		if (!amdgpu_in_reset(adev))
1864 			mutex_unlock(&dm->dc_lock);
1865 	}
1866 
1867 	if (amdgpu_in_reset(adev)) {
1868 		dc_state = dm->cached_dc_state;
1869 
1870 		/*
1871 		 * The dc->current_state is backed up into dm->cached_dc_state
1872 		 * before we commit 0 streams.
1873 		 *
1874 		 * DC will clear link encoder assignments on the real state
1875 		 * but the changes won't propagate over to the copy we made
1876 		 * before the 0 streams commit.
1877 		 *
1878 		 * DC expects that link encoder assignments are *not* valid
1879 		 * when committing a state, so as a workaround we can copy
1880 		 * off of the current state.
1881 		 *
1882 		 * We lose the previous assignments, but we had already
1883 		 * commit 0 streams anyway.
1884 		 */
1885 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
1886 
1887 		r = dm_dmub_hw_init(adev);
1888 		if (r) {
1889 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1890 			dc_state_release(dm->cached_dc_state);
1891 			dm->cached_dc_state = NULL;
1892 			mutex_unlock(&dm->dc_lock);
1893 			return r;
1894 		}
1895 
1896 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
1897 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1898 
1899 		dc_resume(dm->dc);
1900 
1901 		amdgpu_dm_ism_enable(dm);
1902 		amdgpu_dm_irq_resume_early(adev);
1903 
1904 		for (i = 0; i < dc_state->stream_count; i++) {
1905 			dc_state->streams[i]->mode_changed = true;
1906 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
1907 				dc_pipe_update_bits_set_full(&dc_state->stream_status[i].plane_states[j]->update_bits);
1908 			}
1909 		}
1910 
1911 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1912 			amdgpu_dm_outbox_init(adev);
1913 			dc_enable_dmub_outbox(adev->dm.dc);
1914 		}
1915 
1916 		commit_params.streams = dc_state->streams;
1917 		commit_params.stream_count = dc_state->stream_count;
1918 		dc_exit_ips_for_hw_access(dm->dc);
1919 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
1920 
1921 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
1922 
1923 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
1924 
1925 		dc_state_release(dm->cached_dc_state);
1926 		dm->cached_dc_state = NULL;
1927 
1928 		amdgpu_dm_irq_resume_late(adev);
1929 
1930 		mutex_unlock(&dm->dc_lock);
1931 
1932 		/* set the backlight after a reset */
1933 		for (i = 0; i < dm->num_of_edps; i++) {
1934 			if (dm->backlight_dev[i])
1935 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
1936 		}
1937 
1938 		return 0;
1939 	}
1940 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
1941 	dc_state_release(dm_state->context);
1942 	dm_state->context = dc_state_create(dm->dc, NULL);
1943 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1944 
1945 	/* Before powering on DC we need to re-initialize DMUB. */
1946 	dm_dmub_hw_resume(adev);
1947 
1948 	/* Re-enable outbox interrupts for DPIA. */
1949 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1950 		amdgpu_dm_outbox_init(adev);
1951 		dc_enable_dmub_outbox(adev->dm.dc);
1952 	}
1953 
1954 	/* power on hardware */
1955 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
1956 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1957 
1958 	/* program HPD filter */
1959 	dc_resume(dm->dc);
1960 
1961 	scoped_guard(mutex, &dm->dc_lock)
1962 		amdgpu_dm_ism_enable(dm);
1963 
1964 	/*
1965 	 * early enable HPD Rx IRQ, should be done before set mode as short
1966 	 * pulse interrupts are used for MST
1967 	 */
1968 	amdgpu_dm_irq_resume_early(adev);
1969 
1970 	amdgpu_dm_s3_handle_hdmi_cec(ddev, false);
1971 
1972 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
1973 	s3_handle_mst(ddev, false);
1974 
1975 	/* Do detection*/
1976 	drm_connector_list_iter_begin(ddev, &iter);
1977 	drm_for_each_connector_iter(connector, &iter) {
1978 		bool ret;
1979 
1980 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1981 			continue;
1982 
1983 		aconnector = to_amdgpu_dm_connector(connector);
1984 
1985 		if (!aconnector->dc_link)
1986 			continue;
1987 
1988 		/*
1989 		 * this is the case when traversing through already created end sink
1990 		 * MST connectors, should be skipped
1991 		 */
1992 		if (aconnector->mst_root)
1993 			continue;
1994 
1995 		/* Skip eDP detection, when there is no sink present */
1996 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
1997 		    !aconnector->dc_link->edp_sink_present)
1998 			continue;
1999 
2000 		guard(mutex)(&aconnector->hpd_lock);
2001 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
2002 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
2003 
2004 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2005 			amdgpu_dm_emulated_link_detect(aconnector->dc_link);
2006 		} else {
2007 			guard(mutex)(&dm->dc_lock);
2008 			dc_exit_ips_for_hw_access(dm->dc);
2009 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
2010 			if (ret) {
2011 				/* w/a delay for certain panels */
2012 				amdgpu_dm_apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
2013 			}
2014 		}
2015 
2016 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2017 			aconnector->fake_enable = false;
2018 
2019 		if (aconnector->dc_sink)
2020 			dc_sink_release(aconnector->dc_sink);
2021 		aconnector->dc_sink = NULL;
2022 		amdgpu_dm_update_connector_after_detect(aconnector);
2023 	}
2024 	drm_connector_list_iter_end(&iter);
2025 
2026 	dm_destroy_cached_state(adev);
2027 
2028 	/* Do mst topology probing after resuming cached state*/
2029 	drm_connector_list_iter_begin(ddev, &iter);
2030 	drm_for_each_connector_iter(connector, &iter) {
2031 		bool init = false;
2032 
2033 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2034 			continue;
2035 
2036 		aconnector = to_amdgpu_dm_connector(connector);
2037 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2038 		    aconnector->mst_root)
2039 			continue;
2040 
2041 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
2042 			init = !aconnector->mst_mgr.mst_primary;
2043 		}
2044 		if (init)
2045 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
2046 				aconnector->dc_link, false);
2047 		else
2048 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
2049 	}
2050 	drm_connector_list_iter_end(&iter);
2051 
2052 	/* Debug dump: list all DC links and their associated sinks after detection
2053 	 * is complete for all connectors. This provides a comprehensive view of the
2054 	 * final state without repeating the dump for each connector.
2055 	 */
2056 	amdgpu_dm_dump_links_and_sinks(adev);
2057 
2058 	amdgpu_dm_irq_resume_late(adev);
2059 
2060 	amdgpu_dm_smu_write_watermarks_table(adev);
2061 
2062 	drm_kms_helper_hotplug_event(ddev);
2063 
2064 	return 0;
2065 }
2066 
2067 /**
2068  * DOC: DM Lifecycle
2069  *
2070  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
2071  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
2072  * the base driver's device list to be initialized and torn down accordingly.
2073  *
2074  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
2075  */
2076 
2077 static const struct amd_ip_funcs amdgpu_dm_funcs = {
2078 	.name = "dm",
2079 	.early_init = dm_early_init,
2080 	.late_init = dm_late_init,
2081 	.sw_init = dm_sw_init,
2082 	.sw_fini = dm_sw_fini,
2083 	.early_fini = amdgpu_dm_early_fini,
2084 	.hw_init = dm_hw_init,
2085 	.hw_fini = dm_hw_fini,
2086 	.suspend = dm_suspend,
2087 	.resume = dm_resume,
2088 	.is_idle = dm_is_idle,
2089 	.wait_for_idle = dm_wait_for_idle,
2090 	.soft_reset = dm_soft_reset,
2091 	.set_clockgating_state = dm_set_clockgating_state,
2092 	.set_powergating_state = dm_set_powergating_state,
2093 };
2094 
2095 const struct amdgpu_ip_block_version dm_ip_block = {
2096 	.type = AMD_IP_BLOCK_TYPE_DCE,
2097 	.major = 1,
2098 	.minor = 0,
2099 	.rev = 0,
2100 	.funcs = &amdgpu_dm_funcs,
2101 };
2102 
2103 
2104 /**
2105  * DOC: atomic
2106  *
2107  * *WIP*
2108  */
2109 
2110 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
2111 	.fb_create = amdgpu_display_user_framebuffer_create,
2112 	.get_format_info = amdgpu_dm_plane_get_format_info,
2113 	.atomic_check = amdgpu_dm_atomic_check,
2114 	.atomic_commit = drm_atomic_helper_commit,
2115 };
2116 
2117 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2118 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2119 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
2120 };
2121 
2122 /*
2123  * Acquires the lock for the atomic state object and returns
2124  * the new atomic state.
2125  *
2126  * This should only be called during atomic check.
2127  */
2128 int dm_atomic_get_state(struct drm_atomic_commit *state,
2129 			struct dm_atomic_state **dm_state)
2130 {
2131 	struct drm_device *dev = state->dev;
2132 	struct amdgpu_device *adev = drm_to_adev(dev);
2133 	struct amdgpu_display_manager *dm = &adev->dm;
2134 	struct drm_private_state *priv_state;
2135 
2136 	if (*dm_state)
2137 		return 0;
2138 
2139 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
2140 	if (IS_ERR(priv_state))
2141 		return PTR_ERR(priv_state);
2142 
2143 	*dm_state = to_dm_atomic_state(priv_state);
2144 
2145 	return 0;
2146 }
2147 
2148 STATIC_IFN_KUNIT struct dm_atomic_state *
2149 dm_atomic_get_new_state(struct drm_atomic_commit *state)
2150 {
2151 	struct drm_device *dev = state->dev;
2152 	struct amdgpu_device *adev = drm_to_adev(dev);
2153 	struct amdgpu_display_manager *dm = &adev->dm;
2154 	struct drm_private_obj *obj;
2155 	struct drm_private_state *new_obj_state;
2156 	int i;
2157 
2158 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
2159 		if (obj->funcs == dm->atomic_obj.funcs)
2160 			return to_dm_atomic_state(new_obj_state);
2161 	}
2162 
2163 	return NULL;
2164 }
2165 EXPORT_IF_KUNIT(dm_atomic_get_new_state);
2166 
2167 static struct drm_private_state *
2168 dm_atomic_duplicate_state(struct drm_private_obj *obj)
2169 {
2170 	struct dm_atomic_state *old_state, *new_state;
2171 
2172 	new_state = kzalloc_obj(*new_state);
2173 	if (!new_state)
2174 		return NULL;
2175 
2176 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
2177 
2178 	old_state = to_dm_atomic_state(obj->state);
2179 
2180 	if (old_state && old_state->context)
2181 		new_state->context = dc_state_create_copy(old_state->context);
2182 
2183 	if (!new_state->context) {
2184 		kfree(new_state);
2185 		return NULL;
2186 	}
2187 
2188 	return &new_state->base;
2189 }
2190 
2191 STATIC_IFN_KUNIT void dm_atomic_destroy_state(struct drm_private_obj *obj,
2192 					      struct drm_private_state *state)
2193 {
2194 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
2195 
2196 	if (dm_state && dm_state->context)
2197 		dc_state_release(dm_state->context);
2198 
2199 	kfree(dm_state);
2200 }
2201 EXPORT_IF_KUNIT(dm_atomic_destroy_state);
2202 
2203 static struct drm_private_state *
2204 dm_atomic_create_state(struct drm_private_obj *obj)
2205 {
2206 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
2207 	struct dm_atomic_state *dm_state;
2208 	struct dc_state *context;
2209 
2210 	dm_state = kzalloc_obj(*dm_state);
2211 	if (!dm_state)
2212 		return ERR_PTR(-ENOMEM);
2213 
2214 	context = dc_state_create_current_copy(adev->dm.dc);
2215 	if (!context) {
2216 		kfree(dm_state);
2217 		return ERR_PTR(-ENOMEM);
2218 	}
2219 
2220 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
2221 	dm_state->context = context;
2222 
2223 	return &dm_state->base;
2224 }
2225 
2226 static struct drm_private_state_funcs dm_atomic_state_funcs = {
2227 	.atomic_create_state = dm_atomic_create_state,
2228 	.atomic_duplicate_state = dm_atomic_duplicate_state,
2229 	.atomic_destroy_state = dm_atomic_destroy_state,
2230 };
2231 
2232 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
2233 {
2234 	int r;
2235 
2236 	adev->mode_info.mode_config_initialized = true;
2237 
2238 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
2239 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
2240 
2241 	adev_to_drm(adev)->mode_config.max_width = 16384;
2242 	adev_to_drm(adev)->mode_config.max_height = 16384;
2243 
2244 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
2245 	if (adev->asic_type == CHIP_HAWAII)
2246 		/* disable prefer shadow for now due to hibernation issues */
2247 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
2248 	else
2249 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
2250 	/* indicates support for immediate flip */
2251 	adev_to_drm(adev)->mode_config.async_page_flip = true;
2252 
2253 	drm_atomic_private_obj_init(adev_to_drm(adev),
2254 				    &adev->dm.atomic_obj,
2255 				    &dm_atomic_state_funcs);
2256 
2257 	r = amdgpu_display_modeset_create_props(adev);
2258 	if (r)
2259 		return r;
2260 
2261 #ifdef AMD_PRIVATE_COLOR
2262 	if (amdgpu_dm_create_color_properties(adev))
2263 		return -ENOMEM;
2264 #endif
2265 
2266 	r = amdgpu_dm_audio_init(adev);
2267 	if (r)
2268 		return r;
2269 
2270 	return 0;
2271 }
2272 
2273 static int initialize_plane(struct amdgpu_display_manager *dm,
2274 			    struct amdgpu_mode_info *mode_info, int plane_id,
2275 			    enum drm_plane_type plane_type,
2276 			    const struct dc_plane_cap *plane_cap)
2277 {
2278 	struct drm_plane *plane;
2279 	unsigned long possible_crtcs;
2280 	int ret = 0;
2281 
2282 	plane = kzalloc_obj(struct drm_plane);
2283 	if (!plane) {
2284 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
2285 		return -ENOMEM;
2286 	}
2287 	plane->type = plane_type;
2288 
2289 	/*
2290 	 * HACK: IGT tests expect that the primary plane for a CRTC
2291 	 * can only have one possible CRTC. Only expose support for
2292 	 * any CRTC if they're not going to be used as a primary plane
2293 	 * for a CRTC - like overlay or underlay planes.
2294 	 */
2295 	possible_crtcs = 1 << plane_id;
2296 	if (plane_id >= dm->dc->caps.max_streams)
2297 		possible_crtcs = 0xff;
2298 
2299 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2300 
2301 	if (ret) {
2302 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
2303 		kfree(plane);
2304 		return ret;
2305 	}
2306 
2307 	if (mode_info)
2308 		mode_info->planes[plane_id] = plane;
2309 
2310 	return ret;
2311 }
2312 
2313 
2314 /*
2315  * In this architecture, the association
2316  * connector -> encoder -> crtc
2317  * id not really requried. The crtc and connector will hold the
2318  * display_index as an abstraction to use with DAL component
2319  *
2320  * Returns 0 on success
2321  */
2322 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2323 {
2324 	struct amdgpu_display_manager *dm = &adev->dm;
2325 	s32 i;
2326 	struct amdgpu_dm_connector *aconnector = NULL;
2327 	struct amdgpu_encoder *aencoder = NULL;
2328 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
2329 	u32 link_cnt;
2330 	s32 primary_planes;
2331 	enum dc_connection_type new_connection_type = dc_connection_none;
2332 	const struct dc_plane_cap *plane;
2333 	bool psr_feature_enabled = false;
2334 	bool replay_feature_enabled = false;
2335 	int max_overlay = dm->dc->caps.max_slave_planes;
2336 
2337 	dm->display_indexes_num = dm->dc->caps.max_streams;
2338 	/* Update the actual used number of crtc */
2339 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
2340 
2341 	amdgpu_dm_set_irq_funcs(adev);
2342 
2343 	link_cnt = dm->dc->caps.max_links;
2344 	if (amdgpu_dm_mode_config_init(dm->adev)) {
2345 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
2346 		return -EINVAL;
2347 	}
2348 
2349 	/* There is one primary plane per CRTC */
2350 	primary_planes = dm->dc->caps.max_streams;
2351 	if (primary_planes > AMDGPU_MAX_PLANES) {
2352 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
2353 		return -EINVAL;
2354 	}
2355 
2356 	/*
2357 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
2358 	 * Order is reversed to match iteration order in atomic check.
2359 	 */
2360 	for (i = (primary_planes - 1); i >= 0; i--) {
2361 		plane = &dm->dc->caps.planes[i];
2362 
2363 		if (initialize_plane(dm, mode_info, i,
2364 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
2365 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
2366 			goto fail;
2367 		}
2368 	}
2369 
2370 	/*
2371 	 * Initialize overlay planes, index starting after primary planes.
2372 	 * These planes have a higher DRM index than the primary planes since
2373 	 * they should be considered as having a higher z-order.
2374 	 * Order is reversed to match iteration order in atomic check.
2375 	 *
2376 	 * Only support DCN for now, and only expose one so we don't encourage
2377 	 * userspace to use up all the pipes.
2378 	 */
2379 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2380 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2381 
2382 		/* Do not create overlay if MPO disabled */
2383 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
2384 			break;
2385 
2386 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2387 			continue;
2388 
2389 		if (!plane->pixel_format_support.argb8888)
2390 			continue;
2391 
2392 		if (max_overlay-- == 0)
2393 			break;
2394 
2395 		if (initialize_plane(dm, NULL, primary_planes + i,
2396 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
2397 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
2398 			goto fail;
2399 		}
2400 	}
2401 
2402 	for (i = 0; i < dm->dc->caps.max_streams; i++)
2403 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2404 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
2405 			goto fail;
2406 		}
2407 
2408 	/* Use Outbox interrupt */
2409 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2410 	case IP_VERSION(3, 0, 0):
2411 	case IP_VERSION(3, 1, 2):
2412 	case IP_VERSION(3, 1, 3):
2413 	case IP_VERSION(3, 1, 4):
2414 	case IP_VERSION(3, 1, 5):
2415 	case IP_VERSION(3, 1, 6):
2416 	case IP_VERSION(3, 2, 0):
2417 	case IP_VERSION(3, 2, 1):
2418 	case IP_VERSION(2, 1, 0):
2419 	case IP_VERSION(3, 5, 0):
2420 	case IP_VERSION(3, 5, 1):
2421 	case IP_VERSION(3, 6, 0):
2422 	case IP_VERSION(4, 0, 1):
2423 	case IP_VERSION(4, 2, 0):
2424 	case IP_VERSION(4, 2, 1):
2425 	case IP_VERSION(6, 0, 0):
2426 		if (amdgpu_dm_register_outbox_irq_handlers(dm->adev)) {
2427 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2428 			goto fail;
2429 		}
2430 		break;
2431 	default:
2432 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
2433 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
2434 	}
2435 
2436 	/* Determine whether to enable PSR support by default. */
2437 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
2438 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2439 		case IP_VERSION(3, 1, 2):
2440 		case IP_VERSION(3, 1, 3):
2441 		case IP_VERSION(3, 1, 4):
2442 		case IP_VERSION(3, 1, 5):
2443 		case IP_VERSION(3, 1, 6):
2444 		case IP_VERSION(3, 2, 0):
2445 		case IP_VERSION(3, 2, 1):
2446 		case IP_VERSION(3, 5, 0):
2447 		case IP_VERSION(3, 5, 1):
2448 		case IP_VERSION(3, 6, 0):
2449 		case IP_VERSION(4, 0, 1):
2450 		case IP_VERSION(4, 2, 0):
2451 		case IP_VERSION(4, 2, 1):
2452 		case IP_VERSION(6, 0, 0):
2453 			psr_feature_enabled = true;
2454 			break;
2455 		default:
2456 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
2457 			break;
2458 		}
2459 	}
2460 
2461 	/* Determine whether to enable Replay support by default. */
2462 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
2463 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2464 		case IP_VERSION(3, 1, 4):
2465 		case IP_VERSION(3, 2, 0):
2466 		case IP_VERSION(3, 2, 1):
2467 		case IP_VERSION(3, 5, 0):
2468 		case IP_VERSION(3, 5, 1):
2469 		case IP_VERSION(3, 6, 0):
2470 		case IP_VERSION(4, 2, 0):
2471 		case IP_VERSION(4, 2, 1):
2472 		case IP_VERSION(6, 0, 0):
2473 			replay_feature_enabled = true;
2474 			break;
2475 
2476 		default:
2477 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
2478 			break;
2479 		}
2480 	}
2481 
2482 	if (link_cnt > MAX_LINKS) {
2483 		drm_err(adev_to_drm(adev),
2484 			"KMS: Cannot support more than %d display indexes\n",
2485 				MAX_LINKS);
2486 		goto fail;
2487 	}
2488 
2489 	/* loops over all connectors on the board */
2490 	for (i = 0; i < link_cnt; i++) {
2491 		struct dc_link *link = NULL;
2492 
2493 		link = dc_get_link_at_index(dm->dc, i);
2494 
2495 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
2496 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
2497 
2498 			if (!wbcon) {
2499 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
2500 				continue;
2501 			}
2502 
2503 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
2504 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
2505 				kfree(wbcon);
2506 				continue;
2507 			}
2508 
2509 			link->psr_settings.psr_feature_enabled = false;
2510 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
2511 
2512 			continue;
2513 		}
2514 
2515 		aconnector = kzalloc_obj(*aconnector);
2516 		if (!aconnector)
2517 			goto fail;
2518 
2519 		aencoder = kzalloc_obj(*aencoder);
2520 		if (!aencoder)
2521 			goto fail;
2522 
2523 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2524 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
2525 			goto fail;
2526 		}
2527 
2528 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2529 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
2530 			goto fail;
2531 		}
2532 
2533 		if (dm->hpd_rx_offload_wq)
2534 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
2535 				aconnector;
2536 
2537 		if (!dc_link_detect_connection_type(link, &new_connection_type))
2538 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
2539 
2540 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2541 			amdgpu_dm_emulated_link_detect(link);
2542 			amdgpu_dm_update_connector_after_detect(aconnector);
2543 		} else {
2544 			bool ret = false;
2545 
2546 			mutex_lock(&dm->dc_lock);
2547 			dc_exit_ips_for_hw_access(dm->dc);
2548 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
2549 			mutex_unlock(&dm->dc_lock);
2550 
2551 			if (ret) {
2552 				amdgpu_dm_update_connector_after_detect(aconnector);
2553 				amdgpu_dm_setup_backlight_device(dm, aconnector);
2554 
2555 				/* Disable PSR if Replay can be enabled */
2556 				if (replay_feature_enabled)
2557 					if (amdgpu_dm_set_replay_caps(link, aconnector))
2558 						psr_feature_enabled = false;
2559 
2560 				if (psr_feature_enabled) {
2561 					amdgpu_dm_set_psr_caps(link, aconnector);
2562 					drm_info(adev_to_drm(adev), "%s: PSR support %d, DC PSR ver %d, sink PSR ver %d DPCD caps 0x%x su_y_granularity %d\n",
2563 						 aconnector->base.name,
2564 						 link->psr_settings.psr_feature_enabled,
2565 						 link->psr_settings.psr_version,
2566 						 link->dpcd_caps.psr_info.psr_version,
2567 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
2568 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
2569 				}
2570 			}
2571 		}
2572 		amdgpu_set_panel_orientation(&aconnector->base);
2573 	}
2574 
2575 	/* Debug dump: list all DC links and their associated sinks after detection
2576 	 * is complete for all connectors. This provides a comprehensive view of the
2577 	 * final state without repeating the dump for each connector.
2578 	 */
2579 	amdgpu_dm_dump_links_and_sinks(adev);
2580 
2581 	/* Software is initialized. Now we can register interrupt handlers. */
2582 	switch (adev->asic_type) {
2583 #if defined(CONFIG_DRM_AMD_DC_SI)
2584 	case CHIP_TAHITI:
2585 	case CHIP_PITCAIRN:
2586 	case CHIP_VERDE:
2587 	case CHIP_OLAND:
2588 #endif
2589 	case CHIP_BONAIRE:
2590 	case CHIP_HAWAII:
2591 	case CHIP_KAVERI:
2592 	case CHIP_KABINI:
2593 	case CHIP_MULLINS:
2594 	case CHIP_TONGA:
2595 	case CHIP_FIJI:
2596 	case CHIP_CARRIZO:
2597 	case CHIP_STONEY:
2598 	case CHIP_POLARIS11:
2599 	case CHIP_POLARIS10:
2600 	case CHIP_POLARIS12:
2601 	case CHIP_VEGAM:
2602 	case CHIP_VEGA10:
2603 	case CHIP_VEGA12:
2604 	case CHIP_VEGA20:
2605 		if (amdgpu_dm_dce110_register_irq_handlers(dm->adev)) {
2606 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2607 			goto fail;
2608 		}
2609 		break;
2610 	default:
2611 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2612 		case IP_VERSION(1, 0, 0):
2613 		case IP_VERSION(1, 0, 1):
2614 		case IP_VERSION(2, 0, 2):
2615 		case IP_VERSION(2, 0, 3):
2616 		case IP_VERSION(2, 0, 0):
2617 		case IP_VERSION(2, 1, 0):
2618 		case IP_VERSION(3, 0, 0):
2619 		case IP_VERSION(3, 0, 2):
2620 		case IP_VERSION(3, 0, 3):
2621 		case IP_VERSION(3, 0, 1):
2622 		case IP_VERSION(3, 1, 2):
2623 		case IP_VERSION(3, 1, 3):
2624 		case IP_VERSION(3, 1, 4):
2625 		case IP_VERSION(3, 1, 5):
2626 		case IP_VERSION(3, 1, 6):
2627 		case IP_VERSION(3, 2, 0):
2628 		case IP_VERSION(3, 2, 1):
2629 		case IP_VERSION(3, 5, 0):
2630 		case IP_VERSION(3, 5, 1):
2631 		case IP_VERSION(3, 6, 0):
2632 		case IP_VERSION(4, 0, 1):
2633 		case IP_VERSION(4, 2, 0):
2634 		case IP_VERSION(4, 2, 1):
2635 		case IP_VERSION(6, 0, 0):
2636 			if (amdgpu_dm_dcn10_register_irq_handlers(dm->adev)) {
2637 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2638 				goto fail;
2639 			}
2640 			break;
2641 		default:
2642 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
2643 					amdgpu_ip_version(adev, DCE_HWIP, 0));
2644 			goto fail;
2645 		}
2646 		break;
2647 	}
2648 
2649 	return 0;
2650 fail:
2651 	kfree(aencoder);
2652 	kfree(aconnector);
2653 
2654 	return -EINVAL;
2655 }
2656 
2657 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2658 {
2659 	if (dm->atomic_obj.state)
2660 		drm_atomic_private_obj_fini(&dm->atomic_obj);
2661 }
2662 
2663 /******************************************************************************
2664  * amdgpu_display_funcs functions
2665  *****************************************************************************/
2666 
2667 /*
2668  * dm_bandwidth_update - program display watermarks
2669  *
2670  * @adev: amdgpu_device pointer
2671  *
2672  * Calculate and program the display watermarks and line buffer allocation.
2673  */
2674 STATIC_IFN_KUNIT void dm_bandwidth_update(struct amdgpu_device *adev)
2675 {
2676 	/* TODO: implement later */
2677 }
2678 EXPORT_IF_KUNIT(dm_bandwidth_update);
2679 
2680 static const struct amdgpu_display_funcs dm_display_funcs = {
2681 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2682 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2683 	.backlight_set_level = NULL, /* never called for DC */
2684 	.backlight_get_level = NULL, /* never called for DC */
2685 	.hpd_sense = NULL,/* called unconditionally */
2686 	.hpd_set_polarity = NULL, /* called unconditionally */
2687 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2688 	.page_flip_get_scanoutpos =
2689 		dm_crtc_get_scanoutpos,/* called unconditionally */
2690 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2691 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
2692 };
2693 
2694 #if defined(CONFIG_DEBUG_KERNEL_DC)
2695 
2696 static ssize_t s3_debug_store(struct device *device,
2697 			      struct device_attribute *attr,
2698 			      const char *buf,
2699 			      size_t count)
2700 {
2701 	int ret;
2702 	int s3_state;
2703 	struct drm_device *drm_dev = dev_get_drvdata(device);
2704 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
2705 	struct amdgpu_ip_block *ip_block;
2706 
2707 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
2708 	if (!ip_block)
2709 		return -EINVAL;
2710 
2711 	ret = kstrtoint(buf, 0, &s3_state);
2712 
2713 	if (ret == 0) {
2714 		if (s3_state) {
2715 			dm_resume(ip_block);
2716 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
2717 		} else
2718 			dm_suspend(ip_block);
2719 	}
2720 
2721 	return ret == 0 ? count : 0;
2722 }
2723 
2724 DEVICE_ATTR_WO(s3_debug);
2725 
2726 #endif
2727 
2728 static int dm_early_init(struct amdgpu_ip_block *ip_block)
2729 {
2730 	struct amdgpu_device *adev = ip_block->adev;
2731 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
2732 	struct atom_context *ctx = mode_info->atom_context;
2733 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
2734 	u16 data_offset;
2735 
2736 	/* if there is no object header, skip DM */
2737 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
2738 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
2739 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
2740 		return -ENOENT;
2741 	}
2742 
2743 	switch (adev->asic_type) {
2744 #if defined(CONFIG_DRM_AMD_DC_SI)
2745 	case CHIP_TAHITI:
2746 	case CHIP_PITCAIRN:
2747 	case CHIP_VERDE:
2748 		adev->mode_info.num_crtc = 6;
2749 		adev->mode_info.num_hpd = 6;
2750 		adev->mode_info.num_dig = 6;
2751 		break;
2752 	case CHIP_OLAND:
2753 		adev->mode_info.num_crtc = 2;
2754 		adev->mode_info.num_hpd = 2;
2755 		adev->mode_info.num_dig = 2;
2756 		break;
2757 #endif
2758 	case CHIP_BONAIRE:
2759 	case CHIP_HAWAII:
2760 		adev->mode_info.num_crtc = 6;
2761 		adev->mode_info.num_hpd = 6;
2762 		adev->mode_info.num_dig = 6;
2763 		break;
2764 	case CHIP_KAVERI:
2765 		adev->mode_info.num_crtc = 4;
2766 		adev->mode_info.num_hpd = 6;
2767 		adev->mode_info.num_dig = 7;
2768 		break;
2769 	case CHIP_KABINI:
2770 	case CHIP_MULLINS:
2771 		adev->mode_info.num_crtc = 2;
2772 		adev->mode_info.num_hpd = 6;
2773 		adev->mode_info.num_dig = 6;
2774 		break;
2775 	case CHIP_FIJI:
2776 	case CHIP_TONGA:
2777 		adev->mode_info.num_crtc = 6;
2778 		adev->mode_info.num_hpd = 6;
2779 		adev->mode_info.num_dig = 7;
2780 		break;
2781 	case CHIP_CARRIZO:
2782 		adev->mode_info.num_crtc = 3;
2783 		adev->mode_info.num_hpd = 6;
2784 		adev->mode_info.num_dig = 9;
2785 		break;
2786 	case CHIP_STONEY:
2787 		adev->mode_info.num_crtc = 2;
2788 		adev->mode_info.num_hpd = 6;
2789 		adev->mode_info.num_dig = 9;
2790 		break;
2791 	case CHIP_POLARIS11:
2792 	case CHIP_POLARIS12:
2793 		adev->mode_info.num_crtc = 5;
2794 		adev->mode_info.num_hpd = 5;
2795 		adev->mode_info.num_dig = 5;
2796 		break;
2797 	case CHIP_POLARIS10:
2798 	case CHIP_VEGAM:
2799 		adev->mode_info.num_crtc = 6;
2800 		adev->mode_info.num_hpd = 6;
2801 		adev->mode_info.num_dig = 6;
2802 		break;
2803 	case CHIP_VEGA10:
2804 	case CHIP_VEGA12:
2805 	case CHIP_VEGA20:
2806 		adev->mode_info.num_crtc = 6;
2807 		adev->mode_info.num_hpd = 6;
2808 		adev->mode_info.num_dig = 6;
2809 		break;
2810 	default:
2811 
2812 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2813 		case IP_VERSION(2, 0, 2):
2814 		case IP_VERSION(3, 0, 0):
2815 			adev->mode_info.num_crtc = 6;
2816 			adev->mode_info.num_hpd = 6;
2817 			adev->mode_info.num_dig = 6;
2818 			break;
2819 		case IP_VERSION(2, 0, 0):
2820 		case IP_VERSION(3, 0, 2):
2821 			adev->mode_info.num_crtc = 5;
2822 			adev->mode_info.num_hpd = 5;
2823 			adev->mode_info.num_dig = 5;
2824 			break;
2825 		case IP_VERSION(2, 0, 3):
2826 		case IP_VERSION(3, 0, 3):
2827 			adev->mode_info.num_crtc = 2;
2828 			adev->mode_info.num_hpd = 2;
2829 			adev->mode_info.num_dig = 2;
2830 			break;
2831 		case IP_VERSION(1, 0, 0):
2832 		case IP_VERSION(1, 0, 1):
2833 		case IP_VERSION(3, 0, 1):
2834 		case IP_VERSION(2, 1, 0):
2835 		case IP_VERSION(3, 1, 2):
2836 		case IP_VERSION(3, 1, 3):
2837 		case IP_VERSION(3, 1, 4):
2838 		case IP_VERSION(3, 1, 5):
2839 		case IP_VERSION(3, 1, 6):
2840 		case IP_VERSION(3, 2, 0):
2841 		case IP_VERSION(3, 2, 1):
2842 		case IP_VERSION(3, 5, 0):
2843 		case IP_VERSION(3, 5, 1):
2844 		case IP_VERSION(3, 6, 0):
2845 		case IP_VERSION(4, 0, 1):
2846 		case IP_VERSION(4, 2, 0):
2847 		case IP_VERSION(4, 2, 1):
2848 		case IP_VERSION(6, 0, 0):
2849 			adev->mode_info.num_crtc = 4;
2850 			adev->mode_info.num_hpd = 4;
2851 			adev->mode_info.num_dig = 4;
2852 			break;
2853 		default:
2854 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
2855 					amdgpu_ip_version(adev, DCE_HWIP, 0));
2856 			return -EINVAL;
2857 		}
2858 		break;
2859 	}
2860 
2861 	if (adev->mode_info.funcs == NULL)
2862 		adev->mode_info.funcs = &dm_display_funcs;
2863 
2864 	/*
2865 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
2866 	 * adev->reg.audio_endpt.wreg because they are initialised in
2867 	 * amdgpu_device_init()
2868 	 */
2869 #if defined(CONFIG_DEBUG_KERNEL_DC)
2870 	device_create_file(
2871 		adev_to_drm(adev)->dev,
2872 		&dev_attr_s3_debug);
2873 #endif
2874 	adev->dc_enabled = true;
2875 
2876 	return dm_init_microcode(adev);
2877 }
2878 
2879 STATIC_IFN_KUNIT bool modereset_required(struct drm_crtc_state *crtc_state)
2880 {
2881 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
2882 }
2883 EXPORT_IF_KUNIT(modereset_required);
2884 
2885 STATIC_IFN_KUNIT int
2886 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
2887 			    const enum surface_pixel_format format,
2888 			    enum dc_color_space *color_space)
2889 {
2890 	bool full_range;
2891 
2892 	*color_space = COLOR_SPACE_SRGB;
2893 
2894 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
2895 	if (plane_state->state && plane_state->state->plane_color_pipeline)
2896 		return 0;
2897 
2898 	/* DRM color properties only affect non-RGB formats. */
2899 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2900 		return 0;
2901 
2902 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2903 
2904 	switch (plane_state->color_encoding) {
2905 	case DRM_COLOR_YCBCR_BT601:
2906 		if (full_range)
2907 			*color_space = COLOR_SPACE_YCBCR601;
2908 		else
2909 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
2910 		break;
2911 
2912 	case DRM_COLOR_YCBCR_BT709:
2913 		if (full_range)
2914 			*color_space = COLOR_SPACE_YCBCR709;
2915 		else
2916 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
2917 		break;
2918 
2919 	case DRM_COLOR_YCBCR_BT2020:
2920 		if (full_range)
2921 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
2922 		else
2923 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
2924 		break;
2925 
2926 	default:
2927 		return -EINVAL;
2928 	}
2929 
2930 	return 0;
2931 }
2932 EXPORT_IF_KUNIT(fill_plane_color_attributes);
2933 
2934 static int
2935 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2936 			    const struct drm_plane_state *plane_state,
2937 			    struct dc_plane_info *plane_info,
2938 			    struct dc_plane_address *address,
2939 			    bool tmz_surface)
2940 {
2941 	const struct drm_framebuffer *fb = plane_state->fb;
2942 	const struct amdgpu_framebuffer *afb =
2943 		to_amdgpu_framebuffer(plane_state->fb);
2944 	int ret;
2945 
2946 	memset(plane_info, 0, sizeof(*plane_info));
2947 
2948 	switch (fb->format->format) {
2949 	case DRM_FORMAT_C8:
2950 		plane_info->format =
2951 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2952 		break;
2953 	case DRM_FORMAT_RGB565:
2954 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2955 		break;
2956 	case DRM_FORMAT_XRGB8888:
2957 	case DRM_FORMAT_ARGB8888:
2958 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2959 		break;
2960 	case DRM_FORMAT_XRGB2101010:
2961 	case DRM_FORMAT_ARGB2101010:
2962 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2963 		break;
2964 	case DRM_FORMAT_XBGR2101010:
2965 	case DRM_FORMAT_ABGR2101010:
2966 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2967 		break;
2968 	case DRM_FORMAT_XBGR8888:
2969 	case DRM_FORMAT_ABGR8888:
2970 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2971 		break;
2972 	case DRM_FORMAT_NV21:
2973 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2974 		break;
2975 	case DRM_FORMAT_NV12:
2976 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2977 		break;
2978 	case DRM_FORMAT_P010:
2979 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
2980 		break;
2981 	case DRM_FORMAT_XRGB16161616F:
2982 	case DRM_FORMAT_ARGB16161616F:
2983 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
2984 		break;
2985 	case DRM_FORMAT_XBGR16161616F:
2986 	case DRM_FORMAT_ABGR16161616F:
2987 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
2988 		break;
2989 	case DRM_FORMAT_XRGB16161616:
2990 	case DRM_FORMAT_ARGB16161616:
2991 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
2992 		break;
2993 	case DRM_FORMAT_XBGR16161616:
2994 	case DRM_FORMAT_ABGR16161616:
2995 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
2996 		break;
2997 	default:
2998 		drm_err(adev_to_drm(adev),
2999 			"Unsupported screen format %p4cc\n",
3000 			&fb->format->format);
3001 		return -EINVAL;
3002 	}
3003 
3004 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
3005 	case DRM_MODE_ROTATE_0:
3006 		plane_info->rotation = ROTATION_ANGLE_0;
3007 		break;
3008 	case DRM_MODE_ROTATE_90:
3009 		plane_info->rotation = ROTATION_ANGLE_90;
3010 		break;
3011 	case DRM_MODE_ROTATE_180:
3012 		plane_info->rotation = ROTATION_ANGLE_180;
3013 		break;
3014 	case DRM_MODE_ROTATE_270:
3015 		plane_info->rotation = ROTATION_ANGLE_270;
3016 		break;
3017 	default:
3018 		plane_info->rotation = ROTATION_ANGLE_0;
3019 		break;
3020 	}
3021 
3022 
3023 	plane_info->visible = true;
3024 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
3025 
3026 	plane_info->layer_index = plane_state->normalized_zpos;
3027 
3028 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
3029 					  &plane_info->color_space);
3030 	if (ret)
3031 		return ret;
3032 
3033 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
3034 					   plane_info->rotation,
3035 					   &plane_info->tiling_info,
3036 					   &plane_info->plane_size,
3037 					   &plane_info->dcc, address,
3038 					   tmz_surface);
3039 	if (ret)
3040 		return ret;
3041 
3042 	amdgpu_dm_plane_fill_blending_from_plane_state(
3043 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
3044 		&plane_info->global_alpha, &plane_info->global_alpha_value);
3045 
3046 	return 0;
3047 }
3048 
3049 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
3050 				    struct dc_plane_state *dc_plane_state,
3051 				    struct drm_plane_state *plane_state,
3052 				    struct drm_crtc_state *crtc_state)
3053 {
3054 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3055 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
3056 	struct dc_scaling_info scaling_info;
3057 	struct dc_plane_info plane_info;
3058 	int ret;
3059 
3060 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
3061 	if (ret)
3062 		return ret;
3063 
3064 	dc_plane_state->src_rect = scaling_info.src_rect;
3065 	dc_plane_state->dst_rect = scaling_info.dst_rect;
3066 	dc_plane_state->clip_rect = scaling_info.clip_rect;
3067 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
3068 
3069 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
3070 					  &plane_info,
3071 					  &dc_plane_state->address,
3072 					  afb->tmz_surface);
3073 	if (ret)
3074 		return ret;
3075 
3076 	dc_plane_state->format = plane_info.format;
3077 	dc_plane_state->color_space = plane_info.color_space;
3078 	dc_plane_state->format = plane_info.format;
3079 	dc_plane_state->plane_size = plane_info.plane_size;
3080 	dc_plane_state->rotation = plane_info.rotation;
3081 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
3082 	dc_plane_state->stereo_format = plane_info.stereo_format;
3083 	dc_plane_state->tiling_info = plane_info.tiling_info;
3084 	dc_plane_state->visible = plane_info.visible;
3085 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
3086 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
3087 	dc_plane_state->global_alpha = plane_info.global_alpha;
3088 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
3089 	dc_plane_state->dcc = plane_info.dcc;
3090 	dc_plane_state->layer_index = plane_info.layer_index;
3091 	dc_plane_state->flip_int_enabled = true;
3092 
3093 	/*
3094 	 * Always set input transfer function, since plane state is refreshed
3095 	 * every time.
3096 	 */
3097 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
3098 						plane_state,
3099 						dc_plane_state);
3100 	if (ret)
3101 		return ret;
3102 
3103 	return 0;
3104 }
3105 
3106 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
3107 				      struct rect *dirty_rect, int32_t x,
3108 				      s32 y, s32 width, s32 height,
3109 				      int *i, bool ffu)
3110 {
3111 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
3112 
3113 	dirty_rect->x = x;
3114 	dirty_rect->y = y;
3115 	dirty_rect->width = width;
3116 	dirty_rect->height = height;
3117 
3118 	if (ffu)
3119 		drm_dbg(plane->dev,
3120 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
3121 			plane->base.id, width, height);
3122 	else
3123 		drm_dbg(plane->dev,
3124 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
3125 			plane->base.id, x, y, width, height);
3126 
3127 	(*i)++;
3128 }
3129 
3130 /**
3131  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
3132  *
3133  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
3134  *         remote fb
3135  * @old_plane_state: Old state of @plane
3136  * @new_plane_state: New state of @plane
3137  * @crtc_state: New state of CRTC connected to the @plane
3138  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
3139  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
3140  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
3141  *             that have changed will be updated. If PSR SU is not enabled,
3142  *             or if damage clips are not available, the entire screen will be updated.
3143  * @dirty_regions_changed: dirty regions changed
3144  *
3145  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
3146  * (referred to as "damage clips" in DRM nomenclature) that require updating on
3147  * the eDP remote buffer. The responsibility of specifying the dirty regions is
3148  * amdgpu_dm's.
3149  *
3150  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
3151  * plane with regions that require flushing to the eDP remote buffer. In
3152  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
3153  * implicitly provide damage clips without any client support via the plane
3154  * bounds.
3155  */
3156 static void fill_dc_dirty_rects(struct drm_plane *plane,
3157 				struct drm_plane_state *old_plane_state,
3158 				struct drm_plane_state *new_plane_state,
3159 				struct drm_crtc_state *crtc_state,
3160 				struct dc_flip_addrs *flip_addrs,
3161 				bool is_psr_su,
3162 				bool *dirty_regions_changed)
3163 {
3164 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3165 	struct rect *dirty_rects = flip_addrs->dirty_rects;
3166 	u32 num_clips = 0;
3167 	struct drm_mode_rect *clips = NULL;
3168 	bool bb_changed;
3169 	bool fb_changed;
3170 	u32 i = 0;
3171 	*dirty_regions_changed = false;
3172 
3173 	/*
3174 	 * Cursor plane has it's own dirty rect update interface. See
3175 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
3176 	 */
3177 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
3178 		return;
3179 
3180 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
3181 		goto ffu;
3182 
3183 	if (!new_plane_state->ignore_damage_clips) {
3184 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
3185 		clips = drm_plane_get_damage_clips(new_plane_state);
3186 	}
3187 
3188 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
3189 						   is_psr_su)))
3190 		goto ffu;
3191 
3192 	if (!dm_crtc_state->mpo_requested) {
3193 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
3194 			goto ffu;
3195 
3196 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
3197 			fill_dc_dirty_rect(new_plane_state->plane,
3198 					   &dirty_rects[flip_addrs->dirty_rect_count],
3199 					   clips->x1, clips->y1,
3200 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
3201 					   &flip_addrs->dirty_rect_count,
3202 					   false);
3203 		return;
3204 	}
3205 
3206 	/*
3207 	 * MPO is requested. Add entire plane bounding box to dirty rects if
3208 	 * flipped to or damaged.
3209 	 *
3210 	 * If plane is moved or resized, also add old bounding box to dirty
3211 	 * rects.
3212 	 */
3213 	fb_changed = old_plane_state->fb->base.id !=
3214 		     new_plane_state->fb->base.id;
3215 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
3216 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
3217 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
3218 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
3219 
3220 	drm_dbg(plane->dev,
3221 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
3222 		new_plane_state->plane->base.id,
3223 		bb_changed, fb_changed, num_clips);
3224 
3225 	*dirty_regions_changed = bb_changed;
3226 
3227 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
3228 		goto ffu;
3229 
3230 	if (bb_changed) {
3231 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3232 				   new_plane_state->crtc_x,
3233 				   new_plane_state->crtc_y,
3234 				   new_plane_state->crtc_w,
3235 				   new_plane_state->crtc_h, &i, false);
3236 
3237 		/* Add old plane bounding-box if plane is moved or resized */
3238 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3239 				   old_plane_state->crtc_x,
3240 				   old_plane_state->crtc_y,
3241 				   old_plane_state->crtc_w,
3242 				   old_plane_state->crtc_h, &i, false);
3243 	}
3244 
3245 	if (num_clips) {
3246 		for (; i < num_clips; clips++)
3247 			fill_dc_dirty_rect(new_plane_state->plane,
3248 					   &dirty_rects[i], clips->x1,
3249 					   clips->y1, clips->x2 - clips->x1,
3250 					   clips->y2 - clips->y1, &i, false);
3251 	} else if (fb_changed && !bb_changed) {
3252 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3253 				   new_plane_state->crtc_x,
3254 				   new_plane_state->crtc_y,
3255 				   new_plane_state->crtc_w,
3256 				   new_plane_state->crtc_h, &i, false);
3257 	}
3258 
3259 	flip_addrs->dirty_rect_count = i;
3260 	return;
3261 
3262 ffu:
3263 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
3264 			   dm_crtc_state->base.mode.crtc_hdisplay,
3265 			   dm_crtc_state->base.mode.crtc_vdisplay,
3266 			   &flip_addrs->dirty_rect_count, true);
3267 }
3268 
3269 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
3270 					    struct dc_state *dc_state,
3271 					    struct dsc_mst_fairness_vars *vars)
3272 {
3273 	struct dc_stream_state *stream = NULL;
3274 	struct drm_connector *connector;
3275 	struct drm_connector_state *new_con_state;
3276 	struct amdgpu_dm_connector *aconnector;
3277 	struct dm_connector_state *dm_conn_state;
3278 	int i, j, ret;
3279 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
3280 
3281 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3282 
3283 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3284 			continue;
3285 
3286 		aconnector = to_amdgpu_dm_connector(connector);
3287 
3288 		if (!aconnector->mst_output_port)
3289 			continue;
3290 
3291 		if (!new_con_state || !new_con_state->crtc)
3292 			continue;
3293 
3294 		dm_conn_state = to_dm_connector_state(new_con_state);
3295 
3296 		for (j = 0; j < dc_state->stream_count; j++) {
3297 			stream = dc_state->streams[j];
3298 			if (!stream)
3299 				continue;
3300 
3301 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
3302 				break;
3303 
3304 			stream = NULL;
3305 		}
3306 
3307 		if (!stream)
3308 			continue;
3309 
3310 		pbn_div = dm_mst_get_pbn_divider(stream->link);
3311 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
3312 		for (j = 0; j < dc_state->stream_count; j++) {
3313 			if (vars[j].aconnector == aconnector) {
3314 				pbn = vars[j].pbn;
3315 				break;
3316 			}
3317 		}
3318 
3319 		if (j == dc_state->stream_count || pbn_div == 0)
3320 			continue;
3321 
3322 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
3323 
3324 		if (stream->timing.flags.DSC != 1) {
3325 			dm_conn_state->pbn = pbn;
3326 			dm_conn_state->vcpi_slots = slot_num;
3327 
3328 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
3329 							   dm_conn_state->pbn, false);
3330 			if (ret < 0)
3331 				return ret;
3332 
3333 			continue;
3334 		}
3335 
3336 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
3337 		if (vcpi < 0)
3338 			return vcpi;
3339 
3340 		dm_conn_state->pbn = pbn;
3341 		dm_conn_state->vcpi_slots = vcpi;
3342 	}
3343 	return 0;
3344 }
3345 
3346 static void manage_dm_interrupts(struct amdgpu_device *adev,
3347 				 struct amdgpu_crtc *acrtc,
3348 				 struct dm_crtc_state *acrtc_state)
3349 {	/*
3350 	 * We cannot be sure that the frontend index maps to the same
3351 	 * backend index - some even map to more than one.
3352 	 * So we have to go through the CRTC to find the right IRQ.
3353 	 */
3354 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
3355 			adev,
3356 			acrtc->crtc_id);
3357 	struct drm_device *dev = adev_to_drm(adev);
3358 
3359 	struct drm_vblank_crtc_config config = {0};
3360 	struct dc_crtc_timing *timing;
3361 	int offdelay;
3362 
3363 	if (acrtc_state) {
3364 		timing = &acrtc_state->stream->timing;
3365 
3366 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
3367 			   IP_VERSION(3, 5, 0) ||
3368 			   !(adev->flags & AMD_IS_APU)) {
3369 			/*
3370 			 * Older HW and DGPU have issues with instant off;
3371 			 * use a 2 frame offdelay.
3372 			 */
3373 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
3374 						      timing->v_total *
3375 						      timing->h_total,
3376 						      timing->pix_clk_100hz);
3377 
3378 			config.offdelay_ms = offdelay ?: 30;
3379 		} else {
3380 			/* offdelay_ms = 0 will never disable vblank */
3381 			config.offdelay_ms = 1;
3382 			config.disable_immediate = true;
3383 		}
3384 
3385 		drm_crtc_vblank_on_config(&acrtc->base,
3386 					  &config);
3387 		/*
3388 		 * Since pflip_high_irq is no longer registered for DCN, grab an
3389 		 * extra reference to vupdate irq instead to workaround this
3390 		 * issue:
3391 		 * https://gitlab.freedesktop.org/drm/amd/-/work_items/3936
3392 		 *
3393 		 * The callbacks to drm_vblank_on/off should really take care of
3394 		 * this though.
3395 		 */
3396 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3397 		case IP_VERSION(3, 0, 0):
3398 		case IP_VERSION(3, 0, 2):
3399 		case IP_VERSION(3, 0, 3):
3400 		case IP_VERSION(3, 2, 0):
3401 			if (amdgpu_irq_get(adev, &adev->vupdate_irq, irq_type))
3402 				drm_err(dev, "DM_IRQ: Cannot get vupdate irq!\n");
3403 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3404 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
3405 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
3406 #endif
3407 		}
3408 
3409 	} else {
3410 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
3411 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3412 		case IP_VERSION(3, 0, 0):
3413 		case IP_VERSION(3, 0, 2):
3414 		case IP_VERSION(3, 0, 3):
3415 		case IP_VERSION(3, 2, 0):
3416 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3417 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
3418 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
3419 #endif
3420 			if (amdgpu_irq_put(adev, &adev->vupdate_irq, irq_type))
3421 				drm_err(dev, "DM_IRQ: Cannot put vupdate irq!\n");
3422 		}
3423 
3424 		drm_crtc_vblank_off(&acrtc->base);
3425 	}
3426 }
3427 
3428 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
3429 				      struct amdgpu_crtc *acrtc)
3430 {
3431 	int irq_type =
3432 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
3433 
3434 	/* GRPH_PFLIP is not used on DCN; nothing to reapply. */
3435 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0)
3436 		return;
3437 
3438 	/**
3439 	 * This reads the current state for the IRQ and force reapplies
3440 	 * the setting to hardware.
3441 	 */
3442 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
3443 }
3444 
3445 STATIC_IFN_KUNIT bool
3446 is_scaling_state_different(const struct dm_connector_state *dm_state,
3447 			   const struct dm_connector_state *old_dm_state)
3448 {
3449 	if (dm_state->scaling != old_dm_state->scaling)
3450 		return true;
3451 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
3452 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
3453 			return true;
3454 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
3455 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
3456 			return true;
3457 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
3458 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
3459 		return true;
3460 	return false;
3461 }
3462 EXPORT_IF_KUNIT(is_scaling_state_different);
3463 
3464 STATIC_IFN_KUNIT bool
3465 is_content_protection_different(struct drm_crtc_state *new_crtc_state,
3466 				struct drm_crtc_state *old_crtc_state,
3467 				struct drm_connector_state *new_conn_state,
3468 				struct drm_connector_state *old_conn_state,
3469 				const struct drm_connector *connector,
3470 				struct hdcp_workqueue *hdcp_w)
3471 {
3472 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3473 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3474 
3475 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
3476 		connector->index, connector->status, connector->dpms);
3477 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
3478 		old_conn_state->content_protection, new_conn_state->content_protection);
3479 
3480 	if (old_crtc_state)
3481 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
3482 		old_crtc_state->enable,
3483 		old_crtc_state->active,
3484 		old_crtc_state->mode_changed,
3485 		old_crtc_state->active_changed,
3486 		old_crtc_state->connectors_changed);
3487 
3488 	if (new_crtc_state)
3489 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
3490 		new_crtc_state->enable,
3491 		new_crtc_state->active,
3492 		new_crtc_state->mode_changed,
3493 		new_crtc_state->active_changed,
3494 		new_crtc_state->connectors_changed);
3495 
3496 	/* hdcp content type change */
3497 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
3498 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
3499 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3500 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
3501 		return true;
3502 	}
3503 
3504 	/* CP is being re enabled, ignore this */
3505 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
3506 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3507 		if (new_crtc_state && new_crtc_state->mode_changed) {
3508 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3509 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
3510 			return true;
3511 		}
3512 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
3513 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
3514 		return false;
3515 	}
3516 
3517 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
3518 	 *
3519 	 * Handles:	UNDESIRED -> ENABLED
3520 	 */
3521 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
3522 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3523 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3524 
3525 	/* Stream removed and re-enabled
3526 	 *
3527 	 * Can sometimes overlap with the HPD case,
3528 	 * thus set update_hdcp to false to avoid
3529 	 * setting HDCP multiple times.
3530 	 *
3531 	 * Handles:	DESIRED -> DESIRED (Special case)
3532 	 */
3533 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
3534 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
3535 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3536 		dm_con_state->update_hdcp = false;
3537 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
3538 			__func__);
3539 		return true;
3540 	}
3541 
3542 	/* Hot-plug, headless s3, dpms
3543 	 *
3544 	 * Only start HDCP if the display is connected/enabled.
3545 	 * update_hdcp flag will be set to false until the next
3546 	 * HPD comes in.
3547 	 *
3548 	 * Handles:	DESIRED -> DESIRED (Special case)
3549 	 */
3550 	if (dm_con_state->update_hdcp &&
3551 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
3552 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
3553 		dm_con_state->update_hdcp = false;
3554 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
3555 			__func__);
3556 		return true;
3557 	}
3558 
3559 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
3560 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3561 			if (new_crtc_state && new_crtc_state->mode_changed) {
3562 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
3563 					__func__);
3564 				return true;
3565 			}
3566 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
3567 				__func__);
3568 			return false;
3569 		}
3570 
3571 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
3572 		return false;
3573 	}
3574 
3575 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
3576 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
3577 			__func__);
3578 		return true;
3579 	}
3580 
3581 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
3582 	return false;
3583 }
3584 EXPORT_IF_KUNIT(is_content_protection_different);
3585 
3586 static void remove_stream(struct amdgpu_device *adev,
3587 			  struct amdgpu_crtc *acrtc,
3588 			  struct dc_stream_state *stream)
3589 {
3590 	/* this is the update mode case */
3591 
3592 	acrtc->otg_inst = -1;
3593 	acrtc->enabled = false;
3594 }
3595 
3596 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
3597 {
3598 	struct drm_plane *plane;
3599 	struct drm_plane_state *old_plane_state;
3600 	int i;
3601 
3602 	/*
3603 	 * TODO: Make this per-stream so we don't issue redundant updates for
3604 	 * commits with multiple streams.
3605 	 */
3606 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
3607 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
3608 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
3609 }
3610 
3611 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
3612 {
3613 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
3614 
3615 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
3616 }
3617 
3618 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
3619 				    struct drm_plane_state *old_plane_state,
3620 				    struct dc_stream_update *update)
3621 {
3622 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
3623 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
3624 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
3625 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
3626 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3627 	uint64_t address = afb ? afb->address : 0;
3628 	struct dc_cursor_position position = {0};
3629 	struct dc_cursor_attributes attributes;
3630 	int ret;
3631 
3632 	if (!plane->state->fb && !old_plane_state->fb)
3633 		return;
3634 
3635 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
3636 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
3637 		       plane->state->crtc_h);
3638 
3639 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
3640 	if (ret)
3641 		return;
3642 
3643 	if (!position.enable) {
3644 		/* turn off cursor */
3645 		if (crtc_state && crtc_state->stream) {
3646 			dc_stream_set_cursor_position(crtc_state->stream,
3647 						      &position);
3648 			update->cursor_position = &crtc_state->stream->cursor_position;
3649 		}
3650 		return;
3651 	}
3652 
3653 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
3654 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
3655 
3656 	memset(&attributes, 0, sizeof(attributes));
3657 	attributes.address.high_part = upper_32_bits(address);
3658 	attributes.address.low_part  = lower_32_bits(address);
3659 	attributes.width             = plane->state->crtc_w;
3660 	attributes.height            = plane->state->crtc_h;
3661 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
3662 	attributes.rotation_angle    = 0;
3663 	attributes.attribute_flags.value = 0;
3664 
3665 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
3666 	 * legacy gamma setup.
3667 	 */
3668 	if (crtc_state->cm_is_degamma_srgb &&
3669 	    adev->dm.dc->caps.color.dpp.gamma_corr)
3670 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
3671 
3672 	if (afb)
3673 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
3674 
3675 	if (crtc_state->stream) {
3676 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
3677 						     &attributes))
3678 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
3679 
3680 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
3681 
3682 		if (!dc_stream_set_cursor_position(crtc_state->stream,
3683 						   &position))
3684 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
3685 
3686 		update->cursor_position = &crtc_state->stream->cursor_position;
3687 	}
3688 }
3689 
3690 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
3691 					  struct amdgpu_crtc *acrtc_attach,
3692 					  const struct dm_crtc_state *acrtc_state,
3693 					  const u64 current_ts)
3694 {
3695 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
3696 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
3697 	struct amdgpu_dm_connector *aconn =
3698 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
3699 
3700 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
3701 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
3702 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
3703 		if (aconn->sr_skip_count > 0)
3704 			aconn->sr_skip_count--;
3705 
3706 		/* Allow SR when skip count is 0. */
3707 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
3708 
3709 		/*
3710 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
3711 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
3712 		 * can be enabled immediately once OS demonstrates an
3713 		 * adequate number of fast atomic commits to notify KMD
3714 		 * of update events.
3715 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
3716 		 */
3717 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
3718 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
3719 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
3720 				psr_event_hw_programming, false);
3721 
3722 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
3723 				replay_event_hw_programming, false);
3724 		}
3725 	} else {
3726 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
3727 	}
3728 }
3729 
3730 static void dm_arm_vblank_event(struct amdgpu_crtc *acrtc,
3731 				struct dm_crtc_state *acrtc_state,
3732 				bool pflip_update,
3733 				bool cursor_update)
3734 {
3735 	assert_spin_locked(&acrtc->base.dev->event_lock);
3736 
3737 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
3738 		return;
3739 
3740 	if (pflip_update) {
3741 		WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
3742 		WARN_ON(acrtc->event);
3743 
3744 		acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
3745 		acrtc->event = acrtc->base.state->event;
3746 		acrtc->base.state->event = NULL;
3747 
3748 		drm_dbg_state(acrtc->base.dev,
3749 			      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
3750 			      acrtc->crtc_id);
3751 	} else if (cursor_update) {
3752 		acrtc->event = acrtc->base.state->event;
3753 		acrtc->base.state->event = NULL;
3754 	}
3755 }
3756 
3757 /**
3758  * dm_arm_vblank_event_pre_programming - Prepare for programming
3759  * @acrtc: The amdgpu CRTC to prepare
3760  * @acrtc_state: The new CRTC state
3761  * @pflip_update: Whether a page flip is being programmed
3762  * @cursor_update: Whether a cursor update is being programmed
3763  *
3764  * Grab a reference on the vblank counter if a page flip or cursor update is to
3765  * be programmed. Do this before programming so the HW is not in any
3766  * idle-optimized state (such as PSR).
3767  */
3768 static void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *acrtc,
3769 						struct dm_crtc_state *acrtc_state,
3770 						bool pflip_update,
3771 						bool cursor_update)
3772 {
3773 	assert_spin_locked(&acrtc->base.dev->event_lock);
3774 
3775 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
3776 		return;
3777 
3778 	if (pflip_update || cursor_update)
3779 		drm_crtc_vblank_get(&acrtc->base);
3780 }
3781 
3782 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
3783 				    struct drm_device *dev,
3784 				    struct amdgpu_display_manager *dm,
3785 				    struct drm_crtc *pcrtc,
3786 				    bool wait_for_vblank)
3787 {
3788 	u32 i;
3789 	u64 timestamp_ns = ktime_get_ns();
3790 	struct drm_plane *plane;
3791 	struct drm_plane_state *old_plane_state, *new_plane_state;
3792 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
3793 	struct drm_crtc_state *new_pcrtc_state =
3794 			drm_atomic_get_new_crtc_state(state, pcrtc);
3795 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
3796 	struct dm_crtc_state *dm_old_crtc_state =
3797 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
3798 	int planes_count = 0, vpos, hpos;
3799 	unsigned long flags;
3800 	u32 target_vblank, last_flip_vblank;
3801 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
3802 	bool cursor_update = false;
3803 	bool pflip_present = false;
3804 	bool immediate_flip = false;
3805 	bool flip_latched_during_prog = false;
3806 	bool dirty_rects_changed = false;
3807 	bool updated_planes_and_streams = false;
3808 	struct {
3809 		struct dc_surface_update surface_updates[MAX_SURFACES];
3810 		struct dc_plane_info plane_infos[MAX_SURFACES];
3811 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3812 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3813 		struct dc_stream_update stream_update;
3814 	} *bundle;
3815 
3816 	bundle = kzalloc_obj(*bundle);
3817 
3818 	if (!bundle) {
3819 		drm_err(dev, "Failed to allocate update bundle\n");
3820 		goto cleanup;
3821 	}
3822 
3823 	/*
3824 	 * Disable the cursor first if we're disabling all the planes.
3825 	 * It'll remain on the screen after the planes are re-enabled
3826 	 * if we don't.
3827 	 *
3828 	 * If the cursor is transitioning from native to overlay mode, the
3829 	 * native cursor needs to be disabled first.
3830 	 */
3831 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
3832 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
3833 		struct dc_cursor_position cursor_position = {0};
3834 
3835 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
3836 						   &cursor_position))
3837 			drm_err(dev, "DC failed to disable native cursor\n");
3838 
3839 		bundle->stream_update.cursor_position =
3840 				&acrtc_state->stream->cursor_position;
3841 	}
3842 
3843 	if (acrtc_state->active_planes == 0 &&
3844 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
3845 		amdgpu_dm_commit_cursors(state);
3846 
3847 	/* update planes when needed */
3848 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
3849 		struct drm_crtc *crtc = new_plane_state->crtc;
3850 		struct drm_crtc_state *new_crtc_state;
3851 		struct drm_framebuffer *fb = new_plane_state->fb;
3852 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
3853 		bool plane_needs_flip;
3854 		struct dc_plane_state *dc_plane;
3855 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
3856 
3857 		/* Cursor plane is handled after stream updates */
3858 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
3859 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
3860 			if ((fb && crtc == pcrtc) ||
3861 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
3862 				cursor_update = true;
3863 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
3864 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
3865 			}
3866 
3867 			continue;
3868 		}
3869 
3870 		if (!fb || !crtc || pcrtc != crtc)
3871 			continue;
3872 
3873 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
3874 		if (!new_crtc_state->active)
3875 			continue;
3876 
3877 		dc_plane = dm_new_plane_state->dc_state;
3878 		if (!dc_plane)
3879 			continue;
3880 
3881 		bundle->surface_updates[planes_count].surface = dc_plane;
3882 		if (new_pcrtc_state->color_mgmt_changed) {
3883 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
3884 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
3885 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
3886 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
3887 			bundle->surface_updates[planes_count].cm = &dc_plane->cm;
3888 		}
3889 
3890 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
3891 				     &bundle->scaling_infos[planes_count]);
3892 
3893 		bundle->surface_updates[planes_count].scaling_info =
3894 			&bundle->scaling_infos[planes_count];
3895 
3896 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
3897 
3898 		pflip_present = pflip_present || plane_needs_flip;
3899 
3900 		if (!plane_needs_flip) {
3901 			planes_count += 1;
3902 			continue;
3903 		}
3904 
3905 		fill_dc_plane_info_and_addr(
3906 			dm->adev, new_plane_state,
3907 			&bundle->plane_infos[planes_count],
3908 			&bundle->flip_addrs[planes_count].address,
3909 			afb->tmz_surface);
3910 
3911 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
3912 				 new_plane_state->plane->index,
3913 				 bundle->plane_infos[planes_count].dcc.enable);
3914 
3915 		bundle->surface_updates[planes_count].plane_info =
3916 			&bundle->plane_infos[planes_count];
3917 
3918 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
3919 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
3920 			fill_dc_dirty_rects(plane, old_plane_state,
3921 					    new_plane_state, new_crtc_state,
3922 					    &bundle->flip_addrs[planes_count],
3923 					    acrtc_state->stream->link->psr_settings.psr_version ==
3924 					    DC_PSR_VERSION_SU_1,
3925 					    &dirty_rects_changed);
3926 
3927 			/*
3928 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
3929 			 * and enabled it again after dirty regions are stable to avoid video glitch.
3930 			 * PSR-SU will be enabled in
3931 			 * amdgpu_dm_crtc_vblank_control_worker() if user
3932 			 * pause the video during the PSR-SU was disabled.
3933 			 */
3934 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
3935 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
3936 			    dirty_rects_changed) {
3937 				mutex_lock(&dm->dc_lock);
3938 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
3939 				timestamp_ns;
3940 				dc_exit_ips_for_hw_access(dm->dc);
3941 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
3942 					psr_event_hw_programming, true);
3943 				mutex_unlock(&dm->dc_lock);
3944 			}
3945 		}
3946 
3947 		/*
3948 		 * Only allow immediate flips for fast updates that don't
3949 		 * change memory domain, FB pitch, DCC state, rotation or
3950 		 * mirroring.
3951 		 *
3952 		 * dm_crtc_helper_atomic_check() only accepts async flips with
3953 		 * fast updates.
3954 		 */
3955 		if (crtc->state->async_flip &&
3956 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
3957 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
3958 			drm_warn_once(state->dev,
3959 				      "[PLANE:%d:%s] async flip with non-fast update\n",
3960 				      plane->base.id, plane->name);
3961 
3962 		bundle->flip_addrs[planes_count].flip_immediate =
3963 			crtc->state->async_flip &&
3964 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
3965 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
3966 
3967 		immediate_flip |= bundle->flip_addrs[planes_count].flip_immediate;
3968 
3969 		timestamp_ns = ktime_get_ns();
3970 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
3971 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
3972 		bundle->surface_updates[planes_count].surface = dc_plane;
3973 
3974 		if (!bundle->surface_updates[planes_count].surface) {
3975 			drm_err(dev, "No surface for CRTC: id=%d\n",
3976 					acrtc_attach->crtc_id);
3977 			continue;
3978 		}
3979 
3980 		if (plane == pcrtc->primary)
3981 			amdgpu_dm_update_freesync_state_on_stream(
3982 				dm,
3983 				acrtc_state,
3984 				acrtc_state->stream,
3985 				dc_plane,
3986 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
3987 
3988 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
3989 				 __func__,
3990 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
3991 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
3992 
3993 		planes_count += 1;
3994 
3995 	}
3996 
3997 	if (pflip_present) {
3998 		if (!vrr_active) {
3999 			/* Use old throttling in non-vrr fixed refresh rate mode
4000 			 * to keep flip scheduling based on target vblank counts
4001 			 * working in a backwards compatible way, e.g., for
4002 			 * clients using the GLX_OML_sync_control extension or
4003 			 * DRI3/Present extension with defined target_msc.
4004 			 */
4005 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
4006 		} else {
4007 			/* For variable refresh rate mode only:
4008 			 * Get vblank of last completed flip to avoid > 1 vrr
4009 			 * flips per video frame by use of throttling, but allow
4010 			 * flip programming anywhere in the possibly large
4011 			 * variable vrr vblank interval for fine-grained flip
4012 			 * timing control and more opportunity to avoid stutter
4013 			 * on late submission of flips.
4014 			 */
4015 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4016 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
4017 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4018 		}
4019 
4020 		target_vblank = last_flip_vblank + wait_for_vblank;
4021 
4022 		/*
4023 		 * Wait until we're out of the vertical blank period before the one
4024 		 * targeted by the flip
4025 		 */
4026 		while ((acrtc_attach->enabled &&
4027 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
4028 							    0, &vpos, &hpos, NULL,
4029 							    NULL, &pcrtc->hwmode)
4030 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
4031 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
4032 			(int)(target_vblank -
4033 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
4034 			usleep_range(1000, 1100);
4035 		}
4036 
4037 		if (acrtc_state->stream) {
4038 			if (acrtc_state->freesync_vrr_info_changed)
4039 				bundle->stream_update.vrr_infopacket =
4040 					&acrtc_state->stream->vrr_infopacket;
4041 		}
4042 	}
4043 
4044 	scoped_guard(spinlock_irqsave, &pcrtc->dev->event_lock) {
4045 		dm_arm_vblank_event_pre_programming(acrtc_attach, acrtc_state,
4046 						    pflip_present,
4047 						    cursor_update);
4048 		/*
4049 		 * DCE depends on a combination of GRPH_FLIP, VLINE0, and
4050 		 * VUPDATE for event delivery. Only GRPH_FLIP handler can send
4051 		 * pflip events, and it only fires if HW latched to the flip.
4052 		 * Maintain legacy behavior by arming event before programming.
4053 		 */
4054 		if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) {
4055 			dm_arm_vblank_event(acrtc_attach, acrtc_state,
4056 					    pflip_present, cursor_update);
4057 		}
4058 	}
4059 
4060 	/* Update the planes if changed or disable if we don't have any. */
4061 	if ((planes_count || acrtc_state->active_planes == 0) &&
4062 		acrtc_state->stream) {
4063 		/*
4064 		 * If PSR or idle optimizations are enabled then flush out
4065 		 * any pending work before hardware programming.
4066 		 */
4067 		if (dm->vblank_control_workqueue)
4068 			flush_workqueue(dm->vblank_control_workqueue);
4069 
4070 		bundle->stream_update.stream = acrtc_state->stream;
4071 		if (new_pcrtc_state->mode_changed) {
4072 			bundle->stream_update.src = acrtc_state->stream->src;
4073 			bundle->stream_update.dst = acrtc_state->stream->dst;
4074 		}
4075 
4076 		if (new_pcrtc_state->color_mgmt_changed) {
4077 			/*
4078 			 * TODO: This isn't fully correct since we've actually
4079 			 * already modified the stream in place.
4080 			 */
4081 			bundle->stream_update.gamut_remap =
4082 				&acrtc_state->stream->gamut_remap_matrix;
4083 			bundle->stream_update.output_csc_transform =
4084 				&acrtc_state->stream->csc_color_matrix;
4085 			bundle->stream_update.out_transfer_func =
4086 				&acrtc_state->stream->out_transfer_func;
4087 			bundle->stream_update.lut3d_func =
4088 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
4089 			bundle->stream_update.func_shaper =
4090 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
4091 		}
4092 
4093 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
4094 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
4095 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
4096 
4097 		/*
4098 		 * If FreeSync state on the stream has changed then we need to
4099 		 * re-adjust the min/max bounds now that DC doesn't handle this
4100 		 * as part of commit.
4101 		 */
4102 		if (amdgpu_dm_is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
4103 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4104 			dc_stream_adjust_vmin_vmax(
4105 				dm->dc, acrtc_state->stream,
4106 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
4107 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4108 		}
4109 		mutex_lock(&dm->dc_lock);
4110 		update_planes_and_stream_adapter(dm->dc,
4111 					 acrtc_state->update_type,
4112 					 planes_count,
4113 					 acrtc_state->stream,
4114 					 &bundle->stream_update,
4115 					 bundle->surface_updates);
4116 		updated_planes_and_streams = true;
4117 
4118 		/**
4119 		 * Enable or disable the interrupts on the backend.
4120 		 *
4121 		 * Most pipes are put into power gating when unused.
4122 		 *
4123 		 * When power gating is enabled on a pipe we lose the
4124 		 * interrupt enablement state when power gating is disabled.
4125 		 *
4126 		 * So we need to update the IRQ control state in hardware
4127 		 * whenever the pipe turns on (since it could be previously
4128 		 * power gated) or off (since some pipes can't be power gated
4129 		 * on some ASICs).
4130 		 */
4131 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
4132 			dm_update_pflip_irq_state(drm_to_adev(dev),
4133 						  acrtc_attach);
4134 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
4135 					      timestamp_ns);
4136 		mutex_unlock(&dm->dc_lock);
4137 	}
4138 
4139 	/*
4140 	 * Update cursor state *after* programming all the planes.
4141 	 * This avoids redundant programming in the case where we're going
4142 	 * to be disabling a single plane - those pipes are being disabled.
4143 	 */
4144 	if (acrtc_state->active_planes &&
4145 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
4146 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
4147 		amdgpu_dm_commit_cursors(state);
4148 
4149 	/*
4150 	 * DCN specific vblank handling
4151 	 * ============================
4152 	 *
4153 	 * With the event_lock held, arm the vblank event, and determine whether
4154 	 * deliver it immediately, or in VUPDATE_NO_LOCK IRQ (i.e. HW latch
4155 	 * point) handler. Do this *after* programming so that the IRQ handler
4156 	 * will not deliver the event before HW laches onto the programmed
4157 	 * values:
4158 	 *
4159 	 *     Commit thread      IRQ handler                       HW
4160 	 *     -----------------------------------------------------------------
4161 	 *     arm_vblank_event()
4162 	 *                                                          vupdate()
4163 	 *                        vupdate_handler()
4164 	 *                          cook_timestamp()
4165 	 *                          # prev flip already latched,
4166 	 *                          # so flip_latched == true.
4167 	 *                          if event_armed && flip_latched:
4168 	 *                            send_vblank_event()
4169 	 *                            # sent before latch, **BAD!**
4170 	 *     hw_program()
4171 	 *                                                          vupdate()
4172 	 *                                                          **latch**
4173 	 *
4174 	 * There's a consequence of arming after: it's possible for HW to latch
4175 	 * between start of HW programming and acrtc->event/pflip_status arming.
4176 	 * When this happens, the IRQ handler will send the event on the next
4177 	 * immediate latch point, even though HW has already latched. This is
4178 	 * handled by optimistically checking for HW latch after programming,
4179 	 * and if latched, send the event immediately:
4180 	 *
4181 	 *     Commit thread             IRQ handler                HW
4182 	 *     -----------------------------------------------------------------
4183 	 *     hw_program()
4184 	 *                                                          vupdate()
4185 	 *                                                          **latch**
4186 	 *                               vupdate_handler()
4187 	 *                                 cook_timestamp()
4188 	 *                                 # event_armed == false
4189 	 *                                 # **no event sent!**
4190 	 *     arm_vblank_event()
4191 	 *     if flip_latched:
4192 	 *       **send_vblank_event()**
4193 	 *       disarm_vblank_event()
4194 	 *
4195 	 * The IRQ handler is expected to cook the timestamp, but we need to
4196 	 * cook the timestamp before optimistic sending as well. That's because
4197 	 * the following sequence is possible:
4198 	 *
4199 	 *     Commit thread              IRQ handler              HW
4200 	 *     -----------------------------------------------------------------
4201 	 *     hw_program()
4202 	 *     arm_vblank_event()
4203 	 *                                                         vupdate()
4204 	 *                                                         **latch**
4205 	 *     if flip_latched:
4206 	 *       # Need cook before send!
4207 	 *       **cook_timestamp()**
4208 	 *       send_vblank_event()
4209 	 *       disarm_vblank_event()
4210 	 *                                vupdate_handler()
4211 	 *                                  cook_timestamp()
4212 	 *                                  # event_armed == false
4213 	 *                                  # no event sent!
4214 	 *
4215 	 * Cooking twice is OK, since DRM scanout accurate timestamps report A)
4216 	 * the previous vactive start if currently in vactive, or B) the next
4217 	 * vactive start if currently in vblank (see &get_vblank_counter). 'A)'
4218 	 * is what we want for the optimistic send, and for 'B)', we'll cook a
4219 	 * timestamp no later than the next IRQ handler run.
4220 	 *
4221 	 * The more correct fix is to wrap programming and arming with the
4222 	 * event_lock and thus serializing it with the IRQ handler. However,
4223 	 * there are various sleep-waits within
4224 	 * update_planes_and_stream_adapter() that makes spin locking illegal.
4225 	 * And on full updates, it can take 1-2 frame-times to return (see
4226 	 * commit_planes_for_stream).
4227 	 *
4228 	 * On DCE, GRPH_PFLIP IRQ is used and takes care of this.
4229 	 */
4230 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
4231 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4232 
4233 		if (updated_planes_and_streams) {
4234 			flip_latched_during_prog =
4235 				!dc_get_flip_pending_on_otg(dm->dc, acrtc_attach->otg_inst);
4236 		}
4237 
4238 		dm_arm_vblank_event(acrtc_attach, acrtc_state,
4239 				    pflip_present, cursor_update);
4240 
4241 		/*
4242 		 * Deliver the event immediately on immediate flip, or on a
4243 		 * update that has already latched.
4244 		 */
4245 		if ((immediate_flip || flip_latched_during_prog) &&
4246 		    acrtc_attach->pflip_status == AMDGPU_FLIP_SUBMITTED &&
4247 		    acrtc_attach->event) {
4248 			drm_crtc_accurate_vblank_count(&acrtc_attach->base);
4249 			drm_crtc_send_vblank_event(&acrtc_attach->base,
4250 						   acrtc_attach->event);
4251 			acrtc_attach->event = NULL;
4252 			drm_crtc_vblank_put(&acrtc_attach->base);
4253 			acrtc_attach->pflip_status = AMDGPU_FLIP_NONE;
4254 		}
4255 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4256 	}
4257 
4258 cleanup:
4259 	kfree(bundle);
4260 }
4261 
4262 /*
4263  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4264  * @crtc_state: the DRM CRTC state
4265  * @stream_state: the DC stream state.
4266  *
4267  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4268  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4269  */
4270 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4271 						struct dc_stream_state *stream_state)
4272 {
4273 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
4274 }
4275 
4276 /**
4277  * amdgpu_dm_crtc_complete_writeback - finish a pending writeback job
4278  * @acrtc: the CRTC whose pending writeback should be completed
4279  *
4280  * Clears the pending state, signals the writeback out fence and releases the
4281  * vblank reference taken in dm_set_writeback() while the writeback was armed.
4282  * The pending flag is tested and cleared under the writeback job lock, so this
4283  * is safe to call concurrently from the completion vblank IRQ
4284  * (dm_crtc_high_irq()) and from the writeback teardown path
4285  * (dm_clear_writeback()); only the caller that observes the pending job
4286  * performs the completion.
4287  *
4288  * Return: true if a pending writeback job was completed by this call.
4289  */
4290 bool amdgpu_dm_crtc_complete_writeback(struct amdgpu_crtc *acrtc)
4291 {
4292 	unsigned long flags;
4293 	bool pending;
4294 
4295 	if (!acrtc->wb_conn)
4296 		return false;
4297 
4298 	spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
4299 	pending = acrtc->wb_pending;
4300 	acrtc->wb_pending = false;
4301 	acrtc->wb_frame_done = false;
4302 	spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
4303 
4304 	if (!pending)
4305 		return false;
4306 
4307 	drm_writeback_signal_completion(acrtc->wb_conn, 0);
4308 	drm_crtc_vblank_put(&acrtc->base);
4309 
4310 	return true;
4311 }
4312 EXPORT_IF_KUNIT(amdgpu_dm_crtc_complete_writeback);
4313 
4314 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
4315 			      struct amdgpu_crtc *acrtc,
4316 			      struct dm_crtc_state *crtc_state)
4317 {
4318 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
4319 
4320 	/*
4321 	 * If the writeback is still pending when it is torn down (its
4322 	 * completion vblank IRQ never fired), signal the out fence so a
4323 	 * waiting client does not stall and release the vblank reference
4324 	 * taken in dm_set_writeback().
4325 	 */
4326 	amdgpu_dm_crtc_complete_writeback(acrtc);
4327 }
4328 
4329 /**
4330  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
4331  * @state: the drm atomic state
4332  * @dm: the display manager to update mod_power on
4333  *
4334  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
4335  * in preparation for hardware programming. See also
4336  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
4337  */
4338 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
4339 					       struct amdgpu_display_manager *dm)
4340 {
4341 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4342 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4343 	struct amdgpu_dm_connector *aconnector;
4344 	struct drm_crtc *crtc;
4345 	int i = 0;
4346 
4347 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4348 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4349 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4350 
4351 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4352 			continue;
4353 
4354 		/*
4355 		 * Update mod_power on modeset event in preparation for hw
4356 		 * programming. Always use the old stream, since it would have
4357 		 * been previously added to mod_power. If old stream is null (on
4358 		 * crtc enable, for example), mod_power will no-op, which is the
4359 		 * desried behavior.
4360 		 */
4361 		if (old_crtc_state->active) {
4362 			scoped_guard(mutex, &dm->dc_lock) {
4363 				dc_exit_ips_for_hw_access(dm->dc);
4364 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
4365 					psr_event_hw_programming, true);
4366 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
4367 					replay_event_hw_programming, true);
4368 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
4369 					replay_event_general_ui, false);
4370 			}
4371 		}
4372 
4373 		if (new_crtc_state->active) {
4374 			aconnector = (struct amdgpu_dm_connector *)
4375 				dm_new_crtc_state->stream->dm_stream_context;
4376 			if (old_crtc_state->active) {
4377 				mod_power_replace_stream(dm->power_module,
4378 					dm_old_crtc_state->stream,
4379 					dm_new_crtc_state->stream,
4380 					&aconnector->psr_caps);
4381 			} else {
4382 				mod_power_add_stream(dm->power_module,
4383 					dm_new_crtc_state->stream,
4384 					&aconnector->psr_caps);
4385 			}
4386 		} else if (old_crtc_state->active) {
4387 			mod_power_remove_stream(dm->power_module,
4388 				dm_old_crtc_state->stream);
4389 		}
4390 	}
4391 }
4392 
4393 /**
4394  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
4395  * @state: the drm atomic state
4396  * @dm: the display manager to update mod_power on
4397  *
4398  * Notify mod_power of mode_change. This needs to be done after dc_stream
4399  * updates have been committed, and VRR parameters have been updated.
4400  */
4401 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
4402 					      struct amdgpu_display_manager *dm)
4403 {
4404 	struct dm_crtc_state *dm_new_crtc_state;
4405 	struct drm_crtc_state *new_crtc_state;
4406 	struct amdgpu_crtc *acrtc;
4407 	struct drm_crtc *crtc;
4408 	int i = 0;
4409 
4410 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4411 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4412 		acrtc = to_amdgpu_crtc(crtc);
4413 
4414 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4415 			continue;
4416 
4417 		if (new_crtc_state->active) {
4418 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
4419 					&acrtc->dm_irq_params.vrr_params);
4420 			mod_power_notify_mode_change(dm->power_module,
4421 						dm_new_crtc_state->stream,
4422 						false);
4423 
4424 			/*
4425 			 * Block PSR / Replay on the new stream until display settles post-modeset.
4426 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
4427 			 * allow_sr_entry becomes true.
4428 			 */
4429 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
4430 				psr_event_hw_programming, true);
4431 
4432 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
4433 				replay_event_hw_programming | replay_event_general_ui,
4434 				true);
4435 		}
4436 	}
4437 
4438 }
4439 
4440 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
4441 					struct dc_state *dc_state)
4442 {
4443 	struct drm_device *dev = state->dev;
4444 	struct amdgpu_device *adev = drm_to_adev(dev);
4445 	struct amdgpu_display_manager *dm = &adev->dm;
4446 	struct drm_crtc *crtc;
4447 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4448 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4449 	struct drm_connector_state *old_con_state;
4450 	struct drm_connector *connector;
4451 	bool mode_set_reset_required = false;
4452 	u32 i;
4453 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
4454 	bool set_backlight_level = false;
4455 
4456 	/* Disable writeback */
4457 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
4458 		struct dm_connector_state *dm_old_con_state;
4459 		struct amdgpu_crtc *acrtc;
4460 
4461 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
4462 			continue;
4463 
4464 		old_crtc_state = NULL;
4465 
4466 		dm_old_con_state = to_dm_connector_state(old_con_state);
4467 		if (!dm_old_con_state->base.crtc)
4468 			continue;
4469 
4470 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
4471 		if (acrtc)
4472 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4473 
4474 		if (!acrtc || !acrtc->wb_enabled)
4475 			continue;
4476 
4477 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4478 
4479 		dm_clear_writeback(dm, acrtc, dm_old_crtc_state);
4480 		acrtc->wb_enabled = false;
4481 	}
4482 
4483 	amdgpu_dm_mod_power_update_streams(state, dm);
4484 
4485 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4486 				      new_crtc_state, i) {
4487 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4488 
4489 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4490 
4491 		if (old_crtc_state->active &&
4492 		    (!new_crtc_state->active ||
4493 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
4494 			manage_dm_interrupts(adev, acrtc, NULL);
4495 			dc_stream_release(dm_old_crtc_state->stream);
4496 		}
4497 	}
4498 
4499 	drm_atomic_helper_calc_timestamping_constants(state);
4500 
4501 	/* update changed items */
4502 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4503 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4504 
4505 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4506 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4507 
4508 		drm_dbg_state(state->dev,
4509 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
4510 			acrtc->crtc_id,
4511 			new_crtc_state->enable,
4512 			new_crtc_state->active,
4513 			new_crtc_state->planes_changed,
4514 			new_crtc_state->mode_changed,
4515 			new_crtc_state->active_changed,
4516 			new_crtc_state->connectors_changed);
4517 
4518 		/* Disable cursor if disabling crtc */
4519 		if (old_crtc_state->active && !new_crtc_state->active) {
4520 			struct dc_cursor_position position;
4521 
4522 			memset(&position, 0, sizeof(position));
4523 			mutex_lock(&dm->dc_lock);
4524 			dc_exit_ips_for_hw_access(dm->dc);
4525 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
4526 			mutex_unlock(&dm->dc_lock);
4527 		}
4528 
4529 		/* Copy all transient state flags into dc state */
4530 		if (dm_new_crtc_state->stream) {
4531 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4532 							    dm_new_crtc_state->stream);
4533 		}
4534 
4535 		/* handles headless hotplug case, updating new_state and
4536 		 * aconnector as needed
4537 		 */
4538 
4539 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4540 
4541 			drm_dbg_atomic(dev,
4542 				       "Atomic commit: SET crtc id %d: [%p]\n",
4543 				       acrtc->crtc_id, acrtc);
4544 
4545 			if (!dm_new_crtc_state->stream) {
4546 				/*
4547 				 * this could happen because of issues with
4548 				 * userspace notifications delivery.
4549 				 * In this case userspace tries to set mode on
4550 				 * display which is disconnected in fact.
4551 				 * dc_sink is NULL in this case on aconnector.
4552 				 * We expect reset mode will come soon.
4553 				 *
4554 				 * This can also happen when unplug is done
4555 				 * during resume sequence ended
4556 				 *
4557 				 * In this case, we want to pretend we still
4558 				 * have a sink to keep the pipe running so that
4559 				 * hw state is consistent with the sw state
4560 				 */
4561 				drm_dbg_atomic(dev,
4562 					       "Failed to create new stream for crtc %d\n",
4563 						acrtc->base.base.id);
4564 				continue;
4565 			}
4566 
4567 			if (dm_old_crtc_state->stream)
4568 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4569 
4570 			pm_runtime_get_noresume(dev->dev);
4571 
4572 			acrtc->enabled = true;
4573 			acrtc->hw_mode = new_crtc_state->mode;
4574 			crtc->hwmode = new_crtc_state->mode;
4575 			mode_set_reset_required = true;
4576 			set_backlight_level = true;
4577 		} else if (modereset_required(new_crtc_state)) {
4578 			drm_dbg_atomic(dev,
4579 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
4580 				       acrtc->crtc_id, acrtc);
4581 			/* i.e. reset mode */
4582 			if (dm_old_crtc_state->stream)
4583 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4584 
4585 			mode_set_reset_required = true;
4586 		}
4587 	} /* for_each_crtc_in_state() */
4588 
4589 	/* if there mode set or reset, flush vblank work queue */
4590 	if (mode_set_reset_required) {
4591 		if (dm->vblank_control_workqueue)
4592 			flush_workqueue(dm->vblank_control_workqueue);
4593 	}
4594 
4595 	dm_enable_per_frame_crtc_master_sync(dc_state);
4596 	mutex_lock(&dm->dc_lock);
4597 	dc_exit_ips_for_hw_access(dm->dc);
4598 	WARN_ON(!dc_commit_streams(dm->dc, &params));
4599 
4600 	bool frl_stream_found = false;
4601 
4602 	for (i = 0; i < params.stream_count; i++) {
4603 		struct dc_stream_state *stream = params.streams[i];
4604 
4605 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
4606 			frl_stream_found = true;
4607 			break;
4608 		}
4609 	}
4610 	if (frl_stream_found) {
4611 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
4612 				       &dm->hdmi_frl_status_polling_work,
4613 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
4614 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
4615 	} else {
4616 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
4617 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
4618 	}
4619 	/* Allow idle optimization when vblank count is 0 for display off */
4620 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
4621 		dc_allow_idle_optimizations(dm->dc, true);
4622 	mutex_unlock(&dm->dc_lock);
4623 
4624 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4625 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4626 
4627 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4628 
4629 		if (dm_new_crtc_state->stream != NULL) {
4630 			const struct dc_stream_status *status =
4631 					dc_stream_get_status(dm_new_crtc_state->stream);
4632 
4633 			if (!status)
4634 				status = dc_state_get_stream_status(dc_state,
4635 									 dm_new_crtc_state->stream);
4636 			if (!status)
4637 				drm_err(dev,
4638 					"got no status for stream %p on acrtc%p\n",
4639 					dm_new_crtc_state->stream, acrtc);
4640 			else
4641 				acrtc->otg_inst = status->primary_otg_inst;
4642 		}
4643 	}
4644 
4645 	/* During boot up and resume the DC layer will reset the panel brightness
4646 	 * to fix a flicker issue.
4647 	 * It will cause the dm->actual_brightness is not the current panel brightness
4648 	 * level. (the dm->brightness is the correct panel level)
4649 	 * So we set the backlight level with dm->brightness value after set mode
4650 	 */
4651 	if (set_backlight_level) {
4652 		for (i = 0; i < dm->num_of_edps; i++) {
4653 			if (dm->backlight_dev[i])
4654 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
4655 		}
4656 	}
4657 }
4658 
4659 static void dm_set_writeback(struct amdgpu_display_manager *dm,
4660 			      struct dm_crtc_state *crtc_state,
4661 			      struct drm_connector *connector,
4662 			      struct drm_connector_state *new_con_state)
4663 {
4664 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
4665 	struct amdgpu_device *adev = dm->adev;
4666 	struct amdgpu_crtc *acrtc;
4667 	struct dc_writeback_info *wb_info;
4668 	struct pipe_ctx *pipe = NULL;
4669 	struct amdgpu_framebuffer *afb;
4670 	int i = 0;
4671 
4672 	wb_info = kzalloc_obj(*wb_info);
4673 	if (!wb_info) {
4674 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
4675 		goto cleanup;
4676 	}
4677 
4678 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
4679 	if (!acrtc) {
4680 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
4681 		goto cleanup;
4682 	}
4683 
4684 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
4685 	if (!afb) {
4686 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
4687 		goto cleanup;
4688 	}
4689 
4690 	for (i = 0; i < MAX_PIPES; i++) {
4691 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
4692 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
4693 			break;
4694 		}
4695 	}
4696 
4697 	if (!pipe) {
4698 		drm_err(adev_to_drm(adev), "No pipe found for stream\n");
4699 		goto cleanup;
4700 	}
4701 
4702 	/* fill in wb_info */
4703 	wb_info->wb_enabled = true;
4704 
4705 	wb_info->dwb_pipe_inst = 0;
4706 	wb_info->dwb_params.dwbscl_black_color = 0;
4707 	wb_info->dwb_params.hdr_mult = 0x1F000;
4708 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
4709 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
4710 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
4711 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
4712 
4713 	/* width & height from crtc */
4714 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
4715 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
4716 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
4717 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
4718 
4719 	wb_info->dwb_params.cnv_params.crop_en = false;
4720 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
4721 
4722 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
4723 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
4724 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
4725 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
4726 
4727 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
4728 
4729 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
4730 
4731 	wb_info->dwb_params.scaler_taps.h_taps = 1;
4732 	wb_info->dwb_params.scaler_taps.v_taps = 1;
4733 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
4734 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
4735 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
4736 
4737 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
4738 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
4739 
4740 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
4741 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
4742 		wb_info->mcif_buf_params.chroma_address[i] = 0;
4743 	}
4744 
4745 	wb_info->mcif_buf_params.p_vmid = 1;
4746 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
4747 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
4748 		wb_info->mcif_warmup_params.region_size =
4749 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
4750 	}
4751 	wb_info->mcif_warmup_params.p_vmid = 1;
4752 	wb_info->writeback_source_plane = pipe->plane_state;
4753 
4754 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
4755 
4756 	acrtc->wb_conn = wb_conn;
4757 	drm_writeback_queue_job(wb_conn, new_con_state);
4758 
4759 	/*
4760 	 * Writeback completion is detected in the CRTC vblank IRQ
4761 	 * (dm_crtc_high_irq()). Take a vblank reference so the vblank interrupt
4762 	 * stays enabled while the writeback is pending; otherwise a
4763 	 * writeback-only commit right after drm_crtc_vblank_on() (e.g.
4764 	 * re-enabling a CRTC that was disabled) has no other vblank reference,
4765 	 * the IRQ never fires and the out fence times out. The matching put
4766 	 * happens once completion is signalled in dm_crtc_high_irq(), or when
4767 	 * the writeback is torn down in dm_clear_writeback().
4768 	 *
4769 	 * Arm wb_pending only after the reference is held so the completion IRQ
4770 	 * cannot run its matching vblank_put before this get.
4771 	 */
4772 	WARN_ON(drm_crtc_vblank_get(&acrtc->base));
4773 	acrtc->wb_frame_done = false;
4774 	acrtc->wb_pending = true;
4775 
4776 cleanup:
4777 	kfree(wb_info);
4778 }
4779 
4780 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
4781 {
4782 	struct drm_connector_state *old_con_state, *new_con_state;
4783 	struct drm_device *dev = state->dev;
4784 	struct drm_connector *connector;
4785 	struct amdgpu_device *adev = drm_to_adev(dev);
4786 	int i;
4787 
4788 	if (!adev->dm.hdcp_workqueue)
4789 		return;
4790 
4791 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4792 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4793 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4794 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4795 		struct dm_crtc_state *dm_new_crtc_state;
4796 		struct amdgpu_dm_connector *aconnector;
4797 
4798 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4799 			continue;
4800 
4801 		aconnector = to_amdgpu_dm_connector(connector);
4802 
4803 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
4804 
4805 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
4806 			connector->index, connector->status, connector->dpms);
4807 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
4808 			old_con_state->content_protection, new_con_state->content_protection);
4809 
4810 		if (aconnector->dc_sink) {
4811 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
4812 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
4813 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
4814 				aconnector->dc_sink->edid_caps.display_name);
4815 			}
4816 		}
4817 
4818 		new_crtc_state = NULL;
4819 		old_crtc_state = NULL;
4820 
4821 		if (acrtc) {
4822 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
4823 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4824 		}
4825 
4826 		if (old_crtc_state)
4827 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
4828 			old_crtc_state->enable,
4829 			old_crtc_state->active,
4830 			old_crtc_state->mode_changed,
4831 			old_crtc_state->active_changed,
4832 			old_crtc_state->connectors_changed);
4833 
4834 		if (new_crtc_state)
4835 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
4836 			new_crtc_state->enable,
4837 			new_crtc_state->active,
4838 			new_crtc_state->mode_changed,
4839 			new_crtc_state->active_changed,
4840 			new_crtc_state->connectors_changed);
4841 
4842 
4843 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4844 
4845 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
4846 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
4847 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4848 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4849 			dm_new_con_state->update_hdcp = true;
4850 			continue;
4851 		}
4852 
4853 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
4854 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
4855 			/* when display is unplugged from mst hub, connctor will
4856 			 * be destroyed within dm_dp_mst_connector_destroy. connector
4857 			 * hdcp perperties, like type, undesired, desired, enabled,
4858 			 * will be lost. So, save hdcp properties into hdcp_work within
4859 			 * amdgpu_dm_atomic_commit_tail. if the same display is
4860 			 * plugged back with same display index, its hdcp properties
4861 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
4862 			 */
4863 
4864 			bool enable_encryption = false;
4865 
4866 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
4867 				enable_encryption = true;
4868 
4869 			if (aconnector->dc_link && aconnector->dc_sink &&
4870 				aconnector->dc_link->type == dc_connection_mst_branch) {
4871 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
4872 				struct hdcp_workqueue *hdcp_w =
4873 					&hdcp_work[aconnector->dc_link->link_index];
4874 
4875 				hdcp_w->hdcp_content_type[connector->index] =
4876 					new_con_state->hdcp_content_type;
4877 				hdcp_w->content_protection[connector->index] =
4878 					new_con_state->content_protection;
4879 			}
4880 
4881 			if (new_crtc_state && new_crtc_state->mode_changed &&
4882 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
4883 				enable_encryption = true;
4884 
4885 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
4886 
4887 			if (aconnector->dc_link)
4888 				hdcp_update_display(
4889 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
4890 					new_con_state->hdcp_content_type, enable_encryption);
4891 		}
4892 	}
4893 }
4894 
4895 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
4896 {
4897 	struct drm_crtc *crtc;
4898 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4899 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4900 	int i, ret;
4901 
4902 	ret = drm_dp_mst_atomic_setup_commit(state);
4903 	if (ret)
4904 		return ret;
4905 
4906 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4907 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4908 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4909 		/*
4910 		 * Color management settings. We also update color properties
4911 		 * when a modeset is needed, to ensure it gets reprogrammed.
4912 		 */
4913 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
4914 		    (dm_new_crtc_state->base.color_mgmt_changed ||
4915 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
4916 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
4917 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
4918 			if (ret) {
4919 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
4920 				return ret;
4921 			}
4922 		}
4923 	}
4924 
4925 	return 0;
4926 }
4927 
4928 STATIC_IFN_KUNIT void set_multisync_trigger_params(
4929 		struct dc_stream_state *stream)
4930 {
4931 	struct dc_stream_state *master = NULL;
4932 
4933 	if (stream->triggered_crtc_reset.enabled) {
4934 		master = stream->triggered_crtc_reset.event_source;
4935 		stream->triggered_crtc_reset.event =
4936 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
4937 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
4938 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
4939 	}
4940 }
4941 EXPORT_IF_KUNIT(set_multisync_trigger_params);
4942 
4943 STATIC_IFN_KUNIT void set_master_stream(struct dc_stream_state *stream_set[],
4944 					int stream_count)
4945 {
4946 	int j, highest_rfr = 0, master_stream = 0;
4947 
4948 	for (j = 0;  j < stream_count; j++) {
4949 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
4950 			int refresh_rate = 0;
4951 
4952 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
4953 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
4954 			if (refresh_rate > highest_rfr) {
4955 				highest_rfr = refresh_rate;
4956 				master_stream = j;
4957 			}
4958 		}
4959 	}
4960 	for (j = 0;  j < stream_count; j++) {
4961 		if (stream_set[j])
4962 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
4963 	}
4964 }
4965 EXPORT_IF_KUNIT(set_master_stream);
4966 
4967 STATIC_IFN_KUNIT void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
4968 {
4969 	int i = 0;
4970 	struct dc_stream_state *stream;
4971 
4972 	if (context->stream_count < 2)
4973 		return;
4974 	for (i = 0; i < context->stream_count ; i++) {
4975 		if (!context->streams[i])
4976 			continue;
4977 		/*
4978 		 * TODO: add a function to read AMD VSDB bits and set
4979 		 * crtc_sync_master.multi_sync_enabled flag
4980 		 * For now it's set to false
4981 		 */
4982 	}
4983 
4984 	set_master_stream(context->streams, context->stream_count);
4985 
4986 	for (i = 0; i < context->stream_count ; i++) {
4987 		stream = context->streams[i];
4988 
4989 		if (!stream)
4990 			continue;
4991 
4992 		set_multisync_trigger_params(stream);
4993 	}
4994 }
4995 EXPORT_IF_KUNIT(dm_enable_per_frame_crtc_master_sync);
4996 
4997 /**
4998  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
4999  * @state: The atomic state to commit
5000  *
5001  * This will tell DC to commit the constructed DC state from atomic_check,
5002  * programming the hardware. Any failures here implies a hardware failure, since
5003  * atomic check should have filtered anything non-kosher.
5004  */
5005 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
5006 {
5007 	struct drm_device *dev = state->dev;
5008 	struct amdgpu_device *adev = drm_to_adev(dev);
5009 	struct amdgpu_display_manager *dm = &adev->dm;
5010 	struct dm_atomic_state *dm_state;
5011 	struct dc_state *dc_state = NULL;
5012 	u32 i, j;
5013 	struct drm_crtc *crtc;
5014 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5015 	unsigned long flags;
5016 	bool wait_for_vblank = true;
5017 	struct drm_connector *connector;
5018 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
5019 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5020 	int crtc_disable_count = 0;
5021 
5022 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
5023 
5024 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
5025 	drm_dp_mst_atomic_wait_for_dependencies(state);
5026 
5027 	dm_state = dm_atomic_get_new_state(state);
5028 	if (dm_state && dm_state->context) {
5029 		dc_state = dm_state->context;
5030 		amdgpu_dm_commit_streams(state, dc_state);
5031 	}
5032 
5033 	amdgpu_dm_update_hdcp(state);
5034 
5035 	/* Handle connector state changes */
5036 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5037 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5038 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5039 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5040 		struct dc_surface_update *dummy_updates;
5041 		struct dc_stream_update stream_update;
5042 		struct dc_info_packet hdr_packet;
5043 		struct dc_stream_status *status = NULL;
5044 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
5045 
5046 		memset(&stream_update, 0, sizeof(stream_update));
5047 
5048 		if (acrtc) {
5049 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5050 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5051 		}
5052 
5053 		/* Skip any modesets/resets */
5054 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
5055 			continue;
5056 
5057 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5058 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5059 
5060 		scaling_changed = is_scaling_state_different(dm_new_con_state,
5061 							     dm_old_con_state);
5062 
5063 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
5064 			(dm_old_crtc_state->stream->output_color_space !=
5065 				amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
5066 			output_color_space_changed = true;
5067 
5068 		abm_changed = dm_new_crtc_state->abm_level !=
5069 			      dm_old_crtc_state->abm_level;
5070 
5071 		hdr_changed =
5072 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
5073 
5074 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
5075 			continue;
5076 
5077 		stream_update.stream = dm_new_crtc_state->stream;
5078 		if (scaling_changed) {
5079 			amdgpu_dm_update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
5080 					dm_new_con_state, dm_new_crtc_state->stream);
5081 
5082 			stream_update.src = dm_new_crtc_state->stream->src;
5083 			stream_update.dst = dm_new_crtc_state->stream->dst;
5084 		}
5085 
5086 		if (output_color_space_changed) {
5087 			dm_new_crtc_state->stream->output_color_space
5088 				= amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
5089 
5090 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
5091 		}
5092 
5093 		if (abm_changed) {
5094 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
5095 
5096 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
5097 		}
5098 
5099 		if (hdr_changed) {
5100 			amdgpu_dm_fill_hdr_info_packet(new_con_state, &hdr_packet);
5101 			stream_update.hdr_static_metadata = &hdr_packet;
5102 		}
5103 
5104 		status = dc_stream_get_status(dm_new_crtc_state->stream);
5105 
5106 		if (WARN_ON(!status))
5107 			continue;
5108 
5109 		WARN_ON(!status->plane_count);
5110 
5111 		/*
5112 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
5113 		 * Here we create an empty update on each plane.
5114 		 * To fix this, DC should permit updating only stream properties.
5115 		 */
5116 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
5117 		if (!dummy_updates) {
5118 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
5119 			continue;
5120 		}
5121 		for (j = 0; j < status->plane_count; j++)
5122 			dummy_updates[j].surface = status->plane_states[j];
5123 
5124 		sort(dummy_updates, status->plane_count,
5125 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
5126 
5127 		mutex_lock(&dm->dc_lock);
5128 		dc_exit_ips_for_hw_access(dm->dc);
5129 		dc_update_planes_and_stream(dm->dc,
5130 					    dummy_updates,
5131 					    status->plane_count,
5132 					    dm_new_crtc_state->stream,
5133 					    &stream_update);
5134 		mutex_unlock(&dm->dc_lock);
5135 		kfree(dummy_updates);
5136 
5137 		drm_connector_update_privacy_screen(new_con_state);
5138 	}
5139 
5140 	/**
5141 	 * Enable interrupts for CRTCs that are newly enabled or went through
5142 	 * a modeset. It was intentionally deferred until after the front end
5143 	 * state was modified to wait until the OTG was on and so the IRQ
5144 	 * handlers didn't access stale or invalid state.
5145 	 */
5146 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5147 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5148 #ifdef CONFIG_DEBUG_FS
5149 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
5150 #endif
5151 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
5152 		if (old_crtc_state->active && !new_crtc_state->active)
5153 			crtc_disable_count++;
5154 
5155 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5156 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5157 
5158 		/* For freesync config update on crtc state and params for irq */
5159 		amdgpu_dm_update_stream_irq_parameters(dm, dm_new_crtc_state);
5160 
5161 #ifdef CONFIG_DEBUG_FS
5162 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5163 		cur_crc_src = acrtc->dm_irq_params.crc_src;
5164 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5165 #endif
5166 
5167 		if (new_crtc_state->active &&
5168 		    (!old_crtc_state->active ||
5169 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5170 			dc_stream_retain(dm_new_crtc_state->stream);
5171 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
5172 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
5173 		}
5174 		/* Handle vrr on->off / off->on transitions */
5175 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
5176 
5177 #ifdef CONFIG_DEBUG_FS
5178 		if (new_crtc_state->active &&
5179 		    (!old_crtc_state->active ||
5180 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5181 			/**
5182 			 * Frontend may have changed so reapply the CRC capture
5183 			 * settings for the stream.
5184 			 */
5185 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
5186 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
5187 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
5188 					uint8_t cnt;
5189 
5190 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5191 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
5192 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
5193 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
5194 
5195 							/**
5196 							 * It takes 2 frames for HW to stably generate CRC when
5197 							 * resuming from suspend, so we set skip_frame_cnt 2.
5198 							 */
5199 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
5200 						}
5201 					}
5202 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5203 				}
5204 #endif
5205 				if (amdgpu_dm_crtc_configure_crc_source(
5206 					crtc, dm_new_crtc_state, cur_crc_src))
5207 					drm_dbg_atomic(dev, "Failed to configure crc source");
5208 			}
5209 		}
5210 #endif
5211 	}
5212 
5213 	amdgpu_dm_mod_power_setup_streams(state, dm);
5214 
5215 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
5216 		if (new_crtc_state->async_flip)
5217 			wait_for_vblank = false;
5218 
5219 	/* update planes when needed per crtc*/
5220 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
5221 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5222 
5223 		if (dm_new_crtc_state->stream)
5224 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
5225 	}
5226 
5227 	/* Enable writeback */
5228 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
5229 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5230 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5231 
5232 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
5233 			continue;
5234 
5235 		if (!new_con_state->writeback_job)
5236 			continue;
5237 
5238 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5239 
5240 		if (!new_crtc_state)
5241 			continue;
5242 
5243 		if (acrtc->wb_enabled)
5244 			continue;
5245 
5246 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5247 
5248 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
5249 		acrtc->wb_enabled = true;
5250 	}
5251 
5252 	/* Update audio instances for each connector. */
5253 	amdgpu_dm_commit_audio(dev, state);
5254 
5255 	/* restore the backlight level */
5256 	for (i = 0; i < dm->num_of_edps; i++) {
5257 		if (dm->backlight_dev[i] &&
5258 		    (dm->actual_brightness[i] != dm->brightness[i]))
5259 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
5260 	}
5261 
5262 	/*
5263 	 * send vblank event on all events not handled in flip and
5264 	 * mark consumed event for drm_atomic_helper_commit_hw_done
5265 	 */
5266 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5267 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5268 
5269 		if (new_crtc_state->event)
5270 			drm_send_event_locked(dev, &new_crtc_state->event->base);
5271 
5272 		new_crtc_state->event = NULL;
5273 	}
5274 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5275 
5276 	/* Signal HW programming completion */
5277 	drm_atomic_helper_commit_hw_done(state);
5278 
5279 	if (wait_for_vblank)
5280 		drm_atomic_helper_wait_for_flip_done(dev, state);
5281 
5282 	drm_atomic_helper_cleanup_planes(dev, state);
5283 
5284 	/* Don't free the memory if we are hitting this as part of suspend.
5285 	 * This way we don't free any memory during suspend; see
5286 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
5287 	 * non-suspend modeset or when the driver is torn down.
5288 	 */
5289 	if (!adev->in_suspend) {
5290 		/* return the stolen vga memory back to VRAM */
5291 		if (!adev->mman.keep_stolen_vga_memory)
5292 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
5293 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
5294 	}
5295 
5296 	/*
5297 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
5298 	 * so we can put the GPU into runtime suspend if we're not driving any
5299 	 * displays anymore
5300 	 */
5301 	for (i = 0; i < crtc_disable_count; i++)
5302 		pm_runtime_put_autosuspend(dev->dev);
5303 	pm_runtime_mark_last_busy(dev->dev);
5304 
5305 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
5306 }
5307 
5308 /*
5309  * Grabs all modesetting locks to serialize against any blocking commits,
5310  * Waits for completion of all non blocking commits.
5311  */
5312 static int do_aquire_global_lock(struct drm_device *dev,
5313 				 struct drm_atomic_commit *state)
5314 {
5315 	struct drm_crtc *crtc;
5316 	struct drm_crtc_commit *commit;
5317 	long ret;
5318 
5319 	/*
5320 	 * Adding all modeset locks to aquire_ctx will
5321 	 * ensure that when the framework release it the
5322 	 * extra locks we are locking here will get released to
5323 	 */
5324 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
5325 	if (ret)
5326 		return ret;
5327 
5328 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
5329 		spin_lock(&crtc->commit_lock);
5330 		commit = list_first_entry_or_null(&crtc->commit_list,
5331 				struct drm_crtc_commit, commit_entry);
5332 		if (commit)
5333 			drm_crtc_commit_get(commit);
5334 		spin_unlock(&crtc->commit_lock);
5335 
5336 		if (!commit)
5337 			continue;
5338 
5339 		/*
5340 		 * Make sure all pending HW programming completed and
5341 		 * page flips done
5342 		 */
5343 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
5344 
5345 		if (ret > 0)
5346 			ret = wait_for_completion_interruptible_timeout(
5347 					&commit->flip_done, 10*HZ);
5348 
5349 		if (ret == 0)
5350 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
5351 				  crtc->base.id, crtc->name);
5352 
5353 		drm_crtc_commit_put(commit);
5354 	}
5355 
5356 	return ret < 0 ? ret : 0;
5357 }
5358 
5359 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
5360 			 struct drm_atomic_commit *state,
5361 			 struct drm_crtc *crtc,
5362 			 struct drm_crtc_state *old_crtc_state,
5363 			 struct drm_crtc_state *new_crtc_state,
5364 			 bool enable,
5365 			 bool *lock_and_validation_needed)
5366 {
5367 	struct dm_atomic_state *dm_state = NULL;
5368 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5369 	struct dc_stream_state *new_stream;
5370 	struct amdgpu_device *adev = dm->adev;
5371 	int ret = 0;
5372 
5373 	/*
5374 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
5375 	 * update changed items
5376 	 */
5377 	struct amdgpu_crtc *acrtc = NULL;
5378 	struct drm_connector *connector = NULL;
5379 	struct amdgpu_dm_connector *aconnector = NULL;
5380 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
5381 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
5382 
5383 	new_stream = NULL;
5384 
5385 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5386 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5387 	acrtc = to_amdgpu_crtc(crtc);
5388 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
5389 	if (connector)
5390 		aconnector = to_amdgpu_dm_connector(connector);
5391 
5392 	/* TODO This hack should go away */
5393 	if (connector && enable) {
5394 		/* Make sure fake sink is created in plug-in scenario */
5395 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
5396 									connector);
5397 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
5398 									connector);
5399 
5400 		if (WARN_ON(!drm_new_conn_state)) {
5401 			ret = -EINVAL;
5402 			goto fail;
5403 		}
5404 
5405 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
5406 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
5407 
5408 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5409 			goto skip_modeset;
5410 
5411 		new_stream = amdgpu_dm_create_validate_stream_for_sink(connector,
5412 							     &new_crtc_state->mode,
5413 							     dm_new_conn_state,
5414 							     dm_old_crtc_state->stream);
5415 
5416 		/*
5417 		 * we can have no stream on ACTION_SET if a display
5418 		 * was disconnected during S3, in this case it is not an
5419 		 * error, the OS will be updated after detection, and
5420 		 * will do the right thing on next atomic commit
5421 		 */
5422 
5423 		if (!new_stream) {
5424 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
5425 					__func__, acrtc->base.base.id);
5426 			ret = -ENOMEM;
5427 			goto fail;
5428 		}
5429 
5430 		/*
5431 		 * TODO: Check VSDB bits to decide whether this should
5432 		 * be enabled or not.
5433 		 */
5434 		new_stream->triggered_crtc_reset.enabled =
5435 			dm->force_timing_sync;
5436 
5437 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
5438 
5439 		ret = amdgpu_dm_fill_hdr_info_packet(drm_new_conn_state,
5440 					   &new_stream->hdr_static_metadata);
5441 		if (ret)
5442 			goto fail;
5443 
5444 		/*
5445 		 * If we already removed the old stream from the context
5446 		 * (and set the new stream to NULL) then we can't reuse
5447 		 * the old stream even if the stream and scaling are unchanged.
5448 		 * We'll hit the BUG_ON and black screen.
5449 		 *
5450 		 * TODO: Refactor this function to allow this check to work
5451 		 * in all conditions.
5452 		 */
5453 		if (amdgpu_freesync_vid_mode &&
5454 		    dm_new_crtc_state->stream &&
5455 		    amdgpu_dm_is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
5456 			goto skip_modeset;
5457 
5458 		if (dm_new_crtc_state->stream &&
5459 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5460 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
5461 			new_crtc_state->mode_changed = false;
5462 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
5463 					 new_crtc_state->mode_changed);
5464 		}
5465 	}
5466 
5467 	/* mode_changed flag may get updated above, need to check again */
5468 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5469 		goto skip_modeset;
5470 
5471 	drm_dbg_state(state->dev,
5472 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
5473 		acrtc->crtc_id,
5474 		new_crtc_state->enable,
5475 		new_crtc_state->active,
5476 		new_crtc_state->planes_changed,
5477 		new_crtc_state->mode_changed,
5478 		new_crtc_state->active_changed,
5479 		new_crtc_state->connectors_changed);
5480 
5481 	/* Remove stream for any changed/disabled CRTC */
5482 	if (!enable) {
5483 
5484 		if (!dm_old_crtc_state->stream)
5485 			goto skip_modeset;
5486 
5487 		/* Unset freesync video if it was active before */
5488 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
5489 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
5490 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
5491 		}
5492 
5493 		/* Now check if we should set freesync video mode */
5494 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
5495 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5496 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
5497 		    amdgpu_dm_is_timing_unchanged_for_freesync(new_crtc_state,
5498 						     old_crtc_state)) {
5499 			new_crtc_state->mode_changed = false;
5500 			drm_dbg_driver(adev_to_drm(adev),
5501 				"Mode change not required for front porch change, setting mode_changed to %d",
5502 				new_crtc_state->mode_changed);
5503 
5504 			amdgpu_dm_set_freesync_fixed_config(dm_new_crtc_state);
5505 
5506 			goto skip_modeset;
5507 		} else if (amdgpu_freesync_vid_mode && aconnector &&
5508 			   amdgpu_dm_is_freesync_video_mode(&new_crtc_state->mode,
5509 						  aconnector)) {
5510 			struct drm_display_mode *high_mode;
5511 
5512 			high_mode = amdgpu_dm_get_highest_refresh_rate_mode(aconnector, false);
5513 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
5514 				amdgpu_dm_set_freesync_fixed_config(dm_new_crtc_state);
5515 		}
5516 
5517 		ret = dm_atomic_get_state(state, &dm_state);
5518 		if (ret)
5519 			goto fail;
5520 
5521 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
5522 				crtc->base.id);
5523 
5524 		/* i.e. reset mode */
5525 		if (dc_state_remove_stream(
5526 				dm->dc,
5527 				dm_state->context,
5528 				dm_old_crtc_state->stream) != DC_OK) {
5529 			ret = -EINVAL;
5530 			goto fail;
5531 		}
5532 
5533 		dc_stream_release(dm_old_crtc_state->stream);
5534 		dm_new_crtc_state->stream = NULL;
5535 
5536 		amdgpu_dm_reset_freesync_config_for_crtc(dm_new_crtc_state);
5537 
5538 		*lock_and_validation_needed = true;
5539 
5540 	} else {/* Add stream for any updated/enabled CRTC */
5541 		/*
5542 		 * Quick fix to prevent NULL pointer on new_stream when
5543 		 * added MST connectors not found in existing crtc_state in the chained mode
5544 		 * TODO: need to dig out the root cause of that
5545 		 */
5546 		if (!connector)
5547 			goto skip_modeset;
5548 
5549 		if (modereset_required(new_crtc_state))
5550 			goto skip_modeset;
5551 
5552 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
5553 				     dm_old_crtc_state->stream)) {
5554 
5555 			WARN_ON(dm_new_crtc_state->stream);
5556 
5557 			ret = dm_atomic_get_state(state, &dm_state);
5558 			if (ret)
5559 				goto fail;
5560 
5561 			dm_new_crtc_state->stream = new_stream;
5562 
5563 			dc_stream_retain(new_stream);
5564 
5565 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
5566 					 crtc->base.id);
5567 
5568 			if (dc_state_add_stream(
5569 					dm->dc,
5570 					dm_state->context,
5571 					dm_new_crtc_state->stream) != DC_OK) {
5572 				ret = -EINVAL;
5573 				goto fail;
5574 			}
5575 
5576 			*lock_and_validation_needed = true;
5577 		}
5578 	}
5579 
5580 skip_modeset:
5581 	/* Release extra reference */
5582 	if (new_stream)
5583 		dc_stream_release(new_stream);
5584 	new_stream = NULL;
5585 
5586 	/*
5587 	 * We want to do dc stream updates that do not require a
5588 	 * full modeset below.
5589 	 */
5590 	if (!(enable && connector && new_crtc_state->active))
5591 		return 0;
5592 	/*
5593 	 * Given above conditions, the dc state cannot be NULL because:
5594 	 * 1. We're in the process of enabling CRTCs (just been added
5595 	 *    to the dc context, or already is on the context)
5596 	 * 2. Has a valid connector attached, and
5597 	 * 3. Is currently active and enabled.
5598 	 * => The dc stream state currently exists.
5599 	 */
5600 	BUG_ON(dm_new_crtc_state->stream == NULL);
5601 
5602 	/* Scaling or underscan settings */
5603 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
5604 				drm_atomic_crtc_needs_modeset(new_crtc_state))
5605 		amdgpu_dm_update_stream_scaling_settings(adev_to_drm(adev),
5606 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
5607 
5608 	/* ABM settings */
5609 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
5610 
5611 	/*
5612 	 * Color management settings. We also update color properties
5613 	 * when a modeset is needed, to ensure it gets reprogrammed.
5614 	 */
5615 	if (dm_new_crtc_state->base.color_mgmt_changed ||
5616 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
5617 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
5618 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
5619 		if (ret)
5620 			goto fail;
5621 	}
5622 
5623 	/* Update Freesync settings. */
5624 	amdgpu_dm_get_freesync_config_for_crtc(dm_new_crtc_state,
5625 				     dm_new_conn_state);
5626 
5627 	return ret;
5628 
5629 fail:
5630 	if (new_stream)
5631 		dc_stream_release(new_stream);
5632 	return ret;
5633 }
5634 
5635 static bool should_reset_plane(struct drm_atomic_commit *state,
5636 			       struct drm_plane *plane,
5637 			       struct drm_plane_state *old_plane_state,
5638 			       struct drm_plane_state *new_plane_state)
5639 {
5640 	struct drm_plane *other;
5641 	struct drm_plane_state *old_other_state, *new_other_state;
5642 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5643 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
5644 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
5645 	struct drm_connector_state *new_con_state;
5646 	struct drm_connector *connector;
5647 	int i;
5648 
5649 	/*
5650 	 * TODO: Remove this hack for all asics once it proves that the
5651 	 * fast updates works fine on DCN3.2+.
5652 	 */
5653 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
5654 	    state->allow_modeset)
5655 		return true;
5656 
5657 	/* Check for writeback commit */
5658 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
5659 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
5660 			continue;
5661 
5662 		if (new_con_state->writeback_job)
5663 			return true;
5664 	}
5665 
5666 	if (amdgpu_in_reset(adev) && state->allow_modeset)
5667 		return true;
5668 
5669 	/* Exit early if we know that we're adding or removing the plane. */
5670 	if (old_plane_state->crtc != new_plane_state->crtc)
5671 		return true;
5672 
5673 	/* old crtc == new_crtc == NULL, plane not in context. */
5674 	if (!new_plane_state->crtc)
5675 		return false;
5676 
5677 	new_crtc_state =
5678 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
5679 	old_crtc_state =
5680 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
5681 
5682 	if (!new_crtc_state)
5683 		return true;
5684 
5685 	/*
5686 	 * A change in cursor mode means a new dc pipe needs to be acquired or
5687 	 * released from the state
5688 	 */
5689 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
5690 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
5691 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
5692 	    old_dm_crtc_state != NULL &&
5693 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
5694 		return true;
5695 	}
5696 
5697 	/* CRTC Degamma changes currently require us to recreate planes. */
5698 	if (new_crtc_state->color_mgmt_changed)
5699 		return true;
5700 
5701 	/*
5702 	 * On zpos change, planes need to be reordered by removing and re-adding
5703 	 * them one by one to the dc state, in order of descending zpos.
5704 	 *
5705 	 * TODO: We can likely skip bandwidth validation if the only thing that
5706 	 * changed about the plane was it'z z-ordering.
5707 	 */
5708 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
5709 		return true;
5710 
5711 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
5712 		return true;
5713 
5714 	/*
5715 	 * If there are any new primary or overlay planes being added or
5716 	 * removed then the z-order can potentially change. To ensure
5717 	 * correct z-order and pipe acquisition the current DC architecture
5718 	 * requires us to remove and recreate all existing planes.
5719 	 *
5720 	 * TODO: Come up with a more elegant solution for this.
5721 	 */
5722 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
5723 		struct amdgpu_framebuffer *old_afb, *new_afb;
5724 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
5725 
5726 		dm_new_other_state = to_dm_plane_state(new_other_state);
5727 		dm_old_other_state = to_dm_plane_state(old_other_state);
5728 
5729 		if (other->type == DRM_PLANE_TYPE_CURSOR)
5730 			continue;
5731 
5732 		if (old_other_state->crtc != new_plane_state->crtc &&
5733 		    new_other_state->crtc != new_plane_state->crtc)
5734 			continue;
5735 
5736 		if (old_other_state->crtc != new_other_state->crtc)
5737 			return true;
5738 
5739 		/* Src/dst size and scaling updates. */
5740 		if (old_other_state->src_w != new_other_state->src_w ||
5741 		    old_other_state->src_h != new_other_state->src_h ||
5742 		    old_other_state->crtc_w != new_other_state->crtc_w ||
5743 		    old_other_state->crtc_h != new_other_state->crtc_h)
5744 			return true;
5745 
5746 		/* Rotation / mirroring updates. */
5747 		if (old_other_state->rotation != new_other_state->rotation)
5748 			return true;
5749 
5750 		/* Blending updates. */
5751 		if (old_other_state->pixel_blend_mode !=
5752 		    new_other_state->pixel_blend_mode)
5753 			return true;
5754 
5755 		/* Alpha updates. */
5756 		if (old_other_state->alpha != new_other_state->alpha)
5757 			return true;
5758 
5759 		/* Colorspace changes. */
5760 		if (old_other_state->color_range != new_other_state->color_range ||
5761 		    old_other_state->color_encoding != new_other_state->color_encoding)
5762 			return true;
5763 
5764 		/* HDR/Transfer Function changes. */
5765 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
5766 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
5767 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
5768 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
5769 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
5770 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
5771 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
5772 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
5773 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
5774 			return true;
5775 
5776 		/* Framebuffer checks fall at the end. */
5777 		if (!old_other_state->fb || !new_other_state->fb)
5778 			continue;
5779 
5780 		/* Pixel format changes can require bandwidth updates. */
5781 		if (old_other_state->fb->format != new_other_state->fb->format)
5782 			return true;
5783 
5784 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
5785 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
5786 
5787 		/* Tiling and DCC changes also require bandwidth updates. */
5788 		if (old_afb->base.modifier != new_afb->base.modifier)
5789 			return true;
5790 	}
5791 
5792 	return false;
5793 }
5794 
5795 static int dm_update_plane_state(struct dc *dc,
5796 				 struct drm_atomic_commit *state,
5797 				 struct drm_plane *plane,
5798 				 struct drm_plane_state *old_plane_state,
5799 				 struct drm_plane_state *new_plane_state,
5800 				 bool enable,
5801 				 bool *lock_and_validation_needed,
5802 				 bool *is_top_most_overlay)
5803 {
5804 
5805 	struct dm_atomic_state *dm_state = NULL;
5806 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
5807 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5808 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
5809 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
5810 	bool needs_reset, update_native_cursor;
5811 	int ret = 0;
5812 
5813 
5814 	new_plane_crtc = new_plane_state->crtc;
5815 	old_plane_crtc = old_plane_state->crtc;
5816 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
5817 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
5818 
5819 	update_native_cursor = amdgpu_dm_should_update_native_cursor(state,
5820 								     old_plane_crtc,
5821 								     new_plane_crtc,
5822 								     enable);
5823 
5824 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
5825 		ret = amdgpu_dm_check_native_cursor_state(new_plane_crtc, plane,
5826 							  new_plane_state, enable);
5827 		if (ret)
5828 			return ret;
5829 
5830 		return 0;
5831 	}
5832 
5833 	needs_reset = should_reset_plane(state, plane, old_plane_state,
5834 					 new_plane_state);
5835 
5836 	/* Remove any changed/removed planes */
5837 	if (!enable) {
5838 		if (!needs_reset)
5839 			return 0;
5840 
5841 		if (!old_plane_crtc)
5842 			return 0;
5843 
5844 		old_crtc_state = drm_atomic_get_old_crtc_state(
5845 				state, old_plane_crtc);
5846 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5847 
5848 		if (!dm_old_crtc_state->stream)
5849 			return 0;
5850 
5851 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
5852 				plane->base.id, old_plane_crtc->base.id);
5853 
5854 		ret = dm_atomic_get_state(state, &dm_state);
5855 		if (ret)
5856 			return ret;
5857 
5858 		if (!dc_state_remove_plane(
5859 				dc,
5860 				dm_old_crtc_state->stream,
5861 				dm_old_plane_state->dc_state,
5862 				dm_state->context)) {
5863 
5864 			return -EINVAL;
5865 		}
5866 
5867 		if (dm_old_plane_state->dc_state)
5868 			dc_plane_state_release(dm_old_plane_state->dc_state);
5869 
5870 		dm_new_plane_state->dc_state = NULL;
5871 
5872 		*lock_and_validation_needed = true;
5873 
5874 	} else { /* Add new planes */
5875 		struct dc_plane_state *dc_new_plane_state;
5876 
5877 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
5878 			return 0;
5879 
5880 		if (!new_plane_crtc)
5881 			return 0;
5882 
5883 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
5884 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5885 
5886 		if (!dm_new_crtc_state->stream)
5887 			return 0;
5888 
5889 		if (!needs_reset)
5890 			return 0;
5891 
5892 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
5893 		if (ret)
5894 			goto out;
5895 
5896 		WARN_ON(dm_new_plane_state->dc_state);
5897 
5898 		dc_new_plane_state = dc_create_plane_state(dc);
5899 		if (!dc_new_plane_state) {
5900 			ret = -ENOMEM;
5901 			goto out;
5902 		}
5903 
5904 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
5905 				 plane->base.id, new_plane_crtc->base.id);
5906 
5907 		ret = fill_dc_plane_attributes(
5908 			drm_to_adev(new_plane_crtc->dev),
5909 			dc_new_plane_state,
5910 			new_plane_state,
5911 			new_crtc_state);
5912 		if (ret) {
5913 			dc_plane_state_release(dc_new_plane_state);
5914 			goto out;
5915 		}
5916 
5917 		ret = dm_atomic_get_state(state, &dm_state);
5918 		if (ret) {
5919 			dc_plane_state_release(dc_new_plane_state);
5920 			goto out;
5921 		}
5922 
5923 		/*
5924 		 * Any atomic check errors that occur after this will
5925 		 * not need a release. The plane state will be attached
5926 		 * to the stream, and therefore part of the atomic
5927 		 * state. It'll be released when the atomic state is
5928 		 * cleaned.
5929 		 */
5930 		if (!dc_state_add_plane(
5931 				dc,
5932 				dm_new_crtc_state->stream,
5933 				dc_new_plane_state,
5934 				dm_state->context)) {
5935 
5936 			dc_plane_state_release(dc_new_plane_state);
5937 			ret = -EINVAL;
5938 			goto out;
5939 		}
5940 
5941 		dm_new_plane_state->dc_state = dc_new_plane_state;
5942 
5943 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
5944 
5945 		/* Tell DC to do a full surface update every time there
5946 		 * is a plane change. Inefficient, but works for now.
5947 		 */
5948 		dm_new_plane_state->dc_state->update_bits.full_update = 1;
5949 
5950 		*lock_and_validation_needed = true;
5951 	}
5952 
5953 out:
5954 	/* If enabling cursor overlay failed, attempt fallback to native mode */
5955 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
5956 		ret = amdgpu_dm_check_native_cursor_state(new_plane_crtc, plane,
5957 							  new_plane_state, enable);
5958 		if (ret)
5959 			return ret;
5960 
5961 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
5962 	}
5963 
5964 	return ret;
5965 }
5966 
5967 /*
5968  * The normalized_zpos value cannot be used by this iterator directly. It's only
5969  * calculated for enabled planes, potentially causing normalized_zpos collisions
5970  * between enabled/disabled planes in the atomic state. We need a unique value
5971  * so that the iterator will not generate the same object twice, or loop
5972  * indefinitely.
5973  */
5974 struct __drm_planes_state *amdgpu_dm_get_next_zpos(
5975 	struct drm_atomic_commit *state,
5976 	struct __drm_planes_state *prev)
5977 {
5978 	unsigned int highest_zpos = 0, prev_zpos = 256;
5979 	uint32_t highest_id = 0, prev_id = UINT_MAX;
5980 	struct drm_plane_state *new_plane_state;
5981 	struct drm_plane *plane;
5982 	int i, highest_i = -1;
5983 
5984 	if (prev != NULL) {
5985 		prev_zpos = prev->new_state->zpos;
5986 		prev_id = prev->ptr->base.id;
5987 	}
5988 
5989 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
5990 		/* Skip planes with higher zpos than the previously returned */
5991 		if (new_plane_state->zpos > prev_zpos ||
5992 		    (new_plane_state->zpos == prev_zpos &&
5993 		     plane->base.id >= prev_id))
5994 			continue;
5995 
5996 		/* Save the index of the plane with highest zpos */
5997 		if (new_plane_state->zpos > highest_zpos ||
5998 		    (new_plane_state->zpos == highest_zpos &&
5999 		     plane->base.id > highest_id)) {
6000 			highest_zpos = new_plane_state->zpos;
6001 			highest_id = plane->base.id;
6002 			highest_i = i;
6003 		}
6004 	}
6005 
6006 	if (highest_i < 0)
6007 		return NULL;
6008 
6009 	return &state->planes[highest_i];
6010 }
6011 
6012 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
6013 {
6014 	struct drm_connector *connector;
6015 	struct drm_connector_state *conn_state, *old_conn_state;
6016 	struct amdgpu_dm_connector *aconnector = NULL;
6017 	int i;
6018 
6019 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
6020 		if (!conn_state->crtc)
6021 			conn_state = old_conn_state;
6022 
6023 		if (conn_state->crtc != crtc)
6024 			continue;
6025 
6026 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
6027 			continue;
6028 
6029 		aconnector = to_amdgpu_dm_connector(connector);
6030 		if (!aconnector->mst_output_port || !aconnector->mst_root)
6031 			aconnector = NULL;
6032 		else
6033 			break;
6034 	}
6035 
6036 	if (!aconnector)
6037 		return 0;
6038 
6039 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
6040 }
6041 
6042 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
6043 					    struct drm_atomic_commit *state,
6044 					    struct drm_crtc_state *crtc_state)
6045 {
6046 	struct drm_plane *plane;
6047 	struct drm_plane_state *new_plane_state, *old_plane_state;
6048 
6049 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
6050 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
6051 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
6052 
6053 		if (!old_plane_state || !new_plane_state)
6054 			continue;
6055 
6056 		if (old_plane_state->fb && new_plane_state->fb &&
6057 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
6058 			return true;
6059 	}
6060 
6061 	return false;
6062 }
6063 
6064 /**
6065  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
6066  *
6067  * @dev: The DRM device
6068  * @state: The atomic state to commit
6069  *
6070  * Validate that the given atomic state is programmable by DC into hardware.
6071  * This involves constructing a &struct dc_state reflecting the new hardware
6072  * state we wish to commit, then querying DC to see if it is programmable. It's
6073  * important not to modify the existing DC state. Otherwise, atomic_check
6074  * may unexpectedly commit hardware changes.
6075  *
6076  * When validating the DC state, it's important that the right locks are
6077  * acquired. For full updates case which removes/adds/updates streams on one
6078  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
6079  * that any such full update commit will wait for completion of any outstanding
6080  * flip using DRMs synchronization events.
6081  *
6082  * Note that DM adds the affected connectors for all CRTCs in state, when that
6083  * might not seem necessary. This is because DC stream creation requires the
6084  * DC sink, which is tied to the DRM connector state. Cleaning this up should
6085  * be possible but non-trivial - a possible TODO item.
6086  *
6087  * Return: -Error code if validation failed.
6088  */
6089 static int amdgpu_dm_atomic_check(struct drm_device *dev,
6090 				  struct drm_atomic_commit *state)
6091 {
6092 	struct amdgpu_device *adev = drm_to_adev(dev);
6093 	struct dm_atomic_state *dm_state = NULL;
6094 	struct dc *dc = adev->dm.dc;
6095 	struct drm_connector *connector;
6096 	struct drm_connector_state *old_con_state, *new_con_state;
6097 	struct drm_crtc *crtc;
6098 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6099 	struct drm_plane *plane;
6100 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
6101 	enum dc_status status;
6102 	int ret, i;
6103 	bool lock_and_validation_needed = false;
6104 	bool is_top_most_overlay = true;
6105 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6106 	struct drm_dp_mst_topology_mgr *mgr;
6107 	struct drm_dp_mst_topology_state *mst_state;
6108 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
6109 
6110 	trace_amdgpu_dm_atomic_check_begin(state);
6111 
6112 	ret = drm_atomic_helper_check_modeset(dev, state);
6113 	if (ret) {
6114 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed: %pe\n", ERR_PTR(ret));
6115 		goto fail;
6116 	}
6117 
6118 	/* Check connector changes */
6119 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6120 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6121 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6122 
6123 		/* Skip connectors that are disabled or part of modeset already. */
6124 		if (!new_con_state->crtc)
6125 			continue;
6126 
6127 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
6128 		if (IS_ERR(new_crtc_state)) {
6129 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed: %pe\n", new_crtc_state);
6130 			ret = PTR_ERR(new_crtc_state);
6131 			goto fail;
6132 		}
6133 
6134 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
6135 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
6136 			new_crtc_state->connectors_changed = true;
6137 	}
6138 
6139 	if (dc_resource_is_dsc_encoding_supported(dc)) {
6140 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6141 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6142 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
6143 		}
6144 
6145 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6146 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
6147 				ret = add_affected_mst_dsc_crtcs(state, crtc);
6148 				if (ret) {
6149 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed: %pe\n", ERR_PTR(ret));
6150 					goto fail;
6151 				}
6152 			}
6153 		}
6154 	}
6155 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6156 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6157 
6158 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
6159 		    !new_crtc_state->color_mgmt_changed &&
6160 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
6161 			dm_old_crtc_state->dsc_force_changed == false)
6162 			continue;
6163 
6164 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
6165 		if (ret) {
6166 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed: %pe\n", ERR_PTR(ret));
6167 			goto fail;
6168 		}
6169 
6170 		if (!new_crtc_state->enable)
6171 			continue;
6172 
6173 		ret = drm_atomic_add_affected_connectors(state, crtc);
6174 		if (ret) {
6175 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed: %pe\n", ERR_PTR(ret));
6176 			goto fail;
6177 		}
6178 
6179 		ret = drm_atomic_add_affected_planes(state, crtc);
6180 		if (ret) {
6181 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed: %pe\n", ERR_PTR(ret));
6182 			goto fail;
6183 		}
6184 
6185 		if (dm_old_crtc_state->dsc_force_changed)
6186 			new_crtc_state->mode_changed = true;
6187 	}
6188 
6189 	/*
6190 	 * Add all primary and overlay planes on the CRTC to the state
6191 	 * whenever a plane is enabled to maintain correct z-ordering
6192 	 * and to enable fast surface updates.
6193 	 */
6194 	drm_for_each_crtc(crtc, dev) {
6195 		bool modified = false;
6196 
6197 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
6198 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6199 				continue;
6200 
6201 			if (new_plane_state->crtc == crtc ||
6202 			    old_plane_state->crtc == crtc) {
6203 				modified = true;
6204 				break;
6205 			}
6206 		}
6207 
6208 		if (!modified)
6209 			continue;
6210 
6211 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
6212 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6213 				continue;
6214 
6215 			new_plane_state =
6216 				drm_atomic_get_plane_state(state, plane);
6217 
6218 			if (IS_ERR(new_plane_state)) {
6219 				ret = PTR_ERR(new_plane_state);
6220 				drm_dbg_atomic(dev, "new_plane_state is BAD: %pe\n", new_plane_state);
6221 				goto fail;
6222 			}
6223 		}
6224 	}
6225 
6226 	/*
6227 	 * DC consults the zpos (layer_index in DC terminology) to determine the
6228 	 * hw plane on which to enable the hw cursor (see
6229 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
6230 	 * atomic state, so call drm helper to normalize zpos.
6231 	 */
6232 	ret = drm_atomic_normalize_zpos(dev, state);
6233 	if (ret) {
6234 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed: %pe\n", ERR_PTR(ret));
6235 		goto fail;
6236 	}
6237 
6238 	/*
6239 	 * Determine whether cursors on each CRTC should be enabled in native or
6240 	 * overlay mode.
6241 	 */
6242 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6243 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6244 
6245 		ret = amdgpu_dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
6246 						     &dm_new_crtc_state->cursor_mode);
6247 		if (ret) {
6248 			drm_dbg(dev, "Failed to determine cursor mode: %pe\n", ERR_PTR(ret));
6249 			goto fail;
6250 		}
6251 
6252 		/*
6253 		 * If overlay cursor is needed, DC cannot go through the
6254 		 * native cursor update path. All enabled planes on the CRTC
6255 		 * need to be added for DC to not disable a plane by mistake
6256 		 */
6257 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
6258 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
6259 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
6260 				ret = -EINVAL;
6261 				goto fail;
6262 			}
6263 
6264 			ret = drm_atomic_add_affected_planes(state, crtc);
6265 			if (ret)
6266 				goto fail;
6267 		}
6268 	}
6269 
6270 	/* Remove exiting planes if they are modified */
6271 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
6272 
6273 		ret = dm_update_plane_state(dc, state, plane,
6274 					    old_plane_state,
6275 					    new_plane_state,
6276 					    false,
6277 					    &lock_and_validation_needed,
6278 					    &is_top_most_overlay);
6279 		if (ret) {
6280 			drm_dbg_atomic(dev, "dm_update_plane_state() failed: %pe\n", ERR_PTR(ret));
6281 			goto fail;
6282 		}
6283 	}
6284 
6285 	/* Disable all crtcs which require disable */
6286 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6287 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6288 					   old_crtc_state,
6289 					   new_crtc_state,
6290 					   false,
6291 					   &lock_and_validation_needed);
6292 		if (ret) {
6293 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed: %pe\n", ERR_PTR(ret));
6294 			goto fail;
6295 		}
6296 	}
6297 
6298 	/* Enable all crtcs which require enable */
6299 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6300 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6301 					   old_crtc_state,
6302 					   new_crtc_state,
6303 					   true,
6304 					   &lock_and_validation_needed);
6305 		if (ret) {
6306 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed: %pe\n", ERR_PTR(ret));
6307 			goto fail;
6308 		}
6309 	}
6310 
6311 	/* Add new/modified planes */
6312 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
6313 		ret = dm_update_plane_state(dc, state, plane,
6314 					    old_plane_state,
6315 					    new_plane_state,
6316 					    true,
6317 					    &lock_and_validation_needed,
6318 					    &is_top_most_overlay);
6319 		if (ret) {
6320 			drm_dbg_atomic(dev, "dm_update_plane_state() failed: %pe\n", ERR_PTR(ret));
6321 			goto fail;
6322 		}
6323 	}
6324 
6325 #if defined(CONFIG_DRM_AMD_DC_FP)
6326 	if (dc_resource_is_dsc_encoding_supported(dc)) {
6327 		ret = pre_validate_dsc(state, &dm_state, vars);
6328 		if (ret != 0)
6329 			goto fail;
6330 	}
6331 #endif
6332 
6333 	/* Run this here since we want to validate the streams we created */
6334 	ret = drm_atomic_helper_check_planes(dev, state);
6335 	if (ret) {
6336 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed: %pe\n", ERR_PTR(ret));
6337 		goto fail;
6338 	}
6339 
6340 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6341 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6342 		if (dm_new_crtc_state->mpo_requested)
6343 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
6344 	}
6345 
6346 	/* Check cursor restrictions */
6347 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6348 		enum amdgpu_dm_cursor_mode required_cursor_mode;
6349 		int is_rotated, is_scaled;
6350 
6351 		/* Overlay cusor not subject to native cursor restrictions */
6352 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6353 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
6354 			continue;
6355 
6356 		/* Check if rotation or scaling is enabled on DCN 4x and above */
6357 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
6358 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))) {
6359 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
6360 
6361 			is_rotated = new_cursor_state &&
6362 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
6363 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
6364 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
6365 
6366 			if (is_rotated || is_scaled) {
6367 				drm_dbg_driver(
6368 					crtc->dev,
6369 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
6370 					crtc->base.id, crtc->name);
6371 				ret = -EINVAL;
6372 				goto fail;
6373 			}
6374 		}
6375 
6376 		/* If HW can only do native cursor, check restrictions again */
6377 		ret = amdgpu_dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
6378 						     &required_cursor_mode);
6379 		if (ret) {
6380 			drm_dbg_driver(crtc->dev,
6381 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
6382 				       crtc->base.id, crtc->name);
6383 			goto fail;
6384 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
6385 			drm_dbg_driver(crtc->dev,
6386 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
6387 				       crtc->base.id, crtc->name);
6388 			ret = -EINVAL;
6389 			goto fail;
6390 		}
6391 	}
6392 
6393 	if (state->legacy_cursor_update) {
6394 		/*
6395 		 * This is a fast cursor update coming from the plane update
6396 		 * helper, check if it can be done asynchronously for better
6397 		 * performance.
6398 		 */
6399 		state->async_update =
6400 			!drm_atomic_helper_async_check(dev, state);
6401 
6402 		/*
6403 		 * Skip the remaining global validation if this is an async
6404 		 * update. Cursor updates can be done without affecting
6405 		 * state or bandwidth calcs and this avoids the performance
6406 		 * penalty of locking the private state object and
6407 		 * allocating a new dc_state.
6408 		 */
6409 		if (state->async_update)
6410 			return 0;
6411 	}
6412 
6413 	/* Check scaling and underscan changes*/
6414 	/* TODO Removed scaling changes validation due to inability to commit
6415 	 * new stream into context w\o causing full reset. Need to
6416 	 * decide how to handle.
6417 	 */
6418 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6419 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6420 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6421 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6422 
6423 		/* Skip any modesets/resets */
6424 		if (!acrtc || drm_atomic_crtc_needs_modeset(
6425 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
6426 			continue;
6427 
6428 		/* Skip any thing not scale or underscan changes */
6429 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
6430 			continue;
6431 
6432 		lock_and_validation_needed = true;
6433 	}
6434 
6435 	/* set the slot info for each mst_state based on the link encoding format */
6436 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
6437 		struct amdgpu_dm_connector *aconnector;
6438 		struct drm_connector *connector;
6439 		struct drm_connector_list_iter iter;
6440 		u8 link_coding_cap;
6441 
6442 		drm_connector_list_iter_begin(dev, &iter);
6443 		drm_for_each_connector_iter(connector, &iter) {
6444 			if (connector->index == mst_state->mgr->conn_base_id) {
6445 				aconnector = to_amdgpu_dm_connector(connector);
6446 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
6447 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
6448 
6449 				break;
6450 			}
6451 		}
6452 		drm_connector_list_iter_end(&iter);
6453 	}
6454 
6455 	/**
6456 	 * Streams and planes are reset when there are changes that affect
6457 	 * bandwidth. Anything that affects bandwidth needs to go through
6458 	 * DC global validation to ensure that the configuration can be applied
6459 	 * to hardware.
6460 	 *
6461 	 * We have to currently stall out here in atomic_check for outstanding
6462 	 * commits to finish in this case because our IRQ handlers reference
6463 	 * DRM state directly - we can end up disabling interrupts too early
6464 	 * if we don't.
6465 	 *
6466 	 * TODO: Remove this stall and drop DM state private objects.
6467 	 */
6468 	if (lock_and_validation_needed) {
6469 		ret = dm_atomic_get_state(state, &dm_state);
6470 		if (ret) {
6471 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed: %pe\n", ERR_PTR(ret));
6472 			goto fail;
6473 		}
6474 
6475 		ret = do_aquire_global_lock(dev, state);
6476 		if (ret) {
6477 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed: %pe\n", ERR_PTR(ret));
6478 			goto fail;
6479 		}
6480 
6481 #if defined(CONFIG_DRM_AMD_DC_FP)
6482 		if (dc_resource_is_dsc_encoding_supported(dc)) {
6483 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
6484 			if (ret) {
6485 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed: %pe\n", ERR_PTR(ret));
6486 				ret = -EINVAL;
6487 				goto fail;
6488 			}
6489 		}
6490 #endif
6491 
6492 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
6493 		if (ret) {
6494 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed: %pe\n", ERR_PTR(ret));
6495 			goto fail;
6496 		}
6497 
6498 		/*
6499 		 * Perform validation of MST topology in the state:
6500 		 * We need to perform MST atomic check before calling
6501 		 * dc_validate_global_state(), or there is a chance
6502 		 * to get stuck in an infinite loop and hang eventually.
6503 		 */
6504 		ret = drm_dp_mst_atomic_check(state);
6505 		if (ret) {
6506 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed: %pe\n", ERR_PTR(ret));
6507 			goto fail;
6508 		}
6509 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
6510 		if (status != DC_OK) {
6511 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
6512 				       dc_status_to_str(status), status);
6513 			ret = -EINVAL;
6514 			goto fail;
6515 		}
6516 	} else {
6517 		/*
6518 		 * The commit is a fast update. Fast updates shouldn't change
6519 		 * the DC context, affect global validation, and can have their
6520 		 * commit work done in parallel with other commits not touching
6521 		 * the same resource. If we have a new DC context as part of
6522 		 * the DM atomic state from validation we need to free it and
6523 		 * retain the existing one instead.
6524 		 *
6525 		 * Furthermore, since the DM atomic state only contains the DC
6526 		 * context and can safely be annulled, we can free the state
6527 		 * and clear the associated private object now to free
6528 		 * some memory and avoid a possible use-after-free later.
6529 		 */
6530 
6531 		for (i = 0; i < state->num_private_objs; i++) {
6532 			struct drm_private_obj *obj = state->private_objs[i].ptr;
6533 
6534 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
6535 				int j = state->num_private_objs-1;
6536 
6537 				dm_atomic_destroy_state(obj,
6538 						state->private_objs[i].state_to_destroy);
6539 
6540 				/* If i is not at the end of the array then the
6541 				 * last element needs to be moved to where i was
6542 				 * before the array can safely be truncated.
6543 				 */
6544 				if (i != j)
6545 					state->private_objs[i] =
6546 						state->private_objs[j];
6547 
6548 				state->private_objs[j].ptr = NULL;
6549 				state->private_objs[j].state_to_destroy = NULL;
6550 				state->private_objs[j].old_state = NULL;
6551 				state->private_objs[j].new_state = NULL;
6552 
6553 				state->num_private_objs = j;
6554 				break;
6555 			}
6556 		}
6557 	}
6558 
6559 	/* Store the overall update type for use later in atomic check. */
6560 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6561 		struct dm_crtc_state *dm_new_crtc_state =
6562 			to_dm_crtc_state(new_crtc_state);
6563 
6564 		/*
6565 		 * Only allow async flips for fast updates that don't change
6566 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
6567 		 */
6568 		if (new_crtc_state->async_flip &&
6569 		    (lock_and_validation_needed ||
6570 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
6571 			drm_dbg_atomic(crtc->dev,
6572 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
6573 				       crtc->base.id, crtc->name);
6574 			ret = -EINVAL;
6575 			goto fail;
6576 		}
6577 
6578 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
6579 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
6580 	}
6581 
6582 	/* Must be success */
6583 	WARN_ON(ret);
6584 
6585 	trace_amdgpu_dm_atomic_check_finish(state, ret);
6586 
6587 	return ret;
6588 
6589 fail:
6590 	if (ret == -EDEADLK)
6591 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
6592 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
6593 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
6594 	else
6595 		drm_dbg_atomic(dev, "Atomic check failed: %pe\n", ERR_PTR(ret));
6596 
6597 	trace_amdgpu_dm_atomic_check_finish(state, ret);
6598 
6599 	return ret;
6600 }
6601 
6602 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
6603 {
6604 	struct amdgpu_device *adev = drm_to_adev(dev);
6605 	struct dc *dc = adev->dm.dc;
6606 	int i;
6607 
6608 	mutex_lock(&adev->dm.dc_lock);
6609 	if (dc->current_state) {
6610 		for (i = 0; i < dc->current_state->stream_count; ++i)
6611 			dc->current_state->streams[i]
6612 				->triggered_crtc_reset.enabled =
6613 				adev->dm.force_timing_sync;
6614 
6615 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
6616 		dc_trigger_sync(dc, dc->current_state);
6617 	}
6618 	mutex_unlock(&adev->dm.dc_lock);
6619 }
6620 
6621 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
6622 		       u32 value, const char *func_name)
6623 {
6624 #ifdef DM_CHECK_ADDR_0
6625 	if (address == 0) {
6626 		drm_err(adev_to_drm(ctx->driver_context),
6627 			"invalid register write. address = 0");
6628 		return;
6629 	}
6630 #endif
6631 
6632 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
6633 	cgs_write_register(ctx->cgs_device, address, value);
6634 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
6635 }
6636 
6637 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
6638 			  const char *func_name)
6639 {
6640 	u32 value;
6641 #ifdef DM_CHECK_ADDR_0
6642 	if (address == 0) {
6643 		drm_err(adev_to_drm(ctx->driver_context),
6644 			"invalid register read; address = 0\n");
6645 		return 0;
6646 	}
6647 #endif
6648 
6649 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
6650 
6651 	value = cgs_read_register(ctx->cgs_device, address);
6652 
6653 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
6654 
6655 	return value;
6656 }
6657 
6658 void dm_acpi_process_phy_transition_interlock(
6659 	const struct dc_context *ctx,
6660 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
6661 {
6662 	// Not yet implemented
6663 }
6664