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