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