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