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