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