xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision eb51c5a103f63b6e9c3f9cebf7b1e2e1056d3119)
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 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_utils.h>
95 #include <drm/drm_vblank.h>
96 #include <drm/drm_audio_component.h>
97 #include <drm/drm_gem_atomic_helper.h>
98 
99 #include <media/cec-notifier.h>
100 #include <acpi/video.h>
101 
102 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
103 
104 #include "modules/inc/mod_freesync.h"
105 #include "modules/power/power_helpers.h"
106 
107 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
108 
109 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
110 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
111 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
112 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
113 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
114 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
115 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
116 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
117 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
118 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
119 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
120 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
121 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
122 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
123 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
124 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
125 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
126 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
127 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
128 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
129 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
130 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
131 
132 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
134 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
135 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
136 
137 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
138 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
139 
140 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
142 
143 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
144 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
145 
146 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
148 
149 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
151 
152 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
154 
155 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
157 
158 /**
159  * DOC: overview
160  *
161  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
162  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
163  * requests into DC requests, and DC responses into DRM responses.
164  *
165  * The root control structure is &struct amdgpu_display_manager.
166  */
167 
168 /* basic init/fini API */
169 static int amdgpu_dm_init(struct amdgpu_device *adev);
170 static void amdgpu_dm_fini(struct amdgpu_device *adev);
171 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
172 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
173 static struct amdgpu_i2c_adapter *
174 create_i2c(struct ddc_service *ddc_service, bool oem);
175 
176 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
177 {
178 	switch (link->dpcd_caps.dongle_type) {
179 	case DISPLAY_DONGLE_NONE:
180 		return DRM_MODE_SUBCONNECTOR_Native;
181 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
182 		return DRM_MODE_SUBCONNECTOR_VGA;
183 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
184 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
185 		return DRM_MODE_SUBCONNECTOR_DVID;
186 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
187 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
188 		return DRM_MODE_SUBCONNECTOR_HDMIA;
189 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
190 	default:
191 		return DRM_MODE_SUBCONNECTOR_Unknown;
192 	}
193 }
194 
195 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
196 {
197 	struct dc_link *link = aconnector->dc_link;
198 	struct drm_connector *connector = &aconnector->base;
199 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
200 
201 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
202 		return;
203 
204 	if (aconnector->dc_sink)
205 		subconnector = get_subconnector_type(link);
206 
207 	drm_object_property_set_value(&connector->base,
208 			connector->dev->mode_config.dp_subconnector_property,
209 			subconnector);
210 }
211 
212 /*
213  * initializes drm_device display related structures, based on the information
214  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
215  * drm_encoder, drm_mode_config
216  *
217  * Returns 0 on success
218  */
219 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
220 /* removes and deallocates the drm structures, created by the above function */
221 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
222 
223 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
224 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
225 				    u32 link_index,
226 				    struct amdgpu_encoder *amdgpu_encoder);
227 static int amdgpu_dm_encoder_init(struct drm_device *dev,
228 				  struct amdgpu_encoder *aencoder,
229 				  uint32_t link_index);
230 
231 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
232 
233 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state);
234 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
235 
236 static int amdgpu_dm_atomic_check(struct drm_device *dev,
237 				  struct drm_atomic_state *state);
238 
239 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
240 static void handle_hpd_rx_irq(void *param);
241 
242 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
243 					 int bl_idx,
244 					 u32 user_brightness);
245 
246 static bool
247 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
248 				 struct drm_crtc_state *new_crtc_state);
249 /*
250  * dm_vblank_get_counter
251  *
252  * @brief
253  * Get counter for number of vertical blanks
254  *
255  * @param
256  * struct amdgpu_device *adev - [in] desired amdgpu device
257  * int disp_idx - [in] which CRTC to get the counter from
258  *
259  * @return
260  * Counter for vertical blanks
261  */
262 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
263 {
264 	struct amdgpu_crtc *acrtc = NULL;
265 
266 	if (crtc >= adev->mode_info.num_crtc)
267 		return 0;
268 
269 	acrtc = adev->mode_info.crtcs[crtc];
270 
271 	if (!acrtc->dm_irq_params.stream) {
272 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
273 			  crtc);
274 		return 0;
275 	}
276 
277 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
278 }
279 
280 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
281 				  u32 *vbl, u32 *position)
282 {
283 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
284 	struct amdgpu_crtc *acrtc = NULL;
285 	struct dc *dc = adev->dm.dc;
286 
287 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
288 		return -EINVAL;
289 
290 	acrtc = adev->mode_info.crtcs[crtc];
291 
292 	if (!acrtc->dm_irq_params.stream) {
293 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
294 			  crtc);
295 		return 0;
296 	}
297 
298 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
299 		dc_allow_idle_optimizations(dc, false);
300 
301 	/*
302 	 * TODO rework base driver to use values directly.
303 	 * for now parse it back into reg-format
304 	 */
305 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
306 				 &v_blank_start,
307 				 &v_blank_end,
308 				 &h_position,
309 				 &v_position);
310 
311 	*position = v_position | (h_position << 16);
312 	*vbl = v_blank_start | (v_blank_end << 16);
313 
314 	return 0;
315 }
316 
317 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
318 {
319 	/* XXX todo */
320 	return true;
321 }
322 
323 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return 0;
327 }
328 
329 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
330 {
331 	return false;
332 }
333 
334 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
335 {
336 	/* XXX todo */
337 	return 0;
338 }
339 
340 static struct amdgpu_crtc *
341 get_crtc_by_otg_inst(struct amdgpu_device *adev,
342 		     int otg_inst)
343 {
344 	struct drm_device *dev = adev_to_drm(adev);
345 	struct drm_crtc *crtc;
346 	struct amdgpu_crtc *amdgpu_crtc;
347 
348 	if (WARN_ON(otg_inst == -1))
349 		return adev->mode_info.crtcs[0];
350 
351 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
352 		amdgpu_crtc = to_amdgpu_crtc(crtc);
353 
354 		if (amdgpu_crtc->otg_inst == otg_inst)
355 			return amdgpu_crtc;
356 	}
357 
358 	return NULL;
359 }
360 
361 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
362 					      struct dm_crtc_state *new_state)
363 {
364 	if (new_state->stream->adjust.timing_adjust_pending)
365 		return true;
366 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
367 		return true;
368 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
369 		return true;
370 	else
371 		return false;
372 }
373 
374 /*
375  * DC will program planes with their z-order determined by their ordering
376  * in the dc_surface_updates array. This comparator is used to sort them
377  * by descending zpos.
378  */
379 static int dm_plane_layer_index_cmp(const void *a, const void *b)
380 {
381 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
382 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
383 
384 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
385 	return sb->surface->layer_index - sa->surface->layer_index;
386 }
387 
388 /**
389  * update_planes_and_stream_adapter() - Send planes to be updated in DC
390  *
391  * DC has a generic way to update planes and stream via
392  * dc_update_planes_and_stream function; however, DM might need some
393  * adjustments and preparation before calling it. This function is a wrapper
394  * for the dc_update_planes_and_stream that does any required configuration
395  * before passing control to DC.
396  *
397  * @dc: Display Core control structure
398  * @update_type: specify whether it is FULL/MEDIUM/FAST update
399  * @planes_count: planes count to update
400  * @stream: stream state
401  * @stream_update: stream update
402  * @array_of_surface_update: dc surface update pointer
403  *
404  */
405 static inline bool update_planes_and_stream_adapter(struct dc *dc,
406 						    int update_type,
407 						    int planes_count,
408 						    struct dc_stream_state *stream,
409 						    struct dc_stream_update *stream_update,
410 						    struct dc_surface_update *array_of_surface_update)
411 {
412 	sort(array_of_surface_update, planes_count,
413 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
414 
415 	/*
416 	 * Previous frame finished and HW is ready for optimization.
417 	 */
418 	dc_post_update_surfaces_to_stream(dc);
419 
420 	return dc_update_planes_and_stream(dc,
421 					   array_of_surface_update,
422 					   planes_count,
423 					   stream,
424 					   stream_update);
425 }
426 
427 /**
428  * dm_pflip_high_irq() - Handle pageflip interrupt
429  * @interrupt_params: ignored
430  *
431  * Handles the pageflip interrupt by notifying all interested parties
432  * that the pageflip has been completed.
433  */
434 static void dm_pflip_high_irq(void *interrupt_params)
435 {
436 	struct amdgpu_crtc *amdgpu_crtc;
437 	struct common_irq_params *irq_params = interrupt_params;
438 	struct amdgpu_device *adev = irq_params->adev;
439 	struct drm_device *dev = adev_to_drm(adev);
440 	unsigned long flags;
441 	struct drm_pending_vblank_event *e;
442 	u32 vpos, hpos, v_blank_start, v_blank_end;
443 	bool vrr_active;
444 
445 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
446 
447 	/* IRQ could occur when in initial stage */
448 	/* TODO work and BO cleanup */
449 	if (amdgpu_crtc == NULL) {
450 		drm_dbg_state(dev, "CRTC is null, returning.\n");
451 		return;
452 	}
453 
454 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
455 
456 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
457 		drm_dbg_state(dev,
458 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
459 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
460 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
461 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
462 		return;
463 	}
464 
465 	/* page flip completed. */
466 	e = amdgpu_crtc->event;
467 	amdgpu_crtc->event = NULL;
468 
469 	WARN_ON(!e);
470 
471 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
472 
473 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
474 	if (!vrr_active ||
475 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
476 				      &v_blank_end, &hpos, &vpos) ||
477 	    (vpos < v_blank_start)) {
478 		/* Update to correct count and vblank timestamp if racing with
479 		 * vblank irq. This also updates to the correct vblank timestamp
480 		 * even in VRR mode, as scanout is past the front-porch atm.
481 		 */
482 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
483 
484 		/* Wake up userspace by sending the pageflip event with proper
485 		 * count and timestamp of vblank of flip completion.
486 		 */
487 		if (e) {
488 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
489 
490 			/* Event sent, so done with vblank for this flip */
491 			drm_crtc_vblank_put(&amdgpu_crtc->base);
492 		}
493 	} else if (e) {
494 		/* VRR active and inside front-porch: vblank count and
495 		 * timestamp for pageflip event will only be up to date after
496 		 * drm_crtc_handle_vblank() has been executed from late vblank
497 		 * irq handler after start of back-porch (vline 0). We queue the
498 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
499 		 * updated timestamp and count, once it runs after us.
500 		 *
501 		 * We need to open-code this instead of using the helper
502 		 * drm_crtc_arm_vblank_event(), as that helper would
503 		 * call drm_crtc_accurate_vblank_count(), which we must
504 		 * not call in VRR mode while we are in front-porch!
505 		 */
506 
507 		/* sequence will be replaced by real count during send-out. */
508 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
509 		e->pipe = amdgpu_crtc->crtc_id;
510 
511 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
512 		e = NULL;
513 	}
514 
515 	/* Keep track of vblank of this flip for flip throttling. We use the
516 	 * cooked hw counter, as that one incremented at start of this vblank
517 	 * of pageflip completion, so last_flip_vblank is the forbidden count
518 	 * for queueing new pageflips if vsync + VRR is enabled.
519 	 */
520 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
521 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
522 
523 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
524 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
525 
526 	drm_dbg_state(dev,
527 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
528 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
529 }
530 
531 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
532 {
533 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
534 	struct amdgpu_device *adev = work->adev;
535 	struct dc_stream_state *stream = work->stream;
536 	struct dc_crtc_timing_adjust *adjust = work->adjust;
537 
538 	mutex_lock(&adev->dm.dc_lock);
539 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
540 	mutex_unlock(&adev->dm.dc_lock);
541 
542 	dc_stream_release(stream);
543 	kfree(work->adjust);
544 	kfree(work);
545 }
546 
547 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
548 	struct dc_stream_state *stream,
549 	struct dc_crtc_timing_adjust *adjust)
550 {
551 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
552 								GFP_NOWAIT);
553 	if (!offload_work) {
554 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
555 		return;
556 	}
557 
558 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
559 								GFP_NOWAIT);
560 	if (!adjust_copy) {
561 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
562 		kfree(offload_work);
563 		return;
564 	}
565 
566 	dc_stream_retain(stream);
567 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
568 
569 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
570 	offload_work->adev = adev;
571 	offload_work->stream = stream;
572 	offload_work->adjust = adjust_copy;
573 
574 	queue_work(system_wq, &offload_work->work);
575 }
576 
577 static void dm_vupdate_high_irq(void *interrupt_params)
578 {
579 	struct common_irq_params *irq_params = interrupt_params;
580 	struct amdgpu_device *adev = irq_params->adev;
581 	struct amdgpu_crtc *acrtc;
582 	struct drm_device *drm_dev;
583 	struct drm_vblank_crtc *vblank;
584 	ktime_t frame_duration_ns, previous_timestamp;
585 	unsigned long flags;
586 	int vrr_active;
587 
588 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
589 
590 	if (acrtc) {
591 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
592 		drm_dev = acrtc->base.dev;
593 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
594 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
595 		frame_duration_ns = vblank->time - previous_timestamp;
596 
597 		if (frame_duration_ns > 0) {
598 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
599 						frame_duration_ns,
600 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
601 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
602 		}
603 
604 		drm_dbg_vbl(drm_dev,
605 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
606 			    vrr_active);
607 
608 		/* Core vblank handling is done here after end of front-porch in
609 		 * vrr mode, as vblank timestamping will give valid results
610 		 * while now done after front-porch. This will also deliver
611 		 * page-flip completion events that have been queued to us
612 		 * if a pageflip happened inside front-porch.
613 		 */
614 		if (vrr_active && acrtc->dm_irq_params.stream) {
615 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
616 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
617 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
618 				== VRR_STATE_ACTIVE_VARIABLE;
619 
620 			amdgpu_dm_crtc_handle_vblank(acrtc);
621 
622 			/* BTR processing for pre-DCE12 ASICs */
623 			if (adev->family < AMDGPU_FAMILY_AI) {
624 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
625 				mod_freesync_handle_v_update(
626 				    adev->dm.freesync_module,
627 				    acrtc->dm_irq_params.stream,
628 				    &acrtc->dm_irq_params.vrr_params);
629 
630 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
631 					schedule_dc_vmin_vmax(adev,
632 						acrtc->dm_irq_params.stream,
633 						&acrtc->dm_irq_params.vrr_params.adjust);
634 				}
635 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
636 			}
637 		}
638 	}
639 }
640 
641 /**
642  * dm_crtc_high_irq() - Handles CRTC interrupt
643  * @interrupt_params: used for determining the CRTC instance
644  *
645  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
646  * event handler.
647  */
648 static void dm_crtc_high_irq(void *interrupt_params)
649 {
650 	struct common_irq_params *irq_params = interrupt_params;
651 	struct amdgpu_device *adev = irq_params->adev;
652 	struct drm_writeback_job *job;
653 	struct amdgpu_crtc *acrtc;
654 	unsigned long flags;
655 	int vrr_active;
656 
657 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
658 	if (!acrtc)
659 		return;
660 
661 	if (acrtc->wb_conn) {
662 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
663 
664 		if (acrtc->wb_pending) {
665 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
666 						       struct drm_writeback_job,
667 						       list_entry);
668 			acrtc->wb_pending = false;
669 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
670 
671 			if (job) {
672 				unsigned int v_total, refresh_hz;
673 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
674 
675 				v_total = stream->adjust.v_total_max ?
676 					  stream->adjust.v_total_max : stream->timing.v_total;
677 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
678 					     100LL, (v_total * stream->timing.h_total));
679 				mdelay(1000 / refresh_hz);
680 
681 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
682 				dc_stream_fc_disable_writeback(adev->dm.dc,
683 							       acrtc->dm_irq_params.stream, 0);
684 			}
685 		} else
686 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
687 	}
688 
689 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
690 
691 	drm_dbg_vbl(adev_to_drm(adev),
692 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
693 		    vrr_active, acrtc->dm_irq_params.active_planes);
694 
695 	/**
696 	 * Core vblank handling at start of front-porch is only possible
697 	 * in non-vrr mode, as only there vblank timestamping will give
698 	 * valid results while done in front-porch. Otherwise defer it
699 	 * to dm_vupdate_high_irq after end of front-porch.
700 	 */
701 	if (!vrr_active)
702 		amdgpu_dm_crtc_handle_vblank(acrtc);
703 
704 	/**
705 	 * Following stuff must happen at start of vblank, for crc
706 	 * computation and below-the-range btr support in vrr mode.
707 	 */
708 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
709 
710 	/* BTR updates need to happen before VUPDATE on Vega and above. */
711 	if (adev->family < AMDGPU_FAMILY_AI)
712 		return;
713 
714 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
715 
716 	if (acrtc->dm_irq_params.stream &&
717 		acrtc->dm_irq_params.vrr_params.supported) {
718 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
719 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
720 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
721 
722 		mod_freesync_handle_v_update(adev->dm.freesync_module,
723 					     acrtc->dm_irq_params.stream,
724 					     &acrtc->dm_irq_params.vrr_params);
725 
726 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
727 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
728 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
729 					&acrtc->dm_irq_params.vrr_params.adjust);
730 		}
731 	}
732 
733 	/*
734 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
735 	 * In that case, pageflip completion interrupts won't fire and pageflip
736 	 * completion events won't get delivered. Prevent this by sending
737 	 * pending pageflip events from here if a flip is still pending.
738 	 *
739 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
740 	 * avoid race conditions between flip programming and completion,
741 	 * which could cause too early flip completion events.
742 	 */
743 	if (adev->family >= AMDGPU_FAMILY_RV &&
744 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
745 	    acrtc->dm_irq_params.active_planes == 0) {
746 		if (acrtc->event) {
747 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
748 			acrtc->event = NULL;
749 			drm_crtc_vblank_put(&acrtc->base);
750 		}
751 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
752 	}
753 
754 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
755 }
756 
757 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
758 /**
759  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
760  * DCN generation ASICs
761  * @interrupt_params: interrupt parameters
762  *
763  * Used to set crc window/read out crc value at vertical line 0 position
764  */
765 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
766 {
767 	struct common_irq_params *irq_params = interrupt_params;
768 	struct amdgpu_device *adev = irq_params->adev;
769 	struct amdgpu_crtc *acrtc;
770 
771 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
772 
773 	if (!acrtc)
774 		return;
775 
776 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
777 }
778 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
779 
780 /**
781  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
782  * @adev: amdgpu_device pointer
783  * @notify: dmub notification structure
784  *
785  * Dmub AUX or SET_CONFIG command completion processing callback
786  * Copies dmub notification to DM which is to be read by AUX command.
787  * issuing thread and also signals the event to wake up the thread.
788  */
789 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
790 					struct dmub_notification *notify)
791 {
792 	if (adev->dm.dmub_notify)
793 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
794 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
795 		complete(&adev->dm.dmub_aux_transfer_done);
796 }
797 
798 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
799 					struct dmub_notification *notify)
800 {
801 	if (!adev || !notify) {
802 		ASSERT(false);
803 		return;
804 	}
805 
806 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
807 	const uint8_t ddc_line = req->u.aux.ddc_line;
808 
809 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
810 		ASSERT(false);
811 		return;
812 	}
813 
814 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
815 
816 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
817 	memcpy(sync->reply_data, req, sizeof(*req));
818 	complete(&sync->replied);
819 }
820 
821 /**
822  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
823  * @adev: amdgpu_device pointer
824  * @notify: dmub notification structure
825  *
826  * Dmub Hpd interrupt processing callback. Gets displayindex through the
827  * ink index and calls helper to do the processing.
828  */
829 static void dmub_hpd_callback(struct amdgpu_device *adev,
830 			      struct dmub_notification *notify)
831 {
832 	struct amdgpu_dm_connector *aconnector;
833 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
834 	struct drm_connector *connector;
835 	struct drm_connector_list_iter iter;
836 	struct dc_link *link;
837 	u8 link_index = 0;
838 	struct drm_device *dev;
839 
840 	if (adev == NULL)
841 		return;
842 
843 	if (notify == NULL) {
844 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
845 		return;
846 	}
847 
848 	if (notify->link_index > adev->dm.dc->link_count) {
849 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
850 		return;
851 	}
852 
853 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
854 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
855 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
856 		return;
857 	}
858 
859 	link_index = notify->link_index;
860 	link = adev->dm.dc->links[link_index];
861 	dev = adev->dm.ddev;
862 
863 	drm_connector_list_iter_begin(dev, &iter);
864 	drm_for_each_connector_iter(connector, &iter) {
865 
866 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
867 			continue;
868 
869 		aconnector = to_amdgpu_dm_connector(connector);
870 		if (link && aconnector->dc_link == link) {
871 			if (notify->type == DMUB_NOTIFICATION_HPD)
872 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
873 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
874 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
875 			else
876 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
877 						notify->type, link_index);
878 
879 			hpd_aconnector = aconnector;
880 			break;
881 		}
882 	}
883 	drm_connector_list_iter_end(&iter);
884 
885 	if (hpd_aconnector) {
886 		if (notify->type == DMUB_NOTIFICATION_HPD) {
887 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
888 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
889 			handle_hpd_irq_helper(hpd_aconnector);
890 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
891 			handle_hpd_rx_irq(hpd_aconnector);
892 		}
893 	}
894 }
895 
896 /**
897  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
898  * @adev: amdgpu_device pointer
899  * @notify: dmub notification structure
900  *
901  * HPD sense changes can occur during low power states and need to be
902  * notified from firmware to driver.
903  */
904 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
905 			      struct dmub_notification *notify)
906 {
907 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
908 }
909 
910 /**
911  * register_dmub_notify_callback - Sets callback for DMUB notify
912  * @adev: amdgpu_device pointer
913  * @type: Type of dmub notification
914  * @callback: Dmub interrupt callback function
915  * @dmub_int_thread_offload: offload indicator
916  *
917  * API to register a dmub callback handler for a dmub notification
918  * Also sets indicator whether callback processing to be offloaded.
919  * to dmub interrupt handling thread
920  * Return: true if successfully registered, false if there is existing registration
921  */
922 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
923 					  enum dmub_notification_type type,
924 					  dmub_notify_interrupt_callback_t callback,
925 					  bool dmub_int_thread_offload)
926 {
927 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
928 		adev->dm.dmub_callback[type] = callback;
929 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
930 	} else
931 		return false;
932 
933 	return true;
934 }
935 
936 static void dm_handle_hpd_work(struct work_struct *work)
937 {
938 	struct dmub_hpd_work *dmub_hpd_wrk;
939 
940 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
941 
942 	if (!dmub_hpd_wrk->dmub_notify) {
943 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
944 		return;
945 	}
946 
947 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
948 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
949 		dmub_hpd_wrk->dmub_notify);
950 	}
951 
952 	kfree(dmub_hpd_wrk->dmub_notify);
953 	kfree(dmub_hpd_wrk);
954 
955 }
956 
957 static const char *dmub_notification_type_str(enum dmub_notification_type e)
958 {
959 	switch (e) {
960 	case DMUB_NOTIFICATION_NO_DATA:
961 		return "NO_DATA";
962 	case DMUB_NOTIFICATION_AUX_REPLY:
963 		return "AUX_REPLY";
964 	case DMUB_NOTIFICATION_HPD:
965 		return "HPD";
966 	case DMUB_NOTIFICATION_HPD_IRQ:
967 		return "HPD_IRQ";
968 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
969 		return "SET_CONFIG_REPLY";
970 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
971 		return "DPIA_NOTIFICATION";
972 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
973 		return "HPD_SENSE_NOTIFY";
974 	case DMUB_NOTIFICATION_FUSED_IO:
975 		return "FUSED_IO";
976 	default:
977 		return "<unknown>";
978 	}
979 }
980 
981 #define DMUB_TRACE_MAX_READ 64
982 /**
983  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
984  * @interrupt_params: used for determining the Outbox instance
985  *
986  * Handles the Outbox Interrupt
987  * event handler.
988  */
989 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
990 {
991 	struct dmub_notification notify = {0};
992 	struct common_irq_params *irq_params = interrupt_params;
993 	struct amdgpu_device *adev = irq_params->adev;
994 	struct amdgpu_display_manager *dm = &adev->dm;
995 	struct dmcub_trace_buf_entry entry = { 0 };
996 	u32 count = 0;
997 	struct dmub_hpd_work *dmub_hpd_wrk;
998 
999 	do {
1000 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1001 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1002 							entry.param0, entry.param1);
1003 
1004 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1005 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1006 		} else
1007 			break;
1008 
1009 		count++;
1010 
1011 	} while (count <= DMUB_TRACE_MAX_READ);
1012 
1013 	if (count > DMUB_TRACE_MAX_READ)
1014 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1015 
1016 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1017 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1018 
1019 		do {
1020 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1021 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1022 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1023 				continue;
1024 			}
1025 			if (!dm->dmub_callback[notify.type]) {
1026 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1027 					dmub_notification_type_str(notify.type));
1028 				continue;
1029 			}
1030 			if (dm->dmub_thread_offload[notify.type] == true) {
1031 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1032 							   GFP_ATOMIC);
1033 				if (!dmub_hpd_wrk) {
1034 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1035 					return;
1036 				}
1037 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1038 								    GFP_ATOMIC);
1039 				if (!dmub_hpd_wrk->dmub_notify) {
1040 					kfree(dmub_hpd_wrk);
1041 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1042 					return;
1043 				}
1044 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1045 				dmub_hpd_wrk->adev = adev;
1046 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1047 			} else {
1048 				dm->dmub_callback[notify.type](adev, &notify);
1049 			}
1050 		} while (notify.pending_notification);
1051 	}
1052 }
1053 
1054 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1055 		  enum amd_clockgating_state state)
1056 {
1057 	return 0;
1058 }
1059 
1060 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1061 		  enum amd_powergating_state state)
1062 {
1063 	return 0;
1064 }
1065 
1066 /* Prototypes of private functions */
1067 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1068 
1069 /* Allocate memory for FBC compressed data  */
1070 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1071 {
1072 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1073 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1074 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1075 	struct drm_display_mode *mode;
1076 	unsigned long max_size = 0;
1077 
1078 	if (adev->dm.dc->fbc_compressor == NULL)
1079 		return;
1080 
1081 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1082 		return;
1083 
1084 	if (compressor->bo_ptr)
1085 		return;
1086 
1087 
1088 	list_for_each_entry(mode, &connector->modes, head) {
1089 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1090 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1091 	}
1092 
1093 	if (max_size) {
1094 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1095 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1096 			    &compressor->gpu_addr, &compressor->cpu_addr);
1097 
1098 		if (r)
1099 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1100 		else {
1101 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1102 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1103 		}
1104 
1105 	}
1106 
1107 }
1108 
1109 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1110 					  int pipe, bool *enabled,
1111 					  unsigned char *buf, int max_bytes)
1112 {
1113 	struct drm_device *dev = dev_get_drvdata(kdev);
1114 	struct amdgpu_device *adev = drm_to_adev(dev);
1115 	struct drm_connector *connector;
1116 	struct drm_connector_list_iter conn_iter;
1117 	struct amdgpu_dm_connector *aconnector;
1118 	int ret = 0;
1119 
1120 	*enabled = false;
1121 
1122 	mutex_lock(&adev->dm.audio_lock);
1123 
1124 	drm_connector_list_iter_begin(dev, &conn_iter);
1125 	drm_for_each_connector_iter(connector, &conn_iter) {
1126 
1127 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1128 			continue;
1129 
1130 		aconnector = to_amdgpu_dm_connector(connector);
1131 		if (aconnector->audio_inst != port)
1132 			continue;
1133 
1134 		*enabled = true;
1135 		mutex_lock(&connector->eld_mutex);
1136 		ret = drm_eld_size(connector->eld);
1137 		memcpy(buf, connector->eld, min(max_bytes, ret));
1138 		mutex_unlock(&connector->eld_mutex);
1139 
1140 		break;
1141 	}
1142 	drm_connector_list_iter_end(&conn_iter);
1143 
1144 	mutex_unlock(&adev->dm.audio_lock);
1145 
1146 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1147 
1148 	return ret;
1149 }
1150 
1151 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1152 	.get_eld = amdgpu_dm_audio_component_get_eld,
1153 };
1154 
1155 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1156 				       struct device *hda_kdev, void *data)
1157 {
1158 	struct drm_device *dev = dev_get_drvdata(kdev);
1159 	struct amdgpu_device *adev = drm_to_adev(dev);
1160 	struct drm_audio_component *acomp = data;
1161 
1162 	acomp->ops = &amdgpu_dm_audio_component_ops;
1163 	acomp->dev = kdev;
1164 	adev->dm.audio_component = acomp;
1165 
1166 	return 0;
1167 }
1168 
1169 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1170 					  struct device *hda_kdev, void *data)
1171 {
1172 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1173 	struct drm_audio_component *acomp = data;
1174 
1175 	acomp->ops = NULL;
1176 	acomp->dev = NULL;
1177 	adev->dm.audio_component = NULL;
1178 }
1179 
1180 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1181 	.bind	= amdgpu_dm_audio_component_bind,
1182 	.unbind	= amdgpu_dm_audio_component_unbind,
1183 };
1184 
1185 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1186 {
1187 	int i, ret;
1188 
1189 	if (!amdgpu_audio)
1190 		return 0;
1191 
1192 	adev->mode_info.audio.enabled = true;
1193 
1194 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1195 
1196 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1197 		adev->mode_info.audio.pin[i].channels = -1;
1198 		adev->mode_info.audio.pin[i].rate = -1;
1199 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1200 		adev->mode_info.audio.pin[i].status_bits = 0;
1201 		adev->mode_info.audio.pin[i].category_code = 0;
1202 		adev->mode_info.audio.pin[i].connected = false;
1203 		adev->mode_info.audio.pin[i].id =
1204 			adev->dm.dc->res_pool->audios[i]->inst;
1205 		adev->mode_info.audio.pin[i].offset = 0;
1206 	}
1207 
1208 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1209 	if (ret < 0)
1210 		return ret;
1211 
1212 	adev->dm.audio_registered = true;
1213 
1214 	return 0;
1215 }
1216 
1217 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1218 {
1219 	if (!amdgpu_audio)
1220 		return;
1221 
1222 	if (!adev->mode_info.audio.enabled)
1223 		return;
1224 
1225 	if (adev->dm.audio_registered) {
1226 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1227 		adev->dm.audio_registered = false;
1228 	}
1229 
1230 	/* TODO: Disable audio? */
1231 
1232 	adev->mode_info.audio.enabled = false;
1233 }
1234 
1235 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1236 {
1237 	struct drm_audio_component *acomp = adev->dm.audio_component;
1238 
1239 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1240 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1241 
1242 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1243 						 pin, -1);
1244 	}
1245 }
1246 
1247 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1248 {
1249 	const struct dmcub_firmware_header_v1_0 *hdr;
1250 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1251 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1252 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1253 	struct dc *dc = adev->dm.dc;
1254 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1255 	struct abm *abm = adev->dm.dc->res_pool->abm;
1256 	struct dc_context *ctx = adev->dm.dc->ctx;
1257 	struct dmub_srv_hw_params hw_params;
1258 	enum dmub_status status;
1259 	const unsigned char *fw_inst_const, *fw_bss_data;
1260 	u32 i, fw_inst_const_size, fw_bss_data_size;
1261 	bool has_hw_support;
1262 
1263 	if (!dmub_srv)
1264 		/* DMUB isn't supported on the ASIC. */
1265 		return 0;
1266 
1267 	if (!fb_info) {
1268 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1269 		return -EINVAL;
1270 	}
1271 
1272 	if (!dmub_fw) {
1273 		/* Firmware required for DMUB support. */
1274 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	/* initialize register offsets for ASICs with runtime initialization available */
1279 	if (dmub_srv->hw_funcs.init_reg_offsets)
1280 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1281 
1282 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1283 	if (status != DMUB_STATUS_OK) {
1284 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1285 		return -EINVAL;
1286 	}
1287 
1288 	if (!has_hw_support) {
1289 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1290 		return 0;
1291 	}
1292 
1293 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1294 	status = dmub_srv_hw_reset(dmub_srv);
1295 	if (status != DMUB_STATUS_OK)
1296 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1297 
1298 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1299 
1300 	fw_inst_const = dmub_fw->data +
1301 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1302 			PSP_HEADER_BYTES_256;
1303 
1304 	fw_bss_data = dmub_fw->data +
1305 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1306 		      le32_to_cpu(hdr->inst_const_bytes);
1307 
1308 	/* Copy firmware and bios info into FB memory. */
1309 	fw_inst_const_size = adev->dm.fw_inst_size;
1310 
1311 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1312 
1313 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1314 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1315 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1316 	 * will be done by dm_dmub_hw_init
1317 	 */
1318 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1319 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1320 				fw_inst_const_size);
1321 	}
1322 
1323 	if (fw_bss_data_size)
1324 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1325 		       fw_bss_data, fw_bss_data_size);
1326 
1327 	/* Copy firmware bios info into FB memory. */
1328 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1329 	       adev->bios_size);
1330 
1331 	/* Reset regions that need to be reset. */
1332 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1333 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1334 
1335 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1336 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1337 
1338 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1339 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1343 
1344 	/* Initialize hardware. */
1345 	memset(&hw_params, 0, sizeof(hw_params));
1346 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1347 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1348 
1349 	/* backdoor load firmware and trigger dmub running */
1350 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1351 		hw_params.load_inst_const = true;
1352 
1353 	if (dmcu)
1354 		hw_params.psp_version = dmcu->psp_version;
1355 
1356 	for (i = 0; i < fb_info->num_fb; ++i)
1357 		hw_params.fb[i] = &fb_info->fb[i];
1358 
1359 	/* Enable usb4 dpia in the FW APU */
1360 	if (dc->caps.is_apu &&
1361 		dc->res_pool->usb4_dpia_count != 0 &&
1362 		!dc->debug.dpia_debug.bits.disable_dpia) {
1363 		hw_params.dpia_supported = true;
1364 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1365 		hw_params.dpia_hpd_int_enable_supported = false;
1366 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1367 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1368 	}
1369 
1370 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1371 	case IP_VERSION(3, 5, 0):
1372 	case IP_VERSION(3, 5, 1):
1373 	case IP_VERSION(3, 6, 0):
1374 	case IP_VERSION(4, 2, 0):
1375 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1376 		hw_params.lower_hbr3_phy_ssc = true;
1377 		break;
1378 	default:
1379 		break;
1380 	}
1381 
1382 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1383 	if (status != DMUB_STATUS_OK) {
1384 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1385 		return -EINVAL;
1386 	}
1387 
1388 	/* Wait for firmware load to finish. */
1389 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1390 	if (status != DMUB_STATUS_OK)
1391 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1392 
1393 	/* Init DMCU and ABM if available. */
1394 	if (dmcu && abm) {
1395 		dmcu->funcs->dmcu_init(dmcu);
1396 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1397 	}
1398 
1399 	if (!adev->dm.dc->ctx->dmub_srv)
1400 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1401 	if (!adev->dm.dc->ctx->dmub_srv) {
1402 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1403 		return -ENOMEM;
1404 	}
1405 
1406 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1407 		 adev->dm.dmcub_fw_version);
1408 
1409 	/* Keeping sanity checks off if
1410 	 * DCN31 >= 4.0.59.0
1411 	 * DCN314 >= 8.0.16.0
1412 	 * Otherwise, turn on sanity checks
1413 	 */
1414 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1415 	case IP_VERSION(3, 1, 2):
1416 	case IP_VERSION(3, 1, 3):
1417 		if (adev->dm.dmcub_fw_version &&
1418 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1419 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1420 				adev->dm.dc->debug.sanity_checks = true;
1421 		break;
1422 	case IP_VERSION(3, 1, 4):
1423 		if (adev->dm.dmcub_fw_version &&
1424 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1425 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1426 				adev->dm.dc->debug.sanity_checks = true;
1427 		break;
1428 	default:
1429 		break;
1430 	}
1431 
1432 	return 0;
1433 }
1434 
1435 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1436 {
1437 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1438 	enum dmub_status status;
1439 	bool init;
1440 	int r;
1441 
1442 	if (!dmub_srv) {
1443 		/* DMUB isn't supported on the ASIC. */
1444 		return;
1445 	}
1446 
1447 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1448 	if (status != DMUB_STATUS_OK)
1449 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1450 
1451 	if (status == DMUB_STATUS_OK && init) {
1452 		/* Wait for firmware load to finish. */
1453 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1454 		if (status != DMUB_STATUS_OK)
1455 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1456 	} else {
1457 		/* Perform the full hardware initialization. */
1458 		r = dm_dmub_hw_init(adev);
1459 		if (r)
1460 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1461 	}
1462 }
1463 
1464 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1465 {
1466 	u64 pt_base;
1467 	u32 logical_addr_low;
1468 	u32 logical_addr_high;
1469 	u32 agp_base, agp_bot, agp_top;
1470 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1471 
1472 	memset(pa_config, 0, sizeof(*pa_config));
1473 
1474 	agp_base = 0;
1475 	agp_bot = adev->gmc.agp_start >> 24;
1476 	agp_top = adev->gmc.agp_end >> 24;
1477 
1478 	/* AGP aperture is disabled */
1479 	if (agp_bot > agp_top) {
1480 		logical_addr_low = adev->gmc.fb_start >> 18;
1481 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1482 				       AMD_APU_IS_RENOIR |
1483 				       AMD_APU_IS_GREEN_SARDINE))
1484 			/*
1485 			 * Raven2 has a HW issue that it is unable to use the vram which
1486 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1487 			 * workaround that increase system aperture high address (add 1)
1488 			 * to get rid of the VM fault and hardware hang.
1489 			 */
1490 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1491 		else
1492 			logical_addr_high = adev->gmc.fb_end >> 18;
1493 	} else {
1494 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1495 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1496 				       AMD_APU_IS_RENOIR |
1497 				       AMD_APU_IS_GREEN_SARDINE))
1498 			/*
1499 			 * Raven2 has a HW issue that it is unable to use the vram which
1500 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1501 			 * workaround that increase system aperture high address (add 1)
1502 			 * to get rid of the VM fault and hardware hang.
1503 			 */
1504 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1505 		else
1506 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1507 	}
1508 
1509 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1510 
1511 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1512 						   AMDGPU_GPU_PAGE_SHIFT);
1513 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1514 						  AMDGPU_GPU_PAGE_SHIFT);
1515 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1516 						 AMDGPU_GPU_PAGE_SHIFT);
1517 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1518 						AMDGPU_GPU_PAGE_SHIFT);
1519 	page_table_base.high_part = upper_32_bits(pt_base);
1520 	page_table_base.low_part = lower_32_bits(pt_base);
1521 
1522 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1523 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1524 
1525 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1526 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1527 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1528 
1529 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1530 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1531 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1532 
1533 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1534 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1535 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1536 
1537 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1538 
1539 }
1540 
1541 static void force_connector_state(
1542 	struct amdgpu_dm_connector *aconnector,
1543 	enum drm_connector_force force_state)
1544 {
1545 	struct drm_connector *connector = &aconnector->base;
1546 
1547 	mutex_lock(&connector->dev->mode_config.mutex);
1548 	aconnector->base.force = force_state;
1549 	mutex_unlock(&connector->dev->mode_config.mutex);
1550 
1551 	mutex_lock(&aconnector->hpd_lock);
1552 	drm_kms_helper_connector_hotplug_event(connector);
1553 	mutex_unlock(&aconnector->hpd_lock);
1554 }
1555 
1556 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1557 {
1558 	struct hpd_rx_irq_offload_work *offload_work;
1559 	struct amdgpu_dm_connector *aconnector;
1560 	struct dc_link *dc_link;
1561 	struct amdgpu_device *adev;
1562 	enum dc_connection_type new_connection_type = dc_connection_none;
1563 	unsigned long flags;
1564 	union test_response test_response;
1565 
1566 	memset(&test_response, 0, sizeof(test_response));
1567 
1568 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1569 	aconnector = offload_work->offload_wq->aconnector;
1570 	adev = offload_work->adev;
1571 
1572 	if (!aconnector) {
1573 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1574 		goto skip;
1575 	}
1576 
1577 	dc_link = aconnector->dc_link;
1578 
1579 	mutex_lock(&aconnector->hpd_lock);
1580 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1581 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1582 	mutex_unlock(&aconnector->hpd_lock);
1583 
1584 	if (new_connection_type == dc_connection_none)
1585 		goto skip;
1586 
1587 	if (amdgpu_in_reset(adev))
1588 		goto skip;
1589 
1590 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1591 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1592 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1593 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1594 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1595 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1596 		goto skip;
1597 	}
1598 
1599 	mutex_lock(&adev->dm.dc_lock);
1600 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1601 		dc_link_dp_handle_automated_test(dc_link);
1602 
1603 		if (aconnector->timing_changed) {
1604 			/* force connector disconnect and reconnect */
1605 			force_connector_state(aconnector, DRM_FORCE_OFF);
1606 			msleep(100);
1607 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1608 		}
1609 
1610 		test_response.bits.ACK = 1;
1611 
1612 		core_link_write_dpcd(
1613 		dc_link,
1614 		DP_TEST_RESPONSE,
1615 		&test_response.raw,
1616 		sizeof(test_response));
1617 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1618 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1619 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1620 		/* offload_work->data is from handle_hpd_rx_irq->
1621 		 * schedule_hpd_rx_offload_work.this is defer handle
1622 		 * for hpd short pulse. upon here, link status may be
1623 		 * changed, need get latest link status from dpcd
1624 		 * registers. if link status is good, skip run link
1625 		 * training again.
1626 		 */
1627 		union hpd_irq_data irq_data;
1628 
1629 		memset(&irq_data, 0, sizeof(irq_data));
1630 
1631 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1632 		 * request be added to work queue if link lost at end of dc_link_
1633 		 * dp_handle_link_loss
1634 		 */
1635 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1636 		offload_work->offload_wq->is_handling_link_loss = false;
1637 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1638 
1639 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1640 			dc_link_check_link_loss_status(dc_link, &irq_data))
1641 			dc_link_dp_handle_link_loss(dc_link);
1642 	}
1643 	mutex_unlock(&adev->dm.dc_lock);
1644 
1645 skip:
1646 	kfree(offload_work);
1647 
1648 }
1649 
1650 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1651 {
1652 	struct dc *dc = adev->dm.dc;
1653 	int max_caps = dc->caps.max_links;
1654 	int i = 0;
1655 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1656 
1657 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1658 
1659 	if (!hpd_rx_offload_wq)
1660 		return NULL;
1661 
1662 
1663 	for (i = 0; i < max_caps; i++) {
1664 		hpd_rx_offload_wq[i].wq =
1665 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1666 
1667 		if (hpd_rx_offload_wq[i].wq == NULL) {
1668 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1669 			goto out_err;
1670 		}
1671 
1672 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1673 	}
1674 
1675 	return hpd_rx_offload_wq;
1676 
1677 out_err:
1678 	for (i = 0; i < max_caps; i++) {
1679 		if (hpd_rx_offload_wq[i].wq)
1680 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1681 	}
1682 	kfree(hpd_rx_offload_wq);
1683 	return NULL;
1684 }
1685 
1686 struct amdgpu_stutter_quirk {
1687 	u16 chip_vendor;
1688 	u16 chip_device;
1689 	u16 subsys_vendor;
1690 	u16 subsys_device;
1691 	u8 revision;
1692 };
1693 
1694 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1695 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1696 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1697 	{ 0, 0, 0, 0, 0 },
1698 };
1699 
1700 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1701 {
1702 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1703 
1704 	while (p && p->chip_device != 0) {
1705 		if (pdev->vendor == p->chip_vendor &&
1706 		    pdev->device == p->chip_device &&
1707 		    pdev->subsystem_vendor == p->subsys_vendor &&
1708 		    pdev->subsystem_device == p->subsys_device &&
1709 		    pdev->revision == p->revision) {
1710 			return true;
1711 		}
1712 		++p;
1713 	}
1714 	return false;
1715 }
1716 
1717 
1718 void*
1719 dm_allocate_gpu_mem(
1720 		struct amdgpu_device *adev,
1721 		enum dc_gpu_mem_alloc_type type,
1722 		size_t size,
1723 		long long *addr)
1724 {
1725 	struct dal_allocation *da;
1726 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1727 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1728 	int ret;
1729 
1730 	da = kzalloc_obj(struct dal_allocation);
1731 	if (!da)
1732 		return NULL;
1733 
1734 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1735 				      domain, &da->bo,
1736 				      &da->gpu_addr, &da->cpu_ptr);
1737 
1738 	*addr = da->gpu_addr;
1739 
1740 	if (ret) {
1741 		kfree(da);
1742 		return NULL;
1743 	}
1744 
1745 	/* add da to list in dm */
1746 	list_add(&da->list, &adev->dm.da_list);
1747 
1748 	return da->cpu_ptr;
1749 }
1750 
1751 void
1752 dm_free_gpu_mem(
1753 		struct amdgpu_device *adev,
1754 		enum dc_gpu_mem_alloc_type type,
1755 		void *pvMem)
1756 {
1757 	struct dal_allocation *da;
1758 
1759 	/* walk the da list in DM */
1760 	list_for_each_entry(da, &adev->dm.da_list, list) {
1761 		if (pvMem == da->cpu_ptr) {
1762 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1763 			list_del(&da->list);
1764 			kfree(da);
1765 			break;
1766 		}
1767 	}
1768 
1769 }
1770 
1771 static enum dmub_status
1772 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1773 				 enum dmub_gpint_command command_code,
1774 				 uint16_t param,
1775 				 uint32_t timeout_us)
1776 {
1777 	union dmub_gpint_data_register reg, test;
1778 	uint32_t i;
1779 
1780 	/* Assume that VBIOS DMUB is ready to take commands */
1781 
1782 	reg.bits.status = 1;
1783 	reg.bits.command_code = command_code;
1784 	reg.bits.param = param;
1785 
1786 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1787 
1788 	for (i = 0; i < timeout_us; ++i) {
1789 		udelay(1);
1790 
1791 		/* Check if our GPINT got acked */
1792 		reg.bits.status = 0;
1793 		test = (union dmub_gpint_data_register)
1794 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1795 
1796 		if (test.all == reg.all)
1797 			return DMUB_STATUS_OK;
1798 	}
1799 
1800 	return DMUB_STATUS_TIMEOUT;
1801 }
1802 
1803 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1804 {
1805 	void *bb;
1806 	long long addr;
1807 	unsigned int bb_size;
1808 	int i = 0;
1809 	uint16_t chunk;
1810 	enum dmub_gpint_command send_addrs[] = {
1811 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1812 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1813 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1814 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1815 	};
1816 	enum dmub_status ret;
1817 
1818 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1819 	case IP_VERSION(4, 0, 1):
1820 		bb_size = sizeof(struct dml2_soc_bb);
1821 		break;
1822 	case IP_VERSION(4, 2, 0):
1823 		bb_size = sizeof(struct dml2_soc_bb);
1824 		break;
1825 	default:
1826 		return NULL;
1827 	}
1828 
1829 	bb =  dm_allocate_gpu_mem(adev,
1830 				  DC_MEM_ALLOC_TYPE_GART,
1831 				  bb_size,
1832 				  &addr);
1833 	if (!bb)
1834 		return NULL;
1835 
1836 	for (i = 0; i < 4; i++) {
1837 		/* Extract 16-bit chunk */
1838 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1839 		/* Send the chunk */
1840 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1841 		if (ret != DMUB_STATUS_OK)
1842 			goto free_bb;
1843 	}
1844 
1845 	/* Now ask DMUB to copy the bb */
1846 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1847 	if (ret != DMUB_STATUS_OK)
1848 		goto free_bb;
1849 
1850 	return bb;
1851 
1852 free_bb:
1853 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1854 	return NULL;
1855 
1856 }
1857 
1858 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1859 	struct amdgpu_device *adev)
1860 {
1861 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1862 
1863 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1864 	case IP_VERSION(3, 5, 0):
1865 	case IP_VERSION(3, 6, 0):
1866 	case IP_VERSION(3, 5, 1):
1867 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1868 		break;
1869 	case IP_VERSION(4, 2, 0):
1870 		ret =  DMUB_IPS_DISABLE_ALL;
1871 		break;
1872 	default:
1873 		/* ASICs older than DCN35 do not have IPSs */
1874 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1875 			ret = DMUB_IPS_DISABLE_ALL;
1876 		break;
1877 	}
1878 
1879 	return ret;
1880 }
1881 
1882 static int amdgpu_dm_init(struct amdgpu_device *adev)
1883 {
1884 	struct dc_init_data init_data;
1885 	struct dc_callback_init init_params;
1886 	int r;
1887 
1888 	adev->dm.ddev = adev_to_drm(adev);
1889 	adev->dm.adev = adev;
1890 
1891 	/* Zero all the fields */
1892 	memset(&init_data, 0, sizeof(init_data));
1893 	memset(&init_params, 0, sizeof(init_params));
1894 
1895 	mutex_init(&adev->dm.dpia_aux_lock);
1896 	mutex_init(&adev->dm.dc_lock);
1897 	mutex_init(&adev->dm.audio_lock);
1898 
1899 	if (amdgpu_dm_irq_init(adev)) {
1900 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1901 		goto error;
1902 	}
1903 
1904 	init_data.asic_id.chip_family = adev->family;
1905 
1906 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1907 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1908 	init_data.asic_id.chip_id = adev->pdev->device;
1909 
1910 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1911 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1912 	init_data.asic_id.atombios_base_address =
1913 		adev->mode_info.atom_context->bios;
1914 
1915 	init_data.driver = adev;
1916 
1917 	/* cgs_device was created in dm_sw_init() */
1918 	init_data.cgs_device = adev->dm.cgs_device;
1919 
1920 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1921 
1922 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1923 	case IP_VERSION(2, 1, 0):
1924 		switch (adev->dm.dmcub_fw_version) {
1925 		case 0: /* development */
1926 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1927 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1928 			init_data.flags.disable_dmcu = false;
1929 			break;
1930 		default:
1931 			init_data.flags.disable_dmcu = true;
1932 		}
1933 		break;
1934 	case IP_VERSION(2, 0, 3):
1935 		init_data.flags.disable_dmcu = true;
1936 		break;
1937 	default:
1938 		break;
1939 	}
1940 
1941 	/* APU support S/G display by default except:
1942 	 * ASICs before Carrizo,
1943 	 * RAVEN1 (Users reported stability issue)
1944 	 */
1945 
1946 	if (adev->asic_type < CHIP_CARRIZO) {
1947 		init_data.flags.gpu_vm_support = false;
1948 	} else if (adev->asic_type == CHIP_RAVEN) {
1949 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
1950 			init_data.flags.gpu_vm_support = false;
1951 		else
1952 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
1953 	} else {
1954 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
1955 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
1956 		else
1957 			init_data.flags.gpu_vm_support =
1958 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
1959 	}
1960 
1961 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
1962 
1963 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1964 		init_data.flags.fbc_support = true;
1965 
1966 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1967 		init_data.flags.multi_mon_pp_mclk_switch = true;
1968 
1969 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1970 		init_data.flags.disable_fractional_pwm = true;
1971 
1972 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1973 		init_data.flags.edp_no_power_sequencing = true;
1974 
1975 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1976 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1977 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1978 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1979 
1980 	init_data.flags.seamless_boot_edp_requested = false;
1981 
1982 	if (amdgpu_device_seamless_boot_supported(adev)) {
1983 		init_data.flags.seamless_boot_edp_requested = true;
1984 		init_data.flags.allow_seamless_boot_optimization = true;
1985 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
1986 	}
1987 
1988 	init_data.flags.enable_mipi_converter_optimization = true;
1989 
1990 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1991 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1992 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
1993 
1994 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
1995 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
1996 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
1997 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
1998 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
1999 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2000 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2001 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2002 	else
2003 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2004 
2005 	init_data.flags.disable_ips_in_vpb = 0;
2006 
2007 	/* DCN35 and above supports dynamic DTBCLK switch */
2008 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2009 		init_data.flags.allow_0_dtb_clk = true;
2010 
2011 	/* Enable DWB for tested platforms only */
2012 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2013 		init_data.num_virtual_links = 1;
2014 
2015 	/* DCN42 and above dpia switch to unified link training path */
2016 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2017 		init_data.flags.consolidated_dpia_dp_lt = true;
2018 		init_data.flags.enable_dpia_pre_training = true;
2019 		init_data.flags.unify_link_enc_assignment = true;
2020 		init_data.flags.usb4_bw_alloc_support = true;
2021 	}
2022 	retrieve_dmi_info(&adev->dm);
2023 	if (adev->dm.edp0_on_dp1_quirk)
2024 		init_data.flags.support_edp0_on_dp1 = true;
2025 
2026 	if (adev->dm.bb_from_dmub)
2027 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2028 	else
2029 		init_data.bb_from_dmub = NULL;
2030 
2031 	/* Display Core create. */
2032 	adev->dm.dc = dc_create(&init_data);
2033 
2034 	if (adev->dm.dc) {
2035 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2036 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2037 	} else {
2038 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2039 		goto error;
2040 	}
2041 
2042 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2043 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2044 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2045 	}
2046 
2047 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2048 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2049 	if (dm_should_disable_stutter(adev->pdev))
2050 		adev->dm.dc->debug.disable_stutter = true;
2051 
2052 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2053 		adev->dm.dc->debug.disable_stutter = true;
2054 
2055 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2056 		adev->dm.dc->debug.disable_dsc = true;
2057 
2058 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2059 		adev->dm.dc->debug.disable_clock_gate = true;
2060 
2061 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2062 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2063 
2064 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2065 		adev->dm.dc->debug.force_disable_subvp = true;
2066 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2067 	}
2068 
2069 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2070 		adev->dm.dc->debug.using_dml2 = true;
2071 		adev->dm.dc->debug.using_dml21 = true;
2072 	}
2073 
2074 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2075 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2076 
2077 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2078 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2079 
2080 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2081 		adev->dm.dc->debug.skip_detection_link_training = true;
2082 
2083 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2084 
2085 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2086 	adev->dm.dc->debug.ignore_cable_id = true;
2087 
2088 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2089 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2090 
2091 	r = dm_dmub_hw_init(adev);
2092 	if (r) {
2093 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2094 		goto error;
2095 	}
2096 
2097 	dc_hardware_init(adev->dm.dc);
2098 
2099 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2100 	if (!adev->dm.hpd_rx_offload_wq) {
2101 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2102 		goto error;
2103 	}
2104 
2105 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2106 		struct dc_phy_addr_space_config pa_config;
2107 
2108 		mmhub_read_system_context(adev, &pa_config);
2109 
2110 		// Call the DC init_memory func
2111 		dc_setup_system_context(adev->dm.dc, &pa_config);
2112 	}
2113 
2114 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2115 	if (!adev->dm.freesync_module) {
2116 		drm_err(adev_to_drm(adev),
2117 		"failed to initialize freesync_module.\n");
2118 	} else
2119 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2120 				adev->dm.freesync_module);
2121 
2122 	amdgpu_dm_init_color_mod();
2123 
2124 	if (adev->dm.dc->caps.max_links > 0) {
2125 		adev->dm.vblank_control_workqueue =
2126 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2127 		if (!adev->dm.vblank_control_workqueue)
2128 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2129 	}
2130 
2131 	if (adev->dm.dc->caps.ips_support &&
2132 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2133 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2134 
2135 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2136 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2137 
2138 		if (!adev->dm.hdcp_workqueue)
2139 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2140 		else
2141 			drm_dbg_driver(adev_to_drm(adev),
2142 				       "hdcp_workqueue init done %p.\n",
2143 				       adev->dm.hdcp_workqueue);
2144 
2145 		dc_init_callbacks(adev->dm.dc, &init_params);
2146 	}
2147 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2148 		init_completion(&adev->dm.dmub_aux_transfer_done);
2149 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2150 		if (!adev->dm.dmub_notify) {
2151 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2152 			goto error;
2153 		}
2154 
2155 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2156 		if (!adev->dm.delayed_hpd_wq) {
2157 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2158 			goto error;
2159 		}
2160 
2161 		amdgpu_dm_outbox_init(adev);
2162 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2163 			dmub_aux_setconfig_callback, false)) {
2164 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2165 			goto error;
2166 		}
2167 
2168 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2169 			init_completion(&adev->dm.fused_io[i].replied);
2170 
2171 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2172 			dmub_aux_fused_io_callback, false)) {
2173 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2174 			goto error;
2175 		}
2176 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2177 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2178 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2179 		 * align legacy interface initialization sequence. Connection status will be proactivly
2180 		 * detected once in the amdgpu_dm_initialize_drm_device.
2181 		 */
2182 		dc_enable_dmub_outbox(adev->dm.dc);
2183 
2184 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2185 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2186 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2187 	}
2188 
2189 	if (amdgpu_dm_initialize_drm_device(adev)) {
2190 		drm_err(adev_to_drm(adev),
2191 		"failed to initialize sw for display support.\n");
2192 		goto error;
2193 	}
2194 
2195 	/* create fake encoders for MST */
2196 	dm_dp_create_fake_mst_encoders(adev);
2197 
2198 	/* TODO: Add_display_info? */
2199 
2200 	/* TODO use dynamic cursor width */
2201 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2202 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2203 
2204 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2205 		drm_err(adev_to_drm(adev),
2206 		"failed to initialize vblank for display support.\n");
2207 		goto error;
2208 	}
2209 
2210 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2211 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2212 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2213 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2214 
2215 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2216 		adev->dm.secure_display_ctx.support_mul_roi = true;
2217 
2218 #endif
2219 
2220 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2221 
2222 	return 0;
2223 error:
2224 	amdgpu_dm_fini(adev);
2225 
2226 	return -EINVAL;
2227 }
2228 
2229 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2230 {
2231 	struct amdgpu_device *adev = ip_block->adev;
2232 
2233 	amdgpu_dm_audio_fini(adev);
2234 
2235 	return 0;
2236 }
2237 
2238 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2239 {
2240 	int i;
2241 
2242 	if (adev->dm.vblank_control_workqueue) {
2243 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2244 		adev->dm.vblank_control_workqueue = NULL;
2245 	}
2246 
2247 	if (adev->dm.idle_workqueue) {
2248 		if (adev->dm.idle_workqueue->running) {
2249 			adev->dm.idle_workqueue->enable = false;
2250 			flush_work(&adev->dm.idle_workqueue->work);
2251 		}
2252 
2253 		kfree(adev->dm.idle_workqueue);
2254 		adev->dm.idle_workqueue = NULL;
2255 	}
2256 
2257 	amdgpu_dm_destroy_drm_device(&adev->dm);
2258 
2259 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2260 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2261 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2262 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2263 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2264 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2265 			}
2266 		}
2267 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2268 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2269 	}
2270 #endif
2271 	if (adev->dm.hdcp_workqueue) {
2272 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2273 		adev->dm.hdcp_workqueue = NULL;
2274 	}
2275 
2276 	if (adev->dm.dc) {
2277 		dc_deinit_callbacks(adev->dm.dc);
2278 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2279 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2280 			kfree(adev->dm.dmub_notify);
2281 			adev->dm.dmub_notify = NULL;
2282 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2283 			adev->dm.delayed_hpd_wq = NULL;
2284 		}
2285 	}
2286 
2287 	if (adev->dm.dmub_bo)
2288 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2289 				      &adev->dm.dmub_bo_gpu_addr,
2290 				      &adev->dm.dmub_bo_cpu_addr);
2291 
2292 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2293 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2294 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2295 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2296 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2297 			}
2298 		}
2299 
2300 		kfree(adev->dm.hpd_rx_offload_wq);
2301 		adev->dm.hpd_rx_offload_wq = NULL;
2302 	}
2303 
2304 	/* DC Destroy TODO: Replace destroy DAL */
2305 	if (adev->dm.dc)
2306 		dc_destroy(&adev->dm.dc);
2307 	/*
2308 	 * TODO: pageflip, vlank interrupt
2309 	 *
2310 	 * amdgpu_dm_irq_fini(adev);
2311 	 */
2312 
2313 	if (adev->dm.cgs_device) {
2314 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2315 		adev->dm.cgs_device = NULL;
2316 	}
2317 	if (adev->dm.freesync_module) {
2318 		mod_freesync_destroy(adev->dm.freesync_module);
2319 		adev->dm.freesync_module = NULL;
2320 	}
2321 
2322 	mutex_destroy(&adev->dm.audio_lock);
2323 	mutex_destroy(&adev->dm.dc_lock);
2324 	mutex_destroy(&adev->dm.dpia_aux_lock);
2325 }
2326 
2327 static int load_dmcu_fw(struct amdgpu_device *adev)
2328 {
2329 	const char *fw_name_dmcu = NULL;
2330 	int r;
2331 	const struct dmcu_firmware_header_v1_0 *hdr;
2332 
2333 	switch (adev->asic_type) {
2334 #if defined(CONFIG_DRM_AMD_DC_SI)
2335 	case CHIP_TAHITI:
2336 	case CHIP_PITCAIRN:
2337 	case CHIP_VERDE:
2338 	case CHIP_OLAND:
2339 #endif
2340 	case CHIP_BONAIRE:
2341 	case CHIP_HAWAII:
2342 	case CHIP_KAVERI:
2343 	case CHIP_KABINI:
2344 	case CHIP_MULLINS:
2345 	case CHIP_TONGA:
2346 	case CHIP_FIJI:
2347 	case CHIP_CARRIZO:
2348 	case CHIP_STONEY:
2349 	case CHIP_POLARIS11:
2350 	case CHIP_POLARIS10:
2351 	case CHIP_POLARIS12:
2352 	case CHIP_VEGAM:
2353 	case CHIP_VEGA10:
2354 	case CHIP_VEGA12:
2355 	case CHIP_VEGA20:
2356 		return 0;
2357 	case CHIP_NAVI12:
2358 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2359 		break;
2360 	case CHIP_RAVEN:
2361 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2362 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2363 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2364 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2365 		else
2366 			return 0;
2367 		break;
2368 	default:
2369 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2370 		case IP_VERSION(2, 0, 2):
2371 		case IP_VERSION(2, 0, 3):
2372 		case IP_VERSION(2, 0, 0):
2373 		case IP_VERSION(2, 1, 0):
2374 		case IP_VERSION(3, 0, 0):
2375 		case IP_VERSION(3, 0, 2):
2376 		case IP_VERSION(3, 0, 3):
2377 		case IP_VERSION(3, 0, 1):
2378 		case IP_VERSION(3, 1, 2):
2379 		case IP_VERSION(3, 1, 3):
2380 		case IP_VERSION(3, 1, 4):
2381 		case IP_VERSION(3, 1, 5):
2382 		case IP_VERSION(3, 1, 6):
2383 		case IP_VERSION(3, 2, 0):
2384 		case IP_VERSION(3, 2, 1):
2385 		case IP_VERSION(3, 5, 0):
2386 		case IP_VERSION(3, 5, 1):
2387 		case IP_VERSION(3, 6, 0):
2388 		case IP_VERSION(4, 0, 1):
2389 		case IP_VERSION(4, 2, 0):
2390 			return 0;
2391 		default:
2392 			break;
2393 		}
2394 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2395 		return -EINVAL;
2396 	}
2397 
2398 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2399 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2400 		return 0;
2401 	}
2402 
2403 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2404 				 "%s", fw_name_dmcu);
2405 	if (r == -ENODEV) {
2406 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2407 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2408 		adev->dm.fw_dmcu = NULL;
2409 		return 0;
2410 	}
2411 	if (r) {
2412 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2413 			fw_name_dmcu);
2414 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2415 		return r;
2416 	}
2417 
2418 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2419 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2420 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2421 	adev->firmware.fw_size +=
2422 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2423 
2424 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2425 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2426 	adev->firmware.fw_size +=
2427 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2428 
2429 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2430 
2431 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2432 
2433 	return 0;
2434 }
2435 
2436 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2437 {
2438 	struct amdgpu_device *adev = ctx;
2439 
2440 	return dm_read_reg(adev->dm.dc->ctx, address);
2441 }
2442 
2443 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2444 				     uint32_t value)
2445 {
2446 	struct amdgpu_device *adev = ctx;
2447 
2448 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2449 }
2450 
2451 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2452 {
2453 	struct dmub_srv_create_params create_params;
2454 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2455 	struct dmub_srv_region_params region_params;
2456 	struct dmub_srv_region_info region_info;
2457 	struct dmub_srv_memory_params memory_params;
2458 	struct dmub_fw_meta_info fw_info;
2459 	struct dmub_srv_fb_info *fb_info;
2460 	struct dmub_srv *dmub_srv;
2461 	const struct dmcub_firmware_header_v1_0 *hdr;
2462 	enum dmub_asic dmub_asic;
2463 	enum dmub_status status;
2464 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2465 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2466 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2467 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2468 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2469 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2470 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2471 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2472 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2473 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2474 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2475 	};
2476 	int r;
2477 
2478 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2479 	case IP_VERSION(2, 1, 0):
2480 		dmub_asic = DMUB_ASIC_DCN21;
2481 		break;
2482 	case IP_VERSION(3, 0, 0):
2483 		dmub_asic = DMUB_ASIC_DCN30;
2484 		break;
2485 	case IP_VERSION(3, 0, 1):
2486 		dmub_asic = DMUB_ASIC_DCN301;
2487 		break;
2488 	case IP_VERSION(3, 0, 2):
2489 		dmub_asic = DMUB_ASIC_DCN302;
2490 		break;
2491 	case IP_VERSION(3, 0, 3):
2492 		dmub_asic = DMUB_ASIC_DCN303;
2493 		break;
2494 	case IP_VERSION(3, 1, 2):
2495 	case IP_VERSION(3, 1, 3):
2496 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2497 		break;
2498 	case IP_VERSION(3, 1, 4):
2499 		dmub_asic = DMUB_ASIC_DCN314;
2500 		break;
2501 	case IP_VERSION(3, 1, 5):
2502 		dmub_asic = DMUB_ASIC_DCN315;
2503 		break;
2504 	case IP_VERSION(3, 1, 6):
2505 		dmub_asic = DMUB_ASIC_DCN316;
2506 		break;
2507 	case IP_VERSION(3, 2, 0):
2508 		dmub_asic = DMUB_ASIC_DCN32;
2509 		break;
2510 	case IP_VERSION(3, 2, 1):
2511 		dmub_asic = DMUB_ASIC_DCN321;
2512 		break;
2513 	case IP_VERSION(3, 5, 0):
2514 	case IP_VERSION(3, 5, 1):
2515 		dmub_asic = DMUB_ASIC_DCN35;
2516 		break;
2517 	case IP_VERSION(3, 6, 0):
2518 		dmub_asic = DMUB_ASIC_DCN36;
2519 		break;
2520 	case IP_VERSION(4, 0, 1):
2521 		dmub_asic = DMUB_ASIC_DCN401;
2522 		break;
2523 	case IP_VERSION(4, 2, 0):
2524 		dmub_asic = DMUB_ASIC_DCN42;
2525 		break;
2526 	default:
2527 		/* ASIC doesn't support DMUB. */
2528 		return 0;
2529 	}
2530 
2531 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2532 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2533 
2534 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2535 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2536 			AMDGPU_UCODE_ID_DMCUB;
2537 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2538 			adev->dm.dmub_fw;
2539 		adev->firmware.fw_size +=
2540 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2541 
2542 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2543 			 adev->dm.dmcub_fw_version);
2544 	}
2545 
2546 
2547 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2548 	dmub_srv = adev->dm.dmub_srv;
2549 
2550 	if (!dmub_srv) {
2551 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2552 		return -ENOMEM;
2553 	}
2554 
2555 	memset(&create_params, 0, sizeof(create_params));
2556 	create_params.user_ctx = adev;
2557 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2558 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2559 	create_params.asic = dmub_asic;
2560 
2561 	/* Create the DMUB service. */
2562 	status = dmub_srv_create(dmub_srv, &create_params);
2563 	if (status != DMUB_STATUS_OK) {
2564 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2565 		return -EINVAL;
2566 	}
2567 
2568 	/* Extract the FW meta info. */
2569 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2570 
2571 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2572 					      PSP_HEADER_BYTES_256;
2573 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2574 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2575 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2576 					    PSP_HEADER_BYTES_256;
2577 	fw_meta_info_params.fw_bss_data = region_params.bss_data_size ? adev->dm.dmub_fw->data +
2578 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2579 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2580 	fw_meta_info_params.custom_psp_footer_size = 0;
2581 
2582 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2583 	if (status != DMUB_STATUS_OK) {
2584 		/* Skip returning early, just log the error. */
2585 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2586 		// return -EINVAL;
2587 	}
2588 
2589 	/* Calculate the size of all the regions for the DMUB service. */
2590 	memset(&region_params, 0, sizeof(region_params));
2591 
2592 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2593 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2594 	region_params.vbios_size = adev->bios_size;
2595 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2596 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2597 	region_params.window_memory_type = window_memory_type;
2598 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2599 
2600 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2601 					   &region_info);
2602 
2603 	if (status != DMUB_STATUS_OK) {
2604 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2605 		return -EINVAL;
2606 	}
2607 
2608 	/*
2609 	 * Allocate a framebuffer based on the total size of all the regions.
2610 	 * TODO: Move this into GART.
2611 	 */
2612 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2613 				    AMDGPU_GEM_DOMAIN_VRAM |
2614 				    AMDGPU_GEM_DOMAIN_GTT,
2615 				    &adev->dm.dmub_bo,
2616 				    &adev->dm.dmub_bo_gpu_addr,
2617 				    &adev->dm.dmub_bo_cpu_addr);
2618 	if (r)
2619 		return r;
2620 
2621 	/* Rebase the regions on the framebuffer address. */
2622 	memset(&memory_params, 0, sizeof(memory_params));
2623 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2624 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2625 	memory_params.region_info = &region_info;
2626 	memory_params.window_memory_type = window_memory_type;
2627 
2628 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2629 	fb_info = adev->dm.dmub_fb_info;
2630 
2631 	if (!fb_info) {
2632 		drm_err(adev_to_drm(adev),
2633 			"Failed to allocate framebuffer info for DMUB service!\n");
2634 		return -ENOMEM;
2635 	}
2636 
2637 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2638 	if (status != DMUB_STATUS_OK) {
2639 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2640 		return -EINVAL;
2641 	}
2642 
2643 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2644 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2645 
2646 	return 0;
2647 }
2648 
2649 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2650 {
2651 	struct amdgpu_device *adev = ip_block->adev;
2652 	int r;
2653 
2654 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2655 
2656 	if (!adev->dm.cgs_device) {
2657 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2658 		return -EINVAL;
2659 	}
2660 
2661 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2662 	INIT_LIST_HEAD(&adev->dm.da_list);
2663 
2664 	r = dm_dmub_sw_init(adev);
2665 	if (r)
2666 		return r;
2667 
2668 	return load_dmcu_fw(adev);
2669 }
2670 
2671 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2672 {
2673 	struct amdgpu_device *adev = ip_block->adev;
2674 	struct dal_allocation *da;
2675 
2676 	list_for_each_entry(da, &adev->dm.da_list, list) {
2677 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2678 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2679 			list_del(&da->list);
2680 			kfree(da);
2681 			adev->dm.bb_from_dmub = NULL;
2682 			break;
2683 		}
2684 	}
2685 
2686 
2687 	kfree(adev->dm.dmub_fb_info);
2688 	adev->dm.dmub_fb_info = NULL;
2689 
2690 	if (adev->dm.dmub_srv) {
2691 		dmub_srv_destroy(adev->dm.dmub_srv);
2692 		kfree(adev->dm.dmub_srv);
2693 		adev->dm.dmub_srv = NULL;
2694 	}
2695 
2696 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2697 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2698 
2699 	return 0;
2700 }
2701 
2702 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2703 {
2704 	struct amdgpu_dm_connector *aconnector;
2705 	struct drm_connector *connector;
2706 	struct drm_connector_list_iter iter;
2707 	int ret = 0;
2708 
2709 	drm_connector_list_iter_begin(dev, &iter);
2710 	drm_for_each_connector_iter(connector, &iter) {
2711 
2712 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2713 			continue;
2714 
2715 		aconnector = to_amdgpu_dm_connector(connector);
2716 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2717 		    aconnector->mst_mgr.aux) {
2718 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2719 					 aconnector,
2720 					 aconnector->base.base.id);
2721 
2722 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2723 			if (ret < 0) {
2724 				drm_err(dev, "DM_MST: Failed to start MST\n");
2725 				aconnector->dc_link->type =
2726 					dc_connection_single;
2727 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2728 								     aconnector->dc_link);
2729 				break;
2730 			}
2731 		}
2732 	}
2733 	drm_connector_list_iter_end(&iter);
2734 
2735 	return ret;
2736 }
2737 
2738 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2739 {
2740 	struct amdgpu_device *adev = ip_block->adev;
2741 
2742 	struct dmcu_iram_parameters params;
2743 	unsigned int linear_lut[16];
2744 	int i;
2745 	struct dmcu *dmcu = NULL;
2746 
2747 	dmcu = adev->dm.dc->res_pool->dmcu;
2748 
2749 	for (i = 0; i < 16; i++)
2750 		linear_lut[i] = 0xFFFF * i / 15;
2751 
2752 	params.set = 0;
2753 	params.backlight_ramping_override = false;
2754 	params.backlight_ramping_start = 0xCCCC;
2755 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2756 	params.backlight_lut_array_size = 16;
2757 	params.backlight_lut_array = linear_lut;
2758 
2759 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2760 	 * 0xFFFF x 0.01 = 0x28F
2761 	 */
2762 	params.min_abm_backlight = 0x28F;
2763 	/* In the case where abm is implemented on dmcub,
2764 	 * dmcu object will be null.
2765 	 * ABM 2.4 and up are implemented on dmcub.
2766 	 */
2767 	if (dmcu) {
2768 		if (!dmcu_load_iram(dmcu, params))
2769 			return -EINVAL;
2770 	} else if (adev->dm.dc->ctx->dmub_srv) {
2771 		struct dc_link *edp_links[MAX_NUM_EDP];
2772 		int edp_num;
2773 
2774 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2775 		for (i = 0; i < edp_num; i++) {
2776 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2777 				return -EINVAL;
2778 		}
2779 	}
2780 
2781 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2782 }
2783 
2784 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2785 {
2786 	u8 buf[UUID_SIZE];
2787 	guid_t guid;
2788 	int ret;
2789 
2790 	mutex_lock(&mgr->lock);
2791 	if (!mgr->mst_primary)
2792 		goto out_fail;
2793 
2794 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2795 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2796 		goto out_fail;
2797 	}
2798 
2799 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2800 				 DP_MST_EN |
2801 				 DP_UP_REQ_EN |
2802 				 DP_UPSTREAM_IS_SRC);
2803 	if (ret < 0) {
2804 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2805 		goto out_fail;
2806 	}
2807 
2808 	/* Some hubs forget their guids after they resume */
2809 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2810 	if (ret != sizeof(buf)) {
2811 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2812 		goto out_fail;
2813 	}
2814 
2815 	import_guid(&guid, buf);
2816 
2817 	if (guid_is_null(&guid)) {
2818 		guid_gen(&guid);
2819 		export_guid(buf, &guid);
2820 
2821 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2822 
2823 		if (ret != sizeof(buf)) {
2824 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2825 			goto out_fail;
2826 		}
2827 	}
2828 
2829 	guid_copy(&mgr->mst_primary->guid, &guid);
2830 
2831 out_fail:
2832 	mutex_unlock(&mgr->lock);
2833 }
2834 
2835 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2836 {
2837 	struct cec_notifier *n = aconnector->notifier;
2838 
2839 	if (!n)
2840 		return;
2841 
2842 	cec_notifier_phys_addr_invalidate(n);
2843 }
2844 
2845 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2846 {
2847 	struct drm_connector *connector = &aconnector->base;
2848 	struct cec_notifier *n = aconnector->notifier;
2849 
2850 	if (!n)
2851 		return;
2852 
2853 	cec_notifier_set_phys_addr(n,
2854 				   connector->display_info.source_physical_address);
2855 }
2856 
2857 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2858 {
2859 	struct amdgpu_dm_connector *aconnector;
2860 	struct drm_connector *connector;
2861 	struct drm_connector_list_iter conn_iter;
2862 
2863 	drm_connector_list_iter_begin(ddev, &conn_iter);
2864 	drm_for_each_connector_iter(connector, &conn_iter) {
2865 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2866 			continue;
2867 
2868 		aconnector = to_amdgpu_dm_connector(connector);
2869 		if (suspend)
2870 			hdmi_cec_unset_edid(aconnector);
2871 		else
2872 			hdmi_cec_set_edid(aconnector);
2873 	}
2874 	drm_connector_list_iter_end(&conn_iter);
2875 }
2876 
2877 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2878 {
2879 	struct amdgpu_dm_connector *aconnector;
2880 	struct drm_connector *connector;
2881 	struct drm_connector_list_iter iter;
2882 	struct drm_dp_mst_topology_mgr *mgr;
2883 
2884 	drm_connector_list_iter_begin(dev, &iter);
2885 	drm_for_each_connector_iter(connector, &iter) {
2886 
2887 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2888 			continue;
2889 
2890 		aconnector = to_amdgpu_dm_connector(connector);
2891 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2892 		    aconnector->mst_root)
2893 			continue;
2894 
2895 		mgr = &aconnector->mst_mgr;
2896 
2897 		if (suspend) {
2898 			drm_dp_mst_topology_mgr_suspend(mgr);
2899 		} else {
2900 			/* if extended timeout is supported in hardware,
2901 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2902 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2903 			 */
2904 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2905 			if (!dp_is_lttpr_present(aconnector->dc_link))
2906 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2907 
2908 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2909 			 * once topology probing work is pulled out from mst resume into mst
2910 			 * resume 2nd step. mst resume 2nd step should be called after old
2911 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2912 			 */
2913 			resume_mst_branch_status(mgr);
2914 		}
2915 	}
2916 	drm_connector_list_iter_end(&iter);
2917 }
2918 
2919 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2920 {
2921 	int ret = 0;
2922 
2923 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2924 	 * on window driver dc implementation.
2925 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2926 	 * should be passed to smu during boot up and resume from s3.
2927 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2928 	 * dcn20_resource_construct
2929 	 * then call pplib functions below to pass the settings to smu:
2930 	 * smu_set_watermarks_for_clock_ranges
2931 	 * smu_set_watermarks_table
2932 	 * navi10_set_watermarks_table
2933 	 * smu_write_watermarks_table
2934 	 *
2935 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2936 	 * dc has implemented different flow for window driver:
2937 	 * dc_hardware_init / dc_set_power_state
2938 	 * dcn10_init_hw
2939 	 * notify_wm_ranges
2940 	 * set_wm_ranges
2941 	 * -- Linux
2942 	 * smu_set_watermarks_for_clock_ranges
2943 	 * renoir_set_watermarks_table
2944 	 * smu_write_watermarks_table
2945 	 *
2946 	 * For Linux,
2947 	 * dc_hardware_init -> amdgpu_dm_init
2948 	 * dc_set_power_state --> dm_resume
2949 	 *
2950 	 * therefore, this function apply to navi10/12/14 but not Renoir
2951 	 * *
2952 	 */
2953 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2954 	case IP_VERSION(2, 0, 2):
2955 	case IP_VERSION(2, 0, 0):
2956 		break;
2957 	default:
2958 		return 0;
2959 	}
2960 
2961 	ret = amdgpu_dpm_write_watermarks_table(adev);
2962 	if (ret) {
2963 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
2964 		return ret;
2965 	}
2966 
2967 	return 0;
2968 }
2969 
2970 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
2971 {
2972 	struct amdgpu_display_manager *dm = &adev->dm;
2973 	struct amdgpu_i2c_adapter *oem_i2c;
2974 	struct ddc_service *oem_ddc_service;
2975 	int r;
2976 
2977 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
2978 	if (oem_ddc_service) {
2979 		oem_i2c = create_i2c(oem_ddc_service, true);
2980 		if (!oem_i2c) {
2981 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
2982 			return -ENOMEM;
2983 		}
2984 
2985 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
2986 		if (r) {
2987 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
2988 			kfree(oem_i2c);
2989 			return r;
2990 		}
2991 		dm->oem_i2c = oem_i2c;
2992 	}
2993 
2994 	return 0;
2995 }
2996 
2997 /**
2998  * dm_hw_init() - Initialize DC device
2999  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3000  *
3001  * Initialize the &struct amdgpu_display_manager device. This involves calling
3002  * the initializers of each DM component, then populating the struct with them.
3003  *
3004  * Although the function implies hardware initialization, both hardware and
3005  * software are initialized here. Splitting them out to their relevant init
3006  * hooks is a future TODO item.
3007  *
3008  * Some notable things that are initialized here:
3009  *
3010  * - Display Core, both software and hardware
3011  * - DC modules that we need (freesync and color management)
3012  * - DRM software states
3013  * - Interrupt sources and handlers
3014  * - Vblank support
3015  * - Debug FS entries, if enabled
3016  */
3017 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3018 {
3019 	struct amdgpu_device *adev = ip_block->adev;
3020 	int r;
3021 
3022 	/* Create DAL display manager */
3023 	r = amdgpu_dm_init(adev);
3024 	if (r)
3025 		return r;
3026 	amdgpu_dm_hpd_init(adev);
3027 
3028 	r = dm_oem_i2c_hw_init(adev);
3029 	if (r)
3030 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3031 
3032 	return 0;
3033 }
3034 
3035 /**
3036  * dm_hw_fini() - Teardown DC device
3037  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3038  *
3039  * Teardown components within &struct amdgpu_display_manager that require
3040  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3041  * were loaded. Also flush IRQ workqueues and disable them.
3042  */
3043 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3044 {
3045 	struct amdgpu_device *adev = ip_block->adev;
3046 
3047 	amdgpu_dm_hpd_fini(adev);
3048 
3049 	amdgpu_dm_irq_fini(adev);
3050 	amdgpu_dm_fini(adev);
3051 	return 0;
3052 }
3053 
3054 
3055 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3056 				 struct dc_state *state, bool enable)
3057 {
3058 	enum dc_irq_source irq_source;
3059 	struct amdgpu_crtc *acrtc;
3060 	int rc = -EBUSY;
3061 	int i = 0;
3062 
3063 	for (i = 0; i < state->stream_count; i++) {
3064 		acrtc = get_crtc_by_otg_inst(
3065 				adev, state->stream_status[i].primary_otg_inst);
3066 
3067 		if (acrtc && state->stream_status[i].plane_count != 0) {
3068 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3069 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3070 			if (rc)
3071 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3072 					 enable ? "enable" : "disable");
3073 
3074 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3075 				if (enable) {
3076 					if (amdgpu_dm_crtc_vrr_active(
3077 							to_dm_crtc_state(acrtc->base.state)))
3078 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3079 							&acrtc->base, true);
3080 				} else
3081 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3082 							&acrtc->base, false);
3083 
3084 				if (rc)
3085 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3086 						enable ? "en" : "dis");
3087 			}
3088 
3089 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3090 			/* During gpu-reset we disable and then enable vblank irq, so
3091 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3092 			 */
3093 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3094 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3095 		}
3096 	}
3097 
3098 }
3099 
3100 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3101 
3102 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3103 {
3104 	struct dc_state *context __free(state_release) = NULL;
3105 	int i;
3106 	struct dc_stream_state *del_streams[MAX_PIPES];
3107 	int del_streams_count = 0;
3108 	struct dc_commit_streams_params params = {};
3109 
3110 	memset(del_streams, 0, sizeof(del_streams));
3111 
3112 	context = dc_state_create_current_copy(dc);
3113 	if (context == NULL)
3114 		return DC_ERROR_UNEXPECTED;
3115 
3116 	/* First remove from context all streams */
3117 	for (i = 0; i < context->stream_count; i++) {
3118 		struct dc_stream_state *stream = context->streams[i];
3119 
3120 		del_streams[del_streams_count++] = stream;
3121 	}
3122 
3123 	/* Remove all planes for removed streams and then remove the streams */
3124 	for (i = 0; i < del_streams_count; i++) {
3125 		enum dc_status res;
3126 
3127 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3128 			return DC_FAIL_DETACH_SURFACES;
3129 
3130 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3131 		if (res != DC_OK)
3132 			return res;
3133 	}
3134 
3135 	params.streams = context->streams;
3136 	params.stream_count = context->stream_count;
3137 
3138 	return dc_commit_streams(dc, &params);
3139 }
3140 
3141 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3142 {
3143 	int i;
3144 
3145 	if (dm->hpd_rx_offload_wq) {
3146 		for (i = 0; i < dm->dc->caps.max_links; i++)
3147 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3148 	}
3149 }
3150 
3151 static int dm_cache_state(struct amdgpu_device *adev)
3152 {
3153 	int r;
3154 
3155 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3156 	if (IS_ERR(adev->dm.cached_state)) {
3157 		r = PTR_ERR(adev->dm.cached_state);
3158 		adev->dm.cached_state = NULL;
3159 	}
3160 
3161 	return adev->dm.cached_state ? 0 : r;
3162 }
3163 
3164 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3165 {
3166 	struct amdgpu_display_manager *dm = &adev->dm;
3167 	struct drm_device *ddev = adev_to_drm(adev);
3168 	struct dm_plane_state *dm_new_plane_state;
3169 	struct drm_plane_state *new_plane_state;
3170 	struct dm_crtc_state *dm_new_crtc_state;
3171 	struct drm_crtc_state *new_crtc_state;
3172 	struct drm_plane *plane;
3173 	struct drm_crtc *crtc;
3174 	int i;
3175 
3176 	if (!dm->cached_state)
3177 		return;
3178 
3179 	/* Force mode set in atomic commit */
3180 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3181 		new_crtc_state->active_changed = true;
3182 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3183 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3184 	}
3185 
3186 	/*
3187 	 * atomic_check is expected to create the dc states. We need to release
3188 	 * them here, since they were duplicated as part of the suspend
3189 	 * procedure.
3190 	 */
3191 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3192 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3193 		if (dm_new_crtc_state->stream) {
3194 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3195 			dc_stream_release(dm_new_crtc_state->stream);
3196 			dm_new_crtc_state->stream = NULL;
3197 		}
3198 		dm_new_crtc_state->base.color_mgmt_changed = true;
3199 	}
3200 
3201 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3202 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3203 		if (dm_new_plane_state->dc_state) {
3204 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3205 			dc_plane_state_release(dm_new_plane_state->dc_state);
3206 			dm_new_plane_state->dc_state = NULL;
3207 		}
3208 	}
3209 
3210 	drm_atomic_helper_resume(ddev, dm->cached_state);
3211 
3212 	dm->cached_state = NULL;
3213 }
3214 
3215 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3216 {
3217 	struct amdgpu_device *adev = ip_block->adev;
3218 	struct amdgpu_display_manager *dm = &adev->dm;
3219 
3220 	if (amdgpu_in_reset(adev)) {
3221 		enum dc_status res;
3222 
3223 		mutex_lock(&dm->dc_lock);
3224 
3225 		dc_allow_idle_optimizations(adev->dm.dc, false);
3226 
3227 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3228 
3229 		if (dm->cached_dc_state)
3230 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3231 
3232 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3233 		if (res != DC_OK) {
3234 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3235 			return -EINVAL;
3236 		}
3237 
3238 		amdgpu_dm_irq_suspend(adev);
3239 
3240 		hpd_rx_irq_work_suspend(dm);
3241 
3242 		return 0;
3243 	}
3244 
3245 	if (!adev->dm.cached_state) {
3246 		int r = dm_cache_state(adev);
3247 
3248 		if (r)
3249 			return r;
3250 	}
3251 
3252 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3253 
3254 	s3_handle_mst(adev_to_drm(adev), true);
3255 
3256 	amdgpu_dm_irq_suspend(adev);
3257 
3258 	hpd_rx_irq_work_suspend(dm);
3259 
3260 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3261 
3262 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3263 		dc_allow_idle_optimizations(dm->dc, true);
3264 
3265 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3266 
3267 	return 0;
3268 }
3269 
3270 struct drm_connector *
3271 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3272 					     struct drm_crtc *crtc)
3273 {
3274 	u32 i;
3275 	struct drm_connector_state *new_con_state;
3276 	struct drm_connector *connector;
3277 	struct drm_crtc *crtc_from_state;
3278 
3279 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3280 		crtc_from_state = new_con_state->crtc;
3281 
3282 		if (crtc_from_state == crtc)
3283 			return connector;
3284 	}
3285 
3286 	return NULL;
3287 }
3288 
3289 static void emulated_link_detect(struct dc_link *link)
3290 {
3291 	struct dc_sink_init_data sink_init_data = { 0 };
3292 	struct display_sink_capability sink_caps = { 0 };
3293 	enum dc_edid_status edid_status;
3294 	struct dc_context *dc_ctx = link->ctx;
3295 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3296 	struct dc_sink *sink = NULL;
3297 	struct dc_sink *prev_sink = NULL;
3298 
3299 	link->type = dc_connection_none;
3300 	prev_sink = link->local_sink;
3301 
3302 	if (prev_sink)
3303 		dc_sink_release(prev_sink);
3304 
3305 	switch (link->connector_signal) {
3306 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3307 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3308 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3309 		break;
3310 	}
3311 
3312 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3313 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3314 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3315 		break;
3316 	}
3317 
3318 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3319 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3320 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3321 		break;
3322 	}
3323 
3324 	case SIGNAL_TYPE_LVDS: {
3325 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3326 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3327 		break;
3328 	}
3329 
3330 	case SIGNAL_TYPE_EDP: {
3331 		sink_caps.transaction_type =
3332 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3333 		sink_caps.signal = SIGNAL_TYPE_EDP;
3334 		break;
3335 	}
3336 
3337 	case SIGNAL_TYPE_DISPLAY_PORT: {
3338 		sink_caps.transaction_type =
3339 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3340 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3341 		break;
3342 	}
3343 
3344 	default:
3345 		drm_err(dev, "Invalid connector type! signal:%d\n",
3346 			link->connector_signal);
3347 		return;
3348 	}
3349 
3350 	sink_init_data.link = link;
3351 	sink_init_data.sink_signal = sink_caps.signal;
3352 
3353 	sink = dc_sink_create(&sink_init_data);
3354 	if (!sink) {
3355 		drm_err(dev, "Failed to create sink!\n");
3356 		return;
3357 	}
3358 
3359 	/* dc_sink_create returns a new reference */
3360 	link->local_sink = sink;
3361 
3362 	edid_status = dm_helpers_read_local_edid(
3363 			link->ctx,
3364 			link,
3365 			sink);
3366 
3367 	if (edid_status != EDID_OK)
3368 		drm_err(dev, "Failed to read EDID\n");
3369 
3370 }
3371 
3372 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3373 				     struct amdgpu_display_manager *dm)
3374 {
3375 	struct {
3376 		struct dc_surface_update surface_updates[MAX_SURFACES];
3377 		struct dc_plane_info plane_infos[MAX_SURFACES];
3378 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3379 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3380 		struct dc_stream_update stream_update;
3381 	} *bundle __free(kfree);
3382 	int k, m;
3383 
3384 	bundle = kzalloc_obj(*bundle);
3385 
3386 	if (!bundle) {
3387 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3388 		return;
3389 	}
3390 
3391 	for (k = 0; k < dc_state->stream_count; k++) {
3392 		bundle->stream_update.stream = dc_state->streams[k];
3393 
3394 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3395 			bundle->surface_updates[m].surface =
3396 				dc_state->stream_status[k].plane_states[m];
3397 			bundle->surface_updates[m].surface->force_full_update =
3398 				true;
3399 		}
3400 
3401 		update_planes_and_stream_adapter(dm->dc,
3402 					 UPDATE_TYPE_FULL,
3403 					 dc_state->stream_status[k].plane_count,
3404 					 dc_state->streams[k],
3405 					 &bundle->stream_update,
3406 					 bundle->surface_updates);
3407 	}
3408 }
3409 
3410 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3411 					    struct dc_sink *sink)
3412 {
3413 	struct dc_panel_patch *ppatch = NULL;
3414 
3415 	if (!sink)
3416 		return;
3417 
3418 	ppatch = &sink->edid_caps.panel_patch;
3419 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3420 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3421 		drm_dbg_driver(adev_to_drm(adev),
3422 			       "%s: adding a %ds delay as w/a for panel\n",
3423 			       __func__,
3424 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3425 	}
3426 }
3427 
3428 /**
3429  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3430  * @adev: amdgpu device pointer
3431  *
3432  * Iterates through all DC links and dumps information about local and remote
3433  * (MST) sinks. Should be called after connector detection is complete to see
3434  * the final state of all links.
3435  */
3436 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3437 {
3438 	struct dc *dc = adev->dm.dc;
3439 	struct drm_device *dev = adev_to_drm(adev);
3440 	int li;
3441 
3442 	if (!dc)
3443 		return;
3444 
3445 	for (li = 0; li < dc->link_count; li++) {
3446 		struct dc_link *l = dc->links[li];
3447 		const char *name = NULL;
3448 		int rs;
3449 
3450 		if (!l)
3451 			continue;
3452 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3453 			name = l->local_sink->edid_caps.display_name;
3454 		else
3455 			name = "n/a";
3456 
3457 		drm_dbg_kms(dev,
3458 			"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",
3459 			li,
3460 			l->local_sink,
3461 			l->type,
3462 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3463 			l->sink_count,
3464 			name,
3465 			l->dpcd_caps.is_mst_capable,
3466 			l->mst_stream_alloc_table.stream_count);
3467 
3468 		/* Dump remote (MST) sinks if any */
3469 		for (rs = 0; rs < l->sink_count; rs++) {
3470 			struct dc_sink *rsink = l->remote_sinks[rs];
3471 			const char *rname = NULL;
3472 
3473 			if (!rsink)
3474 				continue;
3475 			if (rsink->edid_caps.display_name[0])
3476 				rname = rsink->edid_caps.display_name;
3477 			else
3478 				rname = "n/a";
3479 			drm_dbg_kms(dev,
3480 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3481 				li, rs,
3482 				rsink,
3483 				rsink->sink_signal,
3484 				rname);
3485 		}
3486 	}
3487 }
3488 
3489 static int dm_resume(struct amdgpu_ip_block *ip_block)
3490 {
3491 	struct amdgpu_device *adev = ip_block->adev;
3492 	struct drm_device *ddev = adev_to_drm(adev);
3493 	struct amdgpu_display_manager *dm = &adev->dm;
3494 	struct amdgpu_dm_connector *aconnector;
3495 	struct drm_connector *connector;
3496 	struct drm_connector_list_iter iter;
3497 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3498 	enum dc_connection_type new_connection_type = dc_connection_none;
3499 	struct dc_state *dc_state;
3500 	int i, r, j;
3501 	struct dc_commit_streams_params commit_params = {};
3502 
3503 	if (dm->dc->caps.ips_support) {
3504 		if (!amdgpu_in_reset(adev))
3505 			mutex_lock(&dm->dc_lock);
3506 
3507 		/* Need to set POWER_STATE_D0 first or it will not execute
3508 		 * idle_power_optimizations command to DMUB.
3509 		 */
3510 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3511 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3512 
3513 		if (!amdgpu_in_reset(adev))
3514 			mutex_unlock(&dm->dc_lock);
3515 	}
3516 
3517 	if (amdgpu_in_reset(adev)) {
3518 		dc_state = dm->cached_dc_state;
3519 
3520 		/*
3521 		 * The dc->current_state is backed up into dm->cached_dc_state
3522 		 * before we commit 0 streams.
3523 		 *
3524 		 * DC will clear link encoder assignments on the real state
3525 		 * but the changes won't propagate over to the copy we made
3526 		 * before the 0 streams commit.
3527 		 *
3528 		 * DC expects that link encoder assignments are *not* valid
3529 		 * when committing a state, so as a workaround we can copy
3530 		 * off of the current state.
3531 		 *
3532 		 * We lose the previous assignments, but we had already
3533 		 * commit 0 streams anyway.
3534 		 */
3535 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3536 
3537 		r = dm_dmub_hw_init(adev);
3538 		if (r) {
3539 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3540 			return r;
3541 		}
3542 
3543 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3544 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3545 
3546 		dc_resume(dm->dc);
3547 
3548 		amdgpu_dm_irq_resume_early(adev);
3549 
3550 		for (i = 0; i < dc_state->stream_count; i++) {
3551 			dc_state->streams[i]->mode_changed = true;
3552 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3553 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3554 					= 0xffffffff;
3555 			}
3556 		}
3557 
3558 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3559 			amdgpu_dm_outbox_init(adev);
3560 			dc_enable_dmub_outbox(adev->dm.dc);
3561 		}
3562 
3563 		commit_params.streams = dc_state->streams;
3564 		commit_params.stream_count = dc_state->stream_count;
3565 		dc_exit_ips_for_hw_access(dm->dc);
3566 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3567 
3568 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3569 
3570 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3571 
3572 		dc_state_release(dm->cached_dc_state);
3573 		dm->cached_dc_state = NULL;
3574 
3575 		amdgpu_dm_irq_resume_late(adev);
3576 
3577 		mutex_unlock(&dm->dc_lock);
3578 
3579 		/* set the backlight after a reset */
3580 		for (i = 0; i < dm->num_of_edps; i++) {
3581 			if (dm->backlight_dev[i])
3582 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3583 		}
3584 
3585 		return 0;
3586 	}
3587 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3588 	dc_state_release(dm_state->context);
3589 	dm_state->context = dc_state_create(dm->dc, NULL);
3590 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3591 
3592 	/* Before powering on DC we need to re-initialize DMUB. */
3593 	dm_dmub_hw_resume(adev);
3594 
3595 	/* Re-enable outbox interrupts for DPIA. */
3596 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3597 		amdgpu_dm_outbox_init(adev);
3598 		dc_enable_dmub_outbox(adev->dm.dc);
3599 	}
3600 
3601 	/* power on hardware */
3602 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3603 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3604 
3605 	/* program HPD filter */
3606 	dc_resume(dm->dc);
3607 
3608 	/*
3609 	 * early enable HPD Rx IRQ, should be done before set mode as short
3610 	 * pulse interrupts are used for MST
3611 	 */
3612 	amdgpu_dm_irq_resume_early(adev);
3613 
3614 	s3_handle_hdmi_cec(ddev, false);
3615 
3616 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3617 	s3_handle_mst(ddev, false);
3618 
3619 	/* Do detection*/
3620 	drm_connector_list_iter_begin(ddev, &iter);
3621 	drm_for_each_connector_iter(connector, &iter) {
3622 		bool ret;
3623 
3624 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3625 			continue;
3626 
3627 		aconnector = to_amdgpu_dm_connector(connector);
3628 
3629 		if (!aconnector->dc_link)
3630 			continue;
3631 
3632 		/*
3633 		 * this is the case when traversing through already created end sink
3634 		 * MST connectors, should be skipped
3635 		 */
3636 		if (aconnector->mst_root)
3637 			continue;
3638 
3639 		/* Skip eDP detection, when there is no sink present */
3640 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3641 		    !aconnector->dc_link->edp_sink_present)
3642 			continue;
3643 
3644 		guard(mutex)(&aconnector->hpd_lock);
3645 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3646 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3647 
3648 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3649 			emulated_link_detect(aconnector->dc_link);
3650 		} else {
3651 			guard(mutex)(&dm->dc_lock);
3652 			dc_exit_ips_for_hw_access(dm->dc);
3653 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3654 			if (ret) {
3655 				/* w/a delay for certain panels */
3656 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3657 			}
3658 		}
3659 
3660 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3661 			aconnector->fake_enable = false;
3662 
3663 		if (aconnector->dc_sink)
3664 			dc_sink_release(aconnector->dc_sink);
3665 		aconnector->dc_sink = NULL;
3666 		amdgpu_dm_update_connector_after_detect(aconnector);
3667 	}
3668 	drm_connector_list_iter_end(&iter);
3669 
3670 	dm_destroy_cached_state(adev);
3671 
3672 	/* Do mst topology probing after resuming cached state*/
3673 	drm_connector_list_iter_begin(ddev, &iter);
3674 	drm_for_each_connector_iter(connector, &iter) {
3675 		bool init = false;
3676 
3677 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3678 			continue;
3679 
3680 		aconnector = to_amdgpu_dm_connector(connector);
3681 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3682 		    aconnector->mst_root)
3683 			continue;
3684 
3685 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3686 			init = !aconnector->mst_mgr.mst_primary;
3687 		}
3688 		if (init)
3689 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3690 				aconnector->dc_link, false);
3691 		else
3692 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3693 	}
3694 	drm_connector_list_iter_end(&iter);
3695 
3696 	/* Debug dump: list all DC links and their associated sinks after detection
3697 	 * is complete for all connectors. This provides a comprehensive view of the
3698 	 * final state without repeating the dump for each connector.
3699 	 */
3700 	amdgpu_dm_dump_links_and_sinks(adev);
3701 
3702 	amdgpu_dm_irq_resume_late(adev);
3703 
3704 	amdgpu_dm_smu_write_watermarks_table(adev);
3705 
3706 	drm_kms_helper_hotplug_event(ddev);
3707 
3708 	return 0;
3709 }
3710 
3711 /**
3712  * DOC: DM Lifecycle
3713  *
3714  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3715  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3716  * the base driver's device list to be initialized and torn down accordingly.
3717  *
3718  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3719  */
3720 
3721 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3722 	.name = "dm",
3723 	.early_init = dm_early_init,
3724 	.late_init = dm_late_init,
3725 	.sw_init = dm_sw_init,
3726 	.sw_fini = dm_sw_fini,
3727 	.early_fini = amdgpu_dm_early_fini,
3728 	.hw_init = dm_hw_init,
3729 	.hw_fini = dm_hw_fini,
3730 	.suspend = dm_suspend,
3731 	.resume = dm_resume,
3732 	.is_idle = dm_is_idle,
3733 	.wait_for_idle = dm_wait_for_idle,
3734 	.check_soft_reset = dm_check_soft_reset,
3735 	.soft_reset = dm_soft_reset,
3736 	.set_clockgating_state = dm_set_clockgating_state,
3737 	.set_powergating_state = dm_set_powergating_state,
3738 };
3739 
3740 const struct amdgpu_ip_block_version dm_ip_block = {
3741 	.type = AMD_IP_BLOCK_TYPE_DCE,
3742 	.major = 1,
3743 	.minor = 0,
3744 	.rev = 0,
3745 	.funcs = &amdgpu_dm_funcs,
3746 };
3747 
3748 
3749 /**
3750  * DOC: atomic
3751  *
3752  * *WIP*
3753  */
3754 
3755 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3756 	.fb_create = amdgpu_display_user_framebuffer_create,
3757 	.get_format_info = amdgpu_dm_plane_get_format_info,
3758 	.atomic_check = amdgpu_dm_atomic_check,
3759 	.atomic_commit = drm_atomic_helper_commit,
3760 };
3761 
3762 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3763 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3764 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3765 };
3766 
3767 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3768 {
3769 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3770 	struct amdgpu_dm_backlight_caps *caps;
3771 	struct drm_connector *conn_base;
3772 	struct amdgpu_device *adev;
3773 	struct drm_luminance_range_info *luminance_range;
3774 	struct drm_device *drm;
3775 
3776 	if (aconnector->bl_idx == -1 ||
3777 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3778 		return;
3779 
3780 	conn_base = &aconnector->base;
3781 	drm = conn_base->dev;
3782 	adev = drm_to_adev(drm);
3783 
3784 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3785 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3786 	caps->aux_support = false;
3787 
3788 	if (caps->ext_caps->bits.oled == 1
3789 	    /*
3790 	     * ||
3791 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3792 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3793 	     */)
3794 		caps->aux_support = true;
3795 
3796 	if (amdgpu_backlight == 0)
3797 		caps->aux_support = false;
3798 	else if (amdgpu_backlight == 1)
3799 		caps->aux_support = true;
3800 	if (caps->aux_support)
3801 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3802 
3803 	luminance_range = &conn_base->display_info.luminance_range;
3804 
3805 	if (luminance_range->max_luminance)
3806 		caps->aux_max_input_signal = luminance_range->max_luminance;
3807 	else
3808 		caps->aux_max_input_signal = 512;
3809 
3810 	if (luminance_range->min_luminance)
3811 		caps->aux_min_input_signal = luminance_range->min_luminance;
3812 	else
3813 		caps->aux_min_input_signal = 1;
3814 
3815 	panel_backlight_quirk =
3816 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
3817 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
3818 		if (panel_backlight_quirk->min_brightness) {
3819 			caps->min_input_signal =
3820 				panel_backlight_quirk->min_brightness - 1;
3821 			drm_info(drm,
3822 				 "Applying panel backlight quirk, min_brightness: %d\n",
3823 				 caps->min_input_signal);
3824 		}
3825 		if (panel_backlight_quirk->brightness_mask) {
3826 			drm_info(drm,
3827 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
3828 				 panel_backlight_quirk->brightness_mask);
3829 			caps->brightness_mask =
3830 				panel_backlight_quirk->brightness_mask;
3831 		}
3832 	}
3833 }
3834 
3835 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3836 
3837 void amdgpu_dm_update_connector_after_detect(
3838 		struct amdgpu_dm_connector *aconnector)
3839 {
3840 	struct drm_connector *connector = &aconnector->base;
3841 	struct dc_sink *sink __free(sink_release) = NULL;
3842 	struct drm_device *dev = connector->dev;
3843 
3844 	/* MST handled by drm_mst framework */
3845 	if (aconnector->mst_mgr.mst_state == true)
3846 		return;
3847 
3848 	sink = aconnector->dc_link->local_sink;
3849 	if (sink)
3850 		dc_sink_retain(sink);
3851 
3852 	/*
3853 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3854 	 * the connector sink is set to either fake or physical sink depends on link status.
3855 	 * Skip if already done during boot.
3856 	 */
3857 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3858 			&& aconnector->dc_em_sink) {
3859 
3860 		/*
3861 		 * For S3 resume with headless use eml_sink to fake stream
3862 		 * because on resume connector->sink is set to NULL
3863 		 */
3864 		guard(mutex)(&dev->mode_config.mutex);
3865 
3866 		if (sink) {
3867 			if (aconnector->dc_sink) {
3868 				amdgpu_dm_update_freesync_caps(connector, NULL);
3869 				/*
3870 				 * retain and release below are used to
3871 				 * bump up refcount for sink because the link doesn't point
3872 				 * to it anymore after disconnect, so on next crtc to connector
3873 				 * reshuffle by UMD we will get into unwanted dc_sink release
3874 				 */
3875 				dc_sink_release(aconnector->dc_sink);
3876 			}
3877 			aconnector->dc_sink = sink;
3878 			dc_sink_retain(aconnector->dc_sink);
3879 			amdgpu_dm_update_freesync_caps(connector,
3880 					aconnector->drm_edid);
3881 		} else {
3882 			amdgpu_dm_update_freesync_caps(connector, NULL);
3883 			if (!aconnector->dc_sink) {
3884 				aconnector->dc_sink = aconnector->dc_em_sink;
3885 				dc_sink_retain(aconnector->dc_sink);
3886 			}
3887 		}
3888 
3889 		return;
3890 	}
3891 
3892 	/*
3893 	 * TODO: temporary guard to look for proper fix
3894 	 * if this sink is MST sink, we should not do anything
3895 	 */
3896 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
3897 		return;
3898 
3899 	if (aconnector->dc_sink == sink) {
3900 		/*
3901 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3902 		 * Do nothing!!
3903 		 */
3904 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
3905 				 aconnector->connector_id);
3906 		return;
3907 	}
3908 
3909 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3910 		    aconnector->connector_id, aconnector->dc_sink, sink);
3911 
3912 	/* When polling, DRM has already locked the mutex for us. */
3913 	if (!drm_kms_helper_is_poll_worker())
3914 		mutex_lock(&dev->mode_config.mutex);
3915 
3916 	/*
3917 	 * 1. Update status of the drm connector
3918 	 * 2. Send an event and let userspace tell us what to do
3919 	 */
3920 	if (sink) {
3921 		/*
3922 		 * TODO: check if we still need the S3 mode update workaround.
3923 		 * If yes, put it here.
3924 		 */
3925 		if (aconnector->dc_sink) {
3926 			amdgpu_dm_update_freesync_caps(connector, NULL);
3927 			dc_sink_release(aconnector->dc_sink);
3928 		}
3929 
3930 		aconnector->dc_sink = sink;
3931 		dc_sink_retain(aconnector->dc_sink);
3932 		if (sink->dc_edid.length == 0) {
3933 			aconnector->drm_edid = NULL;
3934 			hdmi_cec_unset_edid(aconnector);
3935 			if (aconnector->dc_link->aux_mode) {
3936 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3937 			}
3938 		} else {
3939 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
3940 
3941 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
3942 			drm_edid_connector_update(connector, aconnector->drm_edid);
3943 
3944 			hdmi_cec_set_edid(aconnector);
3945 			if (aconnector->dc_link->aux_mode)
3946 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
3947 						  connector->display_info.source_physical_address);
3948 		}
3949 
3950 		if (!aconnector->timing_requested) {
3951 			aconnector->timing_requested =
3952 				kzalloc_obj(struct dc_crtc_timing);
3953 			if (!aconnector->timing_requested)
3954 				drm_err(dev,
3955 					"failed to create aconnector->requested_timing\n");
3956 		}
3957 
3958 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid);
3959 		update_connector_ext_caps(aconnector);
3960 	} else {
3961 		hdmi_cec_unset_edid(aconnector);
3962 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3963 		amdgpu_dm_update_freesync_caps(connector, NULL);
3964 		aconnector->num_modes = 0;
3965 		dc_sink_release(aconnector->dc_sink);
3966 		aconnector->dc_sink = NULL;
3967 		drm_edid_free(aconnector->drm_edid);
3968 		aconnector->drm_edid = NULL;
3969 		kfree(aconnector->timing_requested);
3970 		aconnector->timing_requested = NULL;
3971 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3972 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3973 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3974 	}
3975 
3976 	update_subconnector_property(aconnector);
3977 
3978 	/* When polling, the mutex will be unlocked for us by DRM. */
3979 	if (!drm_kms_helper_is_poll_worker())
3980 		mutex_unlock(&dev->mode_config.mutex);
3981 }
3982 
3983 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
3984 {
3985 	if (!sink1 || !sink2)
3986 		return false;
3987 	if (sink1->sink_signal != sink2->sink_signal)
3988 		return false;
3989 
3990 	if (sink1->dc_edid.length != sink2->dc_edid.length)
3991 		return false;
3992 
3993 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
3994 		   sink1->dc_edid.length) != 0)
3995 		return false;
3996 	return true;
3997 }
3998 
3999 
4000 /**
4001  * DOC: hdmi_hpd_debounce_work
4002  *
4003  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4004  * (such as during power save transitions), this delay determines how long to
4005  * wait before processing the HPD event. This allows distinguishing between a
4006  * physical unplug (>hdmi_hpd_debounce_delay)
4007  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4008  *
4009  * If the toggle is less than this delay, the driver compares sink capabilities
4010  * and permits a hotplug event if they changed.
4011  *
4012  * The default value of 1500ms was chosen based on experimental testing with
4013  * various monitors that exhibit spontaneous HPD toggling behavior.
4014  */
4015 static void hdmi_hpd_debounce_work(struct work_struct *work)
4016 {
4017 	struct amdgpu_dm_connector *aconnector =
4018 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4019 			     hdmi_hpd_debounce_work);
4020 	struct drm_connector *connector = &aconnector->base;
4021 	struct drm_device *dev = connector->dev;
4022 	struct amdgpu_device *adev = drm_to_adev(dev);
4023 	struct dc *dc = aconnector->dc_link->ctx->dc;
4024 	bool fake_reconnect = false;
4025 	bool reallow_idle = false;
4026 	bool ret = false;
4027 	guard(mutex)(&aconnector->hpd_lock);
4028 
4029 	/* Re-detect the display */
4030 	scoped_guard(mutex, &adev->dm.dc_lock) {
4031 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4032 			dc_allow_idle_optimizations(dc, false);
4033 			reallow_idle = true;
4034 		}
4035 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4036 	}
4037 
4038 	if (ret) {
4039 		/* Apply workaround delay for certain panels */
4040 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4041 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4042 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4043 			/*
4044 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4045 			*/
4046 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4047 			fake_reconnect = true;
4048 		}
4049 
4050 		/* Update connector state */
4051 		amdgpu_dm_update_connector_after_detect(aconnector);
4052 
4053 		drm_modeset_lock_all(dev);
4054 		dm_restore_drm_connector_state(dev, connector);
4055 		drm_modeset_unlock_all(dev);
4056 
4057 		/* Only notify OS if sink actually changed */
4058 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4059 			drm_kms_helper_hotplug_event(dev);
4060 	}
4061 
4062 	/* Release the cached sink reference */
4063 	if (aconnector->hdmi_prev_sink) {
4064 		dc_sink_release(aconnector->hdmi_prev_sink);
4065 		aconnector->hdmi_prev_sink = NULL;
4066 	}
4067 
4068 	scoped_guard(mutex, &adev->dm.dc_lock) {
4069 		if (reallow_idle && dc->caps.ips_support)
4070 			dc_allow_idle_optimizations(dc, true);
4071 	}
4072 }
4073 
4074 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4075 {
4076 	struct drm_connector *connector = &aconnector->base;
4077 	struct drm_device *dev = connector->dev;
4078 	enum dc_connection_type new_connection_type = dc_connection_none;
4079 	struct amdgpu_device *adev = drm_to_adev(dev);
4080 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4081 	struct dc *dc = aconnector->dc_link->ctx->dc;
4082 	bool ret = false;
4083 	bool debounce_required = false;
4084 
4085 	if (adev->dm.disable_hpd_irq)
4086 		return;
4087 
4088 	/*
4089 	 * In case of failure or MST no need to update connector status or notify the OS
4090 	 * since (for MST case) MST does this in its own context.
4091 	 */
4092 	guard(mutex)(&aconnector->hpd_lock);
4093 
4094 	if (adev->dm.hdcp_workqueue) {
4095 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4096 		dm_con_state->update_hdcp = true;
4097 	}
4098 	if (aconnector->fake_enable)
4099 		aconnector->fake_enable = false;
4100 
4101 	aconnector->timing_changed = false;
4102 
4103 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4104 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4105 
4106 	/*
4107 	 * Check for HDMI disconnect with debounce enabled.
4108 	 */
4109 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4110 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4111 			      new_connection_type == dc_connection_none &&
4112 			      aconnector->dc_link->local_sink != NULL);
4113 
4114 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4115 		emulated_link_detect(aconnector->dc_link);
4116 
4117 		drm_modeset_lock_all(dev);
4118 		dm_restore_drm_connector_state(dev, connector);
4119 		drm_modeset_unlock_all(dev);
4120 
4121 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4122 			drm_kms_helper_connector_hotplug_event(connector);
4123 	} else if (debounce_required) {
4124 		/*
4125 		 * HDMI disconnect detected - schedule delayed work instead of
4126 		 * processing immediately. This allows us to coalesce spurious
4127 		 * HDMI signals from physical unplugs.
4128 		 */
4129 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4130 			    aconnector->hdmi_hpd_debounce_delay_ms);
4131 
4132 		/* Cache the current sink for later comparison */
4133 		if (aconnector->hdmi_prev_sink)
4134 			dc_sink_release(aconnector->hdmi_prev_sink);
4135 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4136 		if (aconnector->hdmi_prev_sink)
4137 			dc_sink_retain(aconnector->hdmi_prev_sink);
4138 
4139 		/* Schedule delayed detection. */
4140 		if (mod_delayed_work(system_wq,
4141 				 &aconnector->hdmi_hpd_debounce_work,
4142 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4143 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4144 
4145 	} else {
4146 
4147 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4148 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4149 			return;
4150 
4151 		scoped_guard(mutex, &adev->dm.dc_lock) {
4152 			dc_exit_ips_for_hw_access(dc);
4153 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4154 		}
4155 		if (ret) {
4156 			/* w/a delay for certain panels */
4157 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4158 			amdgpu_dm_update_connector_after_detect(aconnector);
4159 
4160 			drm_modeset_lock_all(dev);
4161 			dm_restore_drm_connector_state(dev, connector);
4162 			drm_modeset_unlock_all(dev);
4163 
4164 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4165 				drm_kms_helper_connector_hotplug_event(connector);
4166 		}
4167 	}
4168 }
4169 
4170 static void handle_hpd_irq(void *param)
4171 {
4172 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4173 
4174 	handle_hpd_irq_helper(aconnector);
4175 
4176 }
4177 
4178 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4179 							union hpd_irq_data hpd_irq_data)
4180 {
4181 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4182 
4183 	if (!offload_work) {
4184 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4185 		return;
4186 	}
4187 
4188 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4189 	offload_work->data = hpd_irq_data;
4190 	offload_work->offload_wq = offload_wq;
4191 	offload_work->adev = adev;
4192 
4193 	queue_work(offload_wq->wq, &offload_work->work);
4194 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4195 }
4196 
4197 static void handle_hpd_rx_irq(void *param)
4198 {
4199 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4200 	struct drm_connector *connector = &aconnector->base;
4201 	struct drm_device *dev = connector->dev;
4202 	struct dc_link *dc_link = aconnector->dc_link;
4203 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4204 	bool result = false;
4205 	enum dc_connection_type new_connection_type = dc_connection_none;
4206 	struct amdgpu_device *adev = drm_to_adev(dev);
4207 	union hpd_irq_data hpd_irq_data;
4208 	bool link_loss = false;
4209 	bool has_left_work = false;
4210 	int idx = dc_link->link_index;
4211 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4212 	struct dc *dc = aconnector->dc_link->ctx->dc;
4213 
4214 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4215 
4216 	if (adev->dm.disable_hpd_irq)
4217 		return;
4218 
4219 	/*
4220 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4221 	 * conflict, after implement i2c helper, this mutex should be
4222 	 * retired.
4223 	 */
4224 	mutex_lock(&aconnector->hpd_lock);
4225 
4226 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4227 						&link_loss, true, &has_left_work);
4228 
4229 	if (!has_left_work)
4230 		goto out;
4231 
4232 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4233 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4234 		goto out;
4235 	}
4236 
4237 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4238 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4239 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4240 			bool skip = false;
4241 
4242 			/*
4243 			 * DOWN_REP_MSG_RDY is also handled by polling method
4244 			 * mgr->cbs->poll_hpd_irq()
4245 			 */
4246 			spin_lock(&offload_wq->offload_lock);
4247 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4248 
4249 			if (!skip)
4250 				offload_wq->is_handling_mst_msg_rdy_event = true;
4251 
4252 			spin_unlock(&offload_wq->offload_lock);
4253 
4254 			if (!skip)
4255 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4256 
4257 			goto out;
4258 		}
4259 
4260 		if (link_loss) {
4261 			bool skip = false;
4262 
4263 			spin_lock(&offload_wq->offload_lock);
4264 			skip = offload_wq->is_handling_link_loss;
4265 
4266 			if (!skip)
4267 				offload_wq->is_handling_link_loss = true;
4268 
4269 			spin_unlock(&offload_wq->offload_lock);
4270 
4271 			if (!skip)
4272 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4273 
4274 			goto out;
4275 		}
4276 	}
4277 
4278 out:
4279 	if (result && !is_mst_root_connector) {
4280 		/* Downstream Port status changed. */
4281 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4282 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4283 
4284 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4285 			emulated_link_detect(dc_link);
4286 
4287 			if (aconnector->fake_enable)
4288 				aconnector->fake_enable = false;
4289 
4290 			amdgpu_dm_update_connector_after_detect(aconnector);
4291 
4292 
4293 			drm_modeset_lock_all(dev);
4294 			dm_restore_drm_connector_state(dev, connector);
4295 			drm_modeset_unlock_all(dev);
4296 
4297 			drm_kms_helper_connector_hotplug_event(connector);
4298 		} else {
4299 			bool ret = false;
4300 
4301 			mutex_lock(&adev->dm.dc_lock);
4302 			dc_exit_ips_for_hw_access(dc);
4303 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4304 			mutex_unlock(&adev->dm.dc_lock);
4305 
4306 			if (ret) {
4307 				if (aconnector->fake_enable)
4308 					aconnector->fake_enable = false;
4309 
4310 				amdgpu_dm_update_connector_after_detect(aconnector);
4311 
4312 				drm_modeset_lock_all(dev);
4313 				dm_restore_drm_connector_state(dev, connector);
4314 				drm_modeset_unlock_all(dev);
4315 
4316 				drm_kms_helper_connector_hotplug_event(connector);
4317 			}
4318 		}
4319 	}
4320 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4321 		if (adev->dm.hdcp_workqueue)
4322 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4323 	}
4324 
4325 	if (dc_link->type != dc_connection_mst_branch)
4326 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4327 
4328 	mutex_unlock(&aconnector->hpd_lock);
4329 }
4330 
4331 static int register_hpd_handlers(struct amdgpu_device *adev)
4332 {
4333 	struct drm_device *dev = adev_to_drm(adev);
4334 	struct drm_connector *connector;
4335 	struct amdgpu_dm_connector *aconnector;
4336 	const struct dc_link *dc_link;
4337 	struct dc_interrupt_params int_params = {0};
4338 
4339 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4340 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4341 
4342 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4343 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4344 			dmub_hpd_callback, true)) {
4345 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4346 			return -EINVAL;
4347 		}
4348 
4349 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4350 			dmub_hpd_callback, true)) {
4351 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4352 			return -EINVAL;
4353 		}
4354 
4355 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4356 			dmub_hpd_sense_callback, true)) {
4357 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4358 			return -EINVAL;
4359 		}
4360 	}
4361 
4362 	list_for_each_entry(connector,
4363 			&dev->mode_config.connector_list, head)	{
4364 
4365 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4366 			continue;
4367 
4368 		aconnector = to_amdgpu_dm_connector(connector);
4369 		dc_link = aconnector->dc_link;
4370 
4371 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4372 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4373 			int_params.irq_source = dc_link->irq_source_hpd;
4374 
4375 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4376 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4377 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4378 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4379 				return -EINVAL;
4380 			}
4381 
4382 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4383 				handle_hpd_irq, (void *) aconnector))
4384 				return -ENOMEM;
4385 		}
4386 
4387 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4388 
4389 			/* Also register for DP short pulse (hpd_rx). */
4390 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4391 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4392 
4393 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4394 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4395 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4396 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4397 				return -EINVAL;
4398 			}
4399 
4400 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4401 				handle_hpd_rx_irq, (void *) aconnector))
4402 				return -ENOMEM;
4403 		}
4404 	}
4405 	return 0;
4406 }
4407 
4408 /* Register IRQ sources and initialize IRQ callbacks */
4409 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4410 {
4411 	struct dc *dc = adev->dm.dc;
4412 	struct common_irq_params *c_irq_params;
4413 	struct dc_interrupt_params int_params = {0};
4414 	int r;
4415 	int i;
4416 	unsigned int src_id;
4417 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4418 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4419 	const unsigned int vblank_d1 =
4420 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4421 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4422 
4423 	if (adev->family >= AMDGPU_FAMILY_AI)
4424 		client_id = SOC15_IH_CLIENTID_DCE;
4425 
4426 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4427 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4428 
4429 	/*
4430 	 * Actions of amdgpu_irq_add_id():
4431 	 * 1. Register a set() function with base driver.
4432 	 *    Base driver will call set() function to enable/disable an
4433 	 *    interrupt in DC hardware.
4434 	 * 2. Register amdgpu_dm_irq_handler().
4435 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4436 	 *    coming from DC hardware.
4437 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4438 	 *    for acknowledging and handling.
4439 	 */
4440 
4441 	/* Use VBLANK interrupt */
4442 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4443 		src_id = vblank_d1 + i;
4444 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4445 		if (r) {
4446 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4447 			return r;
4448 		}
4449 
4450 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4451 		int_params.irq_source =
4452 			dc_interrupt_to_irq_source(dc, src_id, 0);
4453 
4454 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4455 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4456 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4457 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4458 			return -EINVAL;
4459 		}
4460 
4461 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4462 
4463 		c_irq_params->adev = adev;
4464 		c_irq_params->irq_src = int_params.irq_source;
4465 
4466 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4467 			dm_crtc_high_irq, c_irq_params))
4468 			return -ENOMEM;
4469 	}
4470 
4471 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4472 		/* Use VUPDATE interrupt */
4473 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4474 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4475 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4476 			if (r) {
4477 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4478 				return r;
4479 			}
4480 
4481 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4482 			int_params.irq_source =
4483 				dc_interrupt_to_irq_source(dc, src_id, 0);
4484 
4485 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4486 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4487 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4488 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4489 				return -EINVAL;
4490 			}
4491 
4492 			c_irq_params = &adev->dm.vupdate_params[
4493 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4494 			c_irq_params->adev = adev;
4495 			c_irq_params->irq_src = int_params.irq_source;
4496 
4497 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4498 				dm_vupdate_high_irq, c_irq_params))
4499 				return -ENOMEM;
4500 		}
4501 	}
4502 
4503 	/* Use GRPH_PFLIP interrupt */
4504 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4505 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4506 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4507 		if (r) {
4508 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4509 			return r;
4510 		}
4511 
4512 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4513 		int_params.irq_source =
4514 			dc_interrupt_to_irq_source(dc, i, 0);
4515 
4516 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4517 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4518 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4519 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4520 			return -EINVAL;
4521 		}
4522 
4523 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4524 
4525 		c_irq_params->adev = adev;
4526 		c_irq_params->irq_src = int_params.irq_source;
4527 
4528 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4529 			dm_pflip_high_irq, c_irq_params))
4530 			return -ENOMEM;
4531 	}
4532 
4533 	/* HPD */
4534 	r = amdgpu_irq_add_id(adev, client_id,
4535 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4536 	if (r) {
4537 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4538 		return r;
4539 	}
4540 
4541 	r = register_hpd_handlers(adev);
4542 
4543 	return r;
4544 }
4545 
4546 /* Register IRQ sources and initialize IRQ callbacks */
4547 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4548 {
4549 	struct dc *dc = adev->dm.dc;
4550 	struct common_irq_params *c_irq_params;
4551 	struct dc_interrupt_params int_params = {0};
4552 	int r;
4553 	int i;
4554 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4555 	static const unsigned int vrtl_int_srcid[] = {
4556 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4557 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4558 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4559 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4560 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4561 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4562 	};
4563 #endif
4564 
4565 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4566 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4567 
4568 	/*
4569 	 * Actions of amdgpu_irq_add_id():
4570 	 * 1. Register a set() function with base driver.
4571 	 *    Base driver will call set() function to enable/disable an
4572 	 *    interrupt in DC hardware.
4573 	 * 2. Register amdgpu_dm_irq_handler().
4574 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4575 	 *    coming from DC hardware.
4576 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4577 	 *    for acknowledging and handling.
4578 	 */
4579 
4580 	/* Use VSTARTUP interrupt */
4581 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4582 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4583 			i++) {
4584 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4585 
4586 		if (r) {
4587 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4588 			return r;
4589 		}
4590 
4591 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4592 		int_params.irq_source =
4593 			dc_interrupt_to_irq_source(dc, i, 0);
4594 
4595 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4596 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4597 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4598 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4599 			return -EINVAL;
4600 		}
4601 
4602 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4603 
4604 		c_irq_params->adev = adev;
4605 		c_irq_params->irq_src = int_params.irq_source;
4606 
4607 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4608 			dm_crtc_high_irq, c_irq_params))
4609 			return -ENOMEM;
4610 	}
4611 
4612 	/* Use otg vertical line interrupt */
4613 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4614 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4615 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4616 				vrtl_int_srcid[i], &adev->vline0_irq);
4617 
4618 		if (r) {
4619 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4620 			return r;
4621 		}
4622 
4623 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4624 		int_params.irq_source =
4625 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4626 
4627 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4628 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4629 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4630 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4631 			return -EINVAL;
4632 		}
4633 
4634 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4635 					- DC_IRQ_SOURCE_DC1_VLINE0];
4636 
4637 		c_irq_params->adev = adev;
4638 		c_irq_params->irq_src = int_params.irq_source;
4639 
4640 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4641 			dm_dcn_vertical_interrupt0_high_irq,
4642 			c_irq_params))
4643 			return -ENOMEM;
4644 	}
4645 #endif
4646 
4647 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4648 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4649 	 * to trigger at end of each vblank, regardless of state of the lock,
4650 	 * matching DCE behaviour.
4651 	 */
4652 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4653 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4654 	     i++) {
4655 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4656 
4657 		if (r) {
4658 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4659 			return r;
4660 		}
4661 
4662 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4663 		int_params.irq_source =
4664 			dc_interrupt_to_irq_source(dc, i, 0);
4665 
4666 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4667 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4668 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4669 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4670 			return -EINVAL;
4671 		}
4672 
4673 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4674 
4675 		c_irq_params->adev = adev;
4676 		c_irq_params->irq_src = int_params.irq_source;
4677 
4678 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4679 			dm_vupdate_high_irq, c_irq_params))
4680 			return -ENOMEM;
4681 	}
4682 
4683 	/* Use GRPH_PFLIP interrupt */
4684 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4685 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4686 			i++) {
4687 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4688 		if (r) {
4689 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4690 			return r;
4691 		}
4692 
4693 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4694 		int_params.irq_source =
4695 			dc_interrupt_to_irq_source(dc, i, 0);
4696 
4697 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4698 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4699 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4700 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4701 			return -EINVAL;
4702 		}
4703 
4704 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4705 
4706 		c_irq_params->adev = adev;
4707 		c_irq_params->irq_src = int_params.irq_source;
4708 
4709 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4710 			dm_pflip_high_irq, c_irq_params))
4711 			return -ENOMEM;
4712 	}
4713 
4714 	/* HPD */
4715 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4716 			&adev->hpd_irq);
4717 	if (r) {
4718 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4719 		return r;
4720 	}
4721 
4722 	r = register_hpd_handlers(adev);
4723 
4724 	return r;
4725 }
4726 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4727 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4728 {
4729 	struct dc *dc = adev->dm.dc;
4730 	struct common_irq_params *c_irq_params;
4731 	struct dc_interrupt_params int_params = {0};
4732 	int r, i;
4733 
4734 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4735 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4736 
4737 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4738 			&adev->dmub_outbox_irq);
4739 	if (r) {
4740 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4741 		return r;
4742 	}
4743 
4744 	if (dc->ctx->dmub_srv) {
4745 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4746 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4747 		int_params.irq_source =
4748 		dc_interrupt_to_irq_source(dc, i, 0);
4749 
4750 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4751 
4752 		c_irq_params->adev = adev;
4753 		c_irq_params->irq_src = int_params.irq_source;
4754 
4755 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4756 			dm_dmub_outbox1_low_irq, c_irq_params))
4757 			return -ENOMEM;
4758 	}
4759 
4760 	return 0;
4761 }
4762 
4763 /*
4764  * Acquires the lock for the atomic state object and returns
4765  * the new atomic state.
4766  *
4767  * This should only be called during atomic check.
4768  */
4769 int dm_atomic_get_state(struct drm_atomic_state *state,
4770 			struct dm_atomic_state **dm_state)
4771 {
4772 	struct drm_device *dev = state->dev;
4773 	struct amdgpu_device *adev = drm_to_adev(dev);
4774 	struct amdgpu_display_manager *dm = &adev->dm;
4775 	struct drm_private_state *priv_state;
4776 
4777 	if (*dm_state)
4778 		return 0;
4779 
4780 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4781 	if (IS_ERR(priv_state))
4782 		return PTR_ERR(priv_state);
4783 
4784 	*dm_state = to_dm_atomic_state(priv_state);
4785 
4786 	return 0;
4787 }
4788 
4789 static struct dm_atomic_state *
4790 dm_atomic_get_new_state(struct drm_atomic_state *state)
4791 {
4792 	struct drm_device *dev = state->dev;
4793 	struct amdgpu_device *adev = drm_to_adev(dev);
4794 	struct amdgpu_display_manager *dm = &adev->dm;
4795 	struct drm_private_obj *obj;
4796 	struct drm_private_state *new_obj_state;
4797 	int i;
4798 
4799 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4800 		if (obj->funcs == dm->atomic_obj.funcs)
4801 			return to_dm_atomic_state(new_obj_state);
4802 	}
4803 
4804 	return NULL;
4805 }
4806 
4807 static struct drm_private_state *
4808 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4809 {
4810 	struct dm_atomic_state *old_state, *new_state;
4811 
4812 	new_state = kzalloc_obj(*new_state);
4813 	if (!new_state)
4814 		return NULL;
4815 
4816 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4817 
4818 	old_state = to_dm_atomic_state(obj->state);
4819 
4820 	if (old_state && old_state->context)
4821 		new_state->context = dc_state_create_copy(old_state->context);
4822 
4823 	if (!new_state->context) {
4824 		kfree(new_state);
4825 		return NULL;
4826 	}
4827 
4828 	return &new_state->base;
4829 }
4830 
4831 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4832 				    struct drm_private_state *state)
4833 {
4834 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4835 
4836 	if (dm_state && dm_state->context)
4837 		dc_state_release(dm_state->context);
4838 
4839 	kfree(dm_state);
4840 }
4841 
4842 static struct drm_private_state_funcs dm_atomic_state_funcs = {
4843 	.atomic_duplicate_state = dm_atomic_duplicate_state,
4844 	.atomic_destroy_state = dm_atomic_destroy_state,
4845 };
4846 
4847 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
4848 {
4849 	struct dm_atomic_state *state;
4850 	int r;
4851 
4852 	adev->mode_info.mode_config_initialized = true;
4853 
4854 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4855 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4856 
4857 	adev_to_drm(adev)->mode_config.max_width = 16384;
4858 	adev_to_drm(adev)->mode_config.max_height = 16384;
4859 
4860 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4861 	if (adev->asic_type == CHIP_HAWAII)
4862 		/* disable prefer shadow for now due to hibernation issues */
4863 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4864 	else
4865 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4866 	/* indicates support for immediate flip */
4867 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4868 
4869 	state = kzalloc_obj(*state);
4870 	if (!state)
4871 		return -ENOMEM;
4872 
4873 	state->context = dc_state_create_current_copy(adev->dm.dc);
4874 	if (!state->context) {
4875 		kfree(state);
4876 		return -ENOMEM;
4877 	}
4878 
4879 	drm_atomic_private_obj_init(adev_to_drm(adev),
4880 				    &adev->dm.atomic_obj,
4881 				    &state->base,
4882 				    &dm_atomic_state_funcs);
4883 
4884 	r = amdgpu_display_modeset_create_props(adev);
4885 	if (r) {
4886 		dc_state_release(state->context);
4887 		kfree(state);
4888 		return r;
4889 	}
4890 
4891 #ifdef AMD_PRIVATE_COLOR
4892 	if (amdgpu_dm_create_color_properties(adev)) {
4893 		dc_state_release(state->context);
4894 		kfree(state);
4895 		return -ENOMEM;
4896 	}
4897 #endif
4898 
4899 	r = amdgpu_dm_audio_init(adev);
4900 	if (r) {
4901 		dc_state_release(state->context);
4902 		kfree(state);
4903 		return r;
4904 	}
4905 
4906 	return 0;
4907 }
4908 
4909 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4910 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4911 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
4912 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4913 
4914 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4915 					    int bl_idx)
4916 {
4917 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
4918 
4919 	if (caps->caps_valid)
4920 		return;
4921 
4922 #if defined(CONFIG_ACPI)
4923 	amdgpu_acpi_get_backlight_caps(caps);
4924 
4925 	/* validate the firmware value is sane */
4926 	if (caps->caps_valid) {
4927 		int spread = caps->max_input_signal - caps->min_input_signal;
4928 
4929 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4930 		    caps->min_input_signal < 0 ||
4931 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4932 		    spread < AMDGPU_DM_MIN_SPREAD) {
4933 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
4934 				      caps->min_input_signal, caps->max_input_signal);
4935 			caps->caps_valid = false;
4936 		}
4937 	}
4938 
4939 	if (!caps->caps_valid) {
4940 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4941 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4942 		caps->caps_valid = true;
4943 	}
4944 #else
4945 	if (caps->aux_support)
4946 		return;
4947 
4948 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4949 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4950 	caps->caps_valid = true;
4951 #endif
4952 }
4953 
4954 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
4955 				unsigned int *min, unsigned int *max)
4956 {
4957 	if (!caps)
4958 		return 0;
4959 
4960 	if (caps->aux_support) {
4961 		// Firmware limits are in nits, DC API wants millinits.
4962 		*max = 1000 * caps->aux_max_input_signal;
4963 		*min = 1000 * caps->aux_min_input_signal;
4964 	} else {
4965 		// Firmware limits are 8-bit, PWM control is 16-bit.
4966 		*max = 0x101 * caps->max_input_signal;
4967 		*min = 0x101 * caps->min_input_signal;
4968 	}
4969 	return 1;
4970 }
4971 
4972 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
4973 static inline u32 scale_input_to_fw(int min, int max, u64 input)
4974 {
4975 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
4976 }
4977 
4978 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
4979 static inline u32 scale_fw_to_input(int min, int max, u64 input)
4980 {
4981 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
4982 }
4983 
4984 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
4985 				      unsigned int min, unsigned int max,
4986 				      uint32_t *user_brightness)
4987 {
4988 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
4989 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
4990 	int left, right;
4991 
4992 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
4993 		return;
4994 
4995 	if (!caps->data_points)
4996 		return;
4997 
4998 	/*
4999 	 * Handle the case where brightness is below the first data point
5000 	 * Interpolate between (0,0) and (first_signal, first_lum)
5001 	 */
5002 	if (brightness < caps->luminance_data[0].input_signal) {
5003 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5004 					caps->luminance_data[0].input_signal);
5005 		goto scale;
5006 	}
5007 
5008 	left = 0;
5009 	right = caps->data_points - 1;
5010 	while (left <= right) {
5011 		int mid = left + (right - left) / 2;
5012 		u8 signal = caps->luminance_data[mid].input_signal;
5013 
5014 		/* Exact match found */
5015 		if (signal == brightness) {
5016 			lum = caps->luminance_data[mid].luminance;
5017 			goto scale;
5018 		}
5019 
5020 		if (signal < brightness)
5021 			left = mid + 1;
5022 		else
5023 			right = mid - 1;
5024 	}
5025 
5026 	/* verify bound */
5027 	if (left >= caps->data_points)
5028 		left = caps->data_points - 1;
5029 
5030 	/* At this point, left > right */
5031 	lower_signal = caps->luminance_data[right].input_signal;
5032 	upper_signal = caps->luminance_data[left].input_signal;
5033 	lower_lum = caps->luminance_data[right].luminance;
5034 	upper_lum = caps->luminance_data[left].luminance;
5035 
5036 	/* interpolate */
5037 	if (right == left || !lower_lum)
5038 		lum = upper_lum;
5039 	else
5040 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5041 						    (brightness - lower_signal),
5042 						    upper_signal - lower_signal);
5043 scale:
5044 	*user_brightness = scale_fw_to_input(min, max,
5045 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5046 }
5047 
5048 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5049 					uint32_t brightness)
5050 {
5051 	unsigned int min, max;
5052 
5053 	if (!get_brightness_range(caps, &min, &max))
5054 		return brightness;
5055 
5056 	convert_custom_brightness(caps, min, max, &brightness);
5057 
5058 	// Rescale 0..max to min..max
5059 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5060 }
5061 
5062 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5063 				      uint32_t brightness)
5064 {
5065 	unsigned int min, max;
5066 
5067 	if (!get_brightness_range(caps, &min, &max))
5068 		return brightness;
5069 
5070 	if (brightness < min)
5071 		return 0;
5072 	// Rescale min..max to 0..max
5073 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5074 				 max - min);
5075 }
5076 
5077 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5078 					 int bl_idx,
5079 					 u32 user_brightness)
5080 {
5081 	struct amdgpu_dm_backlight_caps *caps;
5082 	struct dc_link *link;
5083 	u32 brightness;
5084 	bool rc, reallow_idle = false;
5085 	struct drm_connector *connector;
5086 
5087 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5088 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5089 
5090 		if (aconnector->bl_idx != bl_idx)
5091 			continue;
5092 
5093 		/* if connector is off, save the brightness for next time it's on */
5094 		if (!aconnector->base.encoder) {
5095 			dm->brightness[bl_idx] = user_brightness;
5096 			dm->actual_brightness[bl_idx] = 0;
5097 			return;
5098 		}
5099 	}
5100 
5101 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5102 	caps = &dm->backlight_caps[bl_idx];
5103 
5104 	dm->brightness[bl_idx] = user_brightness;
5105 	/* update scratch register */
5106 	if (bl_idx == 0)
5107 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5108 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5109 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5110 
5111 	/* Apply brightness quirk */
5112 	if (caps->brightness_mask)
5113 		brightness |= caps->brightness_mask;
5114 
5115 	/* Change brightness based on AUX property */
5116 	mutex_lock(&dm->dc_lock);
5117 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5118 		dc_allow_idle_optimizations(dm->dc, false);
5119 		reallow_idle = true;
5120 	}
5121 
5122 	if (trace_amdgpu_dm_brightness_enabled()) {
5123 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5124 					   user_brightness,
5125 					   brightness,
5126 					   caps->aux_support,
5127 					   power_supply_is_system_supplied() > 0);
5128 	}
5129 
5130 	if (caps->aux_support) {
5131 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
5132 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
5133 		if (!rc)
5134 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
5135 	} else {
5136 		struct set_backlight_level_params backlight_level_params = { 0 };
5137 
5138 		backlight_level_params.backlight_pwm_u16_16 = brightness;
5139 		backlight_level_params.transition_time_in_ms = 0;
5140 
5141 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
5142 		if (!rc)
5143 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
5144 	}
5145 
5146 	if (dm->dc->caps.ips_support && reallow_idle)
5147 		dc_allow_idle_optimizations(dm->dc, true);
5148 
5149 	mutex_unlock(&dm->dc_lock);
5150 
5151 	if (rc)
5152 		dm->actual_brightness[bl_idx] = user_brightness;
5153 }
5154 
5155 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5156 {
5157 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5158 	int i;
5159 
5160 	for (i = 0; i < dm->num_of_edps; i++) {
5161 		if (bd == dm->backlight_dev[i])
5162 			break;
5163 	}
5164 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5165 		i = 0;
5166 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5167 
5168 	return 0;
5169 }
5170 
5171 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5172 					 int bl_idx)
5173 {
5174 	int ret;
5175 	struct amdgpu_dm_backlight_caps caps;
5176 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5177 
5178 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5179 	caps = dm->backlight_caps[bl_idx];
5180 
5181 	if (caps.aux_support) {
5182 		u32 avg, peak;
5183 
5184 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5185 			return dm->brightness[bl_idx];
5186 		return convert_brightness_to_user(&caps, avg);
5187 	}
5188 
5189 	ret = dc_link_get_backlight_level(link);
5190 
5191 	if (ret == DC_ERROR_UNEXPECTED)
5192 		return dm->brightness[bl_idx];
5193 
5194 	return convert_brightness_to_user(&caps, ret);
5195 }
5196 
5197 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5198 {
5199 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5200 	int i;
5201 
5202 	for (i = 0; i < dm->num_of_edps; i++) {
5203 		if (bd == dm->backlight_dev[i])
5204 			break;
5205 	}
5206 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5207 		i = 0;
5208 	return amdgpu_dm_backlight_get_level(dm, i);
5209 }
5210 
5211 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5212 	.options = BL_CORE_SUSPENDRESUME,
5213 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5214 	.update_status	= amdgpu_dm_backlight_update_status,
5215 };
5216 
5217 static void
5218 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5219 {
5220 	struct drm_device *drm = aconnector->base.dev;
5221 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5222 	struct backlight_properties props = { 0 };
5223 	struct amdgpu_dm_backlight_caps *caps;
5224 	char bl_name[16];
5225 	int min, max;
5226 	int real_brightness;
5227 	int init_brightness;
5228 
5229 	if (aconnector->bl_idx == -1)
5230 		return;
5231 
5232 	if (!acpi_video_backlight_use_native()) {
5233 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5234 		/* Try registering an ACPI video backlight device instead. */
5235 		acpi_video_register_backlight();
5236 		return;
5237 	}
5238 
5239 	caps = &dm->backlight_caps[aconnector->bl_idx];
5240 	if (get_brightness_range(caps, &min, &max)) {
5241 		if (power_supply_is_system_supplied() > 0)
5242 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5243 		else
5244 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5245 		/* min is zero, so max needs to be adjusted */
5246 		props.max_brightness = max - min;
5247 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5248 			caps->ac_level, caps->dc_level);
5249 	} else
5250 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5251 
5252 	init_brightness = props.brightness;
5253 
5254 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5255 		drm_info(drm, "Using custom brightness curve\n");
5256 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5257 	} else
5258 		props.scale = BACKLIGHT_SCALE_LINEAR;
5259 	props.type = BACKLIGHT_RAW;
5260 
5261 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5262 		 drm->primary->index + aconnector->bl_idx);
5263 
5264 	dm->backlight_dev[aconnector->bl_idx] =
5265 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5266 					  &amdgpu_dm_backlight_ops, &props);
5267 	dm->brightness[aconnector->bl_idx] = props.brightness;
5268 
5269 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5270 		drm_err(drm, "DM: Backlight registration failed!\n");
5271 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5272 	} else {
5273 		/*
5274 		 * dm->brightness[x] can be inconsistent just after startup until
5275 		 * ops.get_brightness is called.
5276 		 */
5277 		real_brightness =
5278 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5279 
5280 		if (real_brightness != init_brightness) {
5281 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5282 			dm->brightness[aconnector->bl_idx] = real_brightness;
5283 		}
5284 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5285 	}
5286 }
5287 
5288 static int initialize_plane(struct amdgpu_display_manager *dm,
5289 			    struct amdgpu_mode_info *mode_info, int plane_id,
5290 			    enum drm_plane_type plane_type,
5291 			    const struct dc_plane_cap *plane_cap)
5292 {
5293 	struct drm_plane *plane;
5294 	unsigned long possible_crtcs;
5295 	int ret = 0;
5296 
5297 	plane = kzalloc_obj(struct drm_plane);
5298 	if (!plane) {
5299 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5300 		return -ENOMEM;
5301 	}
5302 	plane->type = plane_type;
5303 
5304 	/*
5305 	 * HACK: IGT tests expect that the primary plane for a CRTC
5306 	 * can only have one possible CRTC. Only expose support for
5307 	 * any CRTC if they're not going to be used as a primary plane
5308 	 * for a CRTC - like overlay or underlay planes.
5309 	 */
5310 	possible_crtcs = 1 << plane_id;
5311 	if (plane_id >= dm->dc->caps.max_streams)
5312 		possible_crtcs = 0xff;
5313 
5314 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5315 
5316 	if (ret) {
5317 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5318 		kfree(plane);
5319 		return ret;
5320 	}
5321 
5322 	if (mode_info)
5323 		mode_info->planes[plane_id] = plane;
5324 
5325 	return ret;
5326 }
5327 
5328 
5329 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5330 				   struct amdgpu_dm_connector *aconnector)
5331 {
5332 	struct amdgpu_dm_backlight_caps *caps;
5333 	struct dc_link *link = aconnector->dc_link;
5334 	int bl_idx = dm->num_of_edps;
5335 
5336 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5337 	    link->type == dc_connection_none)
5338 		return;
5339 
5340 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5341 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5342 		return;
5343 	}
5344 
5345 	aconnector->bl_idx = bl_idx;
5346 
5347 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5348 	dm->backlight_link[bl_idx] = link;
5349 	dm->num_of_edps++;
5350 
5351 	update_connector_ext_caps(aconnector);
5352 	caps = &dm->backlight_caps[aconnector->bl_idx];
5353 
5354 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5355 	if (!caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5356 		drm_object_attach_property(&aconnector->base.base,
5357 					   dm->adev->mode_info.abm_level_property,
5358 					   ABM_SYSFS_CONTROL);
5359 }
5360 
5361 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5362 
5363 /*
5364  * In this architecture, the association
5365  * connector -> encoder -> crtc
5366  * id not really requried. The crtc and connector will hold the
5367  * display_index as an abstraction to use with DAL component
5368  *
5369  * Returns 0 on success
5370  */
5371 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5372 {
5373 	struct amdgpu_display_manager *dm = &adev->dm;
5374 	s32 i;
5375 	struct amdgpu_dm_connector *aconnector = NULL;
5376 	struct amdgpu_encoder *aencoder = NULL;
5377 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5378 	u32 link_cnt;
5379 	s32 primary_planes;
5380 	enum dc_connection_type new_connection_type = dc_connection_none;
5381 	const struct dc_plane_cap *plane;
5382 	bool psr_feature_enabled = false;
5383 	bool replay_feature_enabled = false;
5384 	int max_overlay = dm->dc->caps.max_slave_planes;
5385 
5386 	dm->display_indexes_num = dm->dc->caps.max_streams;
5387 	/* Update the actual used number of crtc */
5388 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5389 
5390 	amdgpu_dm_set_irq_funcs(adev);
5391 
5392 	link_cnt = dm->dc->caps.max_links;
5393 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5394 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5395 		return -EINVAL;
5396 	}
5397 
5398 	/* There is one primary plane per CRTC */
5399 	primary_planes = dm->dc->caps.max_streams;
5400 	if (primary_planes > AMDGPU_MAX_PLANES) {
5401 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5402 		return -EINVAL;
5403 	}
5404 
5405 	/*
5406 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5407 	 * Order is reversed to match iteration order in atomic check.
5408 	 */
5409 	for (i = (primary_planes - 1); i >= 0; i--) {
5410 		plane = &dm->dc->caps.planes[i];
5411 
5412 		if (initialize_plane(dm, mode_info, i,
5413 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5414 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5415 			goto fail;
5416 		}
5417 	}
5418 
5419 	/*
5420 	 * Initialize overlay planes, index starting after primary planes.
5421 	 * These planes have a higher DRM index than the primary planes since
5422 	 * they should be considered as having a higher z-order.
5423 	 * Order is reversed to match iteration order in atomic check.
5424 	 *
5425 	 * Only support DCN for now, and only expose one so we don't encourage
5426 	 * userspace to use up all the pipes.
5427 	 */
5428 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5429 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5430 
5431 		/* Do not create overlay if MPO disabled */
5432 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5433 			break;
5434 
5435 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5436 			continue;
5437 
5438 		if (!plane->pixel_format_support.argb8888)
5439 			continue;
5440 
5441 		if (max_overlay-- == 0)
5442 			break;
5443 
5444 		if (initialize_plane(dm, NULL, primary_planes + i,
5445 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5446 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5447 			goto fail;
5448 		}
5449 	}
5450 
5451 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5452 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5453 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5454 			goto fail;
5455 		}
5456 
5457 	/* Use Outbox interrupt */
5458 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5459 	case IP_VERSION(3, 0, 0):
5460 	case IP_VERSION(3, 1, 2):
5461 	case IP_VERSION(3, 1, 3):
5462 	case IP_VERSION(3, 1, 4):
5463 	case IP_VERSION(3, 1, 5):
5464 	case IP_VERSION(3, 1, 6):
5465 	case IP_VERSION(3, 2, 0):
5466 	case IP_VERSION(3, 2, 1):
5467 	case IP_VERSION(2, 1, 0):
5468 	case IP_VERSION(3, 5, 0):
5469 	case IP_VERSION(3, 5, 1):
5470 	case IP_VERSION(3, 6, 0):
5471 	case IP_VERSION(4, 0, 1):
5472 	case IP_VERSION(4, 2, 0):
5473 		if (register_outbox_irq_handlers(dm->adev)) {
5474 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5475 			goto fail;
5476 		}
5477 		break;
5478 	default:
5479 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5480 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5481 	}
5482 
5483 	/* Determine whether to enable PSR support by default. */
5484 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5485 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5486 		case IP_VERSION(3, 1, 2):
5487 		case IP_VERSION(3, 1, 3):
5488 		case IP_VERSION(3, 1, 4):
5489 		case IP_VERSION(3, 1, 5):
5490 		case IP_VERSION(3, 1, 6):
5491 		case IP_VERSION(3, 2, 0):
5492 		case IP_VERSION(3, 2, 1):
5493 		case IP_VERSION(3, 5, 0):
5494 		case IP_VERSION(3, 5, 1):
5495 		case IP_VERSION(3, 6, 0):
5496 		case IP_VERSION(4, 0, 1):
5497 		case IP_VERSION(4, 2, 0):
5498 			psr_feature_enabled = true;
5499 			break;
5500 		default:
5501 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5502 			break;
5503 		}
5504 	}
5505 
5506 	/* Determine whether to enable Replay support by default. */
5507 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5508 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5509 		case IP_VERSION(3, 1, 4):
5510 		case IP_VERSION(3, 2, 0):
5511 		case IP_VERSION(3, 2, 1):
5512 		case IP_VERSION(3, 5, 0):
5513 		case IP_VERSION(3, 5, 1):
5514 		case IP_VERSION(3, 6, 0):
5515 			replay_feature_enabled = true;
5516 			break;
5517 
5518 		default:
5519 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5520 			break;
5521 		}
5522 	}
5523 
5524 	if (link_cnt > MAX_LINKS) {
5525 		drm_err(adev_to_drm(adev),
5526 			"KMS: Cannot support more than %d display indexes\n",
5527 				MAX_LINKS);
5528 		goto fail;
5529 	}
5530 
5531 	/* loops over all connectors on the board */
5532 	for (i = 0; i < link_cnt; i++) {
5533 		struct dc_link *link = NULL;
5534 
5535 		link = dc_get_link_at_index(dm->dc, i);
5536 
5537 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5538 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5539 
5540 			if (!wbcon) {
5541 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5542 				continue;
5543 			}
5544 
5545 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5546 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5547 				kfree(wbcon);
5548 				continue;
5549 			}
5550 
5551 			link->psr_settings.psr_feature_enabled = false;
5552 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5553 
5554 			continue;
5555 		}
5556 
5557 		aconnector = kzalloc_obj(*aconnector);
5558 		if (!aconnector)
5559 			goto fail;
5560 
5561 		aencoder = kzalloc_obj(*aencoder);
5562 		if (!aencoder)
5563 			goto fail;
5564 
5565 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5566 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5567 			goto fail;
5568 		}
5569 
5570 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5571 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5572 			goto fail;
5573 		}
5574 
5575 		if (dm->hpd_rx_offload_wq)
5576 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5577 				aconnector;
5578 
5579 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5580 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5581 
5582 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5583 			emulated_link_detect(link);
5584 			amdgpu_dm_update_connector_after_detect(aconnector);
5585 		} else {
5586 			bool ret = false;
5587 
5588 			mutex_lock(&dm->dc_lock);
5589 			dc_exit_ips_for_hw_access(dm->dc);
5590 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5591 			mutex_unlock(&dm->dc_lock);
5592 
5593 			if (ret) {
5594 				amdgpu_dm_update_connector_after_detect(aconnector);
5595 				setup_backlight_device(dm, aconnector);
5596 
5597 				/* Disable PSR if Replay can be enabled */
5598 				if (replay_feature_enabled)
5599 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5600 						psr_feature_enabled = false;
5601 
5602 				if (psr_feature_enabled) {
5603 					amdgpu_dm_set_psr_caps(link);
5604 					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",
5605 						 aconnector->base.name,
5606 						 link->psr_settings.psr_feature_enabled,
5607 						 link->psr_settings.psr_version,
5608 						 link->dpcd_caps.psr_info.psr_version,
5609 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5610 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5611 				}
5612 			}
5613 		}
5614 		amdgpu_set_panel_orientation(&aconnector->base);
5615 	}
5616 
5617 	/* Debug dump: list all DC links and their associated sinks after detection
5618 	 * is complete for all connectors. This provides a comprehensive view of the
5619 	 * final state without repeating the dump for each connector.
5620 	 */
5621 	amdgpu_dm_dump_links_and_sinks(adev);
5622 
5623 	/* Software is initialized. Now we can register interrupt handlers. */
5624 	switch (adev->asic_type) {
5625 #if defined(CONFIG_DRM_AMD_DC_SI)
5626 	case CHIP_TAHITI:
5627 	case CHIP_PITCAIRN:
5628 	case CHIP_VERDE:
5629 	case CHIP_OLAND:
5630 #endif
5631 	case CHIP_BONAIRE:
5632 	case CHIP_HAWAII:
5633 	case CHIP_KAVERI:
5634 	case CHIP_KABINI:
5635 	case CHIP_MULLINS:
5636 	case CHIP_TONGA:
5637 	case CHIP_FIJI:
5638 	case CHIP_CARRIZO:
5639 	case CHIP_STONEY:
5640 	case CHIP_POLARIS11:
5641 	case CHIP_POLARIS10:
5642 	case CHIP_POLARIS12:
5643 	case CHIP_VEGAM:
5644 	case CHIP_VEGA10:
5645 	case CHIP_VEGA12:
5646 	case CHIP_VEGA20:
5647 		if (dce110_register_irq_handlers(dm->adev)) {
5648 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5649 			goto fail;
5650 		}
5651 		break;
5652 	default:
5653 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5654 		case IP_VERSION(1, 0, 0):
5655 		case IP_VERSION(1, 0, 1):
5656 		case IP_VERSION(2, 0, 2):
5657 		case IP_VERSION(2, 0, 3):
5658 		case IP_VERSION(2, 0, 0):
5659 		case IP_VERSION(2, 1, 0):
5660 		case IP_VERSION(3, 0, 0):
5661 		case IP_VERSION(3, 0, 2):
5662 		case IP_VERSION(3, 0, 3):
5663 		case IP_VERSION(3, 0, 1):
5664 		case IP_VERSION(3, 1, 2):
5665 		case IP_VERSION(3, 1, 3):
5666 		case IP_VERSION(3, 1, 4):
5667 		case IP_VERSION(3, 1, 5):
5668 		case IP_VERSION(3, 1, 6):
5669 		case IP_VERSION(3, 2, 0):
5670 		case IP_VERSION(3, 2, 1):
5671 		case IP_VERSION(3, 5, 0):
5672 		case IP_VERSION(3, 5, 1):
5673 		case IP_VERSION(3, 6, 0):
5674 		case IP_VERSION(4, 0, 1):
5675 		case IP_VERSION(4, 2, 0):
5676 			if (dcn10_register_irq_handlers(dm->adev)) {
5677 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5678 				goto fail;
5679 			}
5680 			break;
5681 		default:
5682 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5683 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5684 			goto fail;
5685 		}
5686 		break;
5687 	}
5688 
5689 	return 0;
5690 fail:
5691 	kfree(aencoder);
5692 	kfree(aconnector);
5693 
5694 	return -EINVAL;
5695 }
5696 
5697 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5698 {
5699 	if (dm->atomic_obj.state)
5700 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5701 }
5702 
5703 /******************************************************************************
5704  * amdgpu_display_funcs functions
5705  *****************************************************************************/
5706 
5707 /*
5708  * dm_bandwidth_update - program display watermarks
5709  *
5710  * @adev: amdgpu_device pointer
5711  *
5712  * Calculate and program the display watermarks and line buffer allocation.
5713  */
5714 static void dm_bandwidth_update(struct amdgpu_device *adev)
5715 {
5716 	/* TODO: implement later */
5717 }
5718 
5719 static const struct amdgpu_display_funcs dm_display_funcs = {
5720 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5721 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5722 	.backlight_set_level = NULL, /* never called for DC */
5723 	.backlight_get_level = NULL, /* never called for DC */
5724 	.hpd_sense = NULL,/* called unconditionally */
5725 	.hpd_set_polarity = NULL, /* called unconditionally */
5726 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5727 	.page_flip_get_scanoutpos =
5728 		dm_crtc_get_scanoutpos,/* called unconditionally */
5729 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5730 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5731 };
5732 
5733 #if defined(CONFIG_DEBUG_KERNEL_DC)
5734 
5735 static ssize_t s3_debug_store(struct device *device,
5736 			      struct device_attribute *attr,
5737 			      const char *buf,
5738 			      size_t count)
5739 {
5740 	int ret;
5741 	int s3_state;
5742 	struct drm_device *drm_dev = dev_get_drvdata(device);
5743 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5744 	struct amdgpu_ip_block *ip_block;
5745 
5746 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5747 	if (!ip_block)
5748 		return -EINVAL;
5749 
5750 	ret = kstrtoint(buf, 0, &s3_state);
5751 
5752 	if (ret == 0) {
5753 		if (s3_state) {
5754 			dm_resume(ip_block);
5755 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5756 		} else
5757 			dm_suspend(ip_block);
5758 	}
5759 
5760 	return ret == 0 ? count : 0;
5761 }
5762 
5763 DEVICE_ATTR_WO(s3_debug);
5764 
5765 #endif
5766 
5767 static int dm_init_microcode(struct amdgpu_device *adev)
5768 {
5769 	char *fw_name_dmub;
5770 	int r;
5771 
5772 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5773 	case IP_VERSION(2, 1, 0):
5774 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5775 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5776 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5777 		break;
5778 	case IP_VERSION(3, 0, 0):
5779 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5780 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5781 		else
5782 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5783 		break;
5784 	case IP_VERSION(3, 0, 1):
5785 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5786 		break;
5787 	case IP_VERSION(3, 0, 2):
5788 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5789 		break;
5790 	case IP_VERSION(3, 0, 3):
5791 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5792 		break;
5793 	case IP_VERSION(3, 1, 2):
5794 	case IP_VERSION(3, 1, 3):
5795 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5796 		break;
5797 	case IP_VERSION(3, 1, 4):
5798 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5799 		break;
5800 	case IP_VERSION(3, 1, 5):
5801 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5802 		break;
5803 	case IP_VERSION(3, 1, 6):
5804 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5805 		break;
5806 	case IP_VERSION(3, 2, 0):
5807 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5808 		break;
5809 	case IP_VERSION(3, 2, 1):
5810 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5811 		break;
5812 	case IP_VERSION(3, 5, 0):
5813 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5814 		break;
5815 	case IP_VERSION(3, 5, 1):
5816 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5817 		break;
5818 	case IP_VERSION(3, 6, 0):
5819 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5820 		break;
5821 	case IP_VERSION(4, 0, 1):
5822 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5823 		break;
5824 	case IP_VERSION(4, 2, 0):
5825 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
5826 		break;
5827 	default:
5828 		/* ASIC doesn't support DMUB. */
5829 		return 0;
5830 	}
5831 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5832 				 "%s", fw_name_dmub);
5833 	return r;
5834 }
5835 
5836 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5837 {
5838 	struct amdgpu_device *adev = ip_block->adev;
5839 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5840 	struct atom_context *ctx = mode_info->atom_context;
5841 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5842 	u16 data_offset;
5843 
5844 	/* if there is no object header, skip DM */
5845 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5846 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5847 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5848 		return -ENOENT;
5849 	}
5850 
5851 	switch (adev->asic_type) {
5852 #if defined(CONFIG_DRM_AMD_DC_SI)
5853 	case CHIP_TAHITI:
5854 	case CHIP_PITCAIRN:
5855 	case CHIP_VERDE:
5856 		adev->mode_info.num_crtc = 6;
5857 		adev->mode_info.num_hpd = 6;
5858 		adev->mode_info.num_dig = 6;
5859 		break;
5860 	case CHIP_OLAND:
5861 		adev->mode_info.num_crtc = 2;
5862 		adev->mode_info.num_hpd = 2;
5863 		adev->mode_info.num_dig = 2;
5864 		break;
5865 #endif
5866 	case CHIP_BONAIRE:
5867 	case CHIP_HAWAII:
5868 		adev->mode_info.num_crtc = 6;
5869 		adev->mode_info.num_hpd = 6;
5870 		adev->mode_info.num_dig = 6;
5871 		break;
5872 	case CHIP_KAVERI:
5873 		adev->mode_info.num_crtc = 4;
5874 		adev->mode_info.num_hpd = 6;
5875 		adev->mode_info.num_dig = 7;
5876 		break;
5877 	case CHIP_KABINI:
5878 	case CHIP_MULLINS:
5879 		adev->mode_info.num_crtc = 2;
5880 		adev->mode_info.num_hpd = 6;
5881 		adev->mode_info.num_dig = 6;
5882 		break;
5883 	case CHIP_FIJI:
5884 	case CHIP_TONGA:
5885 		adev->mode_info.num_crtc = 6;
5886 		adev->mode_info.num_hpd = 6;
5887 		adev->mode_info.num_dig = 7;
5888 		break;
5889 	case CHIP_CARRIZO:
5890 		adev->mode_info.num_crtc = 3;
5891 		adev->mode_info.num_hpd = 6;
5892 		adev->mode_info.num_dig = 9;
5893 		break;
5894 	case CHIP_STONEY:
5895 		adev->mode_info.num_crtc = 2;
5896 		adev->mode_info.num_hpd = 6;
5897 		adev->mode_info.num_dig = 9;
5898 		break;
5899 	case CHIP_POLARIS11:
5900 	case CHIP_POLARIS12:
5901 		adev->mode_info.num_crtc = 5;
5902 		adev->mode_info.num_hpd = 5;
5903 		adev->mode_info.num_dig = 5;
5904 		break;
5905 	case CHIP_POLARIS10:
5906 	case CHIP_VEGAM:
5907 		adev->mode_info.num_crtc = 6;
5908 		adev->mode_info.num_hpd = 6;
5909 		adev->mode_info.num_dig = 6;
5910 		break;
5911 	case CHIP_VEGA10:
5912 	case CHIP_VEGA12:
5913 	case CHIP_VEGA20:
5914 		adev->mode_info.num_crtc = 6;
5915 		adev->mode_info.num_hpd = 6;
5916 		adev->mode_info.num_dig = 6;
5917 		break;
5918 	default:
5919 
5920 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5921 		case IP_VERSION(2, 0, 2):
5922 		case IP_VERSION(3, 0, 0):
5923 			adev->mode_info.num_crtc = 6;
5924 			adev->mode_info.num_hpd = 6;
5925 			adev->mode_info.num_dig = 6;
5926 			break;
5927 		case IP_VERSION(2, 0, 0):
5928 		case IP_VERSION(3, 0, 2):
5929 			adev->mode_info.num_crtc = 5;
5930 			adev->mode_info.num_hpd = 5;
5931 			adev->mode_info.num_dig = 5;
5932 			break;
5933 		case IP_VERSION(2, 0, 3):
5934 		case IP_VERSION(3, 0, 3):
5935 			adev->mode_info.num_crtc = 2;
5936 			adev->mode_info.num_hpd = 2;
5937 			adev->mode_info.num_dig = 2;
5938 			break;
5939 		case IP_VERSION(1, 0, 0):
5940 		case IP_VERSION(1, 0, 1):
5941 		case IP_VERSION(3, 0, 1):
5942 		case IP_VERSION(2, 1, 0):
5943 		case IP_VERSION(3, 1, 2):
5944 		case IP_VERSION(3, 1, 3):
5945 		case IP_VERSION(3, 1, 4):
5946 		case IP_VERSION(3, 1, 5):
5947 		case IP_VERSION(3, 1, 6):
5948 		case IP_VERSION(3, 2, 0):
5949 		case IP_VERSION(3, 2, 1):
5950 		case IP_VERSION(3, 5, 0):
5951 		case IP_VERSION(3, 5, 1):
5952 		case IP_VERSION(3, 6, 0):
5953 		case IP_VERSION(4, 0, 1):
5954 		case IP_VERSION(4, 2, 0):
5955 			adev->mode_info.num_crtc = 4;
5956 			adev->mode_info.num_hpd = 4;
5957 			adev->mode_info.num_dig = 4;
5958 			break;
5959 		default:
5960 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
5961 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5962 			return -EINVAL;
5963 		}
5964 		break;
5965 	}
5966 
5967 	if (adev->mode_info.funcs == NULL)
5968 		adev->mode_info.funcs = &dm_display_funcs;
5969 
5970 	/*
5971 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
5972 	 * adev->reg.audio_endpt.wreg because they are initialised in
5973 	 * amdgpu_device_init()
5974 	 */
5975 #if defined(CONFIG_DEBUG_KERNEL_DC)
5976 	device_create_file(
5977 		adev_to_drm(adev)->dev,
5978 		&dev_attr_s3_debug);
5979 #endif
5980 	adev->dc_enabled = true;
5981 
5982 	return dm_init_microcode(adev);
5983 }
5984 
5985 static bool modereset_required(struct drm_crtc_state *crtc_state)
5986 {
5987 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
5988 }
5989 
5990 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
5991 {
5992 	drm_encoder_cleanup(encoder);
5993 	kfree(encoder);
5994 }
5995 
5996 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
5997 	.destroy = amdgpu_dm_encoder_destroy,
5998 };
5999 
6000 static int
6001 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6002 			    const enum surface_pixel_format format,
6003 			    enum dc_color_space *color_space)
6004 {
6005 	bool full_range;
6006 
6007 	*color_space = COLOR_SPACE_SRGB;
6008 
6009 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6010 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6011 		return 0;
6012 
6013 	/* DRM color properties only affect non-RGB formats. */
6014 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6015 		return 0;
6016 
6017 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6018 
6019 	switch (plane_state->color_encoding) {
6020 	case DRM_COLOR_YCBCR_BT601:
6021 		if (full_range)
6022 			*color_space = COLOR_SPACE_YCBCR601;
6023 		else
6024 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6025 		break;
6026 
6027 	case DRM_COLOR_YCBCR_BT709:
6028 		if (full_range)
6029 			*color_space = COLOR_SPACE_YCBCR709;
6030 		else
6031 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6032 		break;
6033 
6034 	case DRM_COLOR_YCBCR_BT2020:
6035 		if (full_range)
6036 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6037 		else
6038 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6039 		break;
6040 
6041 	default:
6042 		return -EINVAL;
6043 	}
6044 
6045 	return 0;
6046 }
6047 
6048 static int
6049 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6050 			    const struct drm_plane_state *plane_state,
6051 			    const u64 tiling_flags,
6052 			    struct dc_plane_info *plane_info,
6053 			    struct dc_plane_address *address,
6054 			    bool tmz_surface)
6055 {
6056 	const struct drm_framebuffer *fb = plane_state->fb;
6057 	const struct amdgpu_framebuffer *afb =
6058 		to_amdgpu_framebuffer(plane_state->fb);
6059 	int ret;
6060 
6061 	memset(plane_info, 0, sizeof(*plane_info));
6062 
6063 	switch (fb->format->format) {
6064 	case DRM_FORMAT_C8:
6065 		plane_info->format =
6066 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6067 		break;
6068 	case DRM_FORMAT_RGB565:
6069 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6070 		break;
6071 	case DRM_FORMAT_XRGB8888:
6072 	case DRM_FORMAT_ARGB8888:
6073 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6074 		break;
6075 	case DRM_FORMAT_XRGB2101010:
6076 	case DRM_FORMAT_ARGB2101010:
6077 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6078 		break;
6079 	case DRM_FORMAT_XBGR2101010:
6080 	case DRM_FORMAT_ABGR2101010:
6081 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6082 		break;
6083 	case DRM_FORMAT_XBGR8888:
6084 	case DRM_FORMAT_ABGR8888:
6085 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6086 		break;
6087 	case DRM_FORMAT_NV21:
6088 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6089 		break;
6090 	case DRM_FORMAT_NV12:
6091 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6092 		break;
6093 	case DRM_FORMAT_P010:
6094 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6095 		break;
6096 	case DRM_FORMAT_XRGB16161616F:
6097 	case DRM_FORMAT_ARGB16161616F:
6098 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6099 		break;
6100 	case DRM_FORMAT_XBGR16161616F:
6101 	case DRM_FORMAT_ABGR16161616F:
6102 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6103 		break;
6104 	case DRM_FORMAT_XRGB16161616:
6105 	case DRM_FORMAT_ARGB16161616:
6106 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6107 		break;
6108 	case DRM_FORMAT_XBGR16161616:
6109 	case DRM_FORMAT_ABGR16161616:
6110 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6111 		break;
6112 	default:
6113 		drm_err(adev_to_drm(adev),
6114 			"Unsupported screen format %p4cc\n",
6115 			&fb->format->format);
6116 		return -EINVAL;
6117 	}
6118 
6119 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6120 	case DRM_MODE_ROTATE_0:
6121 		plane_info->rotation = ROTATION_ANGLE_0;
6122 		break;
6123 	case DRM_MODE_ROTATE_90:
6124 		plane_info->rotation = ROTATION_ANGLE_90;
6125 		break;
6126 	case DRM_MODE_ROTATE_180:
6127 		plane_info->rotation = ROTATION_ANGLE_180;
6128 		break;
6129 	case DRM_MODE_ROTATE_270:
6130 		plane_info->rotation = ROTATION_ANGLE_270;
6131 		break;
6132 	default:
6133 		plane_info->rotation = ROTATION_ANGLE_0;
6134 		break;
6135 	}
6136 
6137 
6138 	plane_info->visible = true;
6139 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6140 
6141 	plane_info->layer_index = plane_state->normalized_zpos;
6142 
6143 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6144 					  &plane_info->color_space);
6145 	if (ret)
6146 		return ret;
6147 
6148 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6149 					   plane_info->rotation, tiling_flags,
6150 					   &plane_info->tiling_info,
6151 					   &plane_info->plane_size,
6152 					   &plane_info->dcc, address,
6153 					   tmz_surface);
6154 	if (ret)
6155 		return ret;
6156 
6157 	amdgpu_dm_plane_fill_blending_from_plane_state(
6158 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6159 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6160 
6161 	return 0;
6162 }
6163 
6164 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6165 				    struct dc_plane_state *dc_plane_state,
6166 				    struct drm_plane_state *plane_state,
6167 				    struct drm_crtc_state *crtc_state)
6168 {
6169 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6170 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6171 	struct dc_scaling_info scaling_info;
6172 	struct dc_plane_info plane_info;
6173 	int ret;
6174 
6175 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6176 	if (ret)
6177 		return ret;
6178 
6179 	dc_plane_state->src_rect = scaling_info.src_rect;
6180 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6181 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6182 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6183 
6184 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6185 					  afb->tiling_flags,
6186 					  &plane_info,
6187 					  &dc_plane_state->address,
6188 					  afb->tmz_surface);
6189 	if (ret)
6190 		return ret;
6191 
6192 	dc_plane_state->format = plane_info.format;
6193 	dc_plane_state->color_space = plane_info.color_space;
6194 	dc_plane_state->format = plane_info.format;
6195 	dc_plane_state->plane_size = plane_info.plane_size;
6196 	dc_plane_state->rotation = plane_info.rotation;
6197 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6198 	dc_plane_state->stereo_format = plane_info.stereo_format;
6199 	dc_plane_state->tiling_info = plane_info.tiling_info;
6200 	dc_plane_state->visible = plane_info.visible;
6201 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6202 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6203 	dc_plane_state->global_alpha = plane_info.global_alpha;
6204 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6205 	dc_plane_state->dcc = plane_info.dcc;
6206 	dc_plane_state->layer_index = plane_info.layer_index;
6207 	dc_plane_state->flip_int_enabled = true;
6208 
6209 	/*
6210 	 * Always set input transfer function, since plane state is refreshed
6211 	 * every time.
6212 	 */
6213 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6214 						plane_state,
6215 						dc_plane_state);
6216 	if (ret)
6217 		return ret;
6218 
6219 	return 0;
6220 }
6221 
6222 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6223 				      struct rect *dirty_rect, int32_t x,
6224 				      s32 y, s32 width, s32 height,
6225 				      int *i, bool ffu)
6226 {
6227 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6228 
6229 	dirty_rect->x = x;
6230 	dirty_rect->y = y;
6231 	dirty_rect->width = width;
6232 	dirty_rect->height = height;
6233 
6234 	if (ffu)
6235 		drm_dbg(plane->dev,
6236 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6237 			plane->base.id, width, height);
6238 	else
6239 		drm_dbg(plane->dev,
6240 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6241 			plane->base.id, x, y, width, height);
6242 
6243 	(*i)++;
6244 }
6245 
6246 /**
6247  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6248  *
6249  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6250  *         remote fb
6251  * @old_plane_state: Old state of @plane
6252  * @new_plane_state: New state of @plane
6253  * @crtc_state: New state of CRTC connected to the @plane
6254  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6255  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6256  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6257  *             that have changed will be updated. If PSR SU is not enabled,
6258  *             or if damage clips are not available, the entire screen will be updated.
6259  * @dirty_regions_changed: dirty regions changed
6260  *
6261  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6262  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6263  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6264  * amdgpu_dm's.
6265  *
6266  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6267  * plane with regions that require flushing to the eDP remote buffer. In
6268  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6269  * implicitly provide damage clips without any client support via the plane
6270  * bounds.
6271  */
6272 static void fill_dc_dirty_rects(struct drm_plane *plane,
6273 				struct drm_plane_state *old_plane_state,
6274 				struct drm_plane_state *new_plane_state,
6275 				struct drm_crtc_state *crtc_state,
6276 				struct dc_flip_addrs *flip_addrs,
6277 				bool is_psr_su,
6278 				bool *dirty_regions_changed)
6279 {
6280 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6281 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6282 	u32 num_clips;
6283 	struct drm_mode_rect *clips;
6284 	bool bb_changed;
6285 	bool fb_changed;
6286 	u32 i = 0;
6287 	*dirty_regions_changed = false;
6288 
6289 	/*
6290 	 * Cursor plane has it's own dirty rect update interface. See
6291 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6292 	 */
6293 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6294 		return;
6295 
6296 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6297 		goto ffu;
6298 
6299 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6300 	clips = drm_plane_get_damage_clips(new_plane_state);
6301 
6302 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6303 						   is_psr_su)))
6304 		goto ffu;
6305 
6306 	if (!dm_crtc_state->mpo_requested) {
6307 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6308 			goto ffu;
6309 
6310 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6311 			fill_dc_dirty_rect(new_plane_state->plane,
6312 					   &dirty_rects[flip_addrs->dirty_rect_count],
6313 					   clips->x1, clips->y1,
6314 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6315 					   &flip_addrs->dirty_rect_count,
6316 					   false);
6317 		return;
6318 	}
6319 
6320 	/*
6321 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6322 	 * flipped to or damaged.
6323 	 *
6324 	 * If plane is moved or resized, also add old bounding box to dirty
6325 	 * rects.
6326 	 */
6327 	fb_changed = old_plane_state->fb->base.id !=
6328 		     new_plane_state->fb->base.id;
6329 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6330 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6331 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6332 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6333 
6334 	drm_dbg(plane->dev,
6335 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6336 		new_plane_state->plane->base.id,
6337 		bb_changed, fb_changed, num_clips);
6338 
6339 	*dirty_regions_changed = bb_changed;
6340 
6341 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6342 		goto ffu;
6343 
6344 	if (bb_changed) {
6345 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6346 				   new_plane_state->crtc_x,
6347 				   new_plane_state->crtc_y,
6348 				   new_plane_state->crtc_w,
6349 				   new_plane_state->crtc_h, &i, false);
6350 
6351 		/* Add old plane bounding-box if plane is moved or resized */
6352 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6353 				   old_plane_state->crtc_x,
6354 				   old_plane_state->crtc_y,
6355 				   old_plane_state->crtc_w,
6356 				   old_plane_state->crtc_h, &i, false);
6357 	}
6358 
6359 	if (num_clips) {
6360 		for (; i < num_clips; clips++)
6361 			fill_dc_dirty_rect(new_plane_state->plane,
6362 					   &dirty_rects[i], clips->x1,
6363 					   clips->y1, clips->x2 - clips->x1,
6364 					   clips->y2 - clips->y1, &i, false);
6365 	} else if (fb_changed && !bb_changed) {
6366 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6367 				   new_plane_state->crtc_x,
6368 				   new_plane_state->crtc_y,
6369 				   new_plane_state->crtc_w,
6370 				   new_plane_state->crtc_h, &i, false);
6371 	}
6372 
6373 	flip_addrs->dirty_rect_count = i;
6374 	return;
6375 
6376 ffu:
6377 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6378 			   dm_crtc_state->base.mode.crtc_hdisplay,
6379 			   dm_crtc_state->base.mode.crtc_vdisplay,
6380 			   &flip_addrs->dirty_rect_count, true);
6381 }
6382 
6383 static void update_stream_scaling_settings(struct drm_device *dev,
6384 					   const struct drm_display_mode *mode,
6385 					   const struct dm_connector_state *dm_state,
6386 					   struct dc_stream_state *stream)
6387 {
6388 	enum amdgpu_rmx_type rmx_type;
6389 
6390 	struct rect src = { 0 }; /* viewport in composition space*/
6391 	struct rect dst = { 0 }; /* stream addressable area */
6392 
6393 	/* no mode. nothing to be done */
6394 	if (!mode)
6395 		return;
6396 
6397 	/* Full screen scaling by default */
6398 	src.width = mode->hdisplay;
6399 	src.height = mode->vdisplay;
6400 	dst.width = stream->timing.h_addressable;
6401 	dst.height = stream->timing.v_addressable;
6402 
6403 	if (dm_state) {
6404 		rmx_type = dm_state->scaling;
6405 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6406 			if (src.width * dst.height <
6407 					src.height * dst.width) {
6408 				/* height needs less upscaling/more downscaling */
6409 				dst.width = src.width *
6410 						dst.height / src.height;
6411 			} else {
6412 				/* width needs less upscaling/more downscaling */
6413 				dst.height = src.height *
6414 						dst.width / src.width;
6415 			}
6416 		} else if (rmx_type == RMX_CENTER) {
6417 			dst = src;
6418 		}
6419 
6420 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6421 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6422 
6423 		if (dm_state->underscan_enable) {
6424 			dst.x += dm_state->underscan_hborder / 2;
6425 			dst.y += dm_state->underscan_vborder / 2;
6426 			dst.width -= dm_state->underscan_hborder;
6427 			dst.height -= dm_state->underscan_vborder;
6428 		}
6429 	}
6430 
6431 	stream->src = src;
6432 	stream->dst = dst;
6433 
6434 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6435 		    dst.x, dst.y, dst.width, dst.height);
6436 
6437 }
6438 
6439 static enum dc_color_depth
6440 convert_color_depth_from_display_info(const struct drm_connector *connector,
6441 				      bool is_y420, int requested_bpc)
6442 {
6443 	u8 bpc;
6444 
6445 	if (is_y420) {
6446 		bpc = 8;
6447 
6448 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6449 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6450 			bpc = 16;
6451 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6452 			bpc = 12;
6453 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6454 			bpc = 10;
6455 	} else {
6456 		bpc = (uint8_t)connector->display_info.bpc;
6457 		/* Assume 8 bpc by default if no bpc is specified. */
6458 		bpc = bpc ? bpc : 8;
6459 	}
6460 
6461 	if (requested_bpc > 0) {
6462 		/*
6463 		 * Cap display bpc based on the user requested value.
6464 		 *
6465 		 * The value for state->max_bpc may not correctly updated
6466 		 * depending on when the connector gets added to the state
6467 		 * or if this was called outside of atomic check, so it
6468 		 * can't be used directly.
6469 		 */
6470 		bpc = min_t(u8, bpc, requested_bpc);
6471 
6472 		/* Round down to the nearest even number. */
6473 		bpc = bpc - (bpc & 1);
6474 	}
6475 
6476 	switch (bpc) {
6477 	case 0:
6478 		/*
6479 		 * Temporary Work around, DRM doesn't parse color depth for
6480 		 * EDID revision before 1.4
6481 		 * TODO: Fix edid parsing
6482 		 */
6483 		return COLOR_DEPTH_888;
6484 	case 6:
6485 		return COLOR_DEPTH_666;
6486 	case 8:
6487 		return COLOR_DEPTH_888;
6488 	case 10:
6489 		return COLOR_DEPTH_101010;
6490 	case 12:
6491 		return COLOR_DEPTH_121212;
6492 	case 14:
6493 		return COLOR_DEPTH_141414;
6494 	case 16:
6495 		return COLOR_DEPTH_161616;
6496 	default:
6497 		return COLOR_DEPTH_UNDEFINED;
6498 	}
6499 }
6500 
6501 static enum dc_aspect_ratio
6502 get_aspect_ratio(const struct drm_display_mode *mode_in)
6503 {
6504 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6505 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6506 }
6507 
6508 static enum dc_color_space
6509 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6510 		       const struct drm_connector_state *connector_state)
6511 {
6512 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6513 
6514 	switch (connector_state->colorspace) {
6515 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6516 		if (dc_crtc_timing->flags.Y_ONLY)
6517 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6518 		else
6519 			color_space = COLOR_SPACE_YCBCR601;
6520 		break;
6521 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6522 		if (dc_crtc_timing->flags.Y_ONLY)
6523 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6524 		else
6525 			color_space = COLOR_SPACE_YCBCR709;
6526 		break;
6527 	case DRM_MODE_COLORIMETRY_OPRGB:
6528 		color_space = COLOR_SPACE_ADOBERGB;
6529 		break;
6530 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6531 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6532 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6533 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6534 		else
6535 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6536 		break;
6537 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6538 	default:
6539 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6540 			color_space = COLOR_SPACE_SRGB;
6541 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6542 				color_space = COLOR_SPACE_SRGB_LIMITED;
6543 		/*
6544 		 * 27030khz is the separation point between HDTV and SDTV
6545 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6546 		 * respectively
6547 		 */
6548 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6549 			if (dc_crtc_timing->flags.Y_ONLY)
6550 				color_space =
6551 					COLOR_SPACE_YCBCR709_LIMITED;
6552 			else
6553 				color_space = COLOR_SPACE_YCBCR709;
6554 		} else {
6555 			if (dc_crtc_timing->flags.Y_ONLY)
6556 				color_space =
6557 					COLOR_SPACE_YCBCR601_LIMITED;
6558 			else
6559 				color_space = COLOR_SPACE_YCBCR601;
6560 		}
6561 		break;
6562 	}
6563 
6564 	return color_space;
6565 }
6566 
6567 static enum display_content_type
6568 get_output_content_type(const struct drm_connector_state *connector_state)
6569 {
6570 	switch (connector_state->content_type) {
6571 	default:
6572 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6573 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6574 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6575 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6576 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6577 		return DISPLAY_CONTENT_TYPE_PHOTO;
6578 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6579 		return DISPLAY_CONTENT_TYPE_CINEMA;
6580 	case DRM_MODE_CONTENT_TYPE_GAME:
6581 		return DISPLAY_CONTENT_TYPE_GAME;
6582 	}
6583 }
6584 
6585 static bool adjust_colour_depth_from_display_info(
6586 	struct dc_crtc_timing *timing_out,
6587 	const struct drm_display_info *info)
6588 {
6589 	enum dc_color_depth depth = timing_out->display_color_depth;
6590 	int normalized_clk;
6591 
6592 	do {
6593 		normalized_clk = timing_out->pix_clk_100hz / 10;
6594 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6595 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6596 			normalized_clk /= 2;
6597 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6598 		switch (depth) {
6599 		case COLOR_DEPTH_888:
6600 			break;
6601 		case COLOR_DEPTH_101010:
6602 			normalized_clk = (normalized_clk * 30) / 24;
6603 			break;
6604 		case COLOR_DEPTH_121212:
6605 			normalized_clk = (normalized_clk * 36) / 24;
6606 			break;
6607 		case COLOR_DEPTH_161616:
6608 			normalized_clk = (normalized_clk * 48) / 24;
6609 			break;
6610 		default:
6611 			/* The above depths are the only ones valid for HDMI. */
6612 			return false;
6613 		}
6614 		if (normalized_clk <= info->max_tmds_clock) {
6615 			timing_out->display_color_depth = depth;
6616 			return true;
6617 		}
6618 	} while (--depth > COLOR_DEPTH_666);
6619 	return false;
6620 }
6621 
6622 static void fill_stream_properties_from_drm_display_mode(
6623 	struct dc_stream_state *stream,
6624 	const struct drm_display_mode *mode_in,
6625 	const struct drm_connector *connector,
6626 	const struct drm_connector_state *connector_state,
6627 	const struct dc_stream_state *old_stream,
6628 	int requested_bpc)
6629 {
6630 	struct dc_crtc_timing *timing_out = &stream->timing;
6631 	const struct drm_display_info *info = &connector->display_info;
6632 	struct amdgpu_dm_connector *aconnector = NULL;
6633 	struct hdmi_vendor_infoframe hv_frame;
6634 	struct hdmi_avi_infoframe avi_frame;
6635 	ssize_t err;
6636 
6637 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6638 		aconnector = to_amdgpu_dm_connector(connector);
6639 
6640 	memset(&hv_frame, 0, sizeof(hv_frame));
6641 	memset(&avi_frame, 0, sizeof(avi_frame));
6642 
6643 	timing_out->h_border_left = 0;
6644 	timing_out->h_border_right = 0;
6645 	timing_out->v_border_top = 0;
6646 	timing_out->v_border_bottom = 0;
6647 	/* TODO: un-hardcode */
6648 	if (drm_mode_is_420_only(info, mode_in)
6649 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6650 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6651 	else if (drm_mode_is_420_also(info, mode_in)
6652 			&& aconnector
6653 			&& aconnector->force_yuv420_output)
6654 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6655 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR422)
6656 			&& aconnector
6657 			&& aconnector->force_yuv422_output)
6658 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6659 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
6660 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6661 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6662 	else
6663 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6664 
6665 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6666 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6667 		connector,
6668 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6669 		requested_bpc);
6670 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6671 	timing_out->hdmi_vic = 0;
6672 
6673 	if (old_stream) {
6674 		timing_out->vic = old_stream->timing.vic;
6675 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6676 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6677 	} else {
6678 		timing_out->vic = drm_match_cea_mode(mode_in);
6679 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6680 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6681 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6682 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6683 	}
6684 
6685 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6686 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6687 							       (struct drm_connector *)connector,
6688 							       mode_in);
6689 		if (err < 0)
6690 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6691 				      connector->name, err);
6692 		timing_out->vic = avi_frame.video_code;
6693 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6694 								  (struct drm_connector *)connector,
6695 								  mode_in);
6696 		if (err < 0)
6697 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6698 				      connector->name, err);
6699 		timing_out->hdmi_vic = hv_frame.vic;
6700 	}
6701 
6702 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6703 		timing_out->h_addressable = mode_in->hdisplay;
6704 		timing_out->h_total = mode_in->htotal;
6705 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6706 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6707 		timing_out->v_total = mode_in->vtotal;
6708 		timing_out->v_addressable = mode_in->vdisplay;
6709 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6710 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6711 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6712 	} else {
6713 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6714 		timing_out->h_total = mode_in->crtc_htotal;
6715 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6716 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6717 		timing_out->v_total = mode_in->crtc_vtotal;
6718 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6719 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6720 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6721 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6722 	}
6723 
6724 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6725 
6726 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6727 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6728 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6729 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6730 		    drm_mode_is_420_also(info, mode_in) &&
6731 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6732 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6733 			adjust_colour_depth_from_display_info(timing_out, info);
6734 		}
6735 	}
6736 
6737 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6738 	stream->content_type = get_output_content_type(connector_state);
6739 }
6740 
6741 static void fill_audio_info(struct audio_info *audio_info,
6742 			    const struct drm_connector *drm_connector,
6743 			    const struct dc_sink *dc_sink)
6744 {
6745 	int i = 0;
6746 	int cea_revision = 0;
6747 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6748 
6749 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6750 	audio_info->product_id = edid_caps->product_id;
6751 
6752 	cea_revision = drm_connector->display_info.cea_rev;
6753 
6754 	strscpy(audio_info->display_name,
6755 		edid_caps->display_name,
6756 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6757 
6758 	if (cea_revision >= 3) {
6759 		audio_info->mode_count = edid_caps->audio_mode_count;
6760 
6761 		for (i = 0; i < audio_info->mode_count; ++i) {
6762 			audio_info->modes[i].format_code =
6763 					(enum audio_format_code)
6764 					(edid_caps->audio_modes[i].format_code);
6765 			audio_info->modes[i].channel_count =
6766 					edid_caps->audio_modes[i].channel_count;
6767 			audio_info->modes[i].sample_rates.all =
6768 					edid_caps->audio_modes[i].sample_rate;
6769 			audio_info->modes[i].sample_size =
6770 					edid_caps->audio_modes[i].sample_size;
6771 		}
6772 	}
6773 
6774 	audio_info->flags.all = edid_caps->speaker_flags;
6775 
6776 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6777 	if (drm_connector->latency_present[0]) {
6778 		audio_info->video_latency = drm_connector->video_latency[0];
6779 		audio_info->audio_latency = drm_connector->audio_latency[0];
6780 	}
6781 
6782 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6783 
6784 }
6785 
6786 static void
6787 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6788 				      struct drm_display_mode *dst_mode)
6789 {
6790 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6791 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6792 	dst_mode->crtc_clock = src_mode->crtc_clock;
6793 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6794 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6795 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6796 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6797 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6798 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6799 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6800 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6801 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6802 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6803 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6804 }
6805 
6806 static void
6807 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6808 					const struct drm_display_mode *native_mode,
6809 					bool scale_enabled)
6810 {
6811 	if (scale_enabled || (
6812 	    native_mode->clock == drm_mode->clock &&
6813 	    native_mode->htotal == drm_mode->htotal &&
6814 	    native_mode->vtotal == drm_mode->vtotal)) {
6815 		if (native_mode->crtc_clock)
6816 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6817 	} else {
6818 		/* no scaling nor amdgpu inserted, no need to patch */
6819 	}
6820 }
6821 
6822 static struct dc_sink *
6823 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6824 {
6825 	struct dc_sink_init_data sink_init_data = { 0 };
6826 	struct dc_sink *sink = NULL;
6827 
6828 	sink_init_data.link = link;
6829 	sink_init_data.sink_signal = link->connector_signal;
6830 
6831 	sink = dc_sink_create(&sink_init_data);
6832 	if (!sink) {
6833 		drm_err(dev, "Failed to create sink!\n");
6834 		return NULL;
6835 	}
6836 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6837 
6838 	return sink;
6839 }
6840 
6841 static void set_multisync_trigger_params(
6842 		struct dc_stream_state *stream)
6843 {
6844 	struct dc_stream_state *master = NULL;
6845 
6846 	if (stream->triggered_crtc_reset.enabled) {
6847 		master = stream->triggered_crtc_reset.event_source;
6848 		stream->triggered_crtc_reset.event =
6849 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6850 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6851 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6852 	}
6853 }
6854 
6855 static void set_master_stream(struct dc_stream_state *stream_set[],
6856 			      int stream_count)
6857 {
6858 	int j, highest_rfr = 0, master_stream = 0;
6859 
6860 	for (j = 0;  j < stream_count; j++) {
6861 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
6862 			int refresh_rate = 0;
6863 
6864 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
6865 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
6866 			if (refresh_rate > highest_rfr) {
6867 				highest_rfr = refresh_rate;
6868 				master_stream = j;
6869 			}
6870 		}
6871 	}
6872 	for (j = 0;  j < stream_count; j++) {
6873 		if (stream_set[j])
6874 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
6875 	}
6876 }
6877 
6878 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
6879 {
6880 	int i = 0;
6881 	struct dc_stream_state *stream;
6882 
6883 	if (context->stream_count < 2)
6884 		return;
6885 	for (i = 0; i < context->stream_count ; i++) {
6886 		if (!context->streams[i])
6887 			continue;
6888 		/*
6889 		 * TODO: add a function to read AMD VSDB bits and set
6890 		 * crtc_sync_master.multi_sync_enabled flag
6891 		 * For now it's set to false
6892 		 */
6893 	}
6894 
6895 	set_master_stream(context->streams, context->stream_count);
6896 
6897 	for (i = 0; i < context->stream_count ; i++) {
6898 		stream = context->streams[i];
6899 
6900 		if (!stream)
6901 			continue;
6902 
6903 		set_multisync_trigger_params(stream);
6904 	}
6905 }
6906 
6907 /**
6908  * DOC: FreeSync Video
6909  *
6910  * When a userspace application wants to play a video, the content follows a
6911  * standard format definition that usually specifies the FPS for that format.
6912  * The below list illustrates some video format and the expected FPS,
6913  * respectively:
6914  *
6915  * - TV/NTSC (23.976 FPS)
6916  * - Cinema (24 FPS)
6917  * - TV/PAL (25 FPS)
6918  * - TV/NTSC (29.97 FPS)
6919  * - TV/NTSC (30 FPS)
6920  * - Cinema HFR (48 FPS)
6921  * - TV/PAL (50 FPS)
6922  * - Commonly used (60 FPS)
6923  * - Multiples of 24 (48,72,96 FPS)
6924  *
6925  * The list of standards video format is not huge and can be added to the
6926  * connector modeset list beforehand. With that, userspace can leverage
6927  * FreeSync to extends the front porch in order to attain the target refresh
6928  * rate. Such a switch will happen seamlessly, without screen blanking or
6929  * reprogramming of the output in any other way. If the userspace requests a
6930  * modesetting change compatible with FreeSync modes that only differ in the
6931  * refresh rate, DC will skip the full update and avoid blink during the
6932  * transition. For example, the video player can change the modesetting from
6933  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
6934  * causing any display blink. This same concept can be applied to a mode
6935  * setting change.
6936  */
6937 static struct drm_display_mode *
6938 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
6939 		bool use_probed_modes)
6940 {
6941 	struct drm_display_mode *m, *m_pref = NULL;
6942 	u16 current_refresh, highest_refresh;
6943 	struct list_head *list_head = use_probed_modes ?
6944 		&aconnector->base.probed_modes :
6945 		&aconnector->base.modes;
6946 
6947 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
6948 		return NULL;
6949 
6950 	if (aconnector->freesync_vid_base.clock != 0)
6951 		return &aconnector->freesync_vid_base;
6952 
6953 	/* Find the preferred mode */
6954 	list_for_each_entry(m, list_head, head) {
6955 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
6956 			m_pref = m;
6957 			break;
6958 		}
6959 	}
6960 
6961 	if (!m_pref) {
6962 		/* Probably an EDID with no preferred mode. Fallback to first entry */
6963 		m_pref = list_first_entry_or_null(
6964 				&aconnector->base.modes, struct drm_display_mode, head);
6965 		if (!m_pref) {
6966 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
6967 			return NULL;
6968 		}
6969 	}
6970 
6971 	highest_refresh = drm_mode_vrefresh(m_pref);
6972 
6973 	/*
6974 	 * Find the mode with highest refresh rate with same resolution.
6975 	 * For some monitors, preferred mode is not the mode with highest
6976 	 * supported refresh rate.
6977 	 */
6978 	list_for_each_entry(m, list_head, head) {
6979 		current_refresh  = drm_mode_vrefresh(m);
6980 
6981 		if (m->hdisplay == m_pref->hdisplay &&
6982 		    m->vdisplay == m_pref->vdisplay &&
6983 		    highest_refresh < current_refresh) {
6984 			highest_refresh = current_refresh;
6985 			m_pref = m;
6986 		}
6987 	}
6988 
6989 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
6990 	return m_pref;
6991 }
6992 
6993 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
6994 		struct amdgpu_dm_connector *aconnector)
6995 {
6996 	struct drm_display_mode *high_mode;
6997 	int timing_diff;
6998 
6999 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7000 	if (!high_mode || !mode)
7001 		return false;
7002 
7003 	timing_diff = high_mode->vtotal - mode->vtotal;
7004 
7005 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7006 	    high_mode->hdisplay != mode->hdisplay ||
7007 	    high_mode->vdisplay != mode->vdisplay ||
7008 	    high_mode->hsync_start != mode->hsync_start ||
7009 	    high_mode->hsync_end != mode->hsync_end ||
7010 	    high_mode->htotal != mode->htotal ||
7011 	    high_mode->hskew != mode->hskew ||
7012 	    high_mode->vscan != mode->vscan ||
7013 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7014 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7015 		return false;
7016 	else
7017 		return true;
7018 }
7019 
7020 #if defined(CONFIG_DRM_AMD_DC_FP)
7021 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7022 			    struct dc_sink *sink, struct dc_stream_state *stream,
7023 			    struct dsc_dec_dpcd_caps *dsc_caps)
7024 {
7025 	stream->timing.flags.DSC = 0;
7026 	dsc_caps->is_dsc_supported = false;
7027 
7028 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7029 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7030 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7031 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7032 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7033 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7034 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7035 				dsc_caps);
7036 	}
7037 }
7038 
7039 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7040 				    struct dc_sink *sink, struct dc_stream_state *stream,
7041 				    struct dsc_dec_dpcd_caps *dsc_caps,
7042 				    uint32_t max_dsc_target_bpp_limit_override)
7043 {
7044 	const struct dc_link_settings *verified_link_cap = NULL;
7045 	u32 link_bw_in_kbps;
7046 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7047 	struct dc *dc = sink->ctx->dc;
7048 	struct dc_dsc_bw_range bw_range = {0};
7049 	struct dc_dsc_config dsc_cfg = {0};
7050 	struct dc_dsc_config_options dsc_options = {0};
7051 
7052 	dc_dsc_get_default_config_option(dc, &dsc_options);
7053 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7054 
7055 	verified_link_cap = dc_link_get_link_cap(stream->link);
7056 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7057 	edp_min_bpp_x16 = 8 * 16;
7058 	edp_max_bpp_x16 = 8 * 16;
7059 
7060 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7061 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7062 
7063 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7064 		edp_min_bpp_x16 = edp_max_bpp_x16;
7065 
7066 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7067 				dc->debug.dsc_min_slice_height_override,
7068 				edp_min_bpp_x16, edp_max_bpp_x16,
7069 				dsc_caps,
7070 				&stream->timing,
7071 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7072 				&bw_range)) {
7073 
7074 		if (bw_range.max_kbps < link_bw_in_kbps) {
7075 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7076 					dsc_caps,
7077 					&dsc_options,
7078 					0,
7079 					&stream->timing,
7080 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7081 					&dsc_cfg)) {
7082 				stream->timing.dsc_cfg = dsc_cfg;
7083 				stream->timing.flags.DSC = 1;
7084 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7085 			}
7086 			return;
7087 		}
7088 	}
7089 
7090 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7091 				dsc_caps,
7092 				&dsc_options,
7093 				link_bw_in_kbps,
7094 				&stream->timing,
7095 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7096 				&dsc_cfg)) {
7097 		stream->timing.dsc_cfg = dsc_cfg;
7098 		stream->timing.flags.DSC = 1;
7099 	}
7100 }
7101 
7102 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7103 					struct dc_sink *sink, struct dc_stream_state *stream,
7104 					struct dsc_dec_dpcd_caps *dsc_caps)
7105 {
7106 	struct drm_connector *drm_connector = &aconnector->base;
7107 	u32 link_bandwidth_kbps;
7108 	struct dc *dc = sink->ctx->dc;
7109 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7110 	u32 dsc_max_supported_bw_in_kbps;
7111 	u32 max_dsc_target_bpp_limit_override =
7112 		drm_connector->display_info.max_dsc_bpp;
7113 	struct dc_dsc_config_options dsc_options = {0};
7114 
7115 	dc_dsc_get_default_config_option(dc, &dsc_options);
7116 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7117 
7118 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7119 							dc_link_get_link_cap(aconnector->dc_link));
7120 
7121 	/* Set DSC policy according to dsc_clock_en */
7122 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7123 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7124 
7125 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7126 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7127 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7128 
7129 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7130 
7131 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7132 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7133 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7134 						dsc_caps,
7135 						&dsc_options,
7136 						link_bandwidth_kbps,
7137 						&stream->timing,
7138 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7139 						&stream->timing.dsc_cfg)) {
7140 				stream->timing.flags.DSC = 1;
7141 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7142 							__func__, drm_connector->name);
7143 			}
7144 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7145 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7146 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7147 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7148 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7149 
7150 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7151 					max_supported_bw_in_kbps > 0 &&
7152 					dsc_max_supported_bw_in_kbps > 0)
7153 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7154 						dsc_caps,
7155 						&dsc_options,
7156 						dsc_max_supported_bw_in_kbps,
7157 						&stream->timing,
7158 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7159 						&stream->timing.dsc_cfg)) {
7160 					stream->timing.flags.DSC = 1;
7161 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7162 									 __func__, drm_connector->name);
7163 				}
7164 		}
7165 	}
7166 
7167 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7168 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7169 		stream->timing.flags.DSC = 1;
7170 
7171 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7172 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7173 
7174 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7175 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7176 
7177 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7178 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7179 }
7180 #endif
7181 
7182 static struct dc_stream_state *
7183 create_stream_for_sink(struct drm_connector *connector,
7184 		       const struct drm_display_mode *drm_mode,
7185 		       const struct dm_connector_state *dm_state,
7186 		       const struct dc_stream_state *old_stream,
7187 		       int requested_bpc)
7188 {
7189 	struct drm_device *dev = connector->dev;
7190 	struct amdgpu_dm_connector *aconnector = NULL;
7191 	struct drm_display_mode *preferred_mode = NULL;
7192 	const struct drm_connector_state *con_state = &dm_state->base;
7193 	struct dc_stream_state *stream = NULL;
7194 	struct drm_display_mode mode;
7195 	struct drm_display_mode saved_mode;
7196 	struct drm_display_mode *freesync_mode = NULL;
7197 	bool native_mode_found = false;
7198 	bool recalculate_timing = false;
7199 	bool scale = dm_state->scaling != RMX_OFF;
7200 	int mode_refresh;
7201 	int preferred_refresh = 0;
7202 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7203 #if defined(CONFIG_DRM_AMD_DC_FP)
7204 	struct dsc_dec_dpcd_caps dsc_caps;
7205 #endif
7206 	struct dc_link *link = NULL;
7207 	struct dc_sink *sink = NULL;
7208 
7209 	drm_mode_init(&mode, drm_mode);
7210 	memset(&saved_mode, 0, sizeof(saved_mode));
7211 
7212 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7213 		aconnector = NULL;
7214 		aconnector = to_amdgpu_dm_connector(connector);
7215 		link = aconnector->dc_link;
7216 	} else {
7217 		struct drm_writeback_connector *wbcon = NULL;
7218 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7219 
7220 		wbcon = drm_connector_to_writeback(connector);
7221 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7222 		link = dm_wbcon->link;
7223 	}
7224 
7225 	if (!aconnector || !aconnector->dc_sink) {
7226 		sink = create_fake_sink(dev, link);
7227 		if (!sink)
7228 			return stream;
7229 
7230 	} else {
7231 		sink = aconnector->dc_sink;
7232 		dc_sink_retain(sink);
7233 	}
7234 
7235 	stream = dc_create_stream_for_sink(sink);
7236 
7237 	if (stream == NULL) {
7238 		drm_err(dev, "Failed to create stream for sink!\n");
7239 		goto finish;
7240 	}
7241 
7242 	/* We leave this NULL for writeback connectors */
7243 	stream->dm_stream_context = aconnector;
7244 
7245 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7246 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7247 
7248 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7249 		/* Search for preferred mode */
7250 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7251 			native_mode_found = true;
7252 			break;
7253 		}
7254 	}
7255 	if (!native_mode_found)
7256 		preferred_mode = list_first_entry_or_null(
7257 				&connector->modes,
7258 				struct drm_display_mode,
7259 				head);
7260 
7261 	mode_refresh = drm_mode_vrefresh(&mode);
7262 
7263 	if (preferred_mode == NULL) {
7264 		/*
7265 		 * This may not be an error, the use case is when we have no
7266 		 * usermode calls to reset and set mode upon hotplug. In this
7267 		 * case, we call set mode ourselves to restore the previous mode
7268 		 * and the modelist may not be filled in time.
7269 		 */
7270 		drm_dbg_driver(dev, "No preferred mode found\n");
7271 	} else if (aconnector) {
7272 		recalculate_timing = amdgpu_freesync_vid_mode &&
7273 				 is_freesync_video_mode(&mode, aconnector);
7274 		if (recalculate_timing) {
7275 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7276 			drm_mode_copy(&saved_mode, &mode);
7277 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7278 			drm_mode_copy(&mode, freesync_mode);
7279 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7280 		} else {
7281 			decide_crtc_timing_for_drm_display_mode(
7282 					&mode, preferred_mode, scale);
7283 
7284 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7285 		}
7286 	}
7287 
7288 	if (recalculate_timing)
7289 		drm_mode_set_crtcinfo(&saved_mode, 0);
7290 
7291 	/*
7292 	 * If scaling is enabled and refresh rate didn't change
7293 	 * we copy the vic and polarities of the old timings
7294 	 */
7295 	if (!scale || mode_refresh != preferred_refresh)
7296 		fill_stream_properties_from_drm_display_mode(
7297 			stream, &mode, connector, con_state, NULL,
7298 			requested_bpc);
7299 	else
7300 		fill_stream_properties_from_drm_display_mode(
7301 			stream, &mode, connector, con_state, old_stream,
7302 			requested_bpc);
7303 
7304 	/* The rest isn't needed for writeback connectors */
7305 	if (!aconnector)
7306 		goto finish;
7307 
7308 	if (aconnector->timing_changed) {
7309 		drm_dbg(aconnector->base.dev,
7310 			"overriding timing for automated test, bpc %d, changing to %d\n",
7311 			stream->timing.display_color_depth,
7312 			aconnector->timing_requested->display_color_depth);
7313 		stream->timing = *aconnector->timing_requested;
7314 	}
7315 
7316 #if defined(CONFIG_DRM_AMD_DC_FP)
7317 	/* SST DSC determination policy */
7318 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7319 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7320 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7321 #endif
7322 
7323 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7324 
7325 	fill_audio_info(
7326 		&stream->audio_info,
7327 		connector,
7328 		sink);
7329 
7330 	update_stream_signal(stream, sink);
7331 
7332 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7333 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7334 
7335 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7336 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7337 	    stream->signal == SIGNAL_TYPE_EDP) {
7338 		const struct dc_edid_caps *edid_caps;
7339 		unsigned int disable_colorimetry = 0;
7340 
7341 		if (aconnector->dc_sink) {
7342 			edid_caps = &aconnector->dc_sink->edid_caps;
7343 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7344 		}
7345 
7346 		//
7347 		// should decide stream support vsc sdp colorimetry capability
7348 		// before building vsc info packet
7349 		//
7350 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7351 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7352 						      !disable_colorimetry;
7353 
7354 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7355 			tf = TRANSFER_FUNC_GAMMA_22;
7356 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7357 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7358 
7359 	}
7360 finish:
7361 	dc_sink_release(sink);
7362 
7363 	return stream;
7364 }
7365 
7366 /**
7367  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7368  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7369  * @force: if true, force polling even when DAC load detection was used
7370  *
7371  * Used for connectors that don't support HPD (hotplug detection) to
7372  * periodically check whether the connector is connected to a display.
7373  *
7374  * When connection was determined via DAC load detection, we avoid
7375  * re-running it on normal polls to prevent visible glitches, unless
7376  * @force is set.
7377  *
7378  * Return: The probed connector status (connected/disconnected/unknown).
7379  */
7380 static enum drm_connector_status
7381 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7382 {
7383 	struct drm_connector *connector = &aconnector->base;
7384 	struct drm_device *dev = connector->dev;
7385 	struct amdgpu_device *adev = drm_to_adev(dev);
7386 	struct dc_link *link = aconnector->dc_link;
7387 	enum dc_connection_type conn_type = dc_connection_none;
7388 	enum drm_connector_status status = connector_status_disconnected;
7389 
7390 	/* When we determined the connection using DAC load detection,
7391 	 * do NOT poll the connector do detect disconnect because
7392 	 * that would run DAC load detection again which can cause
7393 	 * visible visual glitches.
7394 	 *
7395 	 * Only allow to poll such a connector again when forcing.
7396 	 */
7397 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7398 		return connector->status;
7399 
7400 	mutex_lock(&aconnector->hpd_lock);
7401 
7402 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7403 	    conn_type != dc_connection_none) {
7404 		mutex_lock(&adev->dm.dc_lock);
7405 
7406 		/* Only call full link detection when a sink isn't created yet,
7407 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7408 		 */
7409 		if (link->local_sink ||
7410 			dc_link_detect(link, DETECT_REASON_HPD))
7411 			status = connector_status_connected;
7412 
7413 		mutex_unlock(&adev->dm.dc_lock);
7414 	}
7415 
7416 	if (connector->status != status) {
7417 		if (status == connector_status_disconnected) {
7418 			if (link->local_sink)
7419 				dc_sink_release(link->local_sink);
7420 
7421 			link->local_sink = NULL;
7422 			link->dpcd_sink_count = 0;
7423 			link->type = dc_connection_none;
7424 		}
7425 
7426 		amdgpu_dm_update_connector_after_detect(aconnector);
7427 	}
7428 
7429 	mutex_unlock(&aconnector->hpd_lock);
7430 	return status;
7431 }
7432 
7433 /**
7434  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7435  *
7436  * A connector is considered connected when it has a sink that is not NULL.
7437  * For connectors that support HPD (hotplug detection), the connection is
7438  * handled in the HPD interrupt.
7439  * For connectors that may not support HPD, such as analog connectors,
7440  * DRM will call this function repeatedly to poll them.
7441  *
7442  * Notes:
7443  * 1. This interface is NOT called in context of HPD irq.
7444  * 2. This interface *is called* in context of user-mode ioctl. Which
7445  *    makes it a bad place for *any* MST-related activity.
7446  *
7447  * @connector: The DRM connector we are checking. We convert it to
7448  *             amdgpu_dm_connector so we can read the DC link and state.
7449  * @force:     If true, do a full detect again. This is used even when
7450  *             a lighter check would normally be used to avoid flicker.
7451  *
7452  * Return: The connector status (connected, disconnected, or unknown).
7453  *
7454  */
7455 static enum drm_connector_status
7456 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7457 {
7458 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7459 
7460 	update_subconnector_property(aconnector);
7461 
7462 	if (aconnector->base.force == DRM_FORCE_ON ||
7463 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7464 		return connector_status_connected;
7465 	else if (aconnector->base.force == DRM_FORCE_OFF)
7466 		return connector_status_disconnected;
7467 
7468 	/* Poll analog connectors and only when either
7469 	 * disconnected or connected to an analog display.
7470 	 */
7471 	if (drm_kms_helper_is_poll_worker() &&
7472 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7473 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7474 		return amdgpu_dm_connector_poll(aconnector, force);
7475 
7476 	return (aconnector->dc_sink ? connector_status_connected :
7477 			connector_status_disconnected);
7478 }
7479 
7480 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7481 					    struct drm_connector_state *connector_state,
7482 					    struct drm_property *property,
7483 					    uint64_t val)
7484 {
7485 	struct drm_device *dev = connector->dev;
7486 	struct amdgpu_device *adev = drm_to_adev(dev);
7487 	struct dm_connector_state *dm_old_state =
7488 		to_dm_connector_state(connector->state);
7489 	struct dm_connector_state *dm_new_state =
7490 		to_dm_connector_state(connector_state);
7491 
7492 	int ret = -EINVAL;
7493 
7494 	if (property == dev->mode_config.scaling_mode_property) {
7495 		enum amdgpu_rmx_type rmx_type;
7496 
7497 		switch (val) {
7498 		case DRM_MODE_SCALE_CENTER:
7499 			rmx_type = RMX_CENTER;
7500 			break;
7501 		case DRM_MODE_SCALE_ASPECT:
7502 			rmx_type = RMX_ASPECT;
7503 			break;
7504 		case DRM_MODE_SCALE_FULLSCREEN:
7505 			rmx_type = RMX_FULL;
7506 			break;
7507 		case DRM_MODE_SCALE_NONE:
7508 		default:
7509 			rmx_type = RMX_OFF;
7510 			break;
7511 		}
7512 
7513 		if (dm_old_state->scaling == rmx_type)
7514 			return 0;
7515 
7516 		dm_new_state->scaling = rmx_type;
7517 		ret = 0;
7518 	} else if (property == adev->mode_info.underscan_hborder_property) {
7519 		dm_new_state->underscan_hborder = val;
7520 		ret = 0;
7521 	} else if (property == adev->mode_info.underscan_vborder_property) {
7522 		dm_new_state->underscan_vborder = val;
7523 		ret = 0;
7524 	} else if (property == adev->mode_info.underscan_property) {
7525 		dm_new_state->underscan_enable = val;
7526 		ret = 0;
7527 	} else if (property == adev->mode_info.abm_level_property) {
7528 		switch (val) {
7529 		case ABM_SYSFS_CONTROL:
7530 			dm_new_state->abm_sysfs_forbidden = false;
7531 			break;
7532 		case ABM_LEVEL_OFF:
7533 			dm_new_state->abm_sysfs_forbidden = true;
7534 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7535 			break;
7536 		default:
7537 			dm_new_state->abm_sysfs_forbidden = true;
7538 			dm_new_state->abm_level = val;
7539 		}
7540 		ret = 0;
7541 	}
7542 
7543 	return ret;
7544 }
7545 
7546 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7547 					    const struct drm_connector_state *state,
7548 					    struct drm_property *property,
7549 					    uint64_t *val)
7550 {
7551 	struct drm_device *dev = connector->dev;
7552 	struct amdgpu_device *adev = drm_to_adev(dev);
7553 	struct dm_connector_state *dm_state =
7554 		to_dm_connector_state(state);
7555 	int ret = -EINVAL;
7556 
7557 	if (property == dev->mode_config.scaling_mode_property) {
7558 		switch (dm_state->scaling) {
7559 		case RMX_CENTER:
7560 			*val = DRM_MODE_SCALE_CENTER;
7561 			break;
7562 		case RMX_ASPECT:
7563 			*val = DRM_MODE_SCALE_ASPECT;
7564 			break;
7565 		case RMX_FULL:
7566 			*val = DRM_MODE_SCALE_FULLSCREEN;
7567 			break;
7568 		case RMX_OFF:
7569 		default:
7570 			*val = DRM_MODE_SCALE_NONE;
7571 			break;
7572 		}
7573 		ret = 0;
7574 	} else if (property == adev->mode_info.underscan_hborder_property) {
7575 		*val = dm_state->underscan_hborder;
7576 		ret = 0;
7577 	} else if (property == adev->mode_info.underscan_vborder_property) {
7578 		*val = dm_state->underscan_vborder;
7579 		ret = 0;
7580 	} else if (property == adev->mode_info.underscan_property) {
7581 		*val = dm_state->underscan_enable;
7582 		ret = 0;
7583 	} else if (property == adev->mode_info.abm_level_property) {
7584 		if (!dm_state->abm_sysfs_forbidden)
7585 			*val = ABM_SYSFS_CONTROL;
7586 		else
7587 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7588 				dm_state->abm_level : 0;
7589 		ret = 0;
7590 	}
7591 
7592 	return ret;
7593 }
7594 
7595 /**
7596  * DOC: panel power savings
7597  *
7598  * The display manager allows you to set your desired **panel power savings**
7599  * level (between 0-4, with 0 representing off), e.g. using the following::
7600  *
7601  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7602  *
7603  * Modifying this value can have implications on color accuracy, so tread
7604  * carefully.
7605  */
7606 
7607 static ssize_t panel_power_savings_show(struct device *device,
7608 					struct device_attribute *attr,
7609 					char *buf)
7610 {
7611 	struct drm_connector *connector = dev_get_drvdata(device);
7612 	struct drm_device *dev = connector->dev;
7613 	u8 val;
7614 
7615 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7616 	val = to_dm_connector_state(connector->state)->abm_level ==
7617 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7618 		to_dm_connector_state(connector->state)->abm_level;
7619 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7620 
7621 	return sysfs_emit(buf, "%u\n", val);
7622 }
7623 
7624 static ssize_t panel_power_savings_store(struct device *device,
7625 					 struct device_attribute *attr,
7626 					 const char *buf, size_t count)
7627 {
7628 	struct drm_connector *connector = dev_get_drvdata(device);
7629 	struct drm_device *dev = connector->dev;
7630 	long val;
7631 	int ret;
7632 
7633 	ret = kstrtol(buf, 0, &val);
7634 
7635 	if (ret)
7636 		return ret;
7637 
7638 	if (val < 0 || val > 4)
7639 		return -EINVAL;
7640 
7641 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7642 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7643 		ret = -EBUSY;
7644 	else
7645 		to_dm_connector_state(connector->state)->abm_level = val ?:
7646 			ABM_LEVEL_IMMEDIATE_DISABLE;
7647 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7648 
7649 	if (ret)
7650 		return ret;
7651 
7652 	drm_kms_helper_hotplug_event(dev);
7653 
7654 	return count;
7655 }
7656 
7657 static DEVICE_ATTR_RW(panel_power_savings);
7658 
7659 static struct attribute *amdgpu_attrs[] = {
7660 	&dev_attr_panel_power_savings.attr,
7661 	NULL
7662 };
7663 
7664 static const struct attribute_group amdgpu_group = {
7665 	.name = "amdgpu",
7666 	.attrs = amdgpu_attrs
7667 };
7668 
7669 static bool
7670 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7671 {
7672 	if (amdgpu_dm_abm_level >= 0)
7673 		return false;
7674 
7675 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7676 		return false;
7677 
7678 	/* check for OLED panels */
7679 	if (amdgpu_dm_connector->bl_idx >= 0) {
7680 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7681 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7682 		struct amdgpu_dm_backlight_caps *caps;
7683 
7684 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7685 		if (caps->aux_support)
7686 			return false;
7687 	}
7688 
7689 	return true;
7690 }
7691 
7692 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7693 {
7694 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7695 
7696 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7697 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7698 
7699 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7700 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7701 }
7702 
7703 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7704 {
7705 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7706 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7707 	struct amdgpu_display_manager *dm = &adev->dm;
7708 
7709 	/*
7710 	 * Call only if mst_mgr was initialized before since it's not done
7711 	 * for all connector types.
7712 	 */
7713 	if (aconnector->mst_mgr.dev)
7714 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7715 
7716 	/* Cancel and flush any pending HDMI HPD debounce work */
7717 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7718 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7719 		if (aconnector->hdmi_prev_sink) {
7720 			dc_sink_release(aconnector->hdmi_prev_sink);
7721 			aconnector->hdmi_prev_sink = NULL;
7722 		}
7723 	}
7724 
7725 	if (aconnector->bl_idx != -1) {
7726 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7727 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7728 	}
7729 
7730 	if (aconnector->dc_em_sink)
7731 		dc_sink_release(aconnector->dc_em_sink);
7732 	aconnector->dc_em_sink = NULL;
7733 	if (aconnector->dc_sink)
7734 		dc_sink_release(aconnector->dc_sink);
7735 	aconnector->dc_sink = NULL;
7736 
7737 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7738 	drm_connector_unregister(connector);
7739 	drm_connector_cleanup(connector);
7740 	kfree(aconnector->dm_dp_aux.aux.name);
7741 
7742 	kfree(connector);
7743 }
7744 
7745 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7746 {
7747 	struct dm_connector_state *state =
7748 		to_dm_connector_state(connector->state);
7749 
7750 	if (connector->state)
7751 		__drm_atomic_helper_connector_destroy_state(connector->state);
7752 
7753 	kfree(state);
7754 
7755 	state = kzalloc_obj(*state);
7756 
7757 	if (state) {
7758 		state->scaling = RMX_OFF;
7759 		state->underscan_enable = false;
7760 		state->underscan_hborder = 0;
7761 		state->underscan_vborder = 0;
7762 		state->base.max_requested_bpc = 8;
7763 		state->vcpi_slots = 0;
7764 		state->pbn = 0;
7765 
7766 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
7767 			if (amdgpu_dm_abm_level <= 0)
7768 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7769 			else
7770 				state->abm_level = amdgpu_dm_abm_level;
7771 		}
7772 
7773 		__drm_atomic_helper_connector_reset(connector, &state->base);
7774 	}
7775 }
7776 
7777 struct drm_connector_state *
7778 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
7779 {
7780 	struct dm_connector_state *state =
7781 		to_dm_connector_state(connector->state);
7782 
7783 	struct dm_connector_state *new_state =
7784 			kmemdup(state, sizeof(*state), GFP_KERNEL);
7785 
7786 	if (!new_state)
7787 		return NULL;
7788 
7789 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
7790 
7791 	new_state->freesync_capable = state->freesync_capable;
7792 	new_state->abm_level = state->abm_level;
7793 	new_state->scaling = state->scaling;
7794 	new_state->underscan_enable = state->underscan_enable;
7795 	new_state->underscan_hborder = state->underscan_hborder;
7796 	new_state->underscan_vborder = state->underscan_vborder;
7797 	new_state->vcpi_slots = state->vcpi_slots;
7798 	new_state->pbn = state->pbn;
7799 	return &new_state->base;
7800 }
7801 
7802 static int
7803 amdgpu_dm_connector_late_register(struct drm_connector *connector)
7804 {
7805 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7806 		to_amdgpu_dm_connector(connector);
7807 	int r;
7808 
7809 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
7810 		r = sysfs_create_group(&connector->kdev->kobj,
7811 				       &amdgpu_group);
7812 		if (r)
7813 			return r;
7814 	}
7815 
7816 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
7817 
7818 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
7819 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
7820 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
7821 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
7822 		if (r)
7823 			return r;
7824 	}
7825 
7826 #if defined(CONFIG_DEBUG_FS)
7827 	connector_debugfs_init(amdgpu_dm_connector);
7828 #endif
7829 
7830 	return 0;
7831 }
7832 
7833 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
7834 {
7835 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7836 	struct dc_link *dc_link = aconnector->dc_link;
7837 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
7838 	const struct drm_edid *drm_edid;
7839 	struct i2c_adapter *ddc;
7840 	struct drm_device *dev = connector->dev;
7841 
7842 	if (dc_link && dc_link->aux_mode)
7843 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7844 	else
7845 		ddc = &aconnector->i2c->base;
7846 
7847 	drm_edid = drm_edid_read_ddc(connector, ddc);
7848 	drm_edid_connector_update(connector, drm_edid);
7849 	if (!drm_edid) {
7850 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
7851 		return;
7852 	}
7853 
7854 	aconnector->drm_edid = drm_edid;
7855 	/* Update emulated (virtual) sink's EDID */
7856 	if (dc_em_sink && dc_link) {
7857 		// FIXME: Get rid of drm_edid_raw()
7858 		const struct edid *edid = drm_edid_raw(drm_edid);
7859 
7860 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
7861 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
7862 			(edid->extensions + 1) * EDID_LENGTH);
7863 		dm_helpers_parse_edid_caps(
7864 			dc_link,
7865 			&dc_em_sink->dc_edid,
7866 			&dc_em_sink->edid_caps);
7867 	}
7868 }
7869 
7870 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
7871 	.reset = amdgpu_dm_connector_funcs_reset,
7872 	.detect = amdgpu_dm_connector_detect,
7873 	.fill_modes = drm_helper_probe_single_connector_modes,
7874 	.destroy = amdgpu_dm_connector_destroy,
7875 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
7876 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
7877 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
7878 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
7879 	.late_register = amdgpu_dm_connector_late_register,
7880 	.early_unregister = amdgpu_dm_connector_unregister,
7881 	.force = amdgpu_dm_connector_funcs_force
7882 };
7883 
7884 static int get_modes(struct drm_connector *connector)
7885 {
7886 	return amdgpu_dm_connector_get_modes(connector);
7887 }
7888 
7889 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
7890 {
7891 	struct drm_connector *connector = &aconnector->base;
7892 	struct dc_link *dc_link = aconnector->dc_link;
7893 	struct dc_sink_init_data init_params = {
7894 			.link = aconnector->dc_link,
7895 			.sink_signal = SIGNAL_TYPE_VIRTUAL
7896 	};
7897 	const struct drm_edid *drm_edid;
7898 	const struct edid *edid;
7899 	struct i2c_adapter *ddc;
7900 
7901 	if (dc_link && dc_link->aux_mode)
7902 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7903 	else
7904 		ddc = &aconnector->i2c->base;
7905 
7906 	drm_edid = drm_edid_read_ddc(connector, ddc);
7907 	drm_edid_connector_update(connector, drm_edid);
7908 	if (!drm_edid) {
7909 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
7910 		return;
7911 	}
7912 
7913 	if (connector->display_info.is_hdmi)
7914 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
7915 
7916 	aconnector->drm_edid = drm_edid;
7917 
7918 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
7919 	aconnector->dc_em_sink = dc_link_add_remote_sink(
7920 		aconnector->dc_link,
7921 		(uint8_t *)edid,
7922 		(edid->extensions + 1) * EDID_LENGTH,
7923 		&init_params);
7924 
7925 	if (aconnector->base.force == DRM_FORCE_ON) {
7926 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
7927 		aconnector->dc_link->local_sink :
7928 		aconnector->dc_em_sink;
7929 		if (aconnector->dc_sink)
7930 			dc_sink_retain(aconnector->dc_sink);
7931 	}
7932 }
7933 
7934 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
7935 {
7936 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
7937 
7938 	/*
7939 	 * In case of headless boot with force on for DP managed connector
7940 	 * Those settings have to be != 0 to get initial modeset
7941 	 */
7942 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7943 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
7944 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
7945 	}
7946 
7947 	create_eml_sink(aconnector);
7948 }
7949 
7950 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
7951 						struct dc_stream_state *stream)
7952 {
7953 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
7954 	struct dc_plane_state *dc_plane_state = NULL;
7955 	struct dc_state *dc_state = NULL;
7956 
7957 	if (!stream)
7958 		goto cleanup;
7959 
7960 	dc_plane_state = dc_create_plane_state(dc);
7961 	if (!dc_plane_state)
7962 		goto cleanup;
7963 
7964 	dc_state = dc_state_create(dc, NULL);
7965 	if (!dc_state)
7966 		goto cleanup;
7967 
7968 	/* populate stream to plane */
7969 	dc_plane_state->src_rect.height  = stream->src.height;
7970 	dc_plane_state->src_rect.width   = stream->src.width;
7971 	dc_plane_state->dst_rect.height  = stream->src.height;
7972 	dc_plane_state->dst_rect.width   = stream->src.width;
7973 	dc_plane_state->clip_rect.height = stream->src.height;
7974 	dc_plane_state->clip_rect.width  = stream->src.width;
7975 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
7976 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
7977 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
7978 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
7979 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
7980 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
7981 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
7982 	dc_plane_state->rotation = ROTATION_ANGLE_0;
7983 	dc_plane_state->is_tiling_rotated = false;
7984 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
7985 
7986 	dc_result = dc_validate_stream(dc, stream);
7987 	if (dc_result == DC_OK)
7988 		dc_result = dc_validate_plane(dc, dc_plane_state);
7989 
7990 	if (dc_result == DC_OK)
7991 		dc_result = dc_state_add_stream(dc, dc_state, stream);
7992 
7993 	if (dc_result == DC_OK && !dc_state_add_plane(
7994 						dc,
7995 						stream,
7996 						dc_plane_state,
7997 						dc_state))
7998 		dc_result = DC_FAIL_ATTACH_SURFACES;
7999 
8000 	if (dc_result == DC_OK)
8001 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8002 
8003 cleanup:
8004 	if (dc_state)
8005 		dc_state_release(dc_state);
8006 
8007 	if (dc_plane_state)
8008 		dc_plane_state_release(dc_plane_state);
8009 
8010 	return dc_result;
8011 }
8012 
8013 struct dc_stream_state *
8014 create_validate_stream_for_sink(struct drm_connector *connector,
8015 				const struct drm_display_mode *drm_mode,
8016 				const struct dm_connector_state *dm_state,
8017 				const struct dc_stream_state *old_stream)
8018 {
8019 	struct amdgpu_dm_connector *aconnector = NULL;
8020 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8021 	struct dc_stream_state *stream;
8022 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8023 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8024 	enum dc_status dc_result = DC_OK;
8025 	uint8_t bpc_limit = 6;
8026 
8027 	if (!dm_state)
8028 		return NULL;
8029 
8030 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8031 		aconnector = to_amdgpu_dm_connector(connector);
8032 
8033 	if (aconnector &&
8034 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8035 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8036 		bpc_limit = 8;
8037 
8038 	do {
8039 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8040 		stream = create_stream_for_sink(connector, drm_mode,
8041 						dm_state, old_stream,
8042 						requested_bpc);
8043 		if (stream == NULL) {
8044 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8045 			break;
8046 		}
8047 
8048 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8049 
8050 		if (!aconnector) /* writeback connector */
8051 			return stream;
8052 
8053 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8054 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8055 
8056 		if (dc_result == DC_OK)
8057 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8058 
8059 		if (dc_result != DC_OK) {
8060 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8061 				      drm_mode->hdisplay,
8062 				      drm_mode->vdisplay,
8063 				      drm_mode->clock,
8064 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8065 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8066 				      dc_status_to_str(dc_result));
8067 
8068 			dc_stream_release(stream);
8069 			stream = NULL;
8070 			requested_bpc -= 2; /* lower bpc to retry validation */
8071 		}
8072 
8073 	} while (stream == NULL && requested_bpc >= bpc_limit);
8074 
8075 	switch (dc_result) {
8076 	/*
8077 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8078 	 * we try to fallback and configure in order:
8079 	 * YUV422 (8bpc, 6bpc)
8080 	 * YUV420 (8bpc, 6bpc)
8081 	 */
8082 	case DC_FAIL_ENC_VALIDATE:
8083 	case DC_EXCEED_DONGLE_CAP:
8084 	case DC_NO_DP_LINK_BANDWIDTH:
8085 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8086 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8087 			break;
8088 		/* first failure; try YUV422 */
8089 		if (!aconnector->force_yuv422_output) {
8090 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8091 				    __func__, __LINE__, dc_result);
8092 			aconnector->force_yuv422_output = true;
8093 		/* recursively entered and YUV422 failed, try YUV420 */
8094 		} else if (!aconnector->force_yuv420_output) {
8095 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8096 				    __func__, __LINE__, dc_result);
8097 			aconnector->force_yuv420_output = true;
8098 		}
8099 		stream = create_validate_stream_for_sink(connector, drm_mode,
8100 							 dm_state, old_stream);
8101 		aconnector->force_yuv422_output = false;
8102 		aconnector->force_yuv420_output = false;
8103 		break;
8104 	case DC_OK:
8105 		break;
8106 	default:
8107 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8108 			    __func__, __LINE__, dc_result);
8109 		break;
8110 	}
8111 
8112 	return stream;
8113 }
8114 
8115 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8116 				   const struct drm_display_mode *mode)
8117 {
8118 	int result = MODE_ERROR;
8119 	struct dc_sink *dc_sink;
8120 	struct drm_display_mode *test_mode;
8121 	/* TODO: Unhardcode stream count */
8122 	struct dc_stream_state *stream;
8123 	/* we always have an amdgpu_dm_connector here since we got
8124 	 * here via the amdgpu_dm_connector_helper_funcs
8125 	 */
8126 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8127 
8128 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8129 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8130 		return result;
8131 
8132 	/*
8133 	 * Only run this the first time mode_valid is called to initilialize
8134 	 * EDID mgmt
8135 	 */
8136 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8137 		!aconnector->dc_em_sink)
8138 		handle_edid_mgmt(aconnector);
8139 
8140 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8141 
8142 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8143 				aconnector->base.force != DRM_FORCE_ON) {
8144 		drm_err(connector->dev, "dc_sink is NULL!\n");
8145 		goto fail;
8146 	}
8147 
8148 	test_mode = drm_mode_duplicate(connector->dev, mode);
8149 	if (!test_mode)
8150 		goto fail;
8151 
8152 	drm_mode_set_crtcinfo(test_mode, 0);
8153 
8154 	stream = create_validate_stream_for_sink(connector, test_mode,
8155 						 to_dm_connector_state(connector->state),
8156 						 NULL);
8157 	drm_mode_destroy(connector->dev, test_mode);
8158 	if (stream) {
8159 		dc_stream_release(stream);
8160 		result = MODE_OK;
8161 	}
8162 
8163 fail:
8164 	/* TODO: error handling*/
8165 	return result;
8166 }
8167 
8168 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8169 				struct dc_info_packet *out)
8170 {
8171 	struct hdmi_drm_infoframe frame;
8172 	unsigned char buf[30]; /* 26 + 4 */
8173 	ssize_t len;
8174 	int ret, i;
8175 
8176 	memset(out, 0, sizeof(*out));
8177 
8178 	if (!state->hdr_output_metadata)
8179 		return 0;
8180 
8181 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8182 	if (ret)
8183 		return ret;
8184 
8185 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8186 	if (len < 0)
8187 		return (int)len;
8188 
8189 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8190 	if (len != 30)
8191 		return -EINVAL;
8192 
8193 	/* Prepare the infopacket for DC. */
8194 	switch (state->connector->connector_type) {
8195 	case DRM_MODE_CONNECTOR_HDMIA:
8196 		out->hb0 = 0x87; /* type */
8197 		out->hb1 = 0x01; /* version */
8198 		out->hb2 = 0x1A; /* length */
8199 		out->sb[0] = buf[3]; /* checksum */
8200 		i = 1;
8201 		break;
8202 
8203 	case DRM_MODE_CONNECTOR_DisplayPort:
8204 	case DRM_MODE_CONNECTOR_eDP:
8205 		out->hb0 = 0x00; /* sdp id, zero */
8206 		out->hb1 = 0x87; /* type */
8207 		out->hb2 = 0x1D; /* payload len - 1 */
8208 		out->hb3 = (0x13 << 2); /* sdp version */
8209 		out->sb[0] = 0x01; /* version */
8210 		out->sb[1] = 0x1A; /* length */
8211 		i = 2;
8212 		break;
8213 
8214 	default:
8215 		return -EINVAL;
8216 	}
8217 
8218 	memcpy(&out->sb[i], &buf[4], 26);
8219 	out->valid = true;
8220 
8221 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8222 		       sizeof(out->sb), false);
8223 
8224 	return 0;
8225 }
8226 
8227 static int
8228 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8229 				 struct drm_atomic_state *state)
8230 {
8231 	struct drm_connector_state *new_con_state =
8232 		drm_atomic_get_new_connector_state(state, conn);
8233 	struct drm_connector_state *old_con_state =
8234 		drm_atomic_get_old_connector_state(state, conn);
8235 	struct drm_crtc *crtc = new_con_state->crtc;
8236 	struct drm_crtc_state *new_crtc_state;
8237 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8238 	int ret;
8239 
8240 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8241 		return -EINVAL;
8242 
8243 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8244 
8245 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8246 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8247 		if (ret < 0)
8248 			return ret;
8249 	}
8250 
8251 	if (!crtc)
8252 		return 0;
8253 
8254 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8255 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8256 		if (IS_ERR(new_crtc_state))
8257 			return PTR_ERR(new_crtc_state);
8258 
8259 		new_crtc_state->mode_changed = true;
8260 	}
8261 
8262 	if (new_con_state->colorspace != old_con_state->colorspace) {
8263 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8264 		if (IS_ERR(new_crtc_state))
8265 			return PTR_ERR(new_crtc_state);
8266 
8267 		new_crtc_state->mode_changed = true;
8268 	}
8269 
8270 	if (new_con_state->content_type != old_con_state->content_type) {
8271 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8272 		if (IS_ERR(new_crtc_state))
8273 			return PTR_ERR(new_crtc_state);
8274 
8275 		new_crtc_state->mode_changed = true;
8276 	}
8277 
8278 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8279 		struct dc_info_packet hdr_infopacket;
8280 
8281 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8282 		if (ret)
8283 			return ret;
8284 
8285 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8286 		if (IS_ERR(new_crtc_state))
8287 			return PTR_ERR(new_crtc_state);
8288 
8289 		/*
8290 		 * DC considers the stream backends changed if the
8291 		 * static metadata changes. Forcing the modeset also
8292 		 * gives a simple way for userspace to switch from
8293 		 * 8bpc to 10bpc when setting the metadata to enter
8294 		 * or exit HDR.
8295 		 *
8296 		 * Changing the static metadata after it's been
8297 		 * set is permissible, however. So only force a
8298 		 * modeset if we're entering or exiting HDR.
8299 		 */
8300 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8301 			!old_con_state->hdr_output_metadata ||
8302 			!new_con_state->hdr_output_metadata;
8303 	}
8304 
8305 	return 0;
8306 }
8307 
8308 static const struct drm_connector_helper_funcs
8309 amdgpu_dm_connector_helper_funcs = {
8310 	/*
8311 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8312 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8313 	 * are missing after user start lightdm. So we need to renew modes list.
8314 	 * in get_modes call back, not just return the modes count
8315 	 */
8316 	.get_modes = get_modes,
8317 	.mode_valid = amdgpu_dm_connector_mode_valid,
8318 	.atomic_check = amdgpu_dm_connector_atomic_check,
8319 };
8320 
8321 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8322 {
8323 
8324 }
8325 
8326 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8327 {
8328 	switch (display_color_depth) {
8329 	case COLOR_DEPTH_666:
8330 		return 6;
8331 	case COLOR_DEPTH_888:
8332 		return 8;
8333 	case COLOR_DEPTH_101010:
8334 		return 10;
8335 	case COLOR_DEPTH_121212:
8336 		return 12;
8337 	case COLOR_DEPTH_141414:
8338 		return 14;
8339 	case COLOR_DEPTH_161616:
8340 		return 16;
8341 	default:
8342 		break;
8343 	}
8344 	return 0;
8345 }
8346 
8347 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8348 					  struct drm_crtc_state *crtc_state,
8349 					  struct drm_connector_state *conn_state)
8350 {
8351 	struct drm_atomic_state *state = crtc_state->state;
8352 	struct drm_connector *connector = conn_state->connector;
8353 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8354 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8355 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8356 	struct drm_dp_mst_topology_mgr *mst_mgr;
8357 	struct drm_dp_mst_port *mst_port;
8358 	struct drm_dp_mst_topology_state *mst_state;
8359 	enum dc_color_depth color_depth;
8360 	int clock, bpp = 0;
8361 	bool is_y420 = false;
8362 
8363 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8364 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8365 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8366 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8367 		enum drm_mode_status result;
8368 
8369 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8370 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8371 			drm_dbg_driver(encoder->dev,
8372 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8373 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8374 				       drm_mode_vrefresh(adjusted_mode));
8375 			dm_new_connector_state->scaling = RMX_ASPECT;
8376 		}
8377 		return 0;
8378 	}
8379 
8380 	if (!aconnector->mst_output_port)
8381 		return 0;
8382 
8383 	mst_port = aconnector->mst_output_port;
8384 	mst_mgr = &aconnector->mst_root->mst_mgr;
8385 
8386 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8387 		return 0;
8388 
8389 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8390 	if (IS_ERR(mst_state))
8391 		return PTR_ERR(mst_state);
8392 
8393 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8394 
8395 	if (!state->duplicated) {
8396 		int max_bpc = conn_state->max_requested_bpc;
8397 
8398 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8399 			  aconnector->force_yuv420_output;
8400 		color_depth = convert_color_depth_from_display_info(connector,
8401 								    is_y420,
8402 								    max_bpc);
8403 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8404 		clock = adjusted_mode->clock;
8405 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8406 	}
8407 
8408 	dm_new_connector_state->vcpi_slots =
8409 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8410 					      dm_new_connector_state->pbn);
8411 	if (dm_new_connector_state->vcpi_slots < 0) {
8412 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8413 		return dm_new_connector_state->vcpi_slots;
8414 	}
8415 	return 0;
8416 }
8417 
8418 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8419 	.disable = dm_encoder_helper_disable,
8420 	.atomic_check = dm_encoder_helper_atomic_check
8421 };
8422 
8423 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8424 					    struct dc_state *dc_state,
8425 					    struct dsc_mst_fairness_vars *vars)
8426 {
8427 	struct dc_stream_state *stream = NULL;
8428 	struct drm_connector *connector;
8429 	struct drm_connector_state *new_con_state;
8430 	struct amdgpu_dm_connector *aconnector;
8431 	struct dm_connector_state *dm_conn_state;
8432 	int i, j, ret;
8433 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8434 
8435 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8436 
8437 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8438 			continue;
8439 
8440 		aconnector = to_amdgpu_dm_connector(connector);
8441 
8442 		if (!aconnector->mst_output_port)
8443 			continue;
8444 
8445 		if (!new_con_state || !new_con_state->crtc)
8446 			continue;
8447 
8448 		dm_conn_state = to_dm_connector_state(new_con_state);
8449 
8450 		for (j = 0; j < dc_state->stream_count; j++) {
8451 			stream = dc_state->streams[j];
8452 			if (!stream)
8453 				continue;
8454 
8455 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8456 				break;
8457 
8458 			stream = NULL;
8459 		}
8460 
8461 		if (!stream)
8462 			continue;
8463 
8464 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8465 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8466 		for (j = 0; j < dc_state->stream_count; j++) {
8467 			if (vars[j].aconnector == aconnector) {
8468 				pbn = vars[j].pbn;
8469 				break;
8470 			}
8471 		}
8472 
8473 		if (j == dc_state->stream_count || pbn_div == 0)
8474 			continue;
8475 
8476 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8477 
8478 		if (stream->timing.flags.DSC != 1) {
8479 			dm_conn_state->pbn = pbn;
8480 			dm_conn_state->vcpi_slots = slot_num;
8481 
8482 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8483 							   dm_conn_state->pbn, false);
8484 			if (ret < 0)
8485 				return ret;
8486 
8487 			continue;
8488 		}
8489 
8490 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8491 		if (vcpi < 0)
8492 			return vcpi;
8493 
8494 		dm_conn_state->pbn = pbn;
8495 		dm_conn_state->vcpi_slots = vcpi;
8496 	}
8497 	return 0;
8498 }
8499 
8500 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8501 {
8502 	switch (st) {
8503 	case SIGNAL_TYPE_HDMI_TYPE_A:
8504 		return DRM_MODE_CONNECTOR_HDMIA;
8505 	case SIGNAL_TYPE_EDP:
8506 		return DRM_MODE_CONNECTOR_eDP;
8507 	case SIGNAL_TYPE_LVDS:
8508 		return DRM_MODE_CONNECTOR_LVDS;
8509 	case SIGNAL_TYPE_RGB:
8510 		return DRM_MODE_CONNECTOR_VGA;
8511 	case SIGNAL_TYPE_DISPLAY_PORT:
8512 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8513 		/* External DP bridges have a different connector type. */
8514 		if (connector_id == CONNECTOR_ID_VGA)
8515 			return DRM_MODE_CONNECTOR_VGA;
8516 		else if (connector_id == CONNECTOR_ID_LVDS)
8517 			return DRM_MODE_CONNECTOR_LVDS;
8518 
8519 		return DRM_MODE_CONNECTOR_DisplayPort;
8520 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8521 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8522 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8523 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8524 			return DRM_MODE_CONNECTOR_DVII;
8525 
8526 		return DRM_MODE_CONNECTOR_DVID;
8527 	case SIGNAL_TYPE_VIRTUAL:
8528 		return DRM_MODE_CONNECTOR_VIRTUAL;
8529 
8530 	default:
8531 		return DRM_MODE_CONNECTOR_Unknown;
8532 	}
8533 }
8534 
8535 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8536 {
8537 	struct drm_encoder *encoder;
8538 
8539 	/* There is only one encoder per connector */
8540 	drm_connector_for_each_possible_encoder(connector, encoder)
8541 		return encoder;
8542 
8543 	return NULL;
8544 }
8545 
8546 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8547 {
8548 	struct drm_encoder *encoder;
8549 	struct amdgpu_encoder *amdgpu_encoder;
8550 
8551 	encoder = amdgpu_dm_connector_to_encoder(connector);
8552 
8553 	if (encoder == NULL)
8554 		return;
8555 
8556 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8557 
8558 	amdgpu_encoder->native_mode.clock = 0;
8559 
8560 	if (!list_empty(&connector->probed_modes)) {
8561 		struct drm_display_mode *preferred_mode = NULL;
8562 
8563 		list_for_each_entry(preferred_mode,
8564 				    &connector->probed_modes,
8565 				    head) {
8566 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8567 				amdgpu_encoder->native_mode = *preferred_mode;
8568 
8569 			break;
8570 		}
8571 
8572 	}
8573 }
8574 
8575 static struct drm_display_mode *
8576 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8577 			     const char *name,
8578 			     int hdisplay, int vdisplay)
8579 {
8580 	struct drm_device *dev = encoder->dev;
8581 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8582 	struct drm_display_mode *mode = NULL;
8583 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8584 
8585 	mode = drm_mode_duplicate(dev, native_mode);
8586 
8587 	if (mode == NULL)
8588 		return NULL;
8589 
8590 	mode->hdisplay = hdisplay;
8591 	mode->vdisplay = vdisplay;
8592 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8593 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8594 
8595 	return mode;
8596 
8597 }
8598 
8599 static const struct amdgpu_dm_mode_size {
8600 	char name[DRM_DISPLAY_MODE_LEN];
8601 	int w;
8602 	int h;
8603 } common_modes[] = {
8604 	{  "640x480",  640,  480},
8605 	{  "800x600",  800,  600},
8606 	{ "1024x768", 1024,  768},
8607 	{ "1280x720", 1280,  720},
8608 	{ "1280x800", 1280,  800},
8609 	{"1280x1024", 1280, 1024},
8610 	{ "1440x900", 1440,  900},
8611 	{"1680x1050", 1680, 1050},
8612 	{"1600x1200", 1600, 1200},
8613 	{"1920x1080", 1920, 1080},
8614 	{"1920x1200", 1920, 1200}
8615 };
8616 
8617 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8618 						 struct drm_connector *connector)
8619 {
8620 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8621 	struct drm_display_mode *mode = NULL;
8622 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8623 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8624 				to_amdgpu_dm_connector(connector);
8625 	int i;
8626 	int n;
8627 
8628 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8629 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8630 		return;
8631 
8632 	n = ARRAY_SIZE(common_modes);
8633 
8634 	for (i = 0; i < n; i++) {
8635 		struct drm_display_mode *curmode = NULL;
8636 		bool mode_existed = false;
8637 
8638 		if (common_modes[i].w > native_mode->hdisplay ||
8639 		    common_modes[i].h > native_mode->vdisplay ||
8640 		   (common_modes[i].w == native_mode->hdisplay &&
8641 		    common_modes[i].h == native_mode->vdisplay))
8642 			continue;
8643 
8644 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8645 			if (common_modes[i].w == curmode->hdisplay &&
8646 			    common_modes[i].h == curmode->vdisplay) {
8647 				mode_existed = true;
8648 				break;
8649 			}
8650 		}
8651 
8652 		if (mode_existed)
8653 			continue;
8654 
8655 		mode = amdgpu_dm_create_common_mode(encoder,
8656 				common_modes[i].name, common_modes[i].w,
8657 				common_modes[i].h);
8658 		if (!mode)
8659 			continue;
8660 
8661 		drm_mode_probed_add(connector, mode);
8662 		amdgpu_dm_connector->num_modes++;
8663 	}
8664 }
8665 
8666 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8667 {
8668 	struct drm_encoder *encoder;
8669 	struct amdgpu_encoder *amdgpu_encoder;
8670 	const struct drm_display_mode *native_mode;
8671 
8672 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8673 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8674 		return;
8675 
8676 	mutex_lock(&connector->dev->mode_config.mutex);
8677 	amdgpu_dm_connector_get_modes(connector);
8678 	mutex_unlock(&connector->dev->mode_config.mutex);
8679 
8680 	encoder = amdgpu_dm_connector_to_encoder(connector);
8681 	if (!encoder)
8682 		return;
8683 
8684 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8685 
8686 	native_mode = &amdgpu_encoder->native_mode;
8687 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8688 		return;
8689 
8690 	drm_connector_set_panel_orientation_with_quirk(connector,
8691 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8692 						       native_mode->hdisplay,
8693 						       native_mode->vdisplay);
8694 }
8695 
8696 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8697 					      const struct drm_edid *drm_edid)
8698 {
8699 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8700 			to_amdgpu_dm_connector(connector);
8701 
8702 	if (drm_edid) {
8703 		/* empty probed_modes */
8704 		INIT_LIST_HEAD(&connector->probed_modes);
8705 		amdgpu_dm_connector->num_modes =
8706 				drm_edid_connector_add_modes(connector);
8707 
8708 		/* sorting the probed modes before calling function
8709 		 * amdgpu_dm_get_native_mode() since EDID can have
8710 		 * more than one preferred mode. The modes that are
8711 		 * later in the probed mode list could be of higher
8712 		 * and preferred resolution. For example, 3840x2160
8713 		 * resolution in base EDID preferred timing and 4096x2160
8714 		 * preferred resolution in DID extension block later.
8715 		 */
8716 		drm_mode_sort(&connector->probed_modes);
8717 		amdgpu_dm_get_native_mode(connector);
8718 
8719 		/* Freesync capabilities are reset by calling
8720 		 * drm_edid_connector_add_modes() and need to be
8721 		 * restored here.
8722 		 */
8723 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8724 	} else {
8725 		amdgpu_dm_connector->num_modes = 0;
8726 	}
8727 }
8728 
8729 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8730 			      struct drm_display_mode *mode)
8731 {
8732 	struct drm_display_mode *m;
8733 
8734 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8735 		if (drm_mode_equal(m, mode))
8736 			return true;
8737 	}
8738 
8739 	return false;
8740 }
8741 
8742 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8743 {
8744 	const struct drm_display_mode *m;
8745 	struct drm_display_mode *new_mode;
8746 	uint i;
8747 	u32 new_modes_count = 0;
8748 
8749 	/* Standard FPS values
8750 	 *
8751 	 * 23.976       - TV/NTSC
8752 	 * 24           - Cinema
8753 	 * 25           - TV/PAL
8754 	 * 29.97        - TV/NTSC
8755 	 * 30           - TV/NTSC
8756 	 * 48           - Cinema HFR
8757 	 * 50           - TV/PAL
8758 	 * 60           - Commonly used
8759 	 * 48,72,96,120 - Multiples of 24
8760 	 */
8761 	static const u32 common_rates[] = {
8762 		23976, 24000, 25000, 29970, 30000,
8763 		48000, 50000, 60000, 72000, 96000, 120000
8764 	};
8765 
8766 	/*
8767 	 * Find mode with highest refresh rate with the same resolution
8768 	 * as the preferred mode. Some monitors report a preferred mode
8769 	 * with lower resolution than the highest refresh rate supported.
8770 	 */
8771 
8772 	m = get_highest_refresh_rate_mode(aconnector, true);
8773 	if (!m)
8774 		return 0;
8775 
8776 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8777 		u64 target_vtotal, target_vtotal_diff;
8778 		u64 num, den;
8779 
8780 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8781 			continue;
8782 
8783 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8784 		    common_rates[i] > aconnector->max_vfreq * 1000)
8785 			continue;
8786 
8787 		num = (unsigned long long)m->clock * 1000 * 1000;
8788 		den = common_rates[i] * (unsigned long long)m->htotal;
8789 		target_vtotal = div_u64(num, den);
8790 		target_vtotal_diff = target_vtotal - m->vtotal;
8791 
8792 		/* Check for illegal modes */
8793 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8794 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8795 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8796 			continue;
8797 
8798 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8799 		if (!new_mode)
8800 			goto out;
8801 
8802 		new_mode->vtotal += (u16)target_vtotal_diff;
8803 		new_mode->vsync_start += (u16)target_vtotal_diff;
8804 		new_mode->vsync_end += (u16)target_vtotal_diff;
8805 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8806 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8807 
8808 		if (!is_duplicate_mode(aconnector, new_mode)) {
8809 			drm_mode_probed_add(&aconnector->base, new_mode);
8810 			new_modes_count += 1;
8811 		} else
8812 			drm_mode_destroy(aconnector->base.dev, new_mode);
8813 	}
8814  out:
8815 	return new_modes_count;
8816 }
8817 
8818 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8819 						   const struct drm_edid *drm_edid)
8820 {
8821 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8822 		to_amdgpu_dm_connector(connector);
8823 
8824 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8825 		return;
8826 
8827 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
8828 		return;
8829 
8830 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
8831 		return;
8832 
8833 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
8834 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
8835 		return;
8836 
8837 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8838 		amdgpu_dm_connector->num_modes +=
8839 			add_fs_modes(amdgpu_dm_connector);
8840 }
8841 
8842 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8843 {
8844 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8845 			to_amdgpu_dm_connector(connector);
8846 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
8847 	struct drm_encoder *encoder;
8848 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8849 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
8850 	const struct dc *dc = dc_link->dc;
8851 
8852 	encoder = amdgpu_dm_connector_to_encoder(connector);
8853 
8854 	if (!drm_edid) {
8855 		amdgpu_dm_connector->num_modes =
8856 				drm_add_modes_noedid(connector, 640, 480);
8857 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8858 			amdgpu_dm_connector->num_modes +=
8859 				drm_add_modes_noedid(connector, 1920, 1080);
8860 
8861 		if (amdgpu_dm_connector->dc_sink &&
8862 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
8863 		    dc_connector_supports_analog(dc_link->link_id.id)) {
8864 			/* Analog monitor connected by DAC load detection.
8865 			 * Add common modes. It will be up to the user to select one that works.
8866 			 */
8867 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
8868 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
8869 					connector, common_modes[i].w, common_modes[i].h);
8870 		}
8871 	} else {
8872 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8873 		if (encoder)
8874 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8875 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8876 	}
8877 	amdgpu_dm_fbc_init(connector);
8878 
8879 	return amdgpu_dm_connector->num_modes;
8880 }
8881 
8882 static const u32 supported_colorspaces =
8883 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8884 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8885 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8886 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8887 
8888 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8889 				     struct amdgpu_dm_connector *aconnector,
8890 				     int connector_type,
8891 				     struct dc_link *link,
8892 				     int link_index)
8893 {
8894 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8895 
8896 	/*
8897 	 * Some of the properties below require access to state, like bpc.
8898 	 * Allocate some default initial connector state with our reset helper.
8899 	 */
8900 	if (aconnector->base.funcs->reset)
8901 		aconnector->base.funcs->reset(&aconnector->base);
8902 
8903 	aconnector->connector_id = link_index;
8904 	aconnector->bl_idx = -1;
8905 	aconnector->dc_link = link;
8906 	aconnector->base.interlace_allowed = false;
8907 	aconnector->base.doublescan_allowed = false;
8908 	aconnector->base.stereo_allowed = false;
8909 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8910 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8911 	aconnector->audio_inst = -1;
8912 	aconnector->pack_sdp_v1_3 = false;
8913 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8914 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8915 	mutex_init(&aconnector->hpd_lock);
8916 	mutex_init(&aconnector->handle_mst_msg_ready);
8917 
8918 	/*
8919 	 * If HDMI HPD debounce delay is set, use the minimum between selected
8920 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
8921 	 */
8922 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
8923 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
8924 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
8925 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
8926 		aconnector->hdmi_prev_sink = NULL;
8927 	} else {
8928 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
8929 	}
8930 
8931 	/*
8932 	 * configure support HPD hot plug connector_>polled default value is 0
8933 	 * which means HPD hot plug not supported
8934 	 */
8935 	switch (connector_type) {
8936 	case DRM_MODE_CONNECTOR_HDMIA:
8937 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8938 		aconnector->base.ycbcr_420_allowed =
8939 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
8940 		break;
8941 	case DRM_MODE_CONNECTOR_DisplayPort:
8942 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8943 		link->link_enc = link_enc_cfg_get_link_enc(link);
8944 		ASSERT(link->link_enc);
8945 		if (link->link_enc)
8946 			aconnector->base.ycbcr_420_allowed =
8947 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
8948 		break;
8949 	case DRM_MODE_CONNECTOR_DVID:
8950 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8951 		break;
8952 	case DRM_MODE_CONNECTOR_DVII:
8953 	case DRM_MODE_CONNECTOR_VGA:
8954 		aconnector->base.polled =
8955 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
8956 		break;
8957 	default:
8958 		break;
8959 	}
8960 
8961 	drm_object_attach_property(&aconnector->base.base,
8962 				dm->ddev->mode_config.scaling_mode_property,
8963 				DRM_MODE_SCALE_NONE);
8964 
8965 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
8966 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
8967 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
8968 
8969 	drm_object_attach_property(&aconnector->base.base,
8970 				adev->mode_info.underscan_property,
8971 				UNDERSCAN_OFF);
8972 	drm_object_attach_property(&aconnector->base.base,
8973 				adev->mode_info.underscan_hborder_property,
8974 				0);
8975 	drm_object_attach_property(&aconnector->base.base,
8976 				adev->mode_info.underscan_vborder_property,
8977 				0);
8978 
8979 	if (!aconnector->mst_root)
8980 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
8981 
8982 	aconnector->base.state->max_bpc = 16;
8983 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
8984 
8985 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8986 		/* Content Type is currently only implemented for HDMI. */
8987 		drm_connector_attach_content_type_property(&aconnector->base);
8988 	}
8989 
8990 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8991 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
8992 			drm_connector_attach_colorspace_property(&aconnector->base);
8993 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
8994 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
8995 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
8996 			drm_connector_attach_colorspace_property(&aconnector->base);
8997 	}
8998 
8999 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9000 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9001 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9002 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9003 
9004 		if (!aconnector->mst_root)
9005 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9006 
9007 		if (adev->dm.hdcp_workqueue)
9008 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9009 	}
9010 
9011 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9012 		struct drm_privacy_screen *privacy_screen;
9013 
9014 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9015 		if (!IS_ERR(privacy_screen)) {
9016 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9017 								     privacy_screen);
9018 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9019 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9020 		}
9021 	}
9022 }
9023 
9024 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9025 			      struct i2c_msg *msgs, int num)
9026 {
9027 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9028 	struct ddc_service *ddc_service = i2c->ddc_service;
9029 	struct i2c_command cmd;
9030 	int i;
9031 	int result = -EIO;
9032 
9033 	if (!ddc_service->ddc_pin)
9034 		return result;
9035 
9036 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9037 
9038 	if (!cmd.payloads)
9039 		return result;
9040 
9041 	cmd.number_of_payloads = num;
9042 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9043 	cmd.speed = 100;
9044 
9045 	for (i = 0; i < num; i++) {
9046 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9047 		cmd.payloads[i].address = msgs[i].addr;
9048 		cmd.payloads[i].length = msgs[i].len;
9049 		cmd.payloads[i].data = msgs[i].buf;
9050 	}
9051 
9052 	if (i2c->oem) {
9053 		if (dc_submit_i2c_oem(
9054 			    ddc_service->ctx->dc,
9055 			    &cmd))
9056 			result = num;
9057 	} else {
9058 		if (dc_submit_i2c(
9059 			    ddc_service->ctx->dc,
9060 			    ddc_service->link->link_index,
9061 			    &cmd))
9062 			result = num;
9063 	}
9064 
9065 	kfree(cmd.payloads);
9066 	return result;
9067 }
9068 
9069 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9070 {
9071 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9072 }
9073 
9074 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9075 	.master_xfer = amdgpu_dm_i2c_xfer,
9076 	.functionality = amdgpu_dm_i2c_func,
9077 };
9078 
9079 static struct amdgpu_i2c_adapter *
9080 create_i2c(struct ddc_service *ddc_service, bool oem)
9081 {
9082 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9083 	struct amdgpu_i2c_adapter *i2c;
9084 
9085 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9086 	if (!i2c)
9087 		return NULL;
9088 	i2c->base.owner = THIS_MODULE;
9089 	i2c->base.dev.parent = &adev->pdev->dev;
9090 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9091 	if (oem)
9092 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9093 	else
9094 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9095 			 ddc_service->link->link_index);
9096 	i2c_set_adapdata(&i2c->base, i2c);
9097 	i2c->ddc_service = ddc_service;
9098 	i2c->oem = oem;
9099 
9100 	return i2c;
9101 }
9102 
9103 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9104 {
9105 	struct cec_connector_info conn_info;
9106 	struct drm_device *ddev = aconnector->base.dev;
9107 	struct device *hdmi_dev = ddev->dev;
9108 
9109 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9110 		drm_info(ddev, "HDMI-CEC feature masked\n");
9111 		return -EINVAL;
9112 	}
9113 
9114 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9115 	aconnector->notifier =
9116 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9117 	if (!aconnector->notifier) {
9118 		drm_err(ddev, "Failed to create cec notifier\n");
9119 		return -ENOMEM;
9120 	}
9121 
9122 	return 0;
9123 }
9124 
9125 /*
9126  * Note: this function assumes that dc_link_detect() was called for the
9127  * dc_link which will be represented by this aconnector.
9128  */
9129 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9130 				    struct amdgpu_dm_connector *aconnector,
9131 				    u32 link_index,
9132 				    struct amdgpu_encoder *aencoder)
9133 {
9134 	int res = 0;
9135 	int connector_type;
9136 	struct dc *dc = dm->dc;
9137 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9138 	struct amdgpu_i2c_adapter *i2c;
9139 
9140 	/* Not needed for writeback connector */
9141 	link->priv = aconnector;
9142 
9143 
9144 	i2c = create_i2c(link->ddc, false);
9145 	if (!i2c) {
9146 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9147 		return -ENOMEM;
9148 	}
9149 
9150 	aconnector->i2c = i2c;
9151 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9152 
9153 	if (res) {
9154 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9155 		goto out_free;
9156 	}
9157 
9158 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9159 
9160 	res = drm_connector_init_with_ddc(
9161 			dm->ddev,
9162 			&aconnector->base,
9163 			&amdgpu_dm_connector_funcs,
9164 			connector_type,
9165 			&i2c->base);
9166 
9167 	if (res) {
9168 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9169 		aconnector->connector_id = -1;
9170 		goto out_free;
9171 	}
9172 
9173 	drm_connector_helper_add(
9174 			&aconnector->base,
9175 			&amdgpu_dm_connector_helper_funcs);
9176 
9177 	amdgpu_dm_connector_init_helper(
9178 		dm,
9179 		aconnector,
9180 		connector_type,
9181 		link,
9182 		link_index);
9183 
9184 	drm_connector_attach_encoder(
9185 		&aconnector->base, &aencoder->base);
9186 
9187 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9188 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9189 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9190 
9191 	if (dc_is_dp_signal(link->connector_signal))
9192 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9193 
9194 out_free:
9195 	if (res) {
9196 		kfree(i2c);
9197 		aconnector->i2c = NULL;
9198 	}
9199 	return res;
9200 }
9201 
9202 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9203 {
9204 	switch (adev->mode_info.num_crtc) {
9205 	case 1:
9206 		return 0x1;
9207 	case 2:
9208 		return 0x3;
9209 	case 3:
9210 		return 0x7;
9211 	case 4:
9212 		return 0xf;
9213 	case 5:
9214 		return 0x1f;
9215 	case 6:
9216 	default:
9217 		return 0x3f;
9218 	}
9219 }
9220 
9221 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9222 				  struct amdgpu_encoder *aencoder,
9223 				  uint32_t link_index)
9224 {
9225 	struct amdgpu_device *adev = drm_to_adev(dev);
9226 
9227 	int res = drm_encoder_init(dev,
9228 				   &aencoder->base,
9229 				   &amdgpu_dm_encoder_funcs,
9230 				   DRM_MODE_ENCODER_TMDS,
9231 				   NULL);
9232 
9233 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9234 
9235 	if (!res)
9236 		aencoder->encoder_id = link_index;
9237 	else
9238 		aencoder->encoder_id = -1;
9239 
9240 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9241 
9242 	return res;
9243 }
9244 
9245 static void manage_dm_interrupts(struct amdgpu_device *adev,
9246 				 struct amdgpu_crtc *acrtc,
9247 				 struct dm_crtc_state *acrtc_state)
9248 {	/*
9249 	 * We cannot be sure that the frontend index maps to the same
9250 	 * backend index - some even map to more than one.
9251 	 * So we have to go through the CRTC to find the right IRQ.
9252 	 */
9253 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9254 			adev,
9255 			acrtc->crtc_id);
9256 	struct drm_device *dev = adev_to_drm(adev);
9257 
9258 	struct drm_vblank_crtc_config config = {0};
9259 	struct dc_crtc_timing *timing;
9260 	int offdelay;
9261 
9262 	if (acrtc_state) {
9263 		timing = &acrtc_state->stream->timing;
9264 
9265 		/*
9266 		 * Depending on when the HW latching event of double-buffered
9267 		 * registers happen relative to the PSR SDP deadline, and how
9268 		 * bad the Panel clock has drifted since the last ALPM off
9269 		 * event, there can be up to 3 frames of delay between sending
9270 		 * the PSR exit cmd to DMUB fw, and when the panel starts
9271 		 * displaying live frames.
9272 		 *
9273 		 * We can set:
9274 		 *
9275 		 * 20/100 * offdelay_ms = 3_frames_ms
9276 		 * => offdelay_ms = 5 * 3_frames_ms
9277 		 *
9278 		 * This ensures that `3_frames_ms` will only be experienced as a
9279 		 * 20% delay on top how long the display has been static, and
9280 		 * thus make the delay less perceivable.
9281 		 */
9282 		if (acrtc_state->stream->link->psr_settings.psr_version <
9283 		    DC_PSR_VERSION_UNSUPPORTED) {
9284 			offdelay = DIV64_U64_ROUND_UP((u64)5 * 3 * 10 *
9285 						      timing->v_total *
9286 						      timing->h_total,
9287 						      timing->pix_clk_100hz);
9288 			config.offdelay_ms = offdelay ?: 30;
9289 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9290 			   IP_VERSION(3, 5, 0) ||
9291 			   !(adev->flags & AMD_IS_APU)) {
9292 			/*
9293 			 * Older HW and DGPU have issues with instant off;
9294 			 * use a 2 frame offdelay.
9295 			 */
9296 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9297 						      timing->v_total *
9298 						      timing->h_total,
9299 						      timing->pix_clk_100hz);
9300 
9301 			config.offdelay_ms = offdelay ?: 30;
9302 		} else {
9303 			/* offdelay_ms = 0 will never disable vblank */
9304 			config.offdelay_ms = 1;
9305 			config.disable_immediate = true;
9306 		}
9307 
9308 		drm_crtc_vblank_on_config(&acrtc->base,
9309 					  &config);
9310 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9311 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9312 		case IP_VERSION(3, 0, 0):
9313 		case IP_VERSION(3, 0, 2):
9314 		case IP_VERSION(3, 0, 3):
9315 		case IP_VERSION(3, 2, 0):
9316 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9317 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9318 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9319 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9320 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9321 #endif
9322 		}
9323 
9324 	} else {
9325 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9326 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9327 		case IP_VERSION(3, 0, 0):
9328 		case IP_VERSION(3, 0, 2):
9329 		case IP_VERSION(3, 0, 3):
9330 		case IP_VERSION(3, 2, 0):
9331 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9332 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9333 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9334 #endif
9335 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9336 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9337 		}
9338 
9339 		drm_crtc_vblank_off(&acrtc->base);
9340 	}
9341 }
9342 
9343 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9344 				      struct amdgpu_crtc *acrtc)
9345 {
9346 	int irq_type =
9347 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9348 
9349 	/**
9350 	 * This reads the current state for the IRQ and force reapplies
9351 	 * the setting to hardware.
9352 	 */
9353 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9354 }
9355 
9356 static bool
9357 is_scaling_state_different(const struct dm_connector_state *dm_state,
9358 			   const struct dm_connector_state *old_dm_state)
9359 {
9360 	if (dm_state->scaling != old_dm_state->scaling)
9361 		return true;
9362 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9363 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9364 			return true;
9365 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9366 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9367 			return true;
9368 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9369 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9370 		return true;
9371 	return false;
9372 }
9373 
9374 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9375 					    struct drm_crtc_state *old_crtc_state,
9376 					    struct drm_connector_state *new_conn_state,
9377 					    struct drm_connector_state *old_conn_state,
9378 					    const struct drm_connector *connector,
9379 					    struct hdcp_workqueue *hdcp_w)
9380 {
9381 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9382 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9383 
9384 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9385 		connector->index, connector->status, connector->dpms);
9386 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9387 		old_conn_state->content_protection, new_conn_state->content_protection);
9388 
9389 	if (old_crtc_state)
9390 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9391 		old_crtc_state->enable,
9392 		old_crtc_state->active,
9393 		old_crtc_state->mode_changed,
9394 		old_crtc_state->active_changed,
9395 		old_crtc_state->connectors_changed);
9396 
9397 	if (new_crtc_state)
9398 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9399 		new_crtc_state->enable,
9400 		new_crtc_state->active,
9401 		new_crtc_state->mode_changed,
9402 		new_crtc_state->active_changed,
9403 		new_crtc_state->connectors_changed);
9404 
9405 	/* hdcp content type change */
9406 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9407 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9408 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9409 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9410 		return true;
9411 	}
9412 
9413 	/* CP is being re enabled, ignore this */
9414 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9415 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9416 		if (new_crtc_state && new_crtc_state->mode_changed) {
9417 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9418 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9419 			return true;
9420 		}
9421 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9422 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9423 		return false;
9424 	}
9425 
9426 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9427 	 *
9428 	 * Handles:	UNDESIRED -> ENABLED
9429 	 */
9430 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9431 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9432 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9433 
9434 	/* Stream removed and re-enabled
9435 	 *
9436 	 * Can sometimes overlap with the HPD case,
9437 	 * thus set update_hdcp to false to avoid
9438 	 * setting HDCP multiple times.
9439 	 *
9440 	 * Handles:	DESIRED -> DESIRED (Special case)
9441 	 */
9442 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9443 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9444 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9445 		dm_con_state->update_hdcp = false;
9446 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9447 			__func__);
9448 		return true;
9449 	}
9450 
9451 	/* Hot-plug, headless s3, dpms
9452 	 *
9453 	 * Only start HDCP if the display is connected/enabled.
9454 	 * update_hdcp flag will be set to false until the next
9455 	 * HPD comes in.
9456 	 *
9457 	 * Handles:	DESIRED -> DESIRED (Special case)
9458 	 */
9459 	if (dm_con_state->update_hdcp &&
9460 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9461 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9462 		dm_con_state->update_hdcp = false;
9463 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9464 			__func__);
9465 		return true;
9466 	}
9467 
9468 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9469 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9470 			if (new_crtc_state && new_crtc_state->mode_changed) {
9471 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9472 					__func__);
9473 				return true;
9474 			}
9475 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9476 				__func__);
9477 			return false;
9478 		}
9479 
9480 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9481 		return false;
9482 	}
9483 
9484 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9485 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9486 			__func__);
9487 		return true;
9488 	}
9489 
9490 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9491 	return false;
9492 }
9493 
9494 static void remove_stream(struct amdgpu_device *adev,
9495 			  struct amdgpu_crtc *acrtc,
9496 			  struct dc_stream_state *stream)
9497 {
9498 	/* this is the update mode case */
9499 
9500 	acrtc->otg_inst = -1;
9501 	acrtc->enabled = false;
9502 }
9503 
9504 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9505 {
9506 
9507 	assert_spin_locked(&acrtc->base.dev->event_lock);
9508 	WARN_ON(acrtc->event);
9509 
9510 	acrtc->event = acrtc->base.state->event;
9511 
9512 	/* Set the flip status */
9513 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9514 
9515 	/* Mark this event as consumed */
9516 	acrtc->base.state->event = NULL;
9517 
9518 	drm_dbg_state(acrtc->base.dev,
9519 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9520 		      acrtc->crtc_id);
9521 }
9522 
9523 static void update_freesync_state_on_stream(
9524 	struct amdgpu_display_manager *dm,
9525 	struct dm_crtc_state *new_crtc_state,
9526 	struct dc_stream_state *new_stream,
9527 	struct dc_plane_state *surface,
9528 	u32 flip_timestamp_in_us)
9529 {
9530 	struct mod_vrr_params vrr_params;
9531 	struct dc_info_packet vrr_infopacket = {0};
9532 	struct amdgpu_device *adev = dm->adev;
9533 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9534 	unsigned long flags;
9535 	bool pack_sdp_v1_3 = false;
9536 	struct amdgpu_dm_connector *aconn;
9537 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9538 
9539 	if (!new_stream)
9540 		return;
9541 
9542 	/*
9543 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9544 	 * For now it's sufficient to just guard against these conditions.
9545 	 */
9546 
9547 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9548 		return;
9549 
9550 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9551 	vrr_params = acrtc->dm_irq_params.vrr_params;
9552 
9553 	if (surface) {
9554 		mod_freesync_handle_preflip(
9555 			dm->freesync_module,
9556 			surface,
9557 			new_stream,
9558 			flip_timestamp_in_us,
9559 			&vrr_params);
9560 
9561 		if (adev->family < AMDGPU_FAMILY_AI &&
9562 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9563 			mod_freesync_handle_v_update(dm->freesync_module,
9564 						     new_stream, &vrr_params);
9565 
9566 			/* Need to call this before the frame ends. */
9567 			dc_stream_adjust_vmin_vmax(dm->dc,
9568 						   new_crtc_state->stream,
9569 						   &vrr_params.adjust);
9570 		}
9571 	}
9572 
9573 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9574 
9575 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9576 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9577 
9578 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9579 			packet_type = PACKET_TYPE_FS_V1;
9580 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9581 			packet_type = PACKET_TYPE_FS_V2;
9582 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9583 			packet_type = PACKET_TYPE_FS_V3;
9584 
9585 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9586 					&new_stream->adaptive_sync_infopacket);
9587 	}
9588 
9589 	mod_freesync_build_vrr_infopacket(
9590 		dm->freesync_module,
9591 		new_stream,
9592 		&vrr_params,
9593 		packet_type,
9594 		TRANSFER_FUNC_UNKNOWN,
9595 		&vrr_infopacket,
9596 		pack_sdp_v1_3);
9597 
9598 	new_crtc_state->freesync_vrr_info_changed |=
9599 		(memcmp(&new_crtc_state->vrr_infopacket,
9600 			&vrr_infopacket,
9601 			sizeof(vrr_infopacket)) != 0);
9602 
9603 	acrtc->dm_irq_params.vrr_params = vrr_params;
9604 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9605 
9606 	new_stream->vrr_infopacket = vrr_infopacket;
9607 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9608 
9609 	if (new_crtc_state->freesync_vrr_info_changed)
9610 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9611 			      new_crtc_state->base.crtc->base.id,
9612 			      (int)new_crtc_state->base.vrr_enabled,
9613 			      (int)vrr_params.state);
9614 
9615 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9616 }
9617 
9618 static void update_stream_irq_parameters(
9619 	struct amdgpu_display_manager *dm,
9620 	struct dm_crtc_state *new_crtc_state)
9621 {
9622 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9623 	struct mod_vrr_params vrr_params;
9624 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9625 	struct amdgpu_device *adev = dm->adev;
9626 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9627 	unsigned long flags;
9628 
9629 	if (!new_stream)
9630 		return;
9631 
9632 	/*
9633 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9634 	 * For now it's sufficient to just guard against these conditions.
9635 	 */
9636 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9637 		return;
9638 
9639 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9640 	vrr_params = acrtc->dm_irq_params.vrr_params;
9641 
9642 	if (new_crtc_state->vrr_supported &&
9643 	    config.min_refresh_in_uhz &&
9644 	    config.max_refresh_in_uhz) {
9645 		/*
9646 		 * if freesync compatible mode was set, config.state will be set
9647 		 * in atomic check
9648 		 */
9649 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9650 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9651 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9652 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9653 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9654 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9655 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9656 		} else {
9657 			config.state = new_crtc_state->base.vrr_enabled ?
9658 						     VRR_STATE_ACTIVE_VARIABLE :
9659 						     VRR_STATE_INACTIVE;
9660 		}
9661 	} else {
9662 		config.state = VRR_STATE_UNSUPPORTED;
9663 	}
9664 
9665 	mod_freesync_build_vrr_params(dm->freesync_module,
9666 				      new_stream,
9667 				      &config, &vrr_params);
9668 
9669 	new_crtc_state->freesync_config = config;
9670 	/* Copy state for access from DM IRQ handler */
9671 	acrtc->dm_irq_params.freesync_config = config;
9672 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9673 	acrtc->dm_irq_params.vrr_params = vrr_params;
9674 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9675 }
9676 
9677 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9678 					    struct dm_crtc_state *new_state)
9679 {
9680 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9681 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9682 
9683 	if (!old_vrr_active && new_vrr_active) {
9684 		/* Transition VRR inactive -> active:
9685 		 * While VRR is active, we must not disable vblank irq, as a
9686 		 * reenable after disable would compute bogus vblank/pflip
9687 		 * timestamps if it likely happened inside display front-porch.
9688 		 *
9689 		 * We also need vupdate irq for the actual core vblank handling
9690 		 * at end of vblank.
9691 		 */
9692 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9693 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9694 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9695 				 __func__, new_state->base.crtc->base.id);
9696 	} else if (old_vrr_active && !new_vrr_active) {
9697 		/* Transition VRR active -> inactive:
9698 		 * Allow vblank irq disable again for fixed refresh rate.
9699 		 */
9700 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9701 		drm_crtc_vblank_put(new_state->base.crtc);
9702 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9703 				 __func__, new_state->base.crtc->base.id);
9704 	}
9705 }
9706 
9707 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9708 {
9709 	struct drm_plane *plane;
9710 	struct drm_plane_state *old_plane_state;
9711 	int i;
9712 
9713 	/*
9714 	 * TODO: Make this per-stream so we don't issue redundant updates for
9715 	 * commits with multiple streams.
9716 	 */
9717 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9718 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9719 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9720 }
9721 
9722 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9723 {
9724 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9725 
9726 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9727 }
9728 
9729 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9730 				    struct drm_plane_state *old_plane_state,
9731 				    struct dc_stream_update *update)
9732 {
9733 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9734 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9735 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9736 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9737 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9738 	uint64_t address = afb ? afb->address : 0;
9739 	struct dc_cursor_position position = {0};
9740 	struct dc_cursor_attributes attributes;
9741 	int ret;
9742 
9743 	if (!plane->state->fb && !old_plane_state->fb)
9744 		return;
9745 
9746 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9747 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9748 		       plane->state->crtc_h);
9749 
9750 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9751 	if (ret)
9752 		return;
9753 
9754 	if (!position.enable) {
9755 		/* turn off cursor */
9756 		if (crtc_state && crtc_state->stream) {
9757 			dc_stream_set_cursor_position(crtc_state->stream,
9758 						      &position);
9759 			update->cursor_position = &crtc_state->stream->cursor_position;
9760 		}
9761 		return;
9762 	}
9763 
9764 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9765 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9766 
9767 	memset(&attributes, 0, sizeof(attributes));
9768 	attributes.address.high_part = upper_32_bits(address);
9769 	attributes.address.low_part  = lower_32_bits(address);
9770 	attributes.width             = plane->state->crtc_w;
9771 	attributes.height            = plane->state->crtc_h;
9772 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9773 	attributes.rotation_angle    = 0;
9774 	attributes.attribute_flags.value = 0;
9775 
9776 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9777 	 * legacy gamma setup.
9778 	 */
9779 	if (crtc_state->cm_is_degamma_srgb &&
9780 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9781 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9782 
9783 	if (afb)
9784 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9785 
9786 	if (crtc_state->stream) {
9787 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9788 						     &attributes))
9789 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9790 
9791 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9792 
9793 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9794 						   &position))
9795 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9796 
9797 		update->cursor_position = &crtc_state->stream->cursor_position;
9798 	}
9799 }
9800 
9801 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9802 					  const struct dm_crtc_state *acrtc_state,
9803 					  const u64 current_ts)
9804 {
9805 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9806 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9807 	struct amdgpu_dm_connector *aconn =
9808 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9809 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9810 
9811 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9812 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9813 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9814 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9815 			     !psr->psr_feature_enabled)
9816 			if (!aconn->disallow_edp_enter_psr)
9817 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9818 	}
9819 
9820 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9821 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9822 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9823 		if (aconn->sr_skip_count > 0)
9824 			aconn->sr_skip_count--;
9825 
9826 		/* Allow SR when skip count is 0. */
9827 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9828 
9829 		/*
9830 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9831 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9832 		 * can be enabled immediately once OS demonstrates an
9833 		 * adequate number of fast atomic commits to notify KMD
9834 		 * of update events. See `vblank_control_worker()`.
9835 		 */
9836 		if (!vrr_active &&
9837 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9838 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9839 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9840 #endif
9841 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9842 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9843 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9844 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9845 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9846 				amdgpu_dm_psr_enable(acrtc_state->stream);
9847 		}
9848 	} else {
9849 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9850 	}
9851 }
9852 
9853 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9854 				    struct drm_device *dev,
9855 				    struct amdgpu_display_manager *dm,
9856 				    struct drm_crtc *pcrtc,
9857 				    bool wait_for_vblank)
9858 {
9859 	u32 i;
9860 	u64 timestamp_ns = ktime_get_ns();
9861 	struct drm_plane *plane;
9862 	struct drm_plane_state *old_plane_state, *new_plane_state;
9863 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9864 	struct drm_crtc_state *new_pcrtc_state =
9865 			drm_atomic_get_new_crtc_state(state, pcrtc);
9866 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9867 	struct dm_crtc_state *dm_old_crtc_state =
9868 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9869 	int planes_count = 0, vpos, hpos;
9870 	unsigned long flags;
9871 	u32 target_vblank, last_flip_vblank;
9872 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9873 	bool cursor_update = false;
9874 	bool pflip_present = false;
9875 	bool dirty_rects_changed = false;
9876 	bool updated_planes_and_streams = false;
9877 	struct {
9878 		struct dc_surface_update surface_updates[MAX_SURFACES];
9879 		struct dc_plane_info plane_infos[MAX_SURFACES];
9880 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9881 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9882 		struct dc_stream_update stream_update;
9883 	} *bundle;
9884 
9885 	bundle = kzalloc_obj(*bundle);
9886 
9887 	if (!bundle) {
9888 		drm_err(dev, "Failed to allocate update bundle\n");
9889 		goto cleanup;
9890 	}
9891 
9892 	/*
9893 	 * Disable the cursor first if we're disabling all the planes.
9894 	 * It'll remain on the screen after the planes are re-enabled
9895 	 * if we don't.
9896 	 *
9897 	 * If the cursor is transitioning from native to overlay mode, the
9898 	 * native cursor needs to be disabled first.
9899 	 */
9900 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9901 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9902 		struct dc_cursor_position cursor_position = {0};
9903 
9904 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9905 						   &cursor_position))
9906 			drm_err(dev, "DC failed to disable native cursor\n");
9907 
9908 		bundle->stream_update.cursor_position =
9909 				&acrtc_state->stream->cursor_position;
9910 	}
9911 
9912 	if (acrtc_state->active_planes == 0 &&
9913 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9914 		amdgpu_dm_commit_cursors(state);
9915 
9916 	/* update planes when needed */
9917 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9918 		struct drm_crtc *crtc = new_plane_state->crtc;
9919 		struct drm_crtc_state *new_crtc_state;
9920 		struct drm_framebuffer *fb = new_plane_state->fb;
9921 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9922 		bool plane_needs_flip;
9923 		struct dc_plane_state *dc_plane;
9924 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9925 
9926 		/* Cursor plane is handled after stream updates */
9927 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9928 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9929 			if ((fb && crtc == pcrtc) ||
9930 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9931 				cursor_update = true;
9932 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
9933 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
9934 			}
9935 
9936 			continue;
9937 		}
9938 
9939 		if (!fb || !crtc || pcrtc != crtc)
9940 			continue;
9941 
9942 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
9943 		if (!new_crtc_state->active)
9944 			continue;
9945 
9946 		dc_plane = dm_new_plane_state->dc_state;
9947 		if (!dc_plane)
9948 			continue;
9949 
9950 		bundle->surface_updates[planes_count].surface = dc_plane;
9951 		if (new_pcrtc_state->color_mgmt_changed) {
9952 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
9953 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
9954 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
9955 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
9956 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
9957 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
9958 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
9959 		}
9960 
9961 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
9962 				     &bundle->scaling_infos[planes_count]);
9963 
9964 		bundle->surface_updates[planes_count].scaling_info =
9965 			&bundle->scaling_infos[planes_count];
9966 
9967 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
9968 
9969 		pflip_present = pflip_present || plane_needs_flip;
9970 
9971 		if (!plane_needs_flip) {
9972 			planes_count += 1;
9973 			continue;
9974 		}
9975 
9976 		fill_dc_plane_info_and_addr(
9977 			dm->adev, new_plane_state,
9978 			afb->tiling_flags,
9979 			&bundle->plane_infos[planes_count],
9980 			&bundle->flip_addrs[planes_count].address,
9981 			afb->tmz_surface);
9982 
9983 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
9984 				 new_plane_state->plane->index,
9985 				 bundle->plane_infos[planes_count].dcc.enable);
9986 
9987 		bundle->surface_updates[planes_count].plane_info =
9988 			&bundle->plane_infos[planes_count];
9989 
9990 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
9991 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
9992 			fill_dc_dirty_rects(plane, old_plane_state,
9993 					    new_plane_state, new_crtc_state,
9994 					    &bundle->flip_addrs[planes_count],
9995 					    acrtc_state->stream->link->psr_settings.psr_version ==
9996 					    DC_PSR_VERSION_SU_1,
9997 					    &dirty_rects_changed);
9998 
9999 			/*
10000 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10001 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10002 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
10003 			 * during the PSR-SU was disabled.
10004 			 */
10005 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10006 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10007 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
10008 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
10009 #endif
10010 			    dirty_rects_changed) {
10011 				mutex_lock(&dm->dc_lock);
10012 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10013 				timestamp_ns;
10014 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10015 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
10016 				mutex_unlock(&dm->dc_lock);
10017 			}
10018 		}
10019 
10020 		/*
10021 		 * Only allow immediate flips for fast updates that don't
10022 		 * change memory domain, FB pitch, DCC state, rotation or
10023 		 * mirroring.
10024 		 *
10025 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10026 		 * fast updates.
10027 		 */
10028 		if (crtc->state->async_flip &&
10029 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10030 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10031 			drm_warn_once(state->dev,
10032 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10033 				      plane->base.id, plane->name);
10034 
10035 		bundle->flip_addrs[planes_count].flip_immediate =
10036 			crtc->state->async_flip &&
10037 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10038 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10039 
10040 		timestamp_ns = ktime_get_ns();
10041 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10042 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10043 		bundle->surface_updates[planes_count].surface = dc_plane;
10044 
10045 		if (!bundle->surface_updates[planes_count].surface) {
10046 			drm_err(dev, "No surface for CRTC: id=%d\n",
10047 					acrtc_attach->crtc_id);
10048 			continue;
10049 		}
10050 
10051 		if (plane == pcrtc->primary)
10052 			update_freesync_state_on_stream(
10053 				dm,
10054 				acrtc_state,
10055 				acrtc_state->stream,
10056 				dc_plane,
10057 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10058 
10059 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10060 				 __func__,
10061 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10062 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10063 
10064 		planes_count += 1;
10065 
10066 	}
10067 
10068 	if (pflip_present) {
10069 		if (!vrr_active) {
10070 			/* Use old throttling in non-vrr fixed refresh rate mode
10071 			 * to keep flip scheduling based on target vblank counts
10072 			 * working in a backwards compatible way, e.g., for
10073 			 * clients using the GLX_OML_sync_control extension or
10074 			 * DRI3/Present extension with defined target_msc.
10075 			 */
10076 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10077 		} else {
10078 			/* For variable refresh rate mode only:
10079 			 * Get vblank of last completed flip to avoid > 1 vrr
10080 			 * flips per video frame by use of throttling, but allow
10081 			 * flip programming anywhere in the possibly large
10082 			 * variable vrr vblank interval for fine-grained flip
10083 			 * timing control and more opportunity to avoid stutter
10084 			 * on late submission of flips.
10085 			 */
10086 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10087 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10088 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10089 		}
10090 
10091 		target_vblank = last_flip_vblank + wait_for_vblank;
10092 
10093 		/*
10094 		 * Wait until we're out of the vertical blank period before the one
10095 		 * targeted by the flip
10096 		 */
10097 		while ((acrtc_attach->enabled &&
10098 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10099 							    0, &vpos, &hpos, NULL,
10100 							    NULL, &pcrtc->hwmode)
10101 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10102 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10103 			(int)(target_vblank -
10104 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10105 			usleep_range(1000, 1100);
10106 		}
10107 
10108 		/**
10109 		 * Prepare the flip event for the pageflip interrupt to handle.
10110 		 *
10111 		 * This only works in the case where we've already turned on the
10112 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10113 		 * from 0 -> n planes we have to skip a hardware generated event
10114 		 * and rely on sending it from software.
10115 		 */
10116 		if (acrtc_attach->base.state->event &&
10117 		    acrtc_state->active_planes > 0) {
10118 			drm_crtc_vblank_get(pcrtc);
10119 
10120 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10121 
10122 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10123 			prepare_flip_isr(acrtc_attach);
10124 
10125 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10126 		}
10127 
10128 		if (acrtc_state->stream) {
10129 			if (acrtc_state->freesync_vrr_info_changed)
10130 				bundle->stream_update.vrr_infopacket =
10131 					&acrtc_state->stream->vrr_infopacket;
10132 		}
10133 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10134 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10135 		if (acrtc_attach->base.state->event) {
10136 			drm_crtc_vblank_get(pcrtc);
10137 			acrtc_attach->event = acrtc_attach->base.state->event;
10138 			acrtc_attach->base.state->event = NULL;
10139 		}
10140 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10141 	}
10142 
10143 	/* Update the planes if changed or disable if we don't have any. */
10144 	if ((planes_count || acrtc_state->active_planes == 0) &&
10145 		acrtc_state->stream) {
10146 		/*
10147 		 * If PSR or idle optimizations are enabled then flush out
10148 		 * any pending work before hardware programming.
10149 		 */
10150 		if (dm->vblank_control_workqueue)
10151 			flush_workqueue(dm->vblank_control_workqueue);
10152 
10153 		bundle->stream_update.stream = acrtc_state->stream;
10154 		if (new_pcrtc_state->mode_changed) {
10155 			bundle->stream_update.src = acrtc_state->stream->src;
10156 			bundle->stream_update.dst = acrtc_state->stream->dst;
10157 		}
10158 
10159 		if (new_pcrtc_state->color_mgmt_changed) {
10160 			/*
10161 			 * TODO: This isn't fully correct since we've actually
10162 			 * already modified the stream in place.
10163 			 */
10164 			bundle->stream_update.gamut_remap =
10165 				&acrtc_state->stream->gamut_remap_matrix;
10166 			bundle->stream_update.output_csc_transform =
10167 				&acrtc_state->stream->csc_color_matrix;
10168 			bundle->stream_update.out_transfer_func =
10169 				&acrtc_state->stream->out_transfer_func;
10170 			bundle->stream_update.lut3d_func =
10171 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10172 			bundle->stream_update.func_shaper =
10173 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10174 		}
10175 
10176 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10177 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10178 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10179 
10180 		mutex_lock(&dm->dc_lock);
10181 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
10182 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
10183 				amdgpu_dm_replay_disable(acrtc_state->stream);
10184 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10185 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
10186 		}
10187 		mutex_unlock(&dm->dc_lock);
10188 
10189 		/*
10190 		 * If FreeSync state on the stream has changed then we need to
10191 		 * re-adjust the min/max bounds now that DC doesn't handle this
10192 		 * as part of commit.
10193 		 */
10194 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10195 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10196 			dc_stream_adjust_vmin_vmax(
10197 				dm->dc, acrtc_state->stream,
10198 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10199 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10200 		}
10201 		mutex_lock(&dm->dc_lock);
10202 		update_planes_and_stream_adapter(dm->dc,
10203 					 acrtc_state->update_type,
10204 					 planes_count,
10205 					 acrtc_state->stream,
10206 					 &bundle->stream_update,
10207 					 bundle->surface_updates);
10208 		updated_planes_and_streams = true;
10209 
10210 		/**
10211 		 * Enable or disable the interrupts on the backend.
10212 		 *
10213 		 * Most pipes are put into power gating when unused.
10214 		 *
10215 		 * When power gating is enabled on a pipe we lose the
10216 		 * interrupt enablement state when power gating is disabled.
10217 		 *
10218 		 * So we need to update the IRQ control state in hardware
10219 		 * whenever the pipe turns on (since it could be previously
10220 		 * power gated) or off (since some pipes can't be power gated
10221 		 * on some ASICs).
10222 		 */
10223 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10224 			dm_update_pflip_irq_state(drm_to_adev(dev),
10225 						  acrtc_attach);
10226 
10227 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
10228 		mutex_unlock(&dm->dc_lock);
10229 	}
10230 
10231 	/*
10232 	 * Update cursor state *after* programming all the planes.
10233 	 * This avoids redundant programming in the case where we're going
10234 	 * to be disabling a single plane - those pipes are being disabled.
10235 	 */
10236 	if (acrtc_state->active_planes &&
10237 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10238 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10239 		amdgpu_dm_commit_cursors(state);
10240 
10241 cleanup:
10242 	kfree(bundle);
10243 }
10244 
10245 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10246 				   struct drm_atomic_state *state)
10247 {
10248 	struct amdgpu_device *adev = drm_to_adev(dev);
10249 	struct amdgpu_dm_connector *aconnector;
10250 	struct drm_connector *connector;
10251 	struct drm_connector_state *old_con_state, *new_con_state;
10252 	struct drm_crtc_state *new_crtc_state;
10253 	struct dm_crtc_state *new_dm_crtc_state;
10254 	const struct dc_stream_status *status;
10255 	int i, inst;
10256 
10257 	/* Notify device removals. */
10258 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10259 		if (old_con_state->crtc != new_con_state->crtc) {
10260 			/* CRTC changes require notification. */
10261 			goto notify;
10262 		}
10263 
10264 		if (!new_con_state->crtc)
10265 			continue;
10266 
10267 		new_crtc_state = drm_atomic_get_new_crtc_state(
10268 			state, new_con_state->crtc);
10269 
10270 		if (!new_crtc_state)
10271 			continue;
10272 
10273 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10274 			continue;
10275 
10276 notify:
10277 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10278 			continue;
10279 
10280 		aconnector = to_amdgpu_dm_connector(connector);
10281 
10282 		mutex_lock(&adev->dm.audio_lock);
10283 		inst = aconnector->audio_inst;
10284 		aconnector->audio_inst = -1;
10285 		mutex_unlock(&adev->dm.audio_lock);
10286 
10287 		amdgpu_dm_audio_eld_notify(adev, inst);
10288 	}
10289 
10290 	/* Notify audio device additions. */
10291 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10292 		if (!new_con_state->crtc)
10293 			continue;
10294 
10295 		new_crtc_state = drm_atomic_get_new_crtc_state(
10296 			state, new_con_state->crtc);
10297 
10298 		if (!new_crtc_state)
10299 			continue;
10300 
10301 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10302 			continue;
10303 
10304 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10305 		if (!new_dm_crtc_state->stream)
10306 			continue;
10307 
10308 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10309 		if (!status)
10310 			continue;
10311 
10312 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10313 			continue;
10314 
10315 		aconnector = to_amdgpu_dm_connector(connector);
10316 
10317 		mutex_lock(&adev->dm.audio_lock);
10318 		inst = status->audio_inst;
10319 		aconnector->audio_inst = inst;
10320 		mutex_unlock(&adev->dm.audio_lock);
10321 
10322 		amdgpu_dm_audio_eld_notify(adev, inst);
10323 	}
10324 }
10325 
10326 /*
10327  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10328  * @crtc_state: the DRM CRTC state
10329  * @stream_state: the DC stream state.
10330  *
10331  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10332  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10333  */
10334 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10335 						struct dc_stream_state *stream_state)
10336 {
10337 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10338 }
10339 
10340 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10341 			      struct dm_crtc_state *crtc_state)
10342 {
10343 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10344 }
10345 
10346 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10347 					struct dc_state *dc_state)
10348 {
10349 	struct drm_device *dev = state->dev;
10350 	struct amdgpu_device *adev = drm_to_adev(dev);
10351 	struct amdgpu_display_manager *dm = &adev->dm;
10352 	struct drm_crtc *crtc;
10353 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10354 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10355 	struct drm_connector_state *old_con_state;
10356 	struct drm_connector *connector;
10357 	bool mode_set_reset_required = false;
10358 	u32 i;
10359 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10360 	bool set_backlight_level = false;
10361 
10362 	/* Disable writeback */
10363 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10364 		struct dm_connector_state *dm_old_con_state;
10365 		struct amdgpu_crtc *acrtc;
10366 
10367 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10368 			continue;
10369 
10370 		old_crtc_state = NULL;
10371 
10372 		dm_old_con_state = to_dm_connector_state(old_con_state);
10373 		if (!dm_old_con_state->base.crtc)
10374 			continue;
10375 
10376 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10377 		if (acrtc)
10378 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10379 
10380 		if (!acrtc || !acrtc->wb_enabled)
10381 			continue;
10382 
10383 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10384 
10385 		dm_clear_writeback(dm, dm_old_crtc_state);
10386 		acrtc->wb_enabled = false;
10387 	}
10388 
10389 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10390 				      new_crtc_state, i) {
10391 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10392 
10393 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10394 
10395 		if (old_crtc_state->active &&
10396 		    (!new_crtc_state->active ||
10397 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10398 			manage_dm_interrupts(adev, acrtc, NULL);
10399 			dc_stream_release(dm_old_crtc_state->stream);
10400 		}
10401 	}
10402 
10403 	drm_atomic_helper_calc_timestamping_constants(state);
10404 
10405 	/* update changed items */
10406 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10407 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10408 
10409 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10410 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10411 
10412 		drm_dbg_state(state->dev,
10413 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10414 			acrtc->crtc_id,
10415 			new_crtc_state->enable,
10416 			new_crtc_state->active,
10417 			new_crtc_state->planes_changed,
10418 			new_crtc_state->mode_changed,
10419 			new_crtc_state->active_changed,
10420 			new_crtc_state->connectors_changed);
10421 
10422 		/* Disable cursor if disabling crtc */
10423 		if (old_crtc_state->active && !new_crtc_state->active) {
10424 			struct dc_cursor_position position;
10425 
10426 			memset(&position, 0, sizeof(position));
10427 			mutex_lock(&dm->dc_lock);
10428 			dc_exit_ips_for_hw_access(dm->dc);
10429 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10430 			mutex_unlock(&dm->dc_lock);
10431 		}
10432 
10433 		/* Copy all transient state flags into dc state */
10434 		if (dm_new_crtc_state->stream) {
10435 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10436 							    dm_new_crtc_state->stream);
10437 		}
10438 
10439 		/* handles headless hotplug case, updating new_state and
10440 		 * aconnector as needed
10441 		 */
10442 
10443 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10444 
10445 			drm_dbg_atomic(dev,
10446 				       "Atomic commit: SET crtc id %d: [%p]\n",
10447 				       acrtc->crtc_id, acrtc);
10448 
10449 			if (!dm_new_crtc_state->stream) {
10450 				/*
10451 				 * this could happen because of issues with
10452 				 * userspace notifications delivery.
10453 				 * In this case userspace tries to set mode on
10454 				 * display which is disconnected in fact.
10455 				 * dc_sink is NULL in this case on aconnector.
10456 				 * We expect reset mode will come soon.
10457 				 *
10458 				 * This can also happen when unplug is done
10459 				 * during resume sequence ended
10460 				 *
10461 				 * In this case, we want to pretend we still
10462 				 * have a sink to keep the pipe running so that
10463 				 * hw state is consistent with the sw state
10464 				 */
10465 				drm_dbg_atomic(dev,
10466 					       "Failed to create new stream for crtc %d\n",
10467 						acrtc->base.base.id);
10468 				continue;
10469 			}
10470 
10471 			if (dm_old_crtc_state->stream)
10472 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10473 
10474 			pm_runtime_get_noresume(dev->dev);
10475 
10476 			acrtc->enabled = true;
10477 			acrtc->hw_mode = new_crtc_state->mode;
10478 			crtc->hwmode = new_crtc_state->mode;
10479 			mode_set_reset_required = true;
10480 			set_backlight_level = true;
10481 		} else if (modereset_required(new_crtc_state)) {
10482 			drm_dbg_atomic(dev,
10483 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10484 				       acrtc->crtc_id, acrtc);
10485 			/* i.e. reset mode */
10486 			if (dm_old_crtc_state->stream)
10487 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10488 
10489 			mode_set_reset_required = true;
10490 		}
10491 	} /* for_each_crtc_in_state() */
10492 
10493 	/* if there mode set or reset, disable eDP PSR, Replay */
10494 	if (mode_set_reset_required) {
10495 		if (dm->vblank_control_workqueue)
10496 			flush_workqueue(dm->vblank_control_workqueue);
10497 
10498 		amdgpu_dm_replay_disable_all(dm);
10499 		amdgpu_dm_psr_disable_all(dm);
10500 	}
10501 
10502 	dm_enable_per_frame_crtc_master_sync(dc_state);
10503 	mutex_lock(&dm->dc_lock);
10504 	dc_exit_ips_for_hw_access(dm->dc);
10505 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10506 
10507 	/* Allow idle optimization when vblank count is 0 for display off */
10508 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10509 		dc_allow_idle_optimizations(dm->dc, true);
10510 	mutex_unlock(&dm->dc_lock);
10511 
10512 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10513 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10514 
10515 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10516 
10517 		if (dm_new_crtc_state->stream != NULL) {
10518 			const struct dc_stream_status *status =
10519 					dc_stream_get_status(dm_new_crtc_state->stream);
10520 
10521 			if (!status)
10522 				status = dc_state_get_stream_status(dc_state,
10523 									 dm_new_crtc_state->stream);
10524 			if (!status)
10525 				drm_err(dev,
10526 					"got no status for stream %p on acrtc%p\n",
10527 					dm_new_crtc_state->stream, acrtc);
10528 			else
10529 				acrtc->otg_inst = status->primary_otg_inst;
10530 		}
10531 	}
10532 
10533 	/* During boot up and resume the DC layer will reset the panel brightness
10534 	 * to fix a flicker issue.
10535 	 * It will cause the dm->actual_brightness is not the current panel brightness
10536 	 * level. (the dm->brightness is the correct panel level)
10537 	 * So we set the backlight level with dm->brightness value after set mode
10538 	 */
10539 	if (set_backlight_level) {
10540 		for (i = 0; i < dm->num_of_edps; i++) {
10541 			if (dm->backlight_dev[i])
10542 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10543 		}
10544 	}
10545 }
10546 
10547 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10548 			      struct dm_crtc_state *crtc_state,
10549 			      struct drm_connector *connector,
10550 			      struct drm_connector_state *new_con_state)
10551 {
10552 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10553 	struct amdgpu_device *adev = dm->adev;
10554 	struct amdgpu_crtc *acrtc;
10555 	struct dc_writeback_info *wb_info;
10556 	struct pipe_ctx *pipe = NULL;
10557 	struct amdgpu_framebuffer *afb;
10558 	int i = 0;
10559 
10560 	wb_info = kzalloc_obj(*wb_info);
10561 	if (!wb_info) {
10562 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10563 		return;
10564 	}
10565 
10566 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10567 	if (!acrtc) {
10568 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10569 		kfree(wb_info);
10570 		return;
10571 	}
10572 
10573 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10574 	if (!afb) {
10575 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10576 		kfree(wb_info);
10577 		return;
10578 	}
10579 
10580 	for (i = 0; i < MAX_PIPES; i++) {
10581 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10582 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10583 			break;
10584 		}
10585 	}
10586 
10587 	/* fill in wb_info */
10588 	wb_info->wb_enabled = true;
10589 
10590 	wb_info->dwb_pipe_inst = 0;
10591 	wb_info->dwb_params.dwbscl_black_color = 0;
10592 	wb_info->dwb_params.hdr_mult = 0x1F000;
10593 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10594 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10595 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10596 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10597 
10598 	/* width & height from crtc */
10599 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10600 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10601 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10602 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10603 
10604 	wb_info->dwb_params.cnv_params.crop_en = false;
10605 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10606 
10607 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10608 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10609 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10610 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10611 
10612 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10613 
10614 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10615 
10616 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10617 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10618 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10619 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10620 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10621 
10622 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10623 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10624 
10625 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10626 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10627 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10628 	}
10629 
10630 	wb_info->mcif_buf_params.p_vmid = 1;
10631 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10632 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10633 		wb_info->mcif_warmup_params.region_size =
10634 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10635 	}
10636 	wb_info->mcif_warmup_params.p_vmid = 1;
10637 	wb_info->writeback_source_plane = pipe->plane_state;
10638 
10639 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10640 
10641 	acrtc->wb_pending = true;
10642 	acrtc->wb_conn = wb_conn;
10643 	drm_writeback_queue_job(wb_conn, new_con_state);
10644 }
10645 
10646 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10647 {
10648 	struct drm_connector_state *old_con_state, *new_con_state;
10649 	struct drm_device *dev = state->dev;
10650 	struct drm_connector *connector;
10651 	struct amdgpu_device *adev = drm_to_adev(dev);
10652 	int i;
10653 
10654 	if (!adev->dm.hdcp_workqueue)
10655 		return;
10656 
10657 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10658 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10659 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10660 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10661 		struct dm_crtc_state *dm_new_crtc_state;
10662 		struct amdgpu_dm_connector *aconnector;
10663 
10664 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10665 			continue;
10666 
10667 		aconnector = to_amdgpu_dm_connector(connector);
10668 
10669 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10670 
10671 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10672 			connector->index, connector->status, connector->dpms);
10673 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10674 			old_con_state->content_protection, new_con_state->content_protection);
10675 
10676 		if (aconnector->dc_sink) {
10677 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10678 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10679 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10680 				aconnector->dc_sink->edid_caps.display_name);
10681 			}
10682 		}
10683 
10684 		new_crtc_state = NULL;
10685 		old_crtc_state = NULL;
10686 
10687 		if (acrtc) {
10688 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10689 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10690 		}
10691 
10692 		if (old_crtc_state)
10693 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10694 			old_crtc_state->enable,
10695 			old_crtc_state->active,
10696 			old_crtc_state->mode_changed,
10697 			old_crtc_state->active_changed,
10698 			old_crtc_state->connectors_changed);
10699 
10700 		if (new_crtc_state)
10701 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10702 			new_crtc_state->enable,
10703 			new_crtc_state->active,
10704 			new_crtc_state->mode_changed,
10705 			new_crtc_state->active_changed,
10706 			new_crtc_state->connectors_changed);
10707 
10708 
10709 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10710 
10711 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10712 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10713 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10714 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10715 			dm_new_con_state->update_hdcp = true;
10716 			continue;
10717 		}
10718 
10719 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10720 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10721 			/* when display is unplugged from mst hub, connctor will
10722 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10723 			 * hdcp perperties, like type, undesired, desired, enabled,
10724 			 * will be lost. So, save hdcp properties into hdcp_work within
10725 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10726 			 * plugged back with same display index, its hdcp properties
10727 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10728 			 */
10729 
10730 			bool enable_encryption = false;
10731 
10732 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10733 				enable_encryption = true;
10734 
10735 			if (aconnector->dc_link && aconnector->dc_sink &&
10736 				aconnector->dc_link->type == dc_connection_mst_branch) {
10737 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10738 				struct hdcp_workqueue *hdcp_w =
10739 					&hdcp_work[aconnector->dc_link->link_index];
10740 
10741 				hdcp_w->hdcp_content_type[connector->index] =
10742 					new_con_state->hdcp_content_type;
10743 				hdcp_w->content_protection[connector->index] =
10744 					new_con_state->content_protection;
10745 			}
10746 
10747 			if (new_crtc_state && new_crtc_state->mode_changed &&
10748 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10749 				enable_encryption = true;
10750 
10751 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10752 
10753 			if (aconnector->dc_link)
10754 				hdcp_update_display(
10755 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10756 					new_con_state->hdcp_content_type, enable_encryption);
10757 		}
10758 	}
10759 }
10760 
10761 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
10762 {
10763 	struct drm_crtc *crtc;
10764 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10765 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10766 	int i, ret;
10767 
10768 	ret = drm_dp_mst_atomic_setup_commit(state);
10769 	if (ret)
10770 		return ret;
10771 
10772 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10773 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10774 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10775 		/*
10776 		 * Color management settings. We also update color properties
10777 		 * when a modeset is needed, to ensure it gets reprogrammed.
10778 		 */
10779 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
10780 		    (dm_new_crtc_state->base.color_mgmt_changed ||
10781 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10782 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10783 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10784 			if (ret) {
10785 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
10786 				return ret;
10787 			}
10788 		}
10789 	}
10790 
10791 	return 0;
10792 }
10793 
10794 /**
10795  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10796  * @state: The atomic state to commit
10797  *
10798  * This will tell DC to commit the constructed DC state from atomic_check,
10799  * programming the hardware. Any failures here implies a hardware failure, since
10800  * atomic check should have filtered anything non-kosher.
10801  */
10802 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10803 {
10804 	struct drm_device *dev = state->dev;
10805 	struct amdgpu_device *adev = drm_to_adev(dev);
10806 	struct amdgpu_display_manager *dm = &adev->dm;
10807 	struct dm_atomic_state *dm_state;
10808 	struct dc_state *dc_state = NULL;
10809 	u32 i, j;
10810 	struct drm_crtc *crtc;
10811 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10812 	unsigned long flags;
10813 	bool wait_for_vblank = true;
10814 	struct drm_connector *connector;
10815 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10816 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10817 	int crtc_disable_count = 0;
10818 
10819 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10820 
10821 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10822 	drm_dp_mst_atomic_wait_for_dependencies(state);
10823 
10824 	dm_state = dm_atomic_get_new_state(state);
10825 	if (dm_state && dm_state->context) {
10826 		dc_state = dm_state->context;
10827 		amdgpu_dm_commit_streams(state, dc_state);
10828 	}
10829 
10830 	amdgpu_dm_update_hdcp(state);
10831 
10832 	/* Handle connector state changes */
10833 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10834 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10835 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10836 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10837 		struct dc_surface_update *dummy_updates;
10838 		struct dc_stream_update stream_update;
10839 		struct dc_info_packet hdr_packet;
10840 		struct dc_stream_status *status = NULL;
10841 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10842 
10843 		memset(&stream_update, 0, sizeof(stream_update));
10844 
10845 		if (acrtc) {
10846 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10847 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10848 		}
10849 
10850 		/* Skip any modesets/resets */
10851 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10852 			continue;
10853 
10854 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10855 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10856 
10857 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10858 							     dm_old_con_state);
10859 
10860 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10861 			(dm_old_crtc_state->stream->output_color_space !=
10862 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10863 			output_color_space_changed = true;
10864 
10865 		abm_changed = dm_new_crtc_state->abm_level !=
10866 			      dm_old_crtc_state->abm_level;
10867 
10868 		hdr_changed =
10869 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10870 
10871 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10872 			continue;
10873 
10874 		stream_update.stream = dm_new_crtc_state->stream;
10875 		if (scaling_changed) {
10876 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
10877 					dm_new_con_state, dm_new_crtc_state->stream);
10878 
10879 			stream_update.src = dm_new_crtc_state->stream->src;
10880 			stream_update.dst = dm_new_crtc_state->stream->dst;
10881 		}
10882 
10883 		if (output_color_space_changed) {
10884 			dm_new_crtc_state->stream->output_color_space
10885 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
10886 
10887 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
10888 		}
10889 
10890 		if (abm_changed) {
10891 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10892 
10893 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10894 		}
10895 
10896 		if (hdr_changed) {
10897 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10898 			stream_update.hdr_static_metadata = &hdr_packet;
10899 		}
10900 
10901 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10902 
10903 		if (WARN_ON(!status))
10904 			continue;
10905 
10906 		WARN_ON(!status->plane_count);
10907 
10908 		/*
10909 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10910 		 * Here we create an empty update on each plane.
10911 		 * To fix this, DC should permit updating only stream properties.
10912 		 */
10913 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
10914 		if (!dummy_updates) {
10915 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
10916 			continue;
10917 		}
10918 		for (j = 0; j < status->plane_count; j++)
10919 			dummy_updates[j].surface = status->plane_states[j];
10920 
10921 		sort(dummy_updates, status->plane_count,
10922 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10923 
10924 		mutex_lock(&dm->dc_lock);
10925 		dc_exit_ips_for_hw_access(dm->dc);
10926 		dc_update_planes_and_stream(dm->dc,
10927 					    dummy_updates,
10928 					    status->plane_count,
10929 					    dm_new_crtc_state->stream,
10930 					    &stream_update);
10931 		mutex_unlock(&dm->dc_lock);
10932 		kfree(dummy_updates);
10933 
10934 		drm_connector_update_privacy_screen(new_con_state);
10935 	}
10936 
10937 	/**
10938 	 * Enable interrupts for CRTCs that are newly enabled or went through
10939 	 * a modeset. It was intentionally deferred until after the front end
10940 	 * state was modified to wait until the OTG was on and so the IRQ
10941 	 * handlers didn't access stale or invalid state.
10942 	 */
10943 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10944 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10945 #ifdef CONFIG_DEBUG_FS
10946 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
10947 #endif
10948 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
10949 		if (old_crtc_state->active && !new_crtc_state->active)
10950 			crtc_disable_count++;
10951 
10952 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10953 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10954 
10955 		/* For freesync config update on crtc state and params for irq */
10956 		update_stream_irq_parameters(dm, dm_new_crtc_state);
10957 
10958 #ifdef CONFIG_DEBUG_FS
10959 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10960 		cur_crc_src = acrtc->dm_irq_params.crc_src;
10961 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10962 #endif
10963 
10964 		if (new_crtc_state->active &&
10965 		    (!old_crtc_state->active ||
10966 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10967 			dc_stream_retain(dm_new_crtc_state->stream);
10968 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
10969 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
10970 		}
10971 		/* Handle vrr on->off / off->on transitions */
10972 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
10973 
10974 #ifdef CONFIG_DEBUG_FS
10975 		if (new_crtc_state->active &&
10976 		    (!old_crtc_state->active ||
10977 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10978 			/**
10979 			 * Frontend may have changed so reapply the CRC capture
10980 			 * settings for the stream.
10981 			 */
10982 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
10983 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
10984 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
10985 					uint8_t cnt;
10986 
10987 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10988 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
10989 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
10990 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
10991 
10992 							/**
10993 							 * It takes 2 frames for HW to stably generate CRC when
10994 							 * resuming from suspend, so we set skip_frame_cnt 2.
10995 							 */
10996 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
10997 						}
10998 					}
10999 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11000 				}
11001 #endif
11002 				if (amdgpu_dm_crtc_configure_crc_source(
11003 					crtc, dm_new_crtc_state, cur_crc_src))
11004 					drm_dbg_atomic(dev, "Failed to configure crc source");
11005 			}
11006 		}
11007 #endif
11008 	}
11009 
11010 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11011 		if (new_crtc_state->async_flip)
11012 			wait_for_vblank = false;
11013 
11014 	/* update planes when needed per crtc*/
11015 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11016 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11017 
11018 		if (dm_new_crtc_state->stream)
11019 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11020 	}
11021 
11022 	/* Enable writeback */
11023 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11024 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11025 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11026 
11027 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11028 			continue;
11029 
11030 		if (!new_con_state->writeback_job)
11031 			continue;
11032 
11033 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11034 
11035 		if (!new_crtc_state)
11036 			continue;
11037 
11038 		if (acrtc->wb_enabled)
11039 			continue;
11040 
11041 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11042 
11043 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11044 		acrtc->wb_enabled = true;
11045 	}
11046 
11047 	/* Update audio instances for each connector. */
11048 	amdgpu_dm_commit_audio(dev, state);
11049 
11050 	/* restore the backlight level */
11051 	for (i = 0; i < dm->num_of_edps; i++) {
11052 		if (dm->backlight_dev[i] &&
11053 		    (dm->actual_brightness[i] != dm->brightness[i]))
11054 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11055 	}
11056 
11057 	/*
11058 	 * send vblank event on all events not handled in flip and
11059 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11060 	 */
11061 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11062 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11063 
11064 		if (new_crtc_state->event)
11065 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11066 
11067 		new_crtc_state->event = NULL;
11068 	}
11069 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11070 
11071 	/* Signal HW programming completion */
11072 	drm_atomic_helper_commit_hw_done(state);
11073 
11074 	if (wait_for_vblank)
11075 		drm_atomic_helper_wait_for_flip_done(dev, state);
11076 
11077 	drm_atomic_helper_cleanup_planes(dev, state);
11078 
11079 	/* Don't free the memory if we are hitting this as part of suspend.
11080 	 * This way we don't free any memory during suspend; see
11081 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11082 	 * non-suspend modeset or when the driver is torn down.
11083 	 */
11084 	if (!adev->in_suspend) {
11085 		/* return the stolen vga memory back to VRAM */
11086 		if (!adev->mman.keep_stolen_vga_memory)
11087 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
11088 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
11089 	}
11090 
11091 	/*
11092 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11093 	 * so we can put the GPU into runtime suspend if we're not driving any
11094 	 * displays anymore
11095 	 */
11096 	for (i = 0; i < crtc_disable_count; i++)
11097 		pm_runtime_put_autosuspend(dev->dev);
11098 	pm_runtime_mark_last_busy(dev->dev);
11099 
11100 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11101 }
11102 
11103 static int dm_force_atomic_commit(struct drm_connector *connector)
11104 {
11105 	int ret = 0;
11106 	struct drm_device *ddev = connector->dev;
11107 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11108 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11109 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11110 	struct drm_connector_state *conn_state;
11111 	struct drm_crtc_state *crtc_state;
11112 	struct drm_plane_state *plane_state;
11113 
11114 	if (!state)
11115 		return -ENOMEM;
11116 
11117 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11118 
11119 	/* Construct an atomic state to restore previous display setting */
11120 
11121 	/*
11122 	 * Attach connectors to drm_atomic_state
11123 	 */
11124 	conn_state = drm_atomic_get_connector_state(state, connector);
11125 
11126 	/* Check for error in getting connector state */
11127 	if (IS_ERR(conn_state)) {
11128 		ret = PTR_ERR(conn_state);
11129 		goto out;
11130 	}
11131 
11132 	/* Attach crtc to drm_atomic_state*/
11133 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11134 
11135 	/* Check for error in getting crtc state */
11136 	if (IS_ERR(crtc_state)) {
11137 		ret = PTR_ERR(crtc_state);
11138 		goto out;
11139 	}
11140 
11141 	/* force a restore */
11142 	crtc_state->mode_changed = true;
11143 
11144 	/* Attach plane to drm_atomic_state */
11145 	plane_state = drm_atomic_get_plane_state(state, plane);
11146 
11147 	/* Check for error in getting plane state */
11148 	if (IS_ERR(plane_state)) {
11149 		ret = PTR_ERR(plane_state);
11150 		goto out;
11151 	}
11152 
11153 	/* Call commit internally with the state we just constructed */
11154 	ret = drm_atomic_commit(state);
11155 
11156 out:
11157 	drm_atomic_state_put(state);
11158 	if (ret)
11159 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11160 
11161 	return ret;
11162 }
11163 
11164 /*
11165  * This function handles all cases when set mode does not come upon hotplug.
11166  * This includes when a display is unplugged then plugged back into the
11167  * same port and when running without usermode desktop manager supprot
11168  */
11169 void dm_restore_drm_connector_state(struct drm_device *dev,
11170 				    struct drm_connector *connector)
11171 {
11172 	struct amdgpu_dm_connector *aconnector;
11173 	struct amdgpu_crtc *disconnected_acrtc;
11174 	struct dm_crtc_state *acrtc_state;
11175 
11176 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11177 		return;
11178 
11179 	aconnector = to_amdgpu_dm_connector(connector);
11180 
11181 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11182 		return;
11183 
11184 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11185 	if (!disconnected_acrtc)
11186 		return;
11187 
11188 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11189 	if (!acrtc_state->stream)
11190 		return;
11191 
11192 	/*
11193 	 * If the previous sink is not released and different from the current,
11194 	 * we deduce we are in a state where we can not rely on usermode call
11195 	 * to turn on the display, so we do it here
11196 	 */
11197 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11198 		dm_force_atomic_commit(&aconnector->base);
11199 }
11200 
11201 /*
11202  * Grabs all modesetting locks to serialize against any blocking commits,
11203  * Waits for completion of all non blocking commits.
11204  */
11205 static int do_aquire_global_lock(struct drm_device *dev,
11206 				 struct drm_atomic_state *state)
11207 {
11208 	struct drm_crtc *crtc;
11209 	struct drm_crtc_commit *commit;
11210 	long ret;
11211 
11212 	/*
11213 	 * Adding all modeset locks to aquire_ctx will
11214 	 * ensure that when the framework release it the
11215 	 * extra locks we are locking here will get released to
11216 	 */
11217 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11218 	if (ret)
11219 		return ret;
11220 
11221 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11222 		spin_lock(&crtc->commit_lock);
11223 		commit = list_first_entry_or_null(&crtc->commit_list,
11224 				struct drm_crtc_commit, commit_entry);
11225 		if (commit)
11226 			drm_crtc_commit_get(commit);
11227 		spin_unlock(&crtc->commit_lock);
11228 
11229 		if (!commit)
11230 			continue;
11231 
11232 		/*
11233 		 * Make sure all pending HW programming completed and
11234 		 * page flips done
11235 		 */
11236 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11237 
11238 		if (ret > 0)
11239 			ret = wait_for_completion_interruptible_timeout(
11240 					&commit->flip_done, 10*HZ);
11241 
11242 		if (ret == 0)
11243 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11244 				  crtc->base.id, crtc->name);
11245 
11246 		drm_crtc_commit_put(commit);
11247 	}
11248 
11249 	return ret < 0 ? ret : 0;
11250 }
11251 
11252 static void get_freesync_config_for_crtc(
11253 	struct dm_crtc_state *new_crtc_state,
11254 	struct dm_connector_state *new_con_state)
11255 {
11256 	struct mod_freesync_config config = {0};
11257 	struct amdgpu_dm_connector *aconnector;
11258 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11259 	int vrefresh = drm_mode_vrefresh(mode);
11260 	bool fs_vid_mode = false;
11261 
11262 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11263 		return;
11264 
11265 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11266 
11267 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11268 					vrefresh >= aconnector->min_vfreq &&
11269 					vrefresh <= aconnector->max_vfreq;
11270 
11271 	if (new_crtc_state->vrr_supported) {
11272 		new_crtc_state->stream->ignore_msa_timing_param = true;
11273 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11274 
11275 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11276 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11277 		config.vsif_supported = true;
11278 		config.btr = true;
11279 
11280 		if (fs_vid_mode) {
11281 			config.state = VRR_STATE_ACTIVE_FIXED;
11282 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11283 			goto out;
11284 		} else if (new_crtc_state->base.vrr_enabled) {
11285 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11286 		} else {
11287 			config.state = VRR_STATE_INACTIVE;
11288 		}
11289 	} else {
11290 		config.state = VRR_STATE_UNSUPPORTED;
11291 	}
11292 out:
11293 	new_crtc_state->freesync_config = config;
11294 }
11295 
11296 static void reset_freesync_config_for_crtc(
11297 	struct dm_crtc_state *new_crtc_state)
11298 {
11299 	new_crtc_state->vrr_supported = false;
11300 
11301 	memset(&new_crtc_state->vrr_infopacket, 0,
11302 	       sizeof(new_crtc_state->vrr_infopacket));
11303 }
11304 
11305 static bool
11306 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11307 				 struct drm_crtc_state *new_crtc_state)
11308 {
11309 	const struct drm_display_mode *old_mode, *new_mode;
11310 
11311 	if (!old_crtc_state || !new_crtc_state)
11312 		return false;
11313 
11314 	old_mode = &old_crtc_state->mode;
11315 	new_mode = &new_crtc_state->mode;
11316 
11317 	if (old_mode->clock       == new_mode->clock &&
11318 	    old_mode->hdisplay    == new_mode->hdisplay &&
11319 	    old_mode->vdisplay    == new_mode->vdisplay &&
11320 	    old_mode->htotal      == new_mode->htotal &&
11321 	    old_mode->vtotal      != new_mode->vtotal &&
11322 	    old_mode->hsync_start == new_mode->hsync_start &&
11323 	    old_mode->vsync_start != new_mode->vsync_start &&
11324 	    old_mode->hsync_end   == new_mode->hsync_end &&
11325 	    old_mode->vsync_end   != new_mode->vsync_end &&
11326 	    old_mode->hskew       == new_mode->hskew &&
11327 	    old_mode->vscan       == new_mode->vscan &&
11328 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11329 	    (new_mode->vsync_end - new_mode->vsync_start))
11330 		return true;
11331 
11332 	return false;
11333 }
11334 
11335 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11336 {
11337 	u64 num, den, res;
11338 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11339 
11340 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11341 
11342 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11343 	den = (unsigned long long)new_crtc_state->mode.htotal *
11344 	      (unsigned long long)new_crtc_state->mode.vtotal;
11345 
11346 	res = div_u64(num, den);
11347 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11348 }
11349 
11350 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11351 			 struct drm_atomic_state *state,
11352 			 struct drm_crtc *crtc,
11353 			 struct drm_crtc_state *old_crtc_state,
11354 			 struct drm_crtc_state *new_crtc_state,
11355 			 bool enable,
11356 			 bool *lock_and_validation_needed)
11357 {
11358 	struct dm_atomic_state *dm_state = NULL;
11359 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11360 	struct dc_stream_state *new_stream;
11361 	struct amdgpu_device *adev = dm->adev;
11362 	int ret = 0;
11363 
11364 	/*
11365 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11366 	 * update changed items
11367 	 */
11368 	struct amdgpu_crtc *acrtc = NULL;
11369 	struct drm_connector *connector = NULL;
11370 	struct amdgpu_dm_connector *aconnector = NULL;
11371 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11372 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11373 
11374 	new_stream = NULL;
11375 
11376 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11377 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11378 	acrtc = to_amdgpu_crtc(crtc);
11379 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11380 	if (connector)
11381 		aconnector = to_amdgpu_dm_connector(connector);
11382 
11383 	/* TODO This hack should go away */
11384 	if (connector && enable) {
11385 		/* Make sure fake sink is created in plug-in scenario */
11386 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11387 									connector);
11388 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11389 									connector);
11390 
11391 		if (WARN_ON(!drm_new_conn_state)) {
11392 			ret = -EINVAL;
11393 			goto fail;
11394 		}
11395 
11396 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11397 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11398 
11399 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11400 			goto skip_modeset;
11401 
11402 		new_stream = create_validate_stream_for_sink(connector,
11403 							     &new_crtc_state->mode,
11404 							     dm_new_conn_state,
11405 							     dm_old_crtc_state->stream);
11406 
11407 		/*
11408 		 * we can have no stream on ACTION_SET if a display
11409 		 * was disconnected during S3, in this case it is not an
11410 		 * error, the OS will be updated after detection, and
11411 		 * will do the right thing on next atomic commit
11412 		 */
11413 
11414 		if (!new_stream) {
11415 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11416 					__func__, acrtc->base.base.id);
11417 			ret = -ENOMEM;
11418 			goto fail;
11419 		}
11420 
11421 		/*
11422 		 * TODO: Check VSDB bits to decide whether this should
11423 		 * be enabled or not.
11424 		 */
11425 		new_stream->triggered_crtc_reset.enabled =
11426 			dm->force_timing_sync;
11427 
11428 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11429 
11430 		ret = fill_hdr_info_packet(drm_new_conn_state,
11431 					   &new_stream->hdr_static_metadata);
11432 		if (ret)
11433 			goto fail;
11434 
11435 		/*
11436 		 * If we already removed the old stream from the context
11437 		 * (and set the new stream to NULL) then we can't reuse
11438 		 * the old stream even if the stream and scaling are unchanged.
11439 		 * We'll hit the BUG_ON and black screen.
11440 		 *
11441 		 * TODO: Refactor this function to allow this check to work
11442 		 * in all conditions.
11443 		 */
11444 		if (amdgpu_freesync_vid_mode &&
11445 		    dm_new_crtc_state->stream &&
11446 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11447 			goto skip_modeset;
11448 
11449 		if (dm_new_crtc_state->stream &&
11450 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11451 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11452 			new_crtc_state->mode_changed = false;
11453 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11454 					 new_crtc_state->mode_changed);
11455 		}
11456 	}
11457 
11458 	/* mode_changed flag may get updated above, need to check again */
11459 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11460 		goto skip_modeset;
11461 
11462 	drm_dbg_state(state->dev,
11463 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11464 		acrtc->crtc_id,
11465 		new_crtc_state->enable,
11466 		new_crtc_state->active,
11467 		new_crtc_state->planes_changed,
11468 		new_crtc_state->mode_changed,
11469 		new_crtc_state->active_changed,
11470 		new_crtc_state->connectors_changed);
11471 
11472 	/* Remove stream for any changed/disabled CRTC */
11473 	if (!enable) {
11474 
11475 		if (!dm_old_crtc_state->stream)
11476 			goto skip_modeset;
11477 
11478 		/* Unset freesync video if it was active before */
11479 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11480 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11481 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11482 		}
11483 
11484 		/* Now check if we should set freesync video mode */
11485 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11486 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11487 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11488 		    is_timing_unchanged_for_freesync(new_crtc_state,
11489 						     old_crtc_state)) {
11490 			new_crtc_state->mode_changed = false;
11491 			drm_dbg_driver(adev_to_drm(adev),
11492 				"Mode change not required for front porch change, setting mode_changed to %d",
11493 				new_crtc_state->mode_changed);
11494 
11495 			set_freesync_fixed_config(dm_new_crtc_state);
11496 
11497 			goto skip_modeset;
11498 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11499 			   is_freesync_video_mode(&new_crtc_state->mode,
11500 						  aconnector)) {
11501 			struct drm_display_mode *high_mode;
11502 
11503 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11504 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11505 				set_freesync_fixed_config(dm_new_crtc_state);
11506 		}
11507 
11508 		ret = dm_atomic_get_state(state, &dm_state);
11509 		if (ret)
11510 			goto fail;
11511 
11512 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11513 				crtc->base.id);
11514 
11515 		/* i.e. reset mode */
11516 		if (dc_state_remove_stream(
11517 				dm->dc,
11518 				dm_state->context,
11519 				dm_old_crtc_state->stream) != DC_OK) {
11520 			ret = -EINVAL;
11521 			goto fail;
11522 		}
11523 
11524 		dc_stream_release(dm_old_crtc_state->stream);
11525 		dm_new_crtc_state->stream = NULL;
11526 
11527 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11528 
11529 		*lock_and_validation_needed = true;
11530 
11531 	} else {/* Add stream for any updated/enabled CRTC */
11532 		/*
11533 		 * Quick fix to prevent NULL pointer on new_stream when
11534 		 * added MST connectors not found in existing crtc_state in the chained mode
11535 		 * TODO: need to dig out the root cause of that
11536 		 */
11537 		if (!connector)
11538 			goto skip_modeset;
11539 
11540 		if (modereset_required(new_crtc_state))
11541 			goto skip_modeset;
11542 
11543 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11544 				     dm_old_crtc_state->stream)) {
11545 
11546 			WARN_ON(dm_new_crtc_state->stream);
11547 
11548 			ret = dm_atomic_get_state(state, &dm_state);
11549 			if (ret)
11550 				goto fail;
11551 
11552 			dm_new_crtc_state->stream = new_stream;
11553 
11554 			dc_stream_retain(new_stream);
11555 
11556 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11557 					 crtc->base.id);
11558 
11559 			if (dc_state_add_stream(
11560 					dm->dc,
11561 					dm_state->context,
11562 					dm_new_crtc_state->stream) != DC_OK) {
11563 				ret = -EINVAL;
11564 				goto fail;
11565 			}
11566 
11567 			*lock_and_validation_needed = true;
11568 		}
11569 	}
11570 
11571 skip_modeset:
11572 	/* Release extra reference */
11573 	if (new_stream)
11574 		dc_stream_release(new_stream);
11575 
11576 	/*
11577 	 * We want to do dc stream updates that do not require a
11578 	 * full modeset below.
11579 	 */
11580 	if (!(enable && connector && new_crtc_state->active))
11581 		return 0;
11582 	/*
11583 	 * Given above conditions, the dc state cannot be NULL because:
11584 	 * 1. We're in the process of enabling CRTCs (just been added
11585 	 *    to the dc context, or already is on the context)
11586 	 * 2. Has a valid connector attached, and
11587 	 * 3. Is currently active and enabled.
11588 	 * => The dc stream state currently exists.
11589 	 */
11590 	BUG_ON(dm_new_crtc_state->stream == NULL);
11591 
11592 	/* Scaling or underscan settings */
11593 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11594 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11595 		update_stream_scaling_settings(adev_to_drm(adev),
11596 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11597 
11598 	/* ABM settings */
11599 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11600 
11601 	/*
11602 	 * Color management settings. We also update color properties
11603 	 * when a modeset is needed, to ensure it gets reprogrammed.
11604 	 */
11605 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11606 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11607 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11608 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11609 		if (ret)
11610 			goto fail;
11611 	}
11612 
11613 	/* Update Freesync settings. */
11614 	get_freesync_config_for_crtc(dm_new_crtc_state,
11615 				     dm_new_conn_state);
11616 
11617 	return ret;
11618 
11619 fail:
11620 	if (new_stream)
11621 		dc_stream_release(new_stream);
11622 	return ret;
11623 }
11624 
11625 static bool should_reset_plane(struct drm_atomic_state *state,
11626 			       struct drm_plane *plane,
11627 			       struct drm_plane_state *old_plane_state,
11628 			       struct drm_plane_state *new_plane_state)
11629 {
11630 	struct drm_plane *other;
11631 	struct drm_plane_state *old_other_state, *new_other_state;
11632 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11633 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11634 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11635 	struct drm_connector_state *new_con_state;
11636 	struct drm_connector *connector;
11637 	int i;
11638 
11639 	/*
11640 	 * TODO: Remove this hack for all asics once it proves that the
11641 	 * fast updates works fine on DCN3.2+.
11642 	 */
11643 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11644 	    state->allow_modeset)
11645 		return true;
11646 
11647 	/* Check for writeback commit */
11648 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11649 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11650 			continue;
11651 
11652 		if (new_con_state->writeback_job)
11653 			return true;
11654 	}
11655 
11656 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11657 		return true;
11658 
11659 	/* Exit early if we know that we're adding or removing the plane. */
11660 	if (old_plane_state->crtc != new_plane_state->crtc)
11661 		return true;
11662 
11663 	/* old crtc == new_crtc == NULL, plane not in context. */
11664 	if (!new_plane_state->crtc)
11665 		return false;
11666 
11667 	new_crtc_state =
11668 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11669 	old_crtc_state =
11670 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11671 
11672 	if (!new_crtc_state)
11673 		return true;
11674 
11675 	/*
11676 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11677 	 * released from the state
11678 	 */
11679 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11680 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11681 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11682 	    old_dm_crtc_state != NULL &&
11683 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11684 		return true;
11685 	}
11686 
11687 	/* CRTC Degamma changes currently require us to recreate planes. */
11688 	if (new_crtc_state->color_mgmt_changed)
11689 		return true;
11690 
11691 	/*
11692 	 * On zpos change, planes need to be reordered by removing and re-adding
11693 	 * them one by one to the dc state, in order of descending zpos.
11694 	 *
11695 	 * TODO: We can likely skip bandwidth validation if the only thing that
11696 	 * changed about the plane was it'z z-ordering.
11697 	 */
11698 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11699 		return true;
11700 
11701 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11702 		return true;
11703 
11704 	/*
11705 	 * If there are any new primary or overlay planes being added or
11706 	 * removed then the z-order can potentially change. To ensure
11707 	 * correct z-order and pipe acquisition the current DC architecture
11708 	 * requires us to remove and recreate all existing planes.
11709 	 *
11710 	 * TODO: Come up with a more elegant solution for this.
11711 	 */
11712 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11713 		struct amdgpu_framebuffer *old_afb, *new_afb;
11714 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11715 
11716 		dm_new_other_state = to_dm_plane_state(new_other_state);
11717 		dm_old_other_state = to_dm_plane_state(old_other_state);
11718 
11719 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11720 			continue;
11721 
11722 		if (old_other_state->crtc != new_plane_state->crtc &&
11723 		    new_other_state->crtc != new_plane_state->crtc)
11724 			continue;
11725 
11726 		if (old_other_state->crtc != new_other_state->crtc)
11727 			return true;
11728 
11729 		/* Src/dst size and scaling updates. */
11730 		if (old_other_state->src_w != new_other_state->src_w ||
11731 		    old_other_state->src_h != new_other_state->src_h ||
11732 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11733 		    old_other_state->crtc_h != new_other_state->crtc_h)
11734 			return true;
11735 
11736 		/* Rotation / mirroring updates. */
11737 		if (old_other_state->rotation != new_other_state->rotation)
11738 			return true;
11739 
11740 		/* Blending updates. */
11741 		if (old_other_state->pixel_blend_mode !=
11742 		    new_other_state->pixel_blend_mode)
11743 			return true;
11744 
11745 		/* Alpha updates. */
11746 		if (old_other_state->alpha != new_other_state->alpha)
11747 			return true;
11748 
11749 		/* Colorspace changes. */
11750 		if (old_other_state->color_range != new_other_state->color_range ||
11751 		    old_other_state->color_encoding != new_other_state->color_encoding)
11752 			return true;
11753 
11754 		/* HDR/Transfer Function changes. */
11755 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11756 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11757 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11758 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11759 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11760 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11761 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11762 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11763 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11764 			return true;
11765 
11766 		/* Framebuffer checks fall at the end. */
11767 		if (!old_other_state->fb || !new_other_state->fb)
11768 			continue;
11769 
11770 		/* Pixel format changes can require bandwidth updates. */
11771 		if (old_other_state->fb->format != new_other_state->fb->format)
11772 			return true;
11773 
11774 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11775 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11776 
11777 		/* Tiling and DCC changes also require bandwidth updates. */
11778 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11779 		    old_afb->base.modifier != new_afb->base.modifier)
11780 			return true;
11781 	}
11782 
11783 	return false;
11784 }
11785 
11786 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11787 			      struct drm_plane_state *new_plane_state,
11788 			      struct drm_framebuffer *fb)
11789 {
11790 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11791 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11792 	unsigned int pitch;
11793 	bool linear;
11794 
11795 	if (fb->width > new_acrtc->max_cursor_width ||
11796 	    fb->height > new_acrtc->max_cursor_height) {
11797 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
11798 				 new_plane_state->fb->width,
11799 				 new_plane_state->fb->height);
11800 		return -EINVAL;
11801 	}
11802 	if (new_plane_state->src_w != fb->width << 16 ||
11803 	    new_plane_state->src_h != fb->height << 16) {
11804 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
11805 		return -EINVAL;
11806 	}
11807 
11808 	/* Pitch in pixels */
11809 	pitch = fb->pitches[0] / fb->format->cpp[0];
11810 
11811 	if (fb->width != pitch) {
11812 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
11813 				 fb->width, pitch);
11814 		return -EINVAL;
11815 	}
11816 
11817 	switch (pitch) {
11818 	case 64:
11819 	case 128:
11820 	case 256:
11821 		/* FB pitch is supported by cursor plane */
11822 		break;
11823 	default:
11824 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
11825 		return -EINVAL;
11826 	}
11827 
11828 	/* Core DRM takes care of checking FB modifiers, so we only need to
11829 	 * check tiling flags when the FB doesn't have a modifier.
11830 	 */
11831 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11832 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
11833 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11834 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11835 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11836 		} else {
11837 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11838 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11839 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11840 		}
11841 		if (!linear) {
11842 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
11843 			return -EINVAL;
11844 		}
11845 	}
11846 
11847 	return 0;
11848 }
11849 
11850 /*
11851  * Helper function for checking the cursor in native mode
11852  */
11853 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11854 					struct drm_plane *plane,
11855 					struct drm_plane_state *new_plane_state,
11856 					bool enable)
11857 {
11858 
11859 	struct amdgpu_crtc *new_acrtc;
11860 	int ret;
11861 
11862 	if (!enable || !new_plane_crtc ||
11863 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11864 		return 0;
11865 
11866 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11867 
11868 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11869 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
11870 		return -EINVAL;
11871 	}
11872 
11873 	if (new_plane_state->fb) {
11874 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11875 						new_plane_state->fb);
11876 		if (ret)
11877 			return ret;
11878 	}
11879 
11880 	return 0;
11881 }
11882 
11883 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11884 					   struct drm_crtc *old_plane_crtc,
11885 					   struct drm_crtc *new_plane_crtc,
11886 					   bool enable)
11887 {
11888 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11889 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11890 
11891 	if (!enable) {
11892 		if (old_plane_crtc == NULL)
11893 			return true;
11894 
11895 		old_crtc_state = drm_atomic_get_old_crtc_state(
11896 			state, old_plane_crtc);
11897 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11898 
11899 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11900 	} else {
11901 		if (new_plane_crtc == NULL)
11902 			return true;
11903 
11904 		new_crtc_state = drm_atomic_get_new_crtc_state(
11905 			state, new_plane_crtc);
11906 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11907 
11908 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11909 	}
11910 }
11911 
11912 static int dm_update_plane_state(struct dc *dc,
11913 				 struct drm_atomic_state *state,
11914 				 struct drm_plane *plane,
11915 				 struct drm_plane_state *old_plane_state,
11916 				 struct drm_plane_state *new_plane_state,
11917 				 bool enable,
11918 				 bool *lock_and_validation_needed,
11919 				 bool *is_top_most_overlay)
11920 {
11921 
11922 	struct dm_atomic_state *dm_state = NULL;
11923 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11924 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11925 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11926 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11927 	bool needs_reset, update_native_cursor;
11928 	int ret = 0;
11929 
11930 
11931 	new_plane_crtc = new_plane_state->crtc;
11932 	old_plane_crtc = old_plane_state->crtc;
11933 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11934 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11935 
11936 	update_native_cursor = dm_should_update_native_cursor(state,
11937 							      old_plane_crtc,
11938 							      new_plane_crtc,
11939 							      enable);
11940 
11941 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11942 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11943 						    new_plane_state, enable);
11944 		if (ret)
11945 			return ret;
11946 
11947 		return 0;
11948 	}
11949 
11950 	needs_reset = should_reset_plane(state, plane, old_plane_state,
11951 					 new_plane_state);
11952 
11953 	/* Remove any changed/removed planes */
11954 	if (!enable) {
11955 		if (!needs_reset)
11956 			return 0;
11957 
11958 		if (!old_plane_crtc)
11959 			return 0;
11960 
11961 		old_crtc_state = drm_atomic_get_old_crtc_state(
11962 				state, old_plane_crtc);
11963 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11964 
11965 		if (!dm_old_crtc_state->stream)
11966 			return 0;
11967 
11968 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
11969 				plane->base.id, old_plane_crtc->base.id);
11970 
11971 		ret = dm_atomic_get_state(state, &dm_state);
11972 		if (ret)
11973 			return ret;
11974 
11975 		if (!dc_state_remove_plane(
11976 				dc,
11977 				dm_old_crtc_state->stream,
11978 				dm_old_plane_state->dc_state,
11979 				dm_state->context)) {
11980 
11981 			return -EINVAL;
11982 		}
11983 
11984 		if (dm_old_plane_state->dc_state)
11985 			dc_plane_state_release(dm_old_plane_state->dc_state);
11986 
11987 		dm_new_plane_state->dc_state = NULL;
11988 
11989 		*lock_and_validation_needed = true;
11990 
11991 	} else { /* Add new planes */
11992 		struct dc_plane_state *dc_new_plane_state;
11993 
11994 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
11995 			return 0;
11996 
11997 		if (!new_plane_crtc)
11998 			return 0;
11999 
12000 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12001 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12002 
12003 		if (!dm_new_crtc_state->stream)
12004 			return 0;
12005 
12006 		if (!needs_reset)
12007 			return 0;
12008 
12009 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12010 		if (ret)
12011 			goto out;
12012 
12013 		WARN_ON(dm_new_plane_state->dc_state);
12014 
12015 		dc_new_plane_state = dc_create_plane_state(dc);
12016 		if (!dc_new_plane_state) {
12017 			ret = -ENOMEM;
12018 			goto out;
12019 		}
12020 
12021 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12022 				 plane->base.id, new_plane_crtc->base.id);
12023 
12024 		ret = fill_dc_plane_attributes(
12025 			drm_to_adev(new_plane_crtc->dev),
12026 			dc_new_plane_state,
12027 			new_plane_state,
12028 			new_crtc_state);
12029 		if (ret) {
12030 			dc_plane_state_release(dc_new_plane_state);
12031 			goto out;
12032 		}
12033 
12034 		ret = dm_atomic_get_state(state, &dm_state);
12035 		if (ret) {
12036 			dc_plane_state_release(dc_new_plane_state);
12037 			goto out;
12038 		}
12039 
12040 		/*
12041 		 * Any atomic check errors that occur after this will
12042 		 * not need a release. The plane state will be attached
12043 		 * to the stream, and therefore part of the atomic
12044 		 * state. It'll be released when the atomic state is
12045 		 * cleaned.
12046 		 */
12047 		if (!dc_state_add_plane(
12048 				dc,
12049 				dm_new_crtc_state->stream,
12050 				dc_new_plane_state,
12051 				dm_state->context)) {
12052 
12053 			dc_plane_state_release(dc_new_plane_state);
12054 			ret = -EINVAL;
12055 			goto out;
12056 		}
12057 
12058 		dm_new_plane_state->dc_state = dc_new_plane_state;
12059 
12060 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12061 
12062 		/* Tell DC to do a full surface update every time there
12063 		 * is a plane change. Inefficient, but works for now.
12064 		 */
12065 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12066 
12067 		*lock_and_validation_needed = true;
12068 	}
12069 
12070 out:
12071 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12072 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12073 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12074 						    new_plane_state, enable);
12075 		if (ret)
12076 			return ret;
12077 
12078 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12079 	}
12080 
12081 	return ret;
12082 }
12083 
12084 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12085 				       int *src_w, int *src_h)
12086 {
12087 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12088 	case DRM_MODE_ROTATE_90:
12089 	case DRM_MODE_ROTATE_270:
12090 		*src_w = plane_state->src_h >> 16;
12091 		*src_h = plane_state->src_w >> 16;
12092 		break;
12093 	case DRM_MODE_ROTATE_0:
12094 	case DRM_MODE_ROTATE_180:
12095 	default:
12096 		*src_w = plane_state->src_w >> 16;
12097 		*src_h = plane_state->src_h >> 16;
12098 		break;
12099 	}
12100 }
12101 
12102 static void
12103 dm_get_plane_scale(struct drm_plane_state *plane_state,
12104 		   int *out_plane_scale_w, int *out_plane_scale_h)
12105 {
12106 	int plane_src_w, plane_src_h;
12107 
12108 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12109 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12110 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12111 }
12112 
12113 /*
12114  * The normalized_zpos value cannot be used by this iterator directly. It's only
12115  * calculated for enabled planes, potentially causing normalized_zpos collisions
12116  * between enabled/disabled planes in the atomic state. We need a unique value
12117  * so that the iterator will not generate the same object twice, or loop
12118  * indefinitely.
12119  */
12120 static inline struct __drm_planes_state *__get_next_zpos(
12121 	struct drm_atomic_state *state,
12122 	struct __drm_planes_state *prev)
12123 {
12124 	unsigned int highest_zpos = 0, prev_zpos = 256;
12125 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12126 	struct drm_plane_state *new_plane_state;
12127 	struct drm_plane *plane;
12128 	int i, highest_i = -1;
12129 
12130 	if (prev != NULL) {
12131 		prev_zpos = prev->new_state->zpos;
12132 		prev_id = prev->ptr->base.id;
12133 	}
12134 
12135 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12136 		/* Skip planes with higher zpos than the previously returned */
12137 		if (new_plane_state->zpos > prev_zpos ||
12138 		    (new_plane_state->zpos == prev_zpos &&
12139 		     plane->base.id >= prev_id))
12140 			continue;
12141 
12142 		/* Save the index of the plane with highest zpos */
12143 		if (new_plane_state->zpos > highest_zpos ||
12144 		    (new_plane_state->zpos == highest_zpos &&
12145 		     plane->base.id > highest_id)) {
12146 			highest_zpos = new_plane_state->zpos;
12147 			highest_id = plane->base.id;
12148 			highest_i = i;
12149 		}
12150 	}
12151 
12152 	if (highest_i < 0)
12153 		return NULL;
12154 
12155 	return &state->planes[highest_i];
12156 }
12157 
12158 /*
12159  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12160  * by descending zpos, as read from the new plane state. This is the same
12161  * ordering as defined by drm_atomic_normalize_zpos().
12162  */
12163 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12164 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12165 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12166 		for_each_if(((plane) = __i->ptr,				\
12167 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12168 			     (old_plane_state) = __i->old_state,		\
12169 			     (new_plane_state) = __i->new_state, 1))
12170 
12171 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12172 {
12173 	struct drm_connector *connector;
12174 	struct drm_connector_state *conn_state, *old_conn_state;
12175 	struct amdgpu_dm_connector *aconnector = NULL;
12176 	int i;
12177 
12178 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12179 		if (!conn_state->crtc)
12180 			conn_state = old_conn_state;
12181 
12182 		if (conn_state->crtc != crtc)
12183 			continue;
12184 
12185 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12186 			continue;
12187 
12188 		aconnector = to_amdgpu_dm_connector(connector);
12189 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12190 			aconnector = NULL;
12191 		else
12192 			break;
12193 	}
12194 
12195 	if (!aconnector)
12196 		return 0;
12197 
12198 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12199 }
12200 
12201 /**
12202  * DOC: Cursor Modes - Native vs Overlay
12203  *
12204  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12205  * plane. It does not require a dedicated hw plane to enable, but it is
12206  * subjected to the same z-order and scaling as the hw plane. It also has format
12207  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12208  * hw plane.
12209  *
12210  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12211  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12212  * cursor behavior more akin to a DRM client's expectations. However, it does
12213  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12214  * available.
12215  */
12216 
12217 /**
12218  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12219  * @adev: amdgpu device
12220  * @state: DRM atomic state
12221  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12222  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12223  *
12224  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12225  * the dm_crtc_state.
12226  *
12227  * The cursor should be enabled in overlay mode if there exists an underlying
12228  * plane - on which the cursor may be blended - that is either YUV formatted, or
12229  * scaled differently from the cursor.
12230  *
12231  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12232  * calling this function.
12233  *
12234  * Return: 0 on success, or an error code if getting the cursor plane state
12235  * failed.
12236  */
12237 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12238 				   struct drm_atomic_state *state,
12239 				   struct dm_crtc_state *dm_crtc_state,
12240 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12241 {
12242 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12243 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12244 	struct drm_plane *plane;
12245 	bool consider_mode_change = false;
12246 	bool entire_crtc_covered = false;
12247 	bool cursor_changed = false;
12248 	int underlying_scale_w, underlying_scale_h;
12249 	int cursor_scale_w, cursor_scale_h;
12250 	int i;
12251 
12252 	/* Overlay cursor not supported on HW before DCN
12253 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12254 	 * as previous DCN generations, so enable native mode on DCN401/420
12255 	 */
12256 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12257 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0)) {
12258 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12259 		return 0;
12260 	}
12261 
12262 	/* Init cursor_mode to be the same as current */
12263 	*cursor_mode = dm_crtc_state->cursor_mode;
12264 
12265 	/*
12266 	 * Cursor mode can change if a plane's format changes, scale changes, is
12267 	 * enabled/disabled, or z-order changes.
12268 	 */
12269 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12270 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12271 
12272 		/* Only care about planes on this CRTC */
12273 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12274 			continue;
12275 
12276 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12277 			cursor_changed = true;
12278 
12279 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12280 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12281 		    old_plane_state->fb->format != plane_state->fb->format) {
12282 			consider_mode_change = true;
12283 			break;
12284 		}
12285 
12286 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12287 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12288 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12289 			consider_mode_change = true;
12290 			break;
12291 		}
12292 	}
12293 
12294 	if (!consider_mode_change && !crtc_state->zpos_changed)
12295 		return 0;
12296 
12297 	/*
12298 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12299 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12300 	 * state.
12301 	 */
12302 	if (!cursor_changed &&
12303 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12304 		return 0;
12305 	}
12306 
12307 	cursor_state = drm_atomic_get_plane_state(state,
12308 						  crtc_state->crtc->cursor);
12309 	if (IS_ERR(cursor_state))
12310 		return PTR_ERR(cursor_state);
12311 
12312 	/* Cursor is disabled */
12313 	if (!cursor_state->fb)
12314 		return 0;
12315 
12316 	/* For all planes in descending z-order (all of which are below cursor
12317 	 * as per zpos definitions), check their scaling and format
12318 	 */
12319 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12320 
12321 		/* Only care about non-cursor planes on this CRTC */
12322 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12323 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12324 			continue;
12325 
12326 		/* Underlying plane is YUV format - use overlay cursor */
12327 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12328 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12329 			return 0;
12330 		}
12331 
12332 		dm_get_plane_scale(plane_state,
12333 				   &underlying_scale_w, &underlying_scale_h);
12334 		dm_get_plane_scale(cursor_state,
12335 				   &cursor_scale_w, &cursor_scale_h);
12336 
12337 		/* Underlying plane has different scale - use overlay cursor */
12338 		if (cursor_scale_w != underlying_scale_w &&
12339 		    cursor_scale_h != underlying_scale_h) {
12340 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12341 			return 0;
12342 		}
12343 
12344 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12345 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12346 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12347 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12348 			entire_crtc_covered = true;
12349 			break;
12350 		}
12351 	}
12352 
12353 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12354 	 * cursor over holes
12355 	 */
12356 	if (entire_crtc_covered)
12357 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12358 	else
12359 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12360 
12361 	return 0;
12362 }
12363 
12364 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12365 					    struct drm_atomic_state *state,
12366 					    struct drm_crtc_state *crtc_state)
12367 {
12368 	struct drm_plane *plane;
12369 	struct drm_plane_state *new_plane_state, *old_plane_state;
12370 
12371 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12372 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12373 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12374 
12375 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12376 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12377 			return false;
12378 		}
12379 
12380 		if (old_plane_state->fb && new_plane_state->fb &&
12381 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12382 			return true;
12383 	}
12384 
12385 	return false;
12386 }
12387 
12388 /**
12389  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12390  *
12391  * @dev: The DRM device
12392  * @state: The atomic state to commit
12393  *
12394  * Validate that the given atomic state is programmable by DC into hardware.
12395  * This involves constructing a &struct dc_state reflecting the new hardware
12396  * state we wish to commit, then querying DC to see if it is programmable. It's
12397  * important not to modify the existing DC state. Otherwise, atomic_check
12398  * may unexpectedly commit hardware changes.
12399  *
12400  * When validating the DC state, it's important that the right locks are
12401  * acquired. For full updates case which removes/adds/updates streams on one
12402  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12403  * that any such full update commit will wait for completion of any outstanding
12404  * flip using DRMs synchronization events.
12405  *
12406  * Note that DM adds the affected connectors for all CRTCs in state, when that
12407  * might not seem necessary. This is because DC stream creation requires the
12408  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12409  * be possible but non-trivial - a possible TODO item.
12410  *
12411  * Return: -Error code if validation failed.
12412  */
12413 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12414 				  struct drm_atomic_state *state)
12415 {
12416 	struct amdgpu_device *adev = drm_to_adev(dev);
12417 	struct dm_atomic_state *dm_state = NULL;
12418 	struct dc *dc = adev->dm.dc;
12419 	struct drm_connector *connector;
12420 	struct drm_connector_state *old_con_state, *new_con_state;
12421 	struct drm_crtc *crtc;
12422 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12423 	struct drm_plane *plane;
12424 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12425 	enum dc_status status;
12426 	int ret, i;
12427 	bool lock_and_validation_needed = false;
12428 	bool is_top_most_overlay = true;
12429 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12430 	struct drm_dp_mst_topology_mgr *mgr;
12431 	struct drm_dp_mst_topology_state *mst_state;
12432 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12433 
12434 	trace_amdgpu_dm_atomic_check_begin(state);
12435 
12436 	ret = drm_atomic_helper_check_modeset(dev, state);
12437 	if (ret) {
12438 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12439 		goto fail;
12440 	}
12441 
12442 	/* Check connector changes */
12443 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12444 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12445 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12446 
12447 		/* Skip connectors that are disabled or part of modeset already. */
12448 		if (!new_con_state->crtc)
12449 			continue;
12450 
12451 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12452 		if (IS_ERR(new_crtc_state)) {
12453 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12454 			ret = PTR_ERR(new_crtc_state);
12455 			goto fail;
12456 		}
12457 
12458 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12459 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12460 			new_crtc_state->connectors_changed = true;
12461 	}
12462 
12463 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12464 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12465 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12466 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12467 				if (ret) {
12468 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12469 					goto fail;
12470 				}
12471 			}
12472 		}
12473 	}
12474 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12475 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12476 
12477 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12478 		    !new_crtc_state->color_mgmt_changed &&
12479 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12480 			dm_old_crtc_state->dsc_force_changed == false)
12481 			continue;
12482 
12483 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12484 		if (ret) {
12485 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12486 			goto fail;
12487 		}
12488 
12489 		if (!new_crtc_state->enable)
12490 			continue;
12491 
12492 		ret = drm_atomic_add_affected_connectors(state, crtc);
12493 		if (ret) {
12494 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12495 			goto fail;
12496 		}
12497 
12498 		ret = drm_atomic_add_affected_planes(state, crtc);
12499 		if (ret) {
12500 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12501 			goto fail;
12502 		}
12503 
12504 		if (dm_old_crtc_state->dsc_force_changed)
12505 			new_crtc_state->mode_changed = true;
12506 	}
12507 
12508 	/*
12509 	 * Add all primary and overlay planes on the CRTC to the state
12510 	 * whenever a plane is enabled to maintain correct z-ordering
12511 	 * and to enable fast surface updates.
12512 	 */
12513 	drm_for_each_crtc(crtc, dev) {
12514 		bool modified = false;
12515 
12516 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12517 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12518 				continue;
12519 
12520 			if (new_plane_state->crtc == crtc ||
12521 			    old_plane_state->crtc == crtc) {
12522 				modified = true;
12523 				break;
12524 			}
12525 		}
12526 
12527 		if (!modified)
12528 			continue;
12529 
12530 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12531 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12532 				continue;
12533 
12534 			new_plane_state =
12535 				drm_atomic_get_plane_state(state, plane);
12536 
12537 			if (IS_ERR(new_plane_state)) {
12538 				ret = PTR_ERR(new_plane_state);
12539 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12540 				goto fail;
12541 			}
12542 		}
12543 	}
12544 
12545 	/*
12546 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12547 	 * hw plane on which to enable the hw cursor (see
12548 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12549 	 * atomic state, so call drm helper to normalize zpos.
12550 	 */
12551 	ret = drm_atomic_normalize_zpos(dev, state);
12552 	if (ret) {
12553 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12554 		goto fail;
12555 	}
12556 
12557 	/*
12558 	 * Determine whether cursors on each CRTC should be enabled in native or
12559 	 * overlay mode.
12560 	 */
12561 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12562 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12563 
12564 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12565 					      &dm_new_crtc_state->cursor_mode);
12566 		if (ret) {
12567 			drm_dbg(dev, "Failed to determine cursor mode\n");
12568 			goto fail;
12569 		}
12570 
12571 		/*
12572 		 * If overlay cursor is needed, DC cannot go through the
12573 		 * native cursor update path. All enabled planes on the CRTC
12574 		 * need to be added for DC to not disable a plane by mistake
12575 		 */
12576 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12577 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
12578 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
12579 				ret = -EINVAL;
12580 				goto fail;
12581 			}
12582 
12583 			ret = drm_atomic_add_affected_planes(state, crtc);
12584 			if (ret)
12585 				goto fail;
12586 		}
12587 	}
12588 
12589 	/* Remove exiting planes if they are modified */
12590 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12591 
12592 		ret = dm_update_plane_state(dc, state, plane,
12593 					    old_plane_state,
12594 					    new_plane_state,
12595 					    false,
12596 					    &lock_and_validation_needed,
12597 					    &is_top_most_overlay);
12598 		if (ret) {
12599 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12600 			goto fail;
12601 		}
12602 	}
12603 
12604 	/* Disable all crtcs which require disable */
12605 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12606 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12607 					   old_crtc_state,
12608 					   new_crtc_state,
12609 					   false,
12610 					   &lock_and_validation_needed);
12611 		if (ret) {
12612 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12613 			goto fail;
12614 		}
12615 	}
12616 
12617 	/* Enable all crtcs which require enable */
12618 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12619 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12620 					   old_crtc_state,
12621 					   new_crtc_state,
12622 					   true,
12623 					   &lock_and_validation_needed);
12624 		if (ret) {
12625 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12626 			goto fail;
12627 		}
12628 	}
12629 
12630 	/* Add new/modified planes */
12631 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12632 		ret = dm_update_plane_state(dc, state, plane,
12633 					    old_plane_state,
12634 					    new_plane_state,
12635 					    true,
12636 					    &lock_and_validation_needed,
12637 					    &is_top_most_overlay);
12638 		if (ret) {
12639 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12640 			goto fail;
12641 		}
12642 	}
12643 
12644 #if defined(CONFIG_DRM_AMD_DC_FP)
12645 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12646 		ret = pre_validate_dsc(state, &dm_state, vars);
12647 		if (ret != 0)
12648 			goto fail;
12649 	}
12650 #endif
12651 
12652 	/* Run this here since we want to validate the streams we created */
12653 	ret = drm_atomic_helper_check_planes(dev, state);
12654 	if (ret) {
12655 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12656 		goto fail;
12657 	}
12658 
12659 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12660 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12661 		if (dm_new_crtc_state->mpo_requested)
12662 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12663 	}
12664 
12665 	/* Check cursor restrictions */
12666 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12667 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12668 		int is_rotated, is_scaled;
12669 
12670 		/* Overlay cusor not subject to native cursor restrictions */
12671 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12672 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12673 			continue;
12674 
12675 		/* Check if rotation or scaling is enabled on DCN401 */
12676 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12677 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12678 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
12679 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12680 
12681 			is_rotated = new_cursor_state &&
12682 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12683 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12684 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12685 
12686 			if (is_rotated || is_scaled) {
12687 				drm_dbg_driver(
12688 					crtc->dev,
12689 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12690 					crtc->base.id, crtc->name);
12691 				ret = -EINVAL;
12692 				goto fail;
12693 			}
12694 		}
12695 
12696 		/* If HW can only do native cursor, check restrictions again */
12697 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12698 					      &required_cursor_mode);
12699 		if (ret) {
12700 			drm_dbg_driver(crtc->dev,
12701 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12702 				       crtc->base.id, crtc->name);
12703 			goto fail;
12704 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12705 			drm_dbg_driver(crtc->dev,
12706 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12707 				       crtc->base.id, crtc->name);
12708 			ret = -EINVAL;
12709 			goto fail;
12710 		}
12711 	}
12712 
12713 	if (state->legacy_cursor_update) {
12714 		/*
12715 		 * This is a fast cursor update coming from the plane update
12716 		 * helper, check if it can be done asynchronously for better
12717 		 * performance.
12718 		 */
12719 		state->async_update =
12720 			!drm_atomic_helper_async_check(dev, state);
12721 
12722 		/*
12723 		 * Skip the remaining global validation if this is an async
12724 		 * update. Cursor updates can be done without affecting
12725 		 * state or bandwidth calcs and this avoids the performance
12726 		 * penalty of locking the private state object and
12727 		 * allocating a new dc_state.
12728 		 */
12729 		if (state->async_update)
12730 			return 0;
12731 	}
12732 
12733 	/* Check scaling and underscan changes*/
12734 	/* TODO Removed scaling changes validation due to inability to commit
12735 	 * new stream into context w\o causing full reset. Need to
12736 	 * decide how to handle.
12737 	 */
12738 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12739 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12740 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12741 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12742 
12743 		/* Skip any modesets/resets */
12744 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12745 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12746 			continue;
12747 
12748 		/* Skip any thing not scale or underscan changes */
12749 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12750 			continue;
12751 
12752 		lock_and_validation_needed = true;
12753 	}
12754 
12755 	/* set the slot info for each mst_state based on the link encoding format */
12756 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12757 		struct amdgpu_dm_connector *aconnector;
12758 		struct drm_connector *connector;
12759 		struct drm_connector_list_iter iter;
12760 		u8 link_coding_cap;
12761 
12762 		drm_connector_list_iter_begin(dev, &iter);
12763 		drm_for_each_connector_iter(connector, &iter) {
12764 			if (connector->index == mst_state->mgr->conn_base_id) {
12765 				aconnector = to_amdgpu_dm_connector(connector);
12766 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12767 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12768 
12769 				break;
12770 			}
12771 		}
12772 		drm_connector_list_iter_end(&iter);
12773 	}
12774 
12775 	/**
12776 	 * Streams and planes are reset when there are changes that affect
12777 	 * bandwidth. Anything that affects bandwidth needs to go through
12778 	 * DC global validation to ensure that the configuration can be applied
12779 	 * to hardware.
12780 	 *
12781 	 * We have to currently stall out here in atomic_check for outstanding
12782 	 * commits to finish in this case because our IRQ handlers reference
12783 	 * DRM state directly - we can end up disabling interrupts too early
12784 	 * if we don't.
12785 	 *
12786 	 * TODO: Remove this stall and drop DM state private objects.
12787 	 */
12788 	if (lock_and_validation_needed) {
12789 		ret = dm_atomic_get_state(state, &dm_state);
12790 		if (ret) {
12791 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12792 			goto fail;
12793 		}
12794 
12795 		ret = do_aquire_global_lock(dev, state);
12796 		if (ret) {
12797 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12798 			goto fail;
12799 		}
12800 
12801 #if defined(CONFIG_DRM_AMD_DC_FP)
12802 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12803 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12804 			if (ret) {
12805 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12806 				ret = -EINVAL;
12807 				goto fail;
12808 			}
12809 		}
12810 #endif
12811 
12812 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12813 		if (ret) {
12814 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12815 			goto fail;
12816 		}
12817 
12818 		/*
12819 		 * Perform validation of MST topology in the state:
12820 		 * We need to perform MST atomic check before calling
12821 		 * dc_validate_global_state(), or there is a chance
12822 		 * to get stuck in an infinite loop and hang eventually.
12823 		 */
12824 		ret = drm_dp_mst_atomic_check(state);
12825 		if (ret) {
12826 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12827 			goto fail;
12828 		}
12829 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12830 		if (status != DC_OK) {
12831 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12832 				       dc_status_to_str(status), status);
12833 			ret = -EINVAL;
12834 			goto fail;
12835 		}
12836 	} else {
12837 		/*
12838 		 * The commit is a fast update. Fast updates shouldn't change
12839 		 * the DC context, affect global validation, and can have their
12840 		 * commit work done in parallel with other commits not touching
12841 		 * the same resource. If we have a new DC context as part of
12842 		 * the DM atomic state from validation we need to free it and
12843 		 * retain the existing one instead.
12844 		 *
12845 		 * Furthermore, since the DM atomic state only contains the DC
12846 		 * context and can safely be annulled, we can free the state
12847 		 * and clear the associated private object now to free
12848 		 * some memory and avoid a possible use-after-free later.
12849 		 */
12850 
12851 		for (i = 0; i < state->num_private_objs; i++) {
12852 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12853 
12854 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12855 				int j = state->num_private_objs-1;
12856 
12857 				dm_atomic_destroy_state(obj,
12858 						state->private_objs[i].state_to_destroy);
12859 
12860 				/* If i is not at the end of the array then the
12861 				 * last element needs to be moved to where i was
12862 				 * before the array can safely be truncated.
12863 				 */
12864 				if (i != j)
12865 					state->private_objs[i] =
12866 						state->private_objs[j];
12867 
12868 				state->private_objs[j].ptr = NULL;
12869 				state->private_objs[j].state_to_destroy = NULL;
12870 				state->private_objs[j].old_state = NULL;
12871 				state->private_objs[j].new_state = NULL;
12872 
12873 				state->num_private_objs = j;
12874 				break;
12875 			}
12876 		}
12877 	}
12878 
12879 	/* Store the overall update type for use later in atomic check. */
12880 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12881 		struct dm_crtc_state *dm_new_crtc_state =
12882 			to_dm_crtc_state(new_crtc_state);
12883 
12884 		/*
12885 		 * Only allow async flips for fast updates that don't change
12886 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12887 		 */
12888 		if (new_crtc_state->async_flip &&
12889 		    (lock_and_validation_needed ||
12890 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12891 			drm_dbg_atomic(crtc->dev,
12892 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12893 				       crtc->base.id, crtc->name);
12894 			ret = -EINVAL;
12895 			goto fail;
12896 		}
12897 
12898 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12899 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12900 	}
12901 
12902 	/* Must be success */
12903 	WARN_ON(ret);
12904 
12905 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12906 
12907 	return ret;
12908 
12909 fail:
12910 	if (ret == -EDEADLK)
12911 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12912 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12913 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12914 	else
12915 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12916 
12917 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12918 
12919 	return ret;
12920 }
12921 
12922 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12923 		unsigned int offset,
12924 		unsigned int total_length,
12925 		u8 *data,
12926 		unsigned int length,
12927 		struct amdgpu_hdmi_vsdb_info *vsdb)
12928 {
12929 	bool res;
12930 	union dmub_rb_cmd cmd;
12931 	struct dmub_cmd_send_edid_cea *input;
12932 	struct dmub_cmd_edid_cea_output *output;
12933 
12934 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12935 		return false;
12936 
12937 	memset(&cmd, 0, sizeof(cmd));
12938 
12939 	input = &cmd.edid_cea.data.input;
12940 
12941 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12942 	cmd.edid_cea.header.sub_type = 0;
12943 	cmd.edid_cea.header.payload_bytes =
12944 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12945 	input->offset = offset;
12946 	input->length = length;
12947 	input->cea_total_length = total_length;
12948 	memcpy(input->payload, data, length);
12949 
12950 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12951 	if (!res) {
12952 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
12953 		return false;
12954 	}
12955 
12956 	output = &cmd.edid_cea.data.output;
12957 
12958 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
12959 		if (!output->ack.success) {
12960 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
12961 					output->ack.offset);
12962 		}
12963 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
12964 		if (!output->amd_vsdb.vsdb_found)
12965 			return false;
12966 
12967 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
12968 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
12969 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
12970 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
12971 	} else {
12972 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
12973 		return false;
12974 	}
12975 
12976 	return true;
12977 }
12978 
12979 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
12980 		u8 *edid_ext, int len,
12981 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12982 {
12983 	int i;
12984 
12985 	/* send extension block to DMCU for parsing */
12986 	for (i = 0; i < len; i += 8) {
12987 		bool res;
12988 		int offset;
12989 
12990 		/* send 8 bytes a time */
12991 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
12992 			return false;
12993 
12994 		if (i+8 == len) {
12995 			/* EDID block sent completed, expect result */
12996 			int version, min_rate, max_rate;
12997 
12998 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
12999 			if (res) {
13000 				/* amd vsdb found */
13001 				vsdb_info->freesync_supported = 1;
13002 				vsdb_info->amd_vsdb_version = version;
13003 				vsdb_info->min_refresh_rate_hz = min_rate;
13004 				vsdb_info->max_refresh_rate_hz = max_rate;
13005 				return true;
13006 			}
13007 			/* not amd vsdb */
13008 			return false;
13009 		}
13010 
13011 		/* check for ack*/
13012 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13013 		if (!res)
13014 			return false;
13015 	}
13016 
13017 	return false;
13018 }
13019 
13020 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13021 		u8 *edid_ext, int len,
13022 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13023 {
13024 	int i;
13025 
13026 	/* send extension block to DMCU for parsing */
13027 	for (i = 0; i < len; i += 8) {
13028 		/* send 8 bytes a time */
13029 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13030 			return false;
13031 	}
13032 
13033 	return vsdb_info->freesync_supported;
13034 }
13035 
13036 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13037 		u8 *edid_ext, int len,
13038 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13039 {
13040 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13041 	bool ret;
13042 
13043 	mutex_lock(&adev->dm.dc_lock);
13044 	if (adev->dm.dmub_srv)
13045 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13046 	else
13047 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13048 	mutex_unlock(&adev->dm.dc_lock);
13049 	return ret;
13050 }
13051 
13052 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13053 				     const struct edid *edid)
13054 {
13055 	u8 *edid_ext = NULL;
13056 	int i;
13057 	int j = 0;
13058 	u16 min_vfreq;
13059 	u16 max_vfreq;
13060 
13061 	if (edid == NULL || edid->extensions == 0)
13062 		return;
13063 
13064 	/* Find DisplayID extension */
13065 	for (i = 0; i < edid->extensions; i++) {
13066 		edid_ext = (void *)(edid + (i + 1));
13067 		if (edid_ext[0] == DISPLAYID_EXT)
13068 			break;
13069 	}
13070 
13071 	if (edid_ext == NULL)
13072 		return;
13073 
13074 	while (j < EDID_LENGTH) {
13075 		/* Get dynamic video timing range from DisplayID if available */
13076 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13077 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13078 			min_vfreq = edid_ext[j+9];
13079 			if (edid_ext[j+1] & 7)
13080 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13081 			else
13082 				max_vfreq = edid_ext[j+10];
13083 
13084 			if (max_vfreq && min_vfreq) {
13085 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13086 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13087 
13088 				return;
13089 			}
13090 		}
13091 		j++;
13092 	}
13093 }
13094 
13095 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13096 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
13097 {
13098 	u8 *edid_ext = NULL;
13099 	int i;
13100 	int j = 0;
13101 	int total_ext_block_len;
13102 
13103 	if (edid == NULL || edid->extensions == 0)
13104 		return -ENODEV;
13105 
13106 	/* Find DisplayID extension */
13107 	for (i = 0; i < edid->extensions; i++) {
13108 		edid_ext = (void *)(edid + (i + 1));
13109 		if (edid_ext[0] == DISPLAYID_EXT)
13110 			break;
13111 	}
13112 
13113 	total_ext_block_len = EDID_LENGTH * edid->extensions;
13114 	while (j < total_ext_block_len - sizeof(struct amd_vsdb_block)) {
13115 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
13116 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
13117 
13118 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
13119 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
13120 			u8 panel_type;
13121 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
13122 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
13123 			drm_dbg_kms(aconnector->base.dev, "Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
13124 			panel_type = (amd_vsdb->color_space_eotf_support & AMD_VDSB_VERSION_3_PANEL_TYPE_MASK) >> AMD_VDSB_VERSION_3_PANEL_TYPE_SHIFT;
13125 			switch (panel_type) {
13126 			case AMD_VSDB_PANEL_TYPE_OLED:
13127 				aconnector->dc_link->panel_type = PANEL_TYPE_OLED;
13128 				break;
13129 			case AMD_VSDB_PANEL_TYPE_MINILED:
13130 				aconnector->dc_link->panel_type = PANEL_TYPE_MINILED;
13131 				break;
13132 			default:
13133 				aconnector->dc_link->panel_type = PANEL_TYPE_NONE;
13134 				break;
13135 			}
13136 			drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n",
13137 				    aconnector->dc_link->panel_type);
13138 
13139 			return true;
13140 		}
13141 		j++;
13142 	}
13143 
13144 	return false;
13145 }
13146 
13147 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13148 			       const struct edid *edid,
13149 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13150 {
13151 	u8 *edid_ext = NULL;
13152 	int i;
13153 	bool valid_vsdb_found = false;
13154 
13155 	/*----- drm_find_cea_extension() -----*/
13156 	/* No EDID or EDID extensions */
13157 	if (edid == NULL || edid->extensions == 0)
13158 		return -ENODEV;
13159 
13160 	/* Find CEA extension */
13161 	for (i = 0; i < edid->extensions; i++) {
13162 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13163 		if (edid_ext[0] == CEA_EXT)
13164 			break;
13165 	}
13166 
13167 	if (i == edid->extensions)
13168 		return -ENODEV;
13169 
13170 	/*----- cea_db_offsets() -----*/
13171 	if (edid_ext[0] != CEA_EXT)
13172 		return -ENODEV;
13173 
13174 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13175 
13176 	return valid_vsdb_found ? i : -ENODEV;
13177 }
13178 
13179 /**
13180  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13181  *
13182  * @connector: Connector to query.
13183  * @drm_edid: DRM EDID from monitor
13184  *
13185  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13186  * track of some of the display information in the internal data struct used by
13187  * amdgpu_dm. This function checks which type of connector we need to set the
13188  * FreeSync parameters.
13189  */
13190 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13191 				    const struct drm_edid *drm_edid)
13192 {
13193 	int i = 0;
13194 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13195 			to_amdgpu_dm_connector(connector);
13196 	struct dm_connector_state *dm_con_state = NULL;
13197 	struct dc_sink *sink;
13198 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13199 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13200 	const struct edid *edid;
13201 	bool freesync_capable = false;
13202 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13203 
13204 	if (!connector->state) {
13205 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13206 		goto update;
13207 	}
13208 
13209 	sink = amdgpu_dm_connector->dc_sink ?
13210 		amdgpu_dm_connector->dc_sink :
13211 		amdgpu_dm_connector->dc_em_sink;
13212 
13213 	drm_edid_connector_update(connector, drm_edid);
13214 
13215 	if (!drm_edid || !sink) {
13216 		dm_con_state = to_dm_connector_state(connector->state);
13217 
13218 		amdgpu_dm_connector->min_vfreq = 0;
13219 		amdgpu_dm_connector->max_vfreq = 0;
13220 		freesync_capable = false;
13221 
13222 		goto update;
13223 	}
13224 
13225 	dm_con_state = to_dm_connector_state(connector->state);
13226 
13227 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13228 		goto update;
13229 
13230 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13231 
13232 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13233 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13234 	     connector->display_info.monitor_range.max_vfreq == 0))
13235 		parse_edid_displayid_vrr(connector, edid);
13236 
13237 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13238 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13239 		if (amdgpu_dm_connector->dc_link &&
13240 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13241 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13242 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13243 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13244 				freesync_capable = true;
13245 		}
13246 
13247 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13248 
13249 		if (vsdb_info.replay_mode) {
13250 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13251 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13252 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13253 		}
13254 
13255 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13256 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13257 		if (i >= 0 && vsdb_info.freesync_supported) {
13258 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13259 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13260 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13261 				freesync_capable = true;
13262 
13263 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13264 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13265 		}
13266 	}
13267 
13268 	if (amdgpu_dm_connector->dc_link)
13269 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13270 
13271 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13272 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13273 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13274 
13275 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
13276 			amdgpu_dm_connector->as_type = as_type;
13277 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13278 
13279 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13280 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13281 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13282 				freesync_capable = true;
13283 
13284 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13285 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13286 		}
13287 	}
13288 
13289 update:
13290 	if (dm_con_state)
13291 		dm_con_state->freesync_capable = freesync_capable;
13292 
13293 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13294 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13295 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13296 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13297 	}
13298 
13299 	if (connector->vrr_capable_property)
13300 		drm_connector_set_vrr_capable_property(connector,
13301 						       freesync_capable);
13302 }
13303 
13304 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13305 {
13306 	struct amdgpu_device *adev = drm_to_adev(dev);
13307 	struct dc *dc = adev->dm.dc;
13308 	int i;
13309 
13310 	mutex_lock(&adev->dm.dc_lock);
13311 	if (dc->current_state) {
13312 		for (i = 0; i < dc->current_state->stream_count; ++i)
13313 			dc->current_state->streams[i]
13314 				->triggered_crtc_reset.enabled =
13315 				adev->dm.force_timing_sync;
13316 
13317 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13318 		dc_trigger_sync(dc, dc->current_state);
13319 	}
13320 	mutex_unlock(&adev->dm.dc_lock);
13321 }
13322 
13323 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13324 {
13325 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13326 		dc_exit_ips_for_hw_access(dc);
13327 }
13328 
13329 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13330 		       u32 value, const char *func_name)
13331 {
13332 #ifdef DM_CHECK_ADDR_0
13333 	if (address == 0) {
13334 		drm_err(adev_to_drm(ctx->driver_context),
13335 			"invalid register write. address = 0");
13336 		return;
13337 	}
13338 #endif
13339 
13340 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13341 	cgs_write_register(ctx->cgs_device, address, value);
13342 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13343 }
13344 
13345 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13346 			  const char *func_name)
13347 {
13348 	u32 value;
13349 #ifdef DM_CHECK_ADDR_0
13350 	if (address == 0) {
13351 		drm_err(adev_to_drm(ctx->driver_context),
13352 			"invalid register read; address = 0\n");
13353 		return 0;
13354 	}
13355 #endif
13356 
13357 	if (ctx->dmub_srv &&
13358 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13359 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13360 		ASSERT(false);
13361 		return 0;
13362 	}
13363 
13364 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13365 
13366 	value = cgs_read_register(ctx->cgs_device, address);
13367 
13368 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13369 
13370 	return value;
13371 }
13372 
13373 int amdgpu_dm_process_dmub_aux_transfer_sync(
13374 		struct dc_context *ctx,
13375 		unsigned int link_index,
13376 		struct aux_payload *payload,
13377 		enum aux_return_code_type *operation_result)
13378 {
13379 	struct amdgpu_device *adev = ctx->driver_context;
13380 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13381 	int ret = -1;
13382 
13383 	mutex_lock(&adev->dm.dpia_aux_lock);
13384 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13385 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13386 		goto out;
13387 	}
13388 
13389 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13390 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13391 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13392 		goto out;
13393 	}
13394 
13395 	if (p_notify->result != AUX_RET_SUCCESS) {
13396 		/*
13397 		 * Transient states before tunneling is enabled could
13398 		 * lead to this error. We can ignore this for now.
13399 		 */
13400 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13401 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13402 					payload->address, payload->length,
13403 					p_notify->result);
13404 		}
13405 		*operation_result = p_notify->result;
13406 		goto out;
13407 	}
13408 
13409 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13410 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13411 		/* The reply is stored in the top nibble of the command. */
13412 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13413 
13414 	/*write req may receive a byte indicating partially written number as well*/
13415 	if (p_notify->aux_reply.length)
13416 		memcpy(payload->data, p_notify->aux_reply.data,
13417 				p_notify->aux_reply.length);
13418 
13419 	/* success */
13420 	ret = p_notify->aux_reply.length;
13421 	*operation_result = p_notify->result;
13422 out:
13423 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13424 	mutex_unlock(&adev->dm.dpia_aux_lock);
13425 	return ret;
13426 }
13427 
13428 static void abort_fused_io(
13429 		struct dc_context *ctx,
13430 		const struct dmub_cmd_fused_request *request
13431 )
13432 {
13433 	union dmub_rb_cmd command = { 0 };
13434 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13435 
13436 	io->header.type = DMUB_CMD__FUSED_IO;
13437 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13438 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13439 	io->request = *request;
13440 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13441 }
13442 
13443 static bool execute_fused_io(
13444 		struct amdgpu_device *dev,
13445 		struct dc_context *ctx,
13446 		union dmub_rb_cmd *commands,
13447 		uint8_t count,
13448 		uint32_t timeout_us
13449 )
13450 {
13451 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13452 
13453 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13454 		return false;
13455 
13456 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13457 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13458 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13459 			&& first->header.ret_status
13460 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13461 
13462 	if (!result)
13463 		return false;
13464 
13465 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13466 		reinit_completion(&sync->replied);
13467 
13468 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13469 
13470 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13471 
13472 		if (reply->identifier == first->request.identifier) {
13473 			first->request = *reply;
13474 			return true;
13475 		}
13476 	}
13477 
13478 	reinit_completion(&sync->replied);
13479 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13480 	abort_fused_io(ctx, &first->request);
13481 	return false;
13482 }
13483 
13484 bool amdgpu_dm_execute_fused_io(
13485 		struct amdgpu_device *dev,
13486 		struct dc_link *link,
13487 		union dmub_rb_cmd *commands,
13488 		uint8_t count,
13489 		uint32_t timeout_us)
13490 {
13491 	struct amdgpu_display_manager *dm = &dev->dm;
13492 
13493 	mutex_lock(&dm->dpia_aux_lock);
13494 
13495 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13496 
13497 	mutex_unlock(&dm->dpia_aux_lock);
13498 	return result;
13499 }
13500 
13501 int amdgpu_dm_process_dmub_set_config_sync(
13502 		struct dc_context *ctx,
13503 		unsigned int link_index,
13504 		struct set_config_cmd_payload *payload,
13505 		enum set_config_status *operation_result)
13506 {
13507 	struct amdgpu_device *adev = ctx->driver_context;
13508 	bool is_cmd_complete;
13509 	int ret;
13510 
13511 	mutex_lock(&adev->dm.dpia_aux_lock);
13512 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13513 			link_index, payload, adev->dm.dmub_notify);
13514 
13515 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13516 		ret = 0;
13517 		*operation_result = adev->dm.dmub_notify->sc_status;
13518 	} else {
13519 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13520 		ret = -1;
13521 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13522 	}
13523 
13524 	if (!is_cmd_complete)
13525 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13526 	mutex_unlock(&adev->dm.dpia_aux_lock);
13527 	return ret;
13528 }
13529 
13530 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13531 {
13532 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13533 }
13534 
13535 bool dm_execute_dmub_cmd_list(const struct dc_context *ctx, unsigned int count, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13536 {
13537 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13538 }
13539 
13540 void dm_acpi_process_phy_transition_interlock(
13541 	const struct dc_context *ctx,
13542 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13543 {
13544 	// Not yet implemented
13545 }
13546