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