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