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