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