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