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