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