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