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