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