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