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