1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25 
26 /* The caprices of the preprocessor require that this be declared right here */
27 #define CREATE_TRACE_POINTS
28 
29 #include "dm_services_types.h"
30 #include "dc.h"
31 #include "dc_link_dp.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "amdgpu_dm_trace.h"
42 #include "dpcd_defs.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 
46 #include "vid.h"
47 #include "amdgpu.h"
48 #include "amdgpu_display.h"
49 #include "amdgpu_ucode.h"
50 #include "atom.h"
51 #include "amdgpu_dm.h"
52 #include "amdgpu_dm_plane.h"
53 #include "amdgpu_dm_crtc.h"
54 #ifdef CONFIG_DRM_AMD_DC_HDCP
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #endif
58 #include "amdgpu_pm.h"
59 #include "amdgpu_atombios.h"
60 
61 #include "amd_shared.h"
62 #include "amdgpu_dm_irq.h"
63 #include "dm_helpers.h"
64 #include "amdgpu_dm_mst_types.h"
65 #if defined(CONFIG_DEBUG_FS)
66 #include "amdgpu_dm_debugfs.h"
67 #endif
68 #include "amdgpu_dm_psr.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
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 			hpd_rx_irq_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 	/* Software is initialized. Now we can register interrupt handlers. */
4375 	switch (adev->asic_type) {
4376 #if defined(CONFIG_DRM_AMD_DC_SI)
4377 	case CHIP_TAHITI:
4378 	case CHIP_PITCAIRN:
4379 	case CHIP_VERDE:
4380 	case CHIP_OLAND:
4381 		if (dce60_register_irq_handlers(dm->adev)) {
4382 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4383 			goto fail;
4384 		}
4385 		break;
4386 #endif
4387 	case CHIP_BONAIRE:
4388 	case CHIP_HAWAII:
4389 	case CHIP_KAVERI:
4390 	case CHIP_KABINI:
4391 	case CHIP_MULLINS:
4392 	case CHIP_TONGA:
4393 	case CHIP_FIJI:
4394 	case CHIP_CARRIZO:
4395 	case CHIP_STONEY:
4396 	case CHIP_POLARIS11:
4397 	case CHIP_POLARIS10:
4398 	case CHIP_POLARIS12:
4399 	case CHIP_VEGAM:
4400 	case CHIP_VEGA10:
4401 	case CHIP_VEGA12:
4402 	case CHIP_VEGA20:
4403 		if (dce110_register_irq_handlers(dm->adev)) {
4404 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4405 			goto fail;
4406 		}
4407 		break;
4408 	default:
4409 		switch (adev->ip_versions[DCE_HWIP][0]) {
4410 		case IP_VERSION(1, 0, 0):
4411 		case IP_VERSION(1, 0, 1):
4412 		case IP_VERSION(2, 0, 2):
4413 		case IP_VERSION(2, 0, 3):
4414 		case IP_VERSION(2, 0, 0):
4415 		case IP_VERSION(2, 1, 0):
4416 		case IP_VERSION(3, 0, 0):
4417 		case IP_VERSION(3, 0, 2):
4418 		case IP_VERSION(3, 0, 3):
4419 		case IP_VERSION(3, 0, 1):
4420 		case IP_VERSION(3, 1, 2):
4421 		case IP_VERSION(3, 1, 3):
4422 		case IP_VERSION(3, 1, 4):
4423 		case IP_VERSION(3, 1, 5):
4424 		case IP_VERSION(3, 1, 6):
4425 		case IP_VERSION(3, 2, 0):
4426 		case IP_VERSION(3, 2, 1):
4427 			if (dcn10_register_irq_handlers(dm->adev)) {
4428 				DRM_ERROR("DM: Failed to initialize IRQ\n");
4429 				goto fail;
4430 			}
4431 			break;
4432 		default:
4433 			DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4434 					adev->ip_versions[DCE_HWIP][0]);
4435 			goto fail;
4436 		}
4437 		break;
4438 	}
4439 
4440 	return 0;
4441 fail:
4442 	kfree(aencoder);
4443 	kfree(aconnector);
4444 
4445 	return -EINVAL;
4446 }
4447 
4448 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4449 {
4450 	drm_atomic_private_obj_fini(&dm->atomic_obj);
4451 	return;
4452 }
4453 
4454 /******************************************************************************
4455  * amdgpu_display_funcs functions
4456  *****************************************************************************/
4457 
4458 /*
4459  * dm_bandwidth_update - program display watermarks
4460  *
4461  * @adev: amdgpu_device pointer
4462  *
4463  * Calculate and program the display watermarks and line buffer allocation.
4464  */
4465 static void dm_bandwidth_update(struct amdgpu_device *adev)
4466 {
4467 	/* TODO: implement later */
4468 }
4469 
4470 static const struct amdgpu_display_funcs dm_display_funcs = {
4471 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4472 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4473 	.backlight_set_level = NULL, /* never called for DC */
4474 	.backlight_get_level = NULL, /* never called for DC */
4475 	.hpd_sense = NULL,/* called unconditionally */
4476 	.hpd_set_polarity = NULL, /* called unconditionally */
4477 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4478 	.page_flip_get_scanoutpos =
4479 		dm_crtc_get_scanoutpos,/* called unconditionally */
4480 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4481 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
4482 };
4483 
4484 #if defined(CONFIG_DEBUG_KERNEL_DC)
4485 
4486 static ssize_t s3_debug_store(struct device *device,
4487 			      struct device_attribute *attr,
4488 			      const char *buf,
4489 			      size_t count)
4490 {
4491 	int ret;
4492 	int s3_state;
4493 	struct drm_device *drm_dev = dev_get_drvdata(device);
4494 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
4495 
4496 	ret = kstrtoint(buf, 0, &s3_state);
4497 
4498 	if (ret == 0) {
4499 		if (s3_state) {
4500 			dm_resume(adev);
4501 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
4502 		} else
4503 			dm_suspend(adev);
4504 	}
4505 
4506 	return ret == 0 ? count : 0;
4507 }
4508 
4509 DEVICE_ATTR_WO(s3_debug);
4510 
4511 #endif
4512 
4513 static int dm_init_microcode(struct amdgpu_device *adev)
4514 {
4515 	char *fw_name_dmub;
4516 	int r;
4517 
4518 	switch (adev->ip_versions[DCE_HWIP][0]) {
4519 	case IP_VERSION(2, 1, 0):
4520 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
4521 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
4522 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
4523 		break;
4524 	case IP_VERSION(3, 0, 0):
4525 		if (adev->ip_versions[GC_HWIP][0] == IP_VERSION(10, 3, 0))
4526 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
4527 		else
4528 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
4529 		break;
4530 	case IP_VERSION(3, 0, 1):
4531 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
4532 		break;
4533 	case IP_VERSION(3, 0, 2):
4534 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
4535 		break;
4536 	case IP_VERSION(3, 0, 3):
4537 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
4538 		break;
4539 	case IP_VERSION(3, 1, 2):
4540 	case IP_VERSION(3, 1, 3):
4541 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
4542 		break;
4543 	case IP_VERSION(3, 1, 4):
4544 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
4545 		break;
4546 	case IP_VERSION(3, 1, 5):
4547 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
4548 		break;
4549 	case IP_VERSION(3, 1, 6):
4550 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
4551 		break;
4552 	case IP_VERSION(3, 2, 0):
4553 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
4554 		break;
4555 	case IP_VERSION(3, 2, 1):
4556 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
4557 		break;
4558 	default:
4559 		/* ASIC doesn't support DMUB. */
4560 		return 0;
4561 	}
4562 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, fw_name_dmub);
4563 	if (r)
4564 		DRM_ERROR("DMUB firmware loading failed: %d\n", r);
4565 	return r;
4566 }
4567 
4568 static int dm_early_init(void *handle)
4569 {
4570 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4571 
4572 	switch (adev->asic_type) {
4573 #if defined(CONFIG_DRM_AMD_DC_SI)
4574 	case CHIP_TAHITI:
4575 	case CHIP_PITCAIRN:
4576 	case CHIP_VERDE:
4577 		adev->mode_info.num_crtc = 6;
4578 		adev->mode_info.num_hpd = 6;
4579 		adev->mode_info.num_dig = 6;
4580 		break;
4581 	case CHIP_OLAND:
4582 		adev->mode_info.num_crtc = 2;
4583 		adev->mode_info.num_hpd = 2;
4584 		adev->mode_info.num_dig = 2;
4585 		break;
4586 #endif
4587 	case CHIP_BONAIRE:
4588 	case CHIP_HAWAII:
4589 		adev->mode_info.num_crtc = 6;
4590 		adev->mode_info.num_hpd = 6;
4591 		adev->mode_info.num_dig = 6;
4592 		break;
4593 	case CHIP_KAVERI:
4594 		adev->mode_info.num_crtc = 4;
4595 		adev->mode_info.num_hpd = 6;
4596 		adev->mode_info.num_dig = 7;
4597 		break;
4598 	case CHIP_KABINI:
4599 	case CHIP_MULLINS:
4600 		adev->mode_info.num_crtc = 2;
4601 		adev->mode_info.num_hpd = 6;
4602 		adev->mode_info.num_dig = 6;
4603 		break;
4604 	case CHIP_FIJI:
4605 	case CHIP_TONGA:
4606 		adev->mode_info.num_crtc = 6;
4607 		adev->mode_info.num_hpd = 6;
4608 		adev->mode_info.num_dig = 7;
4609 		break;
4610 	case CHIP_CARRIZO:
4611 		adev->mode_info.num_crtc = 3;
4612 		adev->mode_info.num_hpd = 6;
4613 		adev->mode_info.num_dig = 9;
4614 		break;
4615 	case CHIP_STONEY:
4616 		adev->mode_info.num_crtc = 2;
4617 		adev->mode_info.num_hpd = 6;
4618 		adev->mode_info.num_dig = 9;
4619 		break;
4620 	case CHIP_POLARIS11:
4621 	case CHIP_POLARIS12:
4622 		adev->mode_info.num_crtc = 5;
4623 		adev->mode_info.num_hpd = 5;
4624 		adev->mode_info.num_dig = 5;
4625 		break;
4626 	case CHIP_POLARIS10:
4627 	case CHIP_VEGAM:
4628 		adev->mode_info.num_crtc = 6;
4629 		adev->mode_info.num_hpd = 6;
4630 		adev->mode_info.num_dig = 6;
4631 		break;
4632 	case CHIP_VEGA10:
4633 	case CHIP_VEGA12:
4634 	case CHIP_VEGA20:
4635 		adev->mode_info.num_crtc = 6;
4636 		adev->mode_info.num_hpd = 6;
4637 		adev->mode_info.num_dig = 6;
4638 		break;
4639 	default:
4640 
4641 		switch (adev->ip_versions[DCE_HWIP][0]) {
4642 		case IP_VERSION(2, 0, 2):
4643 		case IP_VERSION(3, 0, 0):
4644 			adev->mode_info.num_crtc = 6;
4645 			adev->mode_info.num_hpd = 6;
4646 			adev->mode_info.num_dig = 6;
4647 			break;
4648 		case IP_VERSION(2, 0, 0):
4649 		case IP_VERSION(3, 0, 2):
4650 			adev->mode_info.num_crtc = 5;
4651 			adev->mode_info.num_hpd = 5;
4652 			adev->mode_info.num_dig = 5;
4653 			break;
4654 		case IP_VERSION(2, 0, 3):
4655 		case IP_VERSION(3, 0, 3):
4656 			adev->mode_info.num_crtc = 2;
4657 			adev->mode_info.num_hpd = 2;
4658 			adev->mode_info.num_dig = 2;
4659 			break;
4660 		case IP_VERSION(1, 0, 0):
4661 		case IP_VERSION(1, 0, 1):
4662 		case IP_VERSION(3, 0, 1):
4663 		case IP_VERSION(2, 1, 0):
4664 		case IP_VERSION(3, 1, 2):
4665 		case IP_VERSION(3, 1, 3):
4666 		case IP_VERSION(3, 1, 4):
4667 		case IP_VERSION(3, 1, 5):
4668 		case IP_VERSION(3, 1, 6):
4669 		case IP_VERSION(3, 2, 0):
4670 		case IP_VERSION(3, 2, 1):
4671 			adev->mode_info.num_crtc = 4;
4672 			adev->mode_info.num_hpd = 4;
4673 			adev->mode_info.num_dig = 4;
4674 			break;
4675 		default:
4676 			DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4677 					adev->ip_versions[DCE_HWIP][0]);
4678 			return -EINVAL;
4679 		}
4680 		break;
4681 	}
4682 
4683 	amdgpu_dm_set_irq_funcs(adev);
4684 
4685 	if (adev->mode_info.funcs == NULL)
4686 		adev->mode_info.funcs = &dm_display_funcs;
4687 
4688 	/*
4689 	 * Note: Do NOT change adev->audio_endpt_rreg and
4690 	 * adev->audio_endpt_wreg because they are initialised in
4691 	 * amdgpu_device_init()
4692 	 */
4693 #if defined(CONFIG_DEBUG_KERNEL_DC)
4694 	device_create_file(
4695 		adev_to_drm(adev)->dev,
4696 		&dev_attr_s3_debug);
4697 #endif
4698 	adev->dc_enabled = true;
4699 
4700 	return dm_init_microcode(adev);
4701 }
4702 
4703 static bool modereset_required(struct drm_crtc_state *crtc_state)
4704 {
4705 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4706 }
4707 
4708 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4709 {
4710 	drm_encoder_cleanup(encoder);
4711 	kfree(encoder);
4712 }
4713 
4714 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4715 	.destroy = amdgpu_dm_encoder_destroy,
4716 };
4717 
4718 static int
4719 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4720 			    const enum surface_pixel_format format,
4721 			    enum dc_color_space *color_space)
4722 {
4723 	bool full_range;
4724 
4725 	*color_space = COLOR_SPACE_SRGB;
4726 
4727 	/* DRM color properties only affect non-RGB formats. */
4728 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4729 		return 0;
4730 
4731 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4732 
4733 	switch (plane_state->color_encoding) {
4734 	case DRM_COLOR_YCBCR_BT601:
4735 		if (full_range)
4736 			*color_space = COLOR_SPACE_YCBCR601;
4737 		else
4738 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
4739 		break;
4740 
4741 	case DRM_COLOR_YCBCR_BT709:
4742 		if (full_range)
4743 			*color_space = COLOR_SPACE_YCBCR709;
4744 		else
4745 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
4746 		break;
4747 
4748 	case DRM_COLOR_YCBCR_BT2020:
4749 		if (full_range)
4750 			*color_space = COLOR_SPACE_2020_YCBCR;
4751 		else
4752 			return -EINVAL;
4753 		break;
4754 
4755 	default:
4756 		return -EINVAL;
4757 	}
4758 
4759 	return 0;
4760 }
4761 
4762 static int
4763 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4764 			    const struct drm_plane_state *plane_state,
4765 			    const u64 tiling_flags,
4766 			    struct dc_plane_info *plane_info,
4767 			    struct dc_plane_address *address,
4768 			    bool tmz_surface,
4769 			    bool force_disable_dcc)
4770 {
4771 	const struct drm_framebuffer *fb = plane_state->fb;
4772 	const struct amdgpu_framebuffer *afb =
4773 		to_amdgpu_framebuffer(plane_state->fb);
4774 	int ret;
4775 
4776 	memset(plane_info, 0, sizeof(*plane_info));
4777 
4778 	switch (fb->format->format) {
4779 	case DRM_FORMAT_C8:
4780 		plane_info->format =
4781 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4782 		break;
4783 	case DRM_FORMAT_RGB565:
4784 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4785 		break;
4786 	case DRM_FORMAT_XRGB8888:
4787 	case DRM_FORMAT_ARGB8888:
4788 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4789 		break;
4790 	case DRM_FORMAT_XRGB2101010:
4791 	case DRM_FORMAT_ARGB2101010:
4792 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4793 		break;
4794 	case DRM_FORMAT_XBGR2101010:
4795 	case DRM_FORMAT_ABGR2101010:
4796 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4797 		break;
4798 	case DRM_FORMAT_XBGR8888:
4799 	case DRM_FORMAT_ABGR8888:
4800 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4801 		break;
4802 	case DRM_FORMAT_NV21:
4803 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4804 		break;
4805 	case DRM_FORMAT_NV12:
4806 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4807 		break;
4808 	case DRM_FORMAT_P010:
4809 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4810 		break;
4811 	case DRM_FORMAT_XRGB16161616F:
4812 	case DRM_FORMAT_ARGB16161616F:
4813 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4814 		break;
4815 	case DRM_FORMAT_XBGR16161616F:
4816 	case DRM_FORMAT_ABGR16161616F:
4817 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4818 		break;
4819 	case DRM_FORMAT_XRGB16161616:
4820 	case DRM_FORMAT_ARGB16161616:
4821 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4822 		break;
4823 	case DRM_FORMAT_XBGR16161616:
4824 	case DRM_FORMAT_ABGR16161616:
4825 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4826 		break;
4827 	default:
4828 		DRM_ERROR(
4829 			"Unsupported screen format %p4cc\n",
4830 			&fb->format->format);
4831 		return -EINVAL;
4832 	}
4833 
4834 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4835 	case DRM_MODE_ROTATE_0:
4836 		plane_info->rotation = ROTATION_ANGLE_0;
4837 		break;
4838 	case DRM_MODE_ROTATE_90:
4839 		plane_info->rotation = ROTATION_ANGLE_90;
4840 		break;
4841 	case DRM_MODE_ROTATE_180:
4842 		plane_info->rotation = ROTATION_ANGLE_180;
4843 		break;
4844 	case DRM_MODE_ROTATE_270:
4845 		plane_info->rotation = ROTATION_ANGLE_270;
4846 		break;
4847 	default:
4848 		plane_info->rotation = ROTATION_ANGLE_0;
4849 		break;
4850 	}
4851 
4852 
4853 	plane_info->visible = true;
4854 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4855 
4856 	plane_info->layer_index = plane_state->normalized_zpos;
4857 
4858 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
4859 					  &plane_info->color_space);
4860 	if (ret)
4861 		return ret;
4862 
4863 	ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4864 					   plane_info->rotation, tiling_flags,
4865 					   &plane_info->tiling_info,
4866 					   &plane_info->plane_size,
4867 					   &plane_info->dcc, address,
4868 					   tmz_surface, force_disable_dcc);
4869 	if (ret)
4870 		return ret;
4871 
4872 	fill_blending_from_plane_state(
4873 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4874 		&plane_info->global_alpha, &plane_info->global_alpha_value);
4875 
4876 	return 0;
4877 }
4878 
4879 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4880 				    struct dc_plane_state *dc_plane_state,
4881 				    struct drm_plane_state *plane_state,
4882 				    struct drm_crtc_state *crtc_state)
4883 {
4884 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4885 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4886 	struct dc_scaling_info scaling_info;
4887 	struct dc_plane_info plane_info;
4888 	int ret;
4889 	bool force_disable_dcc = false;
4890 
4891 	ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4892 	if (ret)
4893 		return ret;
4894 
4895 	dc_plane_state->src_rect = scaling_info.src_rect;
4896 	dc_plane_state->dst_rect = scaling_info.dst_rect;
4897 	dc_plane_state->clip_rect = scaling_info.clip_rect;
4898 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
4899 
4900 	force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
4901 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
4902 					  afb->tiling_flags,
4903 					  &plane_info,
4904 					  &dc_plane_state->address,
4905 					  afb->tmz_surface,
4906 					  force_disable_dcc);
4907 	if (ret)
4908 		return ret;
4909 
4910 	dc_plane_state->format = plane_info.format;
4911 	dc_plane_state->color_space = plane_info.color_space;
4912 	dc_plane_state->format = plane_info.format;
4913 	dc_plane_state->plane_size = plane_info.plane_size;
4914 	dc_plane_state->rotation = plane_info.rotation;
4915 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
4916 	dc_plane_state->stereo_format = plane_info.stereo_format;
4917 	dc_plane_state->tiling_info = plane_info.tiling_info;
4918 	dc_plane_state->visible = plane_info.visible;
4919 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
4920 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
4921 	dc_plane_state->global_alpha = plane_info.global_alpha;
4922 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
4923 	dc_plane_state->dcc = plane_info.dcc;
4924 	dc_plane_state->layer_index = plane_info.layer_index;
4925 	dc_plane_state->flip_int_enabled = true;
4926 
4927 	/*
4928 	 * Always set input transfer function, since plane state is refreshed
4929 	 * every time.
4930 	 */
4931 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
4932 	if (ret)
4933 		return ret;
4934 
4935 	return 0;
4936 }
4937 
4938 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
4939 				      struct rect *dirty_rect, int32_t x,
4940 				      s32 y, s32 width, s32 height,
4941 				      int *i, bool ffu)
4942 {
4943 	if (*i > DC_MAX_DIRTY_RECTS)
4944 		return;
4945 
4946 	if (*i == DC_MAX_DIRTY_RECTS)
4947 		goto out;
4948 
4949 	dirty_rect->x = x;
4950 	dirty_rect->y = y;
4951 	dirty_rect->width = width;
4952 	dirty_rect->height = height;
4953 
4954 	if (ffu)
4955 		drm_dbg(plane->dev,
4956 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
4957 			plane->base.id, width, height);
4958 	else
4959 		drm_dbg(plane->dev,
4960 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
4961 			plane->base.id, x, y, width, height);
4962 
4963 out:
4964 	(*i)++;
4965 }
4966 
4967 /**
4968  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
4969  *
4970  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
4971  *         remote fb
4972  * @old_plane_state: Old state of @plane
4973  * @new_plane_state: New state of @plane
4974  * @crtc_state: New state of CRTC connected to the @plane
4975  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
4976  *
4977  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
4978  * (referred to as "damage clips" in DRM nomenclature) that require updating on
4979  * the eDP remote buffer. The responsibility of specifying the dirty regions is
4980  * amdgpu_dm's.
4981  *
4982  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
4983  * plane with regions that require flushing to the eDP remote buffer. In
4984  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
4985  * implicitly provide damage clips without any client support via the plane
4986  * bounds.
4987  */
4988 static void fill_dc_dirty_rects(struct drm_plane *plane,
4989 				struct drm_plane_state *old_plane_state,
4990 				struct drm_plane_state *new_plane_state,
4991 				struct drm_crtc_state *crtc_state,
4992 				struct dc_flip_addrs *flip_addrs)
4993 {
4994 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4995 	struct rect *dirty_rects = flip_addrs->dirty_rects;
4996 	u32 num_clips;
4997 	struct drm_mode_rect *clips;
4998 	bool bb_changed;
4999 	bool fb_changed;
5000 	u32 i = 0;
5001 
5002 	/*
5003 	 * Cursor plane has it's own dirty rect update interface. See
5004 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
5005 	 */
5006 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
5007 		return;
5008 
5009 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
5010 	clips = drm_plane_get_damage_clips(new_plane_state);
5011 
5012 	if (!dm_crtc_state->mpo_requested) {
5013 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
5014 			goto ffu;
5015 
5016 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
5017 			fill_dc_dirty_rect(new_plane_state->plane,
5018 					   &dirty_rects[i], clips->x1,
5019 					   clips->y1, clips->x2 - clips->x1,
5020 					   clips->y2 - clips->y1,
5021 					   &flip_addrs->dirty_rect_count,
5022 					   false);
5023 		return;
5024 	}
5025 
5026 	/*
5027 	 * MPO is requested. Add entire plane bounding box to dirty rects if
5028 	 * flipped to or damaged.
5029 	 *
5030 	 * If plane is moved or resized, also add old bounding box to dirty
5031 	 * rects.
5032 	 */
5033 	fb_changed = old_plane_state->fb->base.id !=
5034 		     new_plane_state->fb->base.id;
5035 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
5036 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
5037 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
5038 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
5039 
5040 	drm_dbg(plane->dev,
5041 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
5042 		new_plane_state->plane->base.id,
5043 		bb_changed, fb_changed, num_clips);
5044 
5045 	if (bb_changed) {
5046 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5047 				   new_plane_state->crtc_x,
5048 				   new_plane_state->crtc_y,
5049 				   new_plane_state->crtc_w,
5050 				   new_plane_state->crtc_h, &i, false);
5051 
5052 		/* Add old plane bounding-box if plane is moved or resized */
5053 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5054 				   old_plane_state->crtc_x,
5055 				   old_plane_state->crtc_y,
5056 				   old_plane_state->crtc_w,
5057 				   old_plane_state->crtc_h, &i, false);
5058 	}
5059 
5060 	if (num_clips) {
5061 		for (; i < num_clips; clips++)
5062 			fill_dc_dirty_rect(new_plane_state->plane,
5063 					   &dirty_rects[i], clips->x1,
5064 					   clips->y1, clips->x2 - clips->x1,
5065 					   clips->y2 - clips->y1, &i, false);
5066 	} else if (fb_changed && !bb_changed) {
5067 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5068 				   new_plane_state->crtc_x,
5069 				   new_plane_state->crtc_y,
5070 				   new_plane_state->crtc_w,
5071 				   new_plane_state->crtc_h, &i, false);
5072 	}
5073 
5074 	if (i > DC_MAX_DIRTY_RECTS)
5075 		goto ffu;
5076 
5077 	flip_addrs->dirty_rect_count = i;
5078 	return;
5079 
5080 ffu:
5081 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
5082 			   dm_crtc_state->base.mode.crtc_hdisplay,
5083 			   dm_crtc_state->base.mode.crtc_vdisplay,
5084 			   &flip_addrs->dirty_rect_count, true);
5085 }
5086 
5087 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
5088 					   const struct dm_connector_state *dm_state,
5089 					   struct dc_stream_state *stream)
5090 {
5091 	enum amdgpu_rmx_type rmx_type;
5092 
5093 	struct rect src = { 0 }; /* viewport in composition space*/
5094 	struct rect dst = { 0 }; /* stream addressable area */
5095 
5096 	/* no mode. nothing to be done */
5097 	if (!mode)
5098 		return;
5099 
5100 	/* Full screen scaling by default */
5101 	src.width = mode->hdisplay;
5102 	src.height = mode->vdisplay;
5103 	dst.width = stream->timing.h_addressable;
5104 	dst.height = stream->timing.v_addressable;
5105 
5106 	if (dm_state) {
5107 		rmx_type = dm_state->scaling;
5108 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5109 			if (src.width * dst.height <
5110 					src.height * dst.width) {
5111 				/* height needs less upscaling/more downscaling */
5112 				dst.width = src.width *
5113 						dst.height / src.height;
5114 			} else {
5115 				/* width needs less upscaling/more downscaling */
5116 				dst.height = src.height *
5117 						dst.width / src.width;
5118 			}
5119 		} else if (rmx_type == RMX_CENTER) {
5120 			dst = src;
5121 		}
5122 
5123 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
5124 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
5125 
5126 		if (dm_state->underscan_enable) {
5127 			dst.x += dm_state->underscan_hborder / 2;
5128 			dst.y += dm_state->underscan_vborder / 2;
5129 			dst.width -= dm_state->underscan_hborder;
5130 			dst.height -= dm_state->underscan_vborder;
5131 		}
5132 	}
5133 
5134 	stream->src = src;
5135 	stream->dst = dst;
5136 
5137 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5138 		      dst.x, dst.y, dst.width, dst.height);
5139 
5140 }
5141 
5142 static enum dc_color_depth
5143 convert_color_depth_from_display_info(const struct drm_connector *connector,
5144 				      bool is_y420, int requested_bpc)
5145 {
5146 	u8 bpc;
5147 
5148 	if (is_y420) {
5149 		bpc = 8;
5150 
5151 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
5152 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5153 			bpc = 16;
5154 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5155 			bpc = 12;
5156 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5157 			bpc = 10;
5158 	} else {
5159 		bpc = (uint8_t)connector->display_info.bpc;
5160 		/* Assume 8 bpc by default if no bpc is specified. */
5161 		bpc = bpc ? bpc : 8;
5162 	}
5163 
5164 	if (requested_bpc > 0) {
5165 		/*
5166 		 * Cap display bpc based on the user requested value.
5167 		 *
5168 		 * The value for state->max_bpc may not correctly updated
5169 		 * depending on when the connector gets added to the state
5170 		 * or if this was called outside of atomic check, so it
5171 		 * can't be used directly.
5172 		 */
5173 		bpc = min_t(u8, bpc, requested_bpc);
5174 
5175 		/* Round down to the nearest even number. */
5176 		bpc = bpc - (bpc & 1);
5177 	}
5178 
5179 	switch (bpc) {
5180 	case 0:
5181 		/*
5182 		 * Temporary Work around, DRM doesn't parse color depth for
5183 		 * EDID revision before 1.4
5184 		 * TODO: Fix edid parsing
5185 		 */
5186 		return COLOR_DEPTH_888;
5187 	case 6:
5188 		return COLOR_DEPTH_666;
5189 	case 8:
5190 		return COLOR_DEPTH_888;
5191 	case 10:
5192 		return COLOR_DEPTH_101010;
5193 	case 12:
5194 		return COLOR_DEPTH_121212;
5195 	case 14:
5196 		return COLOR_DEPTH_141414;
5197 	case 16:
5198 		return COLOR_DEPTH_161616;
5199 	default:
5200 		return COLOR_DEPTH_UNDEFINED;
5201 	}
5202 }
5203 
5204 static enum dc_aspect_ratio
5205 get_aspect_ratio(const struct drm_display_mode *mode_in)
5206 {
5207 	/* 1-1 mapping, since both enums follow the HDMI spec. */
5208 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5209 }
5210 
5211 static enum dc_color_space
5212 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5213 {
5214 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
5215 
5216 	switch (dc_crtc_timing->pixel_encoding)	{
5217 	case PIXEL_ENCODING_YCBCR422:
5218 	case PIXEL_ENCODING_YCBCR444:
5219 	case PIXEL_ENCODING_YCBCR420:
5220 	{
5221 		/*
5222 		 * 27030khz is the separation point between HDTV and SDTV
5223 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
5224 		 * respectively
5225 		 */
5226 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
5227 			if (dc_crtc_timing->flags.Y_ONLY)
5228 				color_space =
5229 					COLOR_SPACE_YCBCR709_LIMITED;
5230 			else
5231 				color_space = COLOR_SPACE_YCBCR709;
5232 		} else {
5233 			if (dc_crtc_timing->flags.Y_ONLY)
5234 				color_space =
5235 					COLOR_SPACE_YCBCR601_LIMITED;
5236 			else
5237 				color_space = COLOR_SPACE_YCBCR601;
5238 		}
5239 
5240 	}
5241 	break;
5242 	case PIXEL_ENCODING_RGB:
5243 		color_space = COLOR_SPACE_SRGB;
5244 		break;
5245 
5246 	default:
5247 		WARN_ON(1);
5248 		break;
5249 	}
5250 
5251 	return color_space;
5252 }
5253 
5254 static bool adjust_colour_depth_from_display_info(
5255 	struct dc_crtc_timing *timing_out,
5256 	const struct drm_display_info *info)
5257 {
5258 	enum dc_color_depth depth = timing_out->display_color_depth;
5259 	int normalized_clk;
5260 	do {
5261 		normalized_clk = timing_out->pix_clk_100hz / 10;
5262 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5263 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5264 			normalized_clk /= 2;
5265 		/* Adjusting pix clock following on HDMI spec based on colour depth */
5266 		switch (depth) {
5267 		case COLOR_DEPTH_888:
5268 			break;
5269 		case COLOR_DEPTH_101010:
5270 			normalized_clk = (normalized_clk * 30) / 24;
5271 			break;
5272 		case COLOR_DEPTH_121212:
5273 			normalized_clk = (normalized_clk * 36) / 24;
5274 			break;
5275 		case COLOR_DEPTH_161616:
5276 			normalized_clk = (normalized_clk * 48) / 24;
5277 			break;
5278 		default:
5279 			/* The above depths are the only ones valid for HDMI. */
5280 			return false;
5281 		}
5282 		if (normalized_clk <= info->max_tmds_clock) {
5283 			timing_out->display_color_depth = depth;
5284 			return true;
5285 		}
5286 	} while (--depth > COLOR_DEPTH_666);
5287 	return false;
5288 }
5289 
5290 static void fill_stream_properties_from_drm_display_mode(
5291 	struct dc_stream_state *stream,
5292 	const struct drm_display_mode *mode_in,
5293 	const struct drm_connector *connector,
5294 	const struct drm_connector_state *connector_state,
5295 	const struct dc_stream_state *old_stream,
5296 	int requested_bpc)
5297 {
5298 	struct dc_crtc_timing *timing_out = &stream->timing;
5299 	const struct drm_display_info *info = &connector->display_info;
5300 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5301 	struct hdmi_vendor_infoframe hv_frame;
5302 	struct hdmi_avi_infoframe avi_frame;
5303 
5304 	memset(&hv_frame, 0, sizeof(hv_frame));
5305 	memset(&avi_frame, 0, sizeof(avi_frame));
5306 
5307 	timing_out->h_border_left = 0;
5308 	timing_out->h_border_right = 0;
5309 	timing_out->v_border_top = 0;
5310 	timing_out->v_border_bottom = 0;
5311 	/* TODO: un-hardcode */
5312 	if (drm_mode_is_420_only(info, mode_in)
5313 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5314 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5315 	else if (drm_mode_is_420_also(info, mode_in)
5316 			&& aconnector->force_yuv420_output)
5317 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5318 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5319 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5320 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5321 	else
5322 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5323 
5324 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5325 	timing_out->display_color_depth = convert_color_depth_from_display_info(
5326 		connector,
5327 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5328 		requested_bpc);
5329 	timing_out->scan_type = SCANNING_TYPE_NODATA;
5330 	timing_out->hdmi_vic = 0;
5331 
5332 	if (old_stream) {
5333 		timing_out->vic = old_stream->timing.vic;
5334 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5335 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5336 	} else {
5337 		timing_out->vic = drm_match_cea_mode(mode_in);
5338 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5339 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5340 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5341 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5342 	}
5343 
5344 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5345 		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5346 		timing_out->vic = avi_frame.video_code;
5347 		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5348 		timing_out->hdmi_vic = hv_frame.vic;
5349 	}
5350 
5351 	if (is_freesync_video_mode(mode_in, aconnector)) {
5352 		timing_out->h_addressable = mode_in->hdisplay;
5353 		timing_out->h_total = mode_in->htotal;
5354 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5355 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5356 		timing_out->v_total = mode_in->vtotal;
5357 		timing_out->v_addressable = mode_in->vdisplay;
5358 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5359 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5360 		timing_out->pix_clk_100hz = mode_in->clock * 10;
5361 	} else {
5362 		timing_out->h_addressable = mode_in->crtc_hdisplay;
5363 		timing_out->h_total = mode_in->crtc_htotal;
5364 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5365 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5366 		timing_out->v_total = mode_in->crtc_vtotal;
5367 		timing_out->v_addressable = mode_in->crtc_vdisplay;
5368 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5369 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5370 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5371 	}
5372 
5373 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5374 
5375 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5376 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5377 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5378 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5379 		    drm_mode_is_420_also(info, mode_in) &&
5380 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5381 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5382 			adjust_colour_depth_from_display_info(timing_out, info);
5383 		}
5384 	}
5385 
5386 	stream->output_color_space = get_output_color_space(timing_out);
5387 }
5388 
5389 static void fill_audio_info(struct audio_info *audio_info,
5390 			    const struct drm_connector *drm_connector,
5391 			    const struct dc_sink *dc_sink)
5392 {
5393 	int i = 0;
5394 	int cea_revision = 0;
5395 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5396 
5397 	audio_info->manufacture_id = edid_caps->manufacturer_id;
5398 	audio_info->product_id = edid_caps->product_id;
5399 
5400 	cea_revision = drm_connector->display_info.cea_rev;
5401 
5402 	strscpy(audio_info->display_name,
5403 		edid_caps->display_name,
5404 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5405 
5406 	if (cea_revision >= 3) {
5407 		audio_info->mode_count = edid_caps->audio_mode_count;
5408 
5409 		for (i = 0; i < audio_info->mode_count; ++i) {
5410 			audio_info->modes[i].format_code =
5411 					(enum audio_format_code)
5412 					(edid_caps->audio_modes[i].format_code);
5413 			audio_info->modes[i].channel_count =
5414 					edid_caps->audio_modes[i].channel_count;
5415 			audio_info->modes[i].sample_rates.all =
5416 					edid_caps->audio_modes[i].sample_rate;
5417 			audio_info->modes[i].sample_size =
5418 					edid_caps->audio_modes[i].sample_size;
5419 		}
5420 	}
5421 
5422 	audio_info->flags.all = edid_caps->speaker_flags;
5423 
5424 	/* TODO: We only check for the progressive mode, check for interlace mode too */
5425 	if (drm_connector->latency_present[0]) {
5426 		audio_info->video_latency = drm_connector->video_latency[0];
5427 		audio_info->audio_latency = drm_connector->audio_latency[0];
5428 	}
5429 
5430 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5431 
5432 }
5433 
5434 static void
5435 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5436 				      struct drm_display_mode *dst_mode)
5437 {
5438 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5439 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5440 	dst_mode->crtc_clock = src_mode->crtc_clock;
5441 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5442 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5443 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5444 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5445 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
5446 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
5447 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5448 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5449 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5450 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5451 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5452 }
5453 
5454 static void
5455 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5456 					const struct drm_display_mode *native_mode,
5457 					bool scale_enabled)
5458 {
5459 	if (scale_enabled) {
5460 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5461 	} else if (native_mode->clock == drm_mode->clock &&
5462 			native_mode->htotal == drm_mode->htotal &&
5463 			native_mode->vtotal == drm_mode->vtotal) {
5464 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5465 	} else {
5466 		/* no scaling nor amdgpu inserted, no need to patch */
5467 	}
5468 }
5469 
5470 static struct dc_sink *
5471 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5472 {
5473 	struct dc_sink_init_data sink_init_data = { 0 };
5474 	struct dc_sink *sink = NULL;
5475 	sink_init_data.link = aconnector->dc_link;
5476 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5477 
5478 	sink = dc_sink_create(&sink_init_data);
5479 	if (!sink) {
5480 		DRM_ERROR("Failed to create sink!\n");
5481 		return NULL;
5482 	}
5483 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5484 
5485 	return sink;
5486 }
5487 
5488 static void set_multisync_trigger_params(
5489 		struct dc_stream_state *stream)
5490 {
5491 	struct dc_stream_state *master = NULL;
5492 
5493 	if (stream->triggered_crtc_reset.enabled) {
5494 		master = stream->triggered_crtc_reset.event_source;
5495 		stream->triggered_crtc_reset.event =
5496 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5497 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5498 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5499 	}
5500 }
5501 
5502 static void set_master_stream(struct dc_stream_state *stream_set[],
5503 			      int stream_count)
5504 {
5505 	int j, highest_rfr = 0, master_stream = 0;
5506 
5507 	for (j = 0;  j < stream_count; j++) {
5508 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5509 			int refresh_rate = 0;
5510 
5511 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5512 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5513 			if (refresh_rate > highest_rfr) {
5514 				highest_rfr = refresh_rate;
5515 				master_stream = j;
5516 			}
5517 		}
5518 	}
5519 	for (j = 0;  j < stream_count; j++) {
5520 		if (stream_set[j])
5521 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5522 	}
5523 }
5524 
5525 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5526 {
5527 	int i = 0;
5528 	struct dc_stream_state *stream;
5529 
5530 	if (context->stream_count < 2)
5531 		return;
5532 	for (i = 0; i < context->stream_count ; i++) {
5533 		if (!context->streams[i])
5534 			continue;
5535 		/*
5536 		 * TODO: add a function to read AMD VSDB bits and set
5537 		 * crtc_sync_master.multi_sync_enabled flag
5538 		 * For now it's set to false
5539 		 */
5540 	}
5541 
5542 	set_master_stream(context->streams, context->stream_count);
5543 
5544 	for (i = 0; i < context->stream_count ; i++) {
5545 		stream = context->streams[i];
5546 
5547 		if (!stream)
5548 			continue;
5549 
5550 		set_multisync_trigger_params(stream);
5551 	}
5552 }
5553 
5554 /**
5555  * DOC: FreeSync Video
5556  *
5557  * When a userspace application wants to play a video, the content follows a
5558  * standard format definition that usually specifies the FPS for that format.
5559  * The below list illustrates some video format and the expected FPS,
5560  * respectively:
5561  *
5562  * - TV/NTSC (23.976 FPS)
5563  * - Cinema (24 FPS)
5564  * - TV/PAL (25 FPS)
5565  * - TV/NTSC (29.97 FPS)
5566  * - TV/NTSC (30 FPS)
5567  * - Cinema HFR (48 FPS)
5568  * - TV/PAL (50 FPS)
5569  * - Commonly used (60 FPS)
5570  * - Multiples of 24 (48,72,96 FPS)
5571  *
5572  * The list of standards video format is not huge and can be added to the
5573  * connector modeset list beforehand. With that, userspace can leverage
5574  * FreeSync to extends the front porch in order to attain the target refresh
5575  * rate. Such a switch will happen seamlessly, without screen blanking or
5576  * reprogramming of the output in any other way. If the userspace requests a
5577  * modesetting change compatible with FreeSync modes that only differ in the
5578  * refresh rate, DC will skip the full update and avoid blink during the
5579  * transition. For example, the video player can change the modesetting from
5580  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5581  * causing any display blink. This same concept can be applied to a mode
5582  * setting change.
5583  */
5584 static struct drm_display_mode *
5585 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5586 		bool use_probed_modes)
5587 {
5588 	struct drm_display_mode *m, *m_pref = NULL;
5589 	u16 current_refresh, highest_refresh;
5590 	struct list_head *list_head = use_probed_modes ?
5591 		&aconnector->base.probed_modes :
5592 		&aconnector->base.modes;
5593 
5594 	if (aconnector->freesync_vid_base.clock != 0)
5595 		return &aconnector->freesync_vid_base;
5596 
5597 	/* Find the preferred mode */
5598 	list_for_each_entry (m, list_head, head) {
5599 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
5600 			m_pref = m;
5601 			break;
5602 		}
5603 	}
5604 
5605 	if (!m_pref) {
5606 		/* Probably an EDID with no preferred mode. Fallback to first entry */
5607 		m_pref = list_first_entry_or_null(
5608 				&aconnector->base.modes, struct drm_display_mode, head);
5609 		if (!m_pref) {
5610 			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5611 			return NULL;
5612 		}
5613 	}
5614 
5615 	highest_refresh = drm_mode_vrefresh(m_pref);
5616 
5617 	/*
5618 	 * Find the mode with highest refresh rate with same resolution.
5619 	 * For some monitors, preferred mode is not the mode with highest
5620 	 * supported refresh rate.
5621 	 */
5622 	list_for_each_entry (m, list_head, head) {
5623 		current_refresh  = drm_mode_vrefresh(m);
5624 
5625 		if (m->hdisplay == m_pref->hdisplay &&
5626 		    m->vdisplay == m_pref->vdisplay &&
5627 		    highest_refresh < current_refresh) {
5628 			highest_refresh = current_refresh;
5629 			m_pref = m;
5630 		}
5631 	}
5632 
5633 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5634 	return m_pref;
5635 }
5636 
5637 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5638 		struct amdgpu_dm_connector *aconnector)
5639 {
5640 	struct drm_display_mode *high_mode;
5641 	int timing_diff;
5642 
5643 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
5644 	if (!high_mode || !mode)
5645 		return false;
5646 
5647 	timing_diff = high_mode->vtotal - mode->vtotal;
5648 
5649 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5650 	    high_mode->hdisplay != mode->hdisplay ||
5651 	    high_mode->vdisplay != mode->vdisplay ||
5652 	    high_mode->hsync_start != mode->hsync_start ||
5653 	    high_mode->hsync_end != mode->hsync_end ||
5654 	    high_mode->htotal != mode->htotal ||
5655 	    high_mode->hskew != mode->hskew ||
5656 	    high_mode->vscan != mode->vscan ||
5657 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
5658 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
5659 		return false;
5660 	else
5661 		return true;
5662 }
5663 
5664 #if defined(CONFIG_DRM_AMD_DC_DCN)
5665 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5666 			    struct dc_sink *sink, struct dc_stream_state *stream,
5667 			    struct dsc_dec_dpcd_caps *dsc_caps)
5668 {
5669 	stream->timing.flags.DSC = 0;
5670 	dsc_caps->is_dsc_supported = false;
5671 
5672 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5673 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
5674 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5675 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5676 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5677 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5678 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5679 				dsc_caps);
5680 	}
5681 }
5682 
5683 
5684 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5685 				    struct dc_sink *sink, struct dc_stream_state *stream,
5686 				    struct dsc_dec_dpcd_caps *dsc_caps,
5687 				    uint32_t max_dsc_target_bpp_limit_override)
5688 {
5689 	const struct dc_link_settings *verified_link_cap = NULL;
5690 	u32 link_bw_in_kbps;
5691 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
5692 	struct dc *dc = sink->ctx->dc;
5693 	struct dc_dsc_bw_range bw_range = {0};
5694 	struct dc_dsc_config dsc_cfg = {0};
5695 
5696 	verified_link_cap = dc_link_get_link_cap(stream->link);
5697 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5698 	edp_min_bpp_x16 = 8 * 16;
5699 	edp_max_bpp_x16 = 8 * 16;
5700 
5701 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5702 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5703 
5704 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
5705 		edp_min_bpp_x16 = edp_max_bpp_x16;
5706 
5707 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5708 				dc->debug.dsc_min_slice_height_override,
5709 				edp_min_bpp_x16, edp_max_bpp_x16,
5710 				dsc_caps,
5711 				&stream->timing,
5712 				&bw_range)) {
5713 
5714 		if (bw_range.max_kbps < link_bw_in_kbps) {
5715 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5716 					dsc_caps,
5717 					dc->debug.dsc_min_slice_height_override,
5718 					max_dsc_target_bpp_limit_override,
5719 					0,
5720 					&stream->timing,
5721 					&dsc_cfg)) {
5722 				stream->timing.dsc_cfg = dsc_cfg;
5723 				stream->timing.flags.DSC = 1;
5724 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5725 			}
5726 			return;
5727 		}
5728 	}
5729 
5730 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5731 				dsc_caps,
5732 				dc->debug.dsc_min_slice_height_override,
5733 				max_dsc_target_bpp_limit_override,
5734 				link_bw_in_kbps,
5735 				&stream->timing,
5736 				&dsc_cfg)) {
5737 		stream->timing.dsc_cfg = dsc_cfg;
5738 		stream->timing.flags.DSC = 1;
5739 	}
5740 }
5741 
5742 
5743 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5744 					struct dc_sink *sink, struct dc_stream_state *stream,
5745 					struct dsc_dec_dpcd_caps *dsc_caps)
5746 {
5747 	struct drm_connector *drm_connector = &aconnector->base;
5748 	u32 link_bandwidth_kbps;
5749 	struct dc *dc = sink->ctx->dc;
5750 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
5751 	u32 dsc_max_supported_bw_in_kbps;
5752 	u32 max_dsc_target_bpp_limit_override =
5753 		drm_connector->display_info.max_dsc_bpp;
5754 
5755 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5756 							dc_link_get_link_cap(aconnector->dc_link));
5757 
5758 	/* Set DSC policy according to dsc_clock_en */
5759 	dc_dsc_policy_set_enable_dsc_when_not_needed(
5760 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5761 
5762 	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5763 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5764 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5765 
5766 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5767 
5768 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5769 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5770 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5771 						dsc_caps,
5772 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5773 						max_dsc_target_bpp_limit_override,
5774 						link_bandwidth_kbps,
5775 						&stream->timing,
5776 						&stream->timing.dsc_cfg)) {
5777 				stream->timing.flags.DSC = 1;
5778 				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5779 			}
5780 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5781 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5782 			max_supported_bw_in_kbps = link_bandwidth_kbps;
5783 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5784 
5785 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5786 					max_supported_bw_in_kbps > 0 &&
5787 					dsc_max_supported_bw_in_kbps > 0)
5788 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5789 						dsc_caps,
5790 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5791 						max_dsc_target_bpp_limit_override,
5792 						dsc_max_supported_bw_in_kbps,
5793 						&stream->timing,
5794 						&stream->timing.dsc_cfg)) {
5795 					stream->timing.flags.DSC = 1;
5796 					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5797 									 __func__, drm_connector->name);
5798 				}
5799 		}
5800 	}
5801 
5802 	/* Overwrite the stream flag if DSC is enabled through debugfs */
5803 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5804 		stream->timing.flags.DSC = 1;
5805 
5806 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5807 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5808 
5809 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5810 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5811 
5812 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5813 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5814 }
5815 #endif /* CONFIG_DRM_AMD_DC_DCN */
5816 
5817 static struct dc_stream_state *
5818 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5819 		       const struct drm_display_mode *drm_mode,
5820 		       const struct dm_connector_state *dm_state,
5821 		       const struct dc_stream_state *old_stream,
5822 		       int requested_bpc)
5823 {
5824 	struct drm_display_mode *preferred_mode = NULL;
5825 	struct drm_connector *drm_connector;
5826 	const struct drm_connector_state *con_state =
5827 		dm_state ? &dm_state->base : NULL;
5828 	struct dc_stream_state *stream = NULL;
5829 	struct drm_display_mode mode;
5830 	struct drm_display_mode saved_mode;
5831 	struct drm_display_mode *freesync_mode = NULL;
5832 	bool native_mode_found = false;
5833 	bool recalculate_timing = false;
5834 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5835 	int mode_refresh;
5836 	int preferred_refresh = 0;
5837 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
5838 #if defined(CONFIG_DRM_AMD_DC_DCN)
5839 	struct dsc_dec_dpcd_caps dsc_caps;
5840 #endif
5841 
5842 	struct dc_sink *sink = NULL;
5843 
5844 	drm_mode_init(&mode, drm_mode);
5845 	memset(&saved_mode, 0, sizeof(saved_mode));
5846 
5847 	if (aconnector == NULL) {
5848 		DRM_ERROR("aconnector is NULL!\n");
5849 		return stream;
5850 	}
5851 
5852 	drm_connector = &aconnector->base;
5853 
5854 	if (!aconnector->dc_sink) {
5855 		sink = create_fake_sink(aconnector);
5856 		if (!sink)
5857 			return stream;
5858 	} else {
5859 		sink = aconnector->dc_sink;
5860 		dc_sink_retain(sink);
5861 	}
5862 
5863 	stream = dc_create_stream_for_sink(sink);
5864 
5865 	if (stream == NULL) {
5866 		DRM_ERROR("Failed to create stream for sink!\n");
5867 		goto finish;
5868 	}
5869 
5870 	stream->dm_stream_context = aconnector;
5871 
5872 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5873 		drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5874 
5875 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5876 		/* Search for preferred mode */
5877 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5878 			native_mode_found = true;
5879 			break;
5880 		}
5881 	}
5882 	if (!native_mode_found)
5883 		preferred_mode = list_first_entry_or_null(
5884 				&aconnector->base.modes,
5885 				struct drm_display_mode,
5886 				head);
5887 
5888 	mode_refresh = drm_mode_vrefresh(&mode);
5889 
5890 	if (preferred_mode == NULL) {
5891 		/*
5892 		 * This may not be an error, the use case is when we have no
5893 		 * usermode calls to reset and set mode upon hotplug. In this
5894 		 * case, we call set mode ourselves to restore the previous mode
5895 		 * and the modelist may not be filled in in time.
5896 		 */
5897 		DRM_DEBUG_DRIVER("No preferred mode found\n");
5898 	} else {
5899 		recalculate_timing = amdgpu_freesync_vid_mode &&
5900 				 is_freesync_video_mode(&mode, aconnector);
5901 		if (recalculate_timing) {
5902 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5903 			drm_mode_copy(&saved_mode, &mode);
5904 			drm_mode_copy(&mode, freesync_mode);
5905 		} else {
5906 			decide_crtc_timing_for_drm_display_mode(
5907 					&mode, preferred_mode, scale);
5908 
5909 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
5910 		}
5911 	}
5912 
5913 	if (recalculate_timing)
5914 		drm_mode_set_crtcinfo(&saved_mode, 0);
5915 	else if (!dm_state)
5916 		drm_mode_set_crtcinfo(&mode, 0);
5917 
5918 	/*
5919 	* If scaling is enabled and refresh rate didn't change
5920 	* we copy the vic and polarities of the old timings
5921 	*/
5922 	if (!scale || mode_refresh != preferred_refresh)
5923 		fill_stream_properties_from_drm_display_mode(
5924 			stream, &mode, &aconnector->base, con_state, NULL,
5925 			requested_bpc);
5926 	else
5927 		fill_stream_properties_from_drm_display_mode(
5928 			stream, &mode, &aconnector->base, con_state, old_stream,
5929 			requested_bpc);
5930 
5931 	if (aconnector->timing_changed) {
5932 		DC_LOG_DEBUG("%s: overriding timing for automated test, bpc %d, changing to %d\n",
5933 				__func__,
5934 				stream->timing.display_color_depth,
5935 				aconnector->timing_requested->display_color_depth);
5936 		stream->timing = *aconnector->timing_requested;
5937 	}
5938 
5939 #if defined(CONFIG_DRM_AMD_DC_DCN)
5940 	/* SST DSC determination policy */
5941 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
5942 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
5943 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
5944 #endif
5945 
5946 	update_stream_scaling_settings(&mode, dm_state, stream);
5947 
5948 	fill_audio_info(
5949 		&stream->audio_info,
5950 		drm_connector,
5951 		sink);
5952 
5953 	update_stream_signal(stream, sink);
5954 
5955 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5956 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
5957 
5958 	if (stream->link->psr_settings.psr_feature_enabled) {
5959 		//
5960 		// should decide stream support vsc sdp colorimetry capability
5961 		// before building vsc info packet
5962 		//
5963 		stream->use_vsc_sdp_for_colorimetry = false;
5964 		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
5965 			stream->use_vsc_sdp_for_colorimetry =
5966 				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
5967 		} else {
5968 			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
5969 				stream->use_vsc_sdp_for_colorimetry = true;
5970 		}
5971 		if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
5972 			tf = TRANSFER_FUNC_GAMMA_22;
5973 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
5974 		aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
5975 
5976 	}
5977 finish:
5978 	dc_sink_release(sink);
5979 
5980 	return stream;
5981 }
5982 
5983 static enum drm_connector_status
5984 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
5985 {
5986 	bool connected;
5987 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5988 
5989 	/*
5990 	 * Notes:
5991 	 * 1. This interface is NOT called in context of HPD irq.
5992 	 * 2. This interface *is called* in context of user-mode ioctl. Which
5993 	 * makes it a bad place for *any* MST-related activity.
5994 	 */
5995 
5996 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
5997 	    !aconnector->fake_enable)
5998 		connected = (aconnector->dc_sink != NULL);
5999 	else
6000 		connected = (aconnector->base.force == DRM_FORCE_ON ||
6001 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
6002 
6003 	update_subconnector_property(aconnector);
6004 
6005 	return (connected ? connector_status_connected :
6006 			connector_status_disconnected);
6007 }
6008 
6009 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
6010 					    struct drm_connector_state *connector_state,
6011 					    struct drm_property *property,
6012 					    uint64_t val)
6013 {
6014 	struct drm_device *dev = connector->dev;
6015 	struct amdgpu_device *adev = drm_to_adev(dev);
6016 	struct dm_connector_state *dm_old_state =
6017 		to_dm_connector_state(connector->state);
6018 	struct dm_connector_state *dm_new_state =
6019 		to_dm_connector_state(connector_state);
6020 
6021 	int ret = -EINVAL;
6022 
6023 	if (property == dev->mode_config.scaling_mode_property) {
6024 		enum amdgpu_rmx_type rmx_type;
6025 
6026 		switch (val) {
6027 		case DRM_MODE_SCALE_CENTER:
6028 			rmx_type = RMX_CENTER;
6029 			break;
6030 		case DRM_MODE_SCALE_ASPECT:
6031 			rmx_type = RMX_ASPECT;
6032 			break;
6033 		case DRM_MODE_SCALE_FULLSCREEN:
6034 			rmx_type = RMX_FULL;
6035 			break;
6036 		case DRM_MODE_SCALE_NONE:
6037 		default:
6038 			rmx_type = RMX_OFF;
6039 			break;
6040 		}
6041 
6042 		if (dm_old_state->scaling == rmx_type)
6043 			return 0;
6044 
6045 		dm_new_state->scaling = rmx_type;
6046 		ret = 0;
6047 	} else if (property == adev->mode_info.underscan_hborder_property) {
6048 		dm_new_state->underscan_hborder = val;
6049 		ret = 0;
6050 	} else if (property == adev->mode_info.underscan_vborder_property) {
6051 		dm_new_state->underscan_vborder = val;
6052 		ret = 0;
6053 	} else if (property == adev->mode_info.underscan_property) {
6054 		dm_new_state->underscan_enable = val;
6055 		ret = 0;
6056 	} else if (property == adev->mode_info.abm_level_property) {
6057 		dm_new_state->abm_level = val;
6058 		ret = 0;
6059 	}
6060 
6061 	return ret;
6062 }
6063 
6064 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
6065 					    const struct drm_connector_state *state,
6066 					    struct drm_property *property,
6067 					    uint64_t *val)
6068 {
6069 	struct drm_device *dev = connector->dev;
6070 	struct amdgpu_device *adev = drm_to_adev(dev);
6071 	struct dm_connector_state *dm_state =
6072 		to_dm_connector_state(state);
6073 	int ret = -EINVAL;
6074 
6075 	if (property == dev->mode_config.scaling_mode_property) {
6076 		switch (dm_state->scaling) {
6077 		case RMX_CENTER:
6078 			*val = DRM_MODE_SCALE_CENTER;
6079 			break;
6080 		case RMX_ASPECT:
6081 			*val = DRM_MODE_SCALE_ASPECT;
6082 			break;
6083 		case RMX_FULL:
6084 			*val = DRM_MODE_SCALE_FULLSCREEN;
6085 			break;
6086 		case RMX_OFF:
6087 		default:
6088 			*val = DRM_MODE_SCALE_NONE;
6089 			break;
6090 		}
6091 		ret = 0;
6092 	} else if (property == adev->mode_info.underscan_hborder_property) {
6093 		*val = dm_state->underscan_hborder;
6094 		ret = 0;
6095 	} else if (property == adev->mode_info.underscan_vborder_property) {
6096 		*val = dm_state->underscan_vborder;
6097 		ret = 0;
6098 	} else if (property == adev->mode_info.underscan_property) {
6099 		*val = dm_state->underscan_enable;
6100 		ret = 0;
6101 	} else if (property == adev->mode_info.abm_level_property) {
6102 		*val = dm_state->abm_level;
6103 		ret = 0;
6104 	}
6105 
6106 	return ret;
6107 }
6108 
6109 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6110 {
6111 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6112 
6113 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6114 }
6115 
6116 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6117 {
6118 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6119 	const struct dc_link *link = aconnector->dc_link;
6120 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6121 	struct amdgpu_display_manager *dm = &adev->dm;
6122 	int i;
6123 
6124 	/*
6125 	 * Call only if mst_mgr was initialized before since it's not done
6126 	 * for all connector types.
6127 	 */
6128 	if (aconnector->mst_mgr.dev)
6129 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6130 
6131 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
6132 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
6133 	for (i = 0; i < dm->num_of_edps; i++) {
6134 		if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6135 			backlight_device_unregister(dm->backlight_dev[i]);
6136 			dm->backlight_dev[i] = NULL;
6137 		}
6138 	}
6139 #endif
6140 
6141 	if (aconnector->dc_em_sink)
6142 		dc_sink_release(aconnector->dc_em_sink);
6143 	aconnector->dc_em_sink = NULL;
6144 	if (aconnector->dc_sink)
6145 		dc_sink_release(aconnector->dc_sink);
6146 	aconnector->dc_sink = NULL;
6147 
6148 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6149 	drm_connector_unregister(connector);
6150 	drm_connector_cleanup(connector);
6151 	if (aconnector->i2c) {
6152 		i2c_del_adapter(&aconnector->i2c->base);
6153 		kfree(aconnector->i2c);
6154 	}
6155 	kfree(aconnector->dm_dp_aux.aux.name);
6156 
6157 	kfree(connector);
6158 }
6159 
6160 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6161 {
6162 	struct dm_connector_state *state =
6163 		to_dm_connector_state(connector->state);
6164 
6165 	if (connector->state)
6166 		__drm_atomic_helper_connector_destroy_state(connector->state);
6167 
6168 	kfree(state);
6169 
6170 	state = kzalloc(sizeof(*state), GFP_KERNEL);
6171 
6172 	if (state) {
6173 		state->scaling = RMX_OFF;
6174 		state->underscan_enable = false;
6175 		state->underscan_hborder = 0;
6176 		state->underscan_vborder = 0;
6177 		state->base.max_requested_bpc = 8;
6178 		state->vcpi_slots = 0;
6179 		state->pbn = 0;
6180 
6181 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6182 			state->abm_level = amdgpu_dm_abm_level;
6183 
6184 		__drm_atomic_helper_connector_reset(connector, &state->base);
6185 	}
6186 }
6187 
6188 struct drm_connector_state *
6189 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6190 {
6191 	struct dm_connector_state *state =
6192 		to_dm_connector_state(connector->state);
6193 
6194 	struct dm_connector_state *new_state =
6195 			kmemdup(state, sizeof(*state), GFP_KERNEL);
6196 
6197 	if (!new_state)
6198 		return NULL;
6199 
6200 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6201 
6202 	new_state->freesync_capable = state->freesync_capable;
6203 	new_state->abm_level = state->abm_level;
6204 	new_state->scaling = state->scaling;
6205 	new_state->underscan_enable = state->underscan_enable;
6206 	new_state->underscan_hborder = state->underscan_hborder;
6207 	new_state->underscan_vborder = state->underscan_vborder;
6208 	new_state->vcpi_slots = state->vcpi_slots;
6209 	new_state->pbn = state->pbn;
6210 	return &new_state->base;
6211 }
6212 
6213 static int
6214 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6215 {
6216 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6217 		to_amdgpu_dm_connector(connector);
6218 	int r;
6219 
6220 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6221 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6222 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6223 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6224 		if (r)
6225 			return r;
6226 	}
6227 
6228 #if defined(CONFIG_DEBUG_FS)
6229 	connector_debugfs_init(amdgpu_dm_connector);
6230 #endif
6231 
6232 	return 0;
6233 }
6234 
6235 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6236 	.reset = amdgpu_dm_connector_funcs_reset,
6237 	.detect = amdgpu_dm_connector_detect,
6238 	.fill_modes = drm_helper_probe_single_connector_modes,
6239 	.destroy = amdgpu_dm_connector_destroy,
6240 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6241 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6242 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6243 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6244 	.late_register = amdgpu_dm_connector_late_register,
6245 	.early_unregister = amdgpu_dm_connector_unregister
6246 };
6247 
6248 static int get_modes(struct drm_connector *connector)
6249 {
6250 	return amdgpu_dm_connector_get_modes(connector);
6251 }
6252 
6253 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6254 {
6255 	struct dc_sink_init_data init_params = {
6256 			.link = aconnector->dc_link,
6257 			.sink_signal = SIGNAL_TYPE_VIRTUAL
6258 	};
6259 	struct edid *edid;
6260 
6261 	if (!aconnector->base.edid_blob_ptr) {
6262 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6263 				aconnector->base.name);
6264 
6265 		aconnector->base.force = DRM_FORCE_OFF;
6266 		return;
6267 	}
6268 
6269 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6270 
6271 	aconnector->edid = edid;
6272 
6273 	aconnector->dc_em_sink = dc_link_add_remote_sink(
6274 		aconnector->dc_link,
6275 		(uint8_t *)edid,
6276 		(edid->extensions + 1) * EDID_LENGTH,
6277 		&init_params);
6278 
6279 	if (aconnector->base.force == DRM_FORCE_ON) {
6280 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
6281 		aconnector->dc_link->local_sink :
6282 		aconnector->dc_em_sink;
6283 		dc_sink_retain(aconnector->dc_sink);
6284 	}
6285 }
6286 
6287 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6288 {
6289 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6290 
6291 	/*
6292 	 * In case of headless boot with force on for DP managed connector
6293 	 * Those settings have to be != 0 to get initial modeset
6294 	 */
6295 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6296 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6297 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6298 	}
6299 
6300 	create_eml_sink(aconnector);
6301 }
6302 
6303 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
6304 						struct dc_stream_state *stream)
6305 {
6306 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
6307 	struct dc_plane_state *dc_plane_state = NULL;
6308 	struct dc_state *dc_state = NULL;
6309 
6310 	if (!stream)
6311 		goto cleanup;
6312 
6313 	dc_plane_state = dc_create_plane_state(dc);
6314 	if (!dc_plane_state)
6315 		goto cleanup;
6316 
6317 	dc_state = dc_create_state(dc);
6318 	if (!dc_state)
6319 		goto cleanup;
6320 
6321 	/* populate stream to plane */
6322 	dc_plane_state->src_rect.height  = stream->src.height;
6323 	dc_plane_state->src_rect.width   = stream->src.width;
6324 	dc_plane_state->dst_rect.height  = stream->src.height;
6325 	dc_plane_state->dst_rect.width   = stream->src.width;
6326 	dc_plane_state->clip_rect.height = stream->src.height;
6327 	dc_plane_state->clip_rect.width  = stream->src.width;
6328 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
6329 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
6330 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
6331 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
6332 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
6333 	dc_plane_state->tiling_info.gfx9.swizzle =  DC_SW_UNKNOWN;
6334 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6335 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
6336 	dc_plane_state->rotation = ROTATION_ANGLE_0;
6337 	dc_plane_state->is_tiling_rotated = false;
6338 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
6339 
6340 	dc_result = dc_validate_stream(dc, stream);
6341 	if (dc_result == DC_OK)
6342 		dc_result = dc_validate_plane(dc, dc_plane_state);
6343 
6344 	if (dc_result == DC_OK)
6345 		dc_result = dc_add_stream_to_ctx(dc, dc_state, stream);
6346 
6347 	if (dc_result == DC_OK && !dc_add_plane_to_context(
6348 						dc,
6349 						stream,
6350 						dc_plane_state,
6351 						dc_state))
6352 		dc_result = DC_FAIL_ATTACH_SURFACES;
6353 
6354 	if (dc_result == DC_OK)
6355 		dc_result = dc_validate_global_state(dc, dc_state, true);
6356 
6357 cleanup:
6358 	if (dc_state)
6359 		dc_release_state(dc_state);
6360 
6361 	if (dc_plane_state)
6362 		dc_plane_state_release(dc_plane_state);
6363 
6364 	return dc_result;
6365 }
6366 
6367 struct dc_stream_state *
6368 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6369 				const struct drm_display_mode *drm_mode,
6370 				const struct dm_connector_state *dm_state,
6371 				const struct dc_stream_state *old_stream)
6372 {
6373 	struct drm_connector *connector = &aconnector->base;
6374 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6375 	struct dc_stream_state *stream;
6376 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6377 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6378 	enum dc_status dc_result = DC_OK;
6379 
6380 	do {
6381 		stream = create_stream_for_sink(aconnector, drm_mode,
6382 						dm_state, old_stream,
6383 						requested_bpc);
6384 		if (stream == NULL) {
6385 			DRM_ERROR("Failed to create stream for sink!\n");
6386 			break;
6387 		}
6388 
6389 		dc_result = dc_validate_stream(adev->dm.dc, stream);
6390 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6391 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6392 
6393 		if (dc_result == DC_OK)
6394 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
6395 
6396 		if (dc_result != DC_OK) {
6397 			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6398 				      drm_mode->hdisplay,
6399 				      drm_mode->vdisplay,
6400 				      drm_mode->clock,
6401 				      dc_result,
6402 				      dc_status_to_str(dc_result));
6403 
6404 			dc_stream_release(stream);
6405 			stream = NULL;
6406 			requested_bpc -= 2; /* lower bpc to retry validation */
6407 		}
6408 
6409 	} while (stream == NULL && requested_bpc >= 6);
6410 
6411 	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6412 		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6413 
6414 		aconnector->force_yuv420_output = true;
6415 		stream = create_validate_stream_for_sink(aconnector, drm_mode,
6416 						dm_state, old_stream);
6417 		aconnector->force_yuv420_output = false;
6418 	}
6419 
6420 	return stream;
6421 }
6422 
6423 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6424 				   struct drm_display_mode *mode)
6425 {
6426 	int result = MODE_ERROR;
6427 	struct dc_sink *dc_sink;
6428 	/* TODO: Unhardcode stream count */
6429 	struct dc_stream_state *stream;
6430 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6431 
6432 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6433 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
6434 		return result;
6435 
6436 	/*
6437 	 * Only run this the first time mode_valid is called to initilialize
6438 	 * EDID mgmt
6439 	 */
6440 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6441 		!aconnector->dc_em_sink)
6442 		handle_edid_mgmt(aconnector);
6443 
6444 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6445 
6446 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6447 				aconnector->base.force != DRM_FORCE_ON) {
6448 		DRM_ERROR("dc_sink is NULL!\n");
6449 		goto fail;
6450 	}
6451 
6452 	stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6453 	if (stream) {
6454 		dc_stream_release(stream);
6455 		result = MODE_OK;
6456 	}
6457 
6458 fail:
6459 	/* TODO: error handling*/
6460 	return result;
6461 }
6462 
6463 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6464 				struct dc_info_packet *out)
6465 {
6466 	struct hdmi_drm_infoframe frame;
6467 	unsigned char buf[30]; /* 26 + 4 */
6468 	ssize_t len;
6469 	int ret, i;
6470 
6471 	memset(out, 0, sizeof(*out));
6472 
6473 	if (!state->hdr_output_metadata)
6474 		return 0;
6475 
6476 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6477 	if (ret)
6478 		return ret;
6479 
6480 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6481 	if (len < 0)
6482 		return (int)len;
6483 
6484 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
6485 	if (len != 30)
6486 		return -EINVAL;
6487 
6488 	/* Prepare the infopacket for DC. */
6489 	switch (state->connector->connector_type) {
6490 	case DRM_MODE_CONNECTOR_HDMIA:
6491 		out->hb0 = 0x87; /* type */
6492 		out->hb1 = 0x01; /* version */
6493 		out->hb2 = 0x1A; /* length */
6494 		out->sb[0] = buf[3]; /* checksum */
6495 		i = 1;
6496 		break;
6497 
6498 	case DRM_MODE_CONNECTOR_DisplayPort:
6499 	case DRM_MODE_CONNECTOR_eDP:
6500 		out->hb0 = 0x00; /* sdp id, zero */
6501 		out->hb1 = 0x87; /* type */
6502 		out->hb2 = 0x1D; /* payload len - 1 */
6503 		out->hb3 = (0x13 << 2); /* sdp version */
6504 		out->sb[0] = 0x01; /* version */
6505 		out->sb[1] = 0x1A; /* length */
6506 		i = 2;
6507 		break;
6508 
6509 	default:
6510 		return -EINVAL;
6511 	}
6512 
6513 	memcpy(&out->sb[i], &buf[4], 26);
6514 	out->valid = true;
6515 
6516 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6517 		       sizeof(out->sb), false);
6518 
6519 	return 0;
6520 }
6521 
6522 static int
6523 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6524 				 struct drm_atomic_state *state)
6525 {
6526 	struct drm_connector_state *new_con_state =
6527 		drm_atomic_get_new_connector_state(state, conn);
6528 	struct drm_connector_state *old_con_state =
6529 		drm_atomic_get_old_connector_state(state, conn);
6530 	struct drm_crtc *crtc = new_con_state->crtc;
6531 	struct drm_crtc_state *new_crtc_state;
6532 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6533 	int ret;
6534 
6535 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
6536 
6537 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6538 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6539 		if (ret < 0)
6540 			return ret;
6541 	}
6542 
6543 	if (!crtc)
6544 		return 0;
6545 
6546 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6547 		struct dc_info_packet hdr_infopacket;
6548 
6549 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6550 		if (ret)
6551 			return ret;
6552 
6553 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6554 		if (IS_ERR(new_crtc_state))
6555 			return PTR_ERR(new_crtc_state);
6556 
6557 		/*
6558 		 * DC considers the stream backends changed if the
6559 		 * static metadata changes. Forcing the modeset also
6560 		 * gives a simple way for userspace to switch from
6561 		 * 8bpc to 10bpc when setting the metadata to enter
6562 		 * or exit HDR.
6563 		 *
6564 		 * Changing the static metadata after it's been
6565 		 * set is permissible, however. So only force a
6566 		 * modeset if we're entering or exiting HDR.
6567 		 */
6568 		new_crtc_state->mode_changed =
6569 			!old_con_state->hdr_output_metadata ||
6570 			!new_con_state->hdr_output_metadata;
6571 	}
6572 
6573 	return 0;
6574 }
6575 
6576 static const struct drm_connector_helper_funcs
6577 amdgpu_dm_connector_helper_funcs = {
6578 	/*
6579 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
6580 	 * modes will be filtered by drm_mode_validate_size(), and those modes
6581 	 * are missing after user start lightdm. So we need to renew modes list.
6582 	 * in get_modes call back, not just return the modes count
6583 	 */
6584 	.get_modes = get_modes,
6585 	.mode_valid = amdgpu_dm_connector_mode_valid,
6586 	.atomic_check = amdgpu_dm_connector_atomic_check,
6587 };
6588 
6589 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6590 {
6591 
6592 }
6593 
6594 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6595 {
6596 	switch (display_color_depth) {
6597 	case COLOR_DEPTH_666:
6598 		return 6;
6599 	case COLOR_DEPTH_888:
6600 		return 8;
6601 	case COLOR_DEPTH_101010:
6602 		return 10;
6603 	case COLOR_DEPTH_121212:
6604 		return 12;
6605 	case COLOR_DEPTH_141414:
6606 		return 14;
6607 	case COLOR_DEPTH_161616:
6608 		return 16;
6609 	default:
6610 		break;
6611 	}
6612 	return 0;
6613 }
6614 
6615 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6616 					  struct drm_crtc_state *crtc_state,
6617 					  struct drm_connector_state *conn_state)
6618 {
6619 	struct drm_atomic_state *state = crtc_state->state;
6620 	struct drm_connector *connector = conn_state->connector;
6621 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6622 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6623 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6624 	struct drm_dp_mst_topology_mgr *mst_mgr;
6625 	struct drm_dp_mst_port *mst_port;
6626 	struct drm_dp_mst_topology_state *mst_state;
6627 	enum dc_color_depth color_depth;
6628 	int clock, bpp = 0;
6629 	bool is_y420 = false;
6630 
6631 	if (!aconnector->mst_output_port || !aconnector->dc_sink)
6632 		return 0;
6633 
6634 	mst_port = aconnector->mst_output_port;
6635 	mst_mgr = &aconnector->mst_root->mst_mgr;
6636 
6637 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6638 		return 0;
6639 
6640 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6641 	if (IS_ERR(mst_state))
6642 		return PTR_ERR(mst_state);
6643 
6644 	if (!mst_state->pbn_div)
6645 		mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
6646 
6647 	if (!state->duplicated) {
6648 		int max_bpc = conn_state->max_requested_bpc;
6649 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6650 			  aconnector->force_yuv420_output;
6651 		color_depth = convert_color_depth_from_display_info(connector,
6652 								    is_y420,
6653 								    max_bpc);
6654 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6655 		clock = adjusted_mode->clock;
6656 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6657 	}
6658 
6659 	dm_new_connector_state->vcpi_slots =
6660 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6661 					      dm_new_connector_state->pbn);
6662 	if (dm_new_connector_state->vcpi_slots < 0) {
6663 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6664 		return dm_new_connector_state->vcpi_slots;
6665 	}
6666 	return 0;
6667 }
6668 
6669 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6670 	.disable = dm_encoder_helper_disable,
6671 	.atomic_check = dm_encoder_helper_atomic_check
6672 };
6673 
6674 #if defined(CONFIG_DRM_AMD_DC_DCN)
6675 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6676 					    struct dc_state *dc_state,
6677 					    struct dsc_mst_fairness_vars *vars)
6678 {
6679 	struct dc_stream_state *stream = NULL;
6680 	struct drm_connector *connector;
6681 	struct drm_connector_state *new_con_state;
6682 	struct amdgpu_dm_connector *aconnector;
6683 	struct dm_connector_state *dm_conn_state;
6684 	int i, j, ret;
6685 	int vcpi, pbn_div, pbn, slot_num = 0;
6686 
6687 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
6688 
6689 		aconnector = to_amdgpu_dm_connector(connector);
6690 
6691 		if (!aconnector->mst_output_port)
6692 			continue;
6693 
6694 		if (!new_con_state || !new_con_state->crtc)
6695 			continue;
6696 
6697 		dm_conn_state = to_dm_connector_state(new_con_state);
6698 
6699 		for (j = 0; j < dc_state->stream_count; j++) {
6700 			stream = dc_state->streams[j];
6701 			if (!stream)
6702 				continue;
6703 
6704 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6705 				break;
6706 
6707 			stream = NULL;
6708 		}
6709 
6710 		if (!stream)
6711 			continue;
6712 
6713 		pbn_div = dm_mst_get_pbn_divider(stream->link);
6714 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
6715 		for (j = 0; j < dc_state->stream_count; j++) {
6716 			if (vars[j].aconnector == aconnector) {
6717 				pbn = vars[j].pbn;
6718 				break;
6719 			}
6720 		}
6721 
6722 		if (j == dc_state->stream_count)
6723 			continue;
6724 
6725 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
6726 
6727 		if (stream->timing.flags.DSC != 1) {
6728 			dm_conn_state->pbn = pbn;
6729 			dm_conn_state->vcpi_slots = slot_num;
6730 
6731 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
6732 							   dm_conn_state->pbn, false);
6733 			if (ret < 0)
6734 				return ret;
6735 
6736 			continue;
6737 		}
6738 
6739 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
6740 		if (vcpi < 0)
6741 			return vcpi;
6742 
6743 		dm_conn_state->pbn = pbn;
6744 		dm_conn_state->vcpi_slots = vcpi;
6745 	}
6746 	return 0;
6747 }
6748 #endif
6749 
6750 static int to_drm_connector_type(enum signal_type st)
6751 {
6752 	switch (st) {
6753 	case SIGNAL_TYPE_HDMI_TYPE_A:
6754 		return DRM_MODE_CONNECTOR_HDMIA;
6755 	case SIGNAL_TYPE_EDP:
6756 		return DRM_MODE_CONNECTOR_eDP;
6757 	case SIGNAL_TYPE_LVDS:
6758 		return DRM_MODE_CONNECTOR_LVDS;
6759 	case SIGNAL_TYPE_RGB:
6760 		return DRM_MODE_CONNECTOR_VGA;
6761 	case SIGNAL_TYPE_DISPLAY_PORT:
6762 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
6763 		return DRM_MODE_CONNECTOR_DisplayPort;
6764 	case SIGNAL_TYPE_DVI_DUAL_LINK:
6765 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
6766 		return DRM_MODE_CONNECTOR_DVID;
6767 	case SIGNAL_TYPE_VIRTUAL:
6768 		return DRM_MODE_CONNECTOR_VIRTUAL;
6769 
6770 	default:
6771 		return DRM_MODE_CONNECTOR_Unknown;
6772 	}
6773 }
6774 
6775 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6776 {
6777 	struct drm_encoder *encoder;
6778 
6779 	/* There is only one encoder per connector */
6780 	drm_connector_for_each_possible_encoder(connector, encoder)
6781 		return encoder;
6782 
6783 	return NULL;
6784 }
6785 
6786 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6787 {
6788 	struct drm_encoder *encoder;
6789 	struct amdgpu_encoder *amdgpu_encoder;
6790 
6791 	encoder = amdgpu_dm_connector_to_encoder(connector);
6792 
6793 	if (encoder == NULL)
6794 		return;
6795 
6796 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6797 
6798 	amdgpu_encoder->native_mode.clock = 0;
6799 
6800 	if (!list_empty(&connector->probed_modes)) {
6801 		struct drm_display_mode *preferred_mode = NULL;
6802 
6803 		list_for_each_entry(preferred_mode,
6804 				    &connector->probed_modes,
6805 				    head) {
6806 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6807 				amdgpu_encoder->native_mode = *preferred_mode;
6808 
6809 			break;
6810 		}
6811 
6812 	}
6813 }
6814 
6815 static struct drm_display_mode *
6816 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6817 			     char *name,
6818 			     int hdisplay, int vdisplay)
6819 {
6820 	struct drm_device *dev = encoder->dev;
6821 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6822 	struct drm_display_mode *mode = NULL;
6823 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6824 
6825 	mode = drm_mode_duplicate(dev, native_mode);
6826 
6827 	if (mode == NULL)
6828 		return NULL;
6829 
6830 	mode->hdisplay = hdisplay;
6831 	mode->vdisplay = vdisplay;
6832 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6833 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6834 
6835 	return mode;
6836 
6837 }
6838 
6839 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6840 						 struct drm_connector *connector)
6841 {
6842 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6843 	struct drm_display_mode *mode = NULL;
6844 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6845 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6846 				to_amdgpu_dm_connector(connector);
6847 	int i;
6848 	int n;
6849 	struct mode_size {
6850 		char name[DRM_DISPLAY_MODE_LEN];
6851 		int w;
6852 		int h;
6853 	} common_modes[] = {
6854 		{  "640x480",  640,  480},
6855 		{  "800x600",  800,  600},
6856 		{ "1024x768", 1024,  768},
6857 		{ "1280x720", 1280,  720},
6858 		{ "1280x800", 1280,  800},
6859 		{"1280x1024", 1280, 1024},
6860 		{ "1440x900", 1440,  900},
6861 		{"1680x1050", 1680, 1050},
6862 		{"1600x1200", 1600, 1200},
6863 		{"1920x1080", 1920, 1080},
6864 		{"1920x1200", 1920, 1200}
6865 	};
6866 
6867 	n = ARRAY_SIZE(common_modes);
6868 
6869 	for (i = 0; i < n; i++) {
6870 		struct drm_display_mode *curmode = NULL;
6871 		bool mode_existed = false;
6872 
6873 		if (common_modes[i].w > native_mode->hdisplay ||
6874 		    common_modes[i].h > native_mode->vdisplay ||
6875 		   (common_modes[i].w == native_mode->hdisplay &&
6876 		    common_modes[i].h == native_mode->vdisplay))
6877 			continue;
6878 
6879 		list_for_each_entry(curmode, &connector->probed_modes, head) {
6880 			if (common_modes[i].w == curmode->hdisplay &&
6881 			    common_modes[i].h == curmode->vdisplay) {
6882 				mode_existed = true;
6883 				break;
6884 			}
6885 		}
6886 
6887 		if (mode_existed)
6888 			continue;
6889 
6890 		mode = amdgpu_dm_create_common_mode(encoder,
6891 				common_modes[i].name, common_modes[i].w,
6892 				common_modes[i].h);
6893 		if (!mode)
6894 			continue;
6895 
6896 		drm_mode_probed_add(connector, mode);
6897 		amdgpu_dm_connector->num_modes++;
6898 	}
6899 }
6900 
6901 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6902 {
6903 	struct drm_encoder *encoder;
6904 	struct amdgpu_encoder *amdgpu_encoder;
6905 	const struct drm_display_mode *native_mode;
6906 
6907 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6908 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6909 		return;
6910 
6911 	mutex_lock(&connector->dev->mode_config.mutex);
6912 	amdgpu_dm_connector_get_modes(connector);
6913 	mutex_unlock(&connector->dev->mode_config.mutex);
6914 
6915 	encoder = amdgpu_dm_connector_to_encoder(connector);
6916 	if (!encoder)
6917 		return;
6918 
6919 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6920 
6921 	native_mode = &amdgpu_encoder->native_mode;
6922 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6923 		return;
6924 
6925 	drm_connector_set_panel_orientation_with_quirk(connector,
6926 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6927 						       native_mode->hdisplay,
6928 						       native_mode->vdisplay);
6929 }
6930 
6931 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6932 					      struct edid *edid)
6933 {
6934 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6935 			to_amdgpu_dm_connector(connector);
6936 
6937 	if (edid) {
6938 		/* empty probed_modes */
6939 		INIT_LIST_HEAD(&connector->probed_modes);
6940 		amdgpu_dm_connector->num_modes =
6941 				drm_add_edid_modes(connector, edid);
6942 
6943 		/* sorting the probed modes before calling function
6944 		 * amdgpu_dm_get_native_mode() since EDID can have
6945 		 * more than one preferred mode. The modes that are
6946 		 * later in the probed mode list could be of higher
6947 		 * and preferred resolution. For example, 3840x2160
6948 		 * resolution in base EDID preferred timing and 4096x2160
6949 		 * preferred resolution in DID extension block later.
6950 		 */
6951 		drm_mode_sort(&connector->probed_modes);
6952 		amdgpu_dm_get_native_mode(connector);
6953 
6954 		/* Freesync capabilities are reset by calling
6955 		 * drm_add_edid_modes() and need to be
6956 		 * restored here.
6957 		 */
6958 		amdgpu_dm_update_freesync_caps(connector, edid);
6959 	} else {
6960 		amdgpu_dm_connector->num_modes = 0;
6961 	}
6962 }
6963 
6964 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
6965 			      struct drm_display_mode *mode)
6966 {
6967 	struct drm_display_mode *m;
6968 
6969 	list_for_each_entry (m, &aconnector->base.probed_modes, head) {
6970 		if (drm_mode_equal(m, mode))
6971 			return true;
6972 	}
6973 
6974 	return false;
6975 }
6976 
6977 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
6978 {
6979 	const struct drm_display_mode *m;
6980 	struct drm_display_mode *new_mode;
6981 	uint i;
6982 	u32 new_modes_count = 0;
6983 
6984 	/* Standard FPS values
6985 	 *
6986 	 * 23.976       - TV/NTSC
6987 	 * 24 	        - Cinema
6988 	 * 25 	        - TV/PAL
6989 	 * 29.97        - TV/NTSC
6990 	 * 30 	        - TV/NTSC
6991 	 * 48 	        - Cinema HFR
6992 	 * 50 	        - TV/PAL
6993 	 * 60 	        - Commonly used
6994 	 * 48,72,96,120 - Multiples of 24
6995 	 */
6996 	static const u32 common_rates[] = {
6997 		23976, 24000, 25000, 29970, 30000,
6998 		48000, 50000, 60000, 72000, 96000, 120000
6999 	};
7000 
7001 	/*
7002 	 * Find mode with highest refresh rate with the same resolution
7003 	 * as the preferred mode. Some monitors report a preferred mode
7004 	 * with lower resolution than the highest refresh rate supported.
7005 	 */
7006 
7007 	m = get_highest_refresh_rate_mode(aconnector, true);
7008 	if (!m)
7009 		return 0;
7010 
7011 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
7012 		u64 target_vtotal, target_vtotal_diff;
7013 		u64 num, den;
7014 
7015 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
7016 			continue;
7017 
7018 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
7019 		    common_rates[i] > aconnector->max_vfreq * 1000)
7020 			continue;
7021 
7022 		num = (unsigned long long)m->clock * 1000 * 1000;
7023 		den = common_rates[i] * (unsigned long long)m->htotal;
7024 		target_vtotal = div_u64(num, den);
7025 		target_vtotal_diff = target_vtotal - m->vtotal;
7026 
7027 		/* Check for illegal modes */
7028 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
7029 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
7030 		    m->vtotal + target_vtotal_diff < m->vsync_end)
7031 			continue;
7032 
7033 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
7034 		if (!new_mode)
7035 			goto out;
7036 
7037 		new_mode->vtotal += (u16)target_vtotal_diff;
7038 		new_mode->vsync_start += (u16)target_vtotal_diff;
7039 		new_mode->vsync_end += (u16)target_vtotal_diff;
7040 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
7041 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
7042 
7043 		if (!is_duplicate_mode(aconnector, new_mode)) {
7044 			drm_mode_probed_add(&aconnector->base, new_mode);
7045 			new_modes_count += 1;
7046 		} else
7047 			drm_mode_destroy(aconnector->base.dev, new_mode);
7048 	}
7049  out:
7050 	return new_modes_count;
7051 }
7052 
7053 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
7054 						   struct edid *edid)
7055 {
7056 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7057 		to_amdgpu_dm_connector(connector);
7058 
7059 	if (!(amdgpu_freesync_vid_mode && edid))
7060 		return;
7061 
7062 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
7063 		amdgpu_dm_connector->num_modes +=
7064 			add_fs_modes(amdgpu_dm_connector);
7065 }
7066 
7067 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
7068 {
7069 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7070 			to_amdgpu_dm_connector(connector);
7071 	struct drm_encoder *encoder;
7072 	struct edid *edid = amdgpu_dm_connector->edid;
7073 
7074 	encoder = amdgpu_dm_connector_to_encoder(connector);
7075 
7076 	if (!drm_edid_is_valid(edid)) {
7077 		amdgpu_dm_connector->num_modes =
7078 				drm_add_modes_noedid(connector, 640, 480);
7079 	} else {
7080 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
7081 		amdgpu_dm_connector_add_common_modes(encoder, connector);
7082 		amdgpu_dm_connector_add_freesync_modes(connector, edid);
7083 	}
7084 	amdgpu_dm_fbc_init(connector);
7085 
7086 	return amdgpu_dm_connector->num_modes;
7087 }
7088 
7089 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
7090 				     struct amdgpu_dm_connector *aconnector,
7091 				     int connector_type,
7092 				     struct dc_link *link,
7093 				     int link_index)
7094 {
7095 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
7096 
7097 	/*
7098 	 * Some of the properties below require access to state, like bpc.
7099 	 * Allocate some default initial connector state with our reset helper.
7100 	 */
7101 	if (aconnector->base.funcs->reset)
7102 		aconnector->base.funcs->reset(&aconnector->base);
7103 
7104 	aconnector->connector_id = link_index;
7105 	aconnector->dc_link = link;
7106 	aconnector->base.interlace_allowed = false;
7107 	aconnector->base.doublescan_allowed = false;
7108 	aconnector->base.stereo_allowed = false;
7109 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
7110 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
7111 	aconnector->audio_inst = -1;
7112 	mutex_init(&aconnector->hpd_lock);
7113 
7114 	/*
7115 	 * configure support HPD hot plug connector_>polled default value is 0
7116 	 * which means HPD hot plug not supported
7117 	 */
7118 	switch (connector_type) {
7119 	case DRM_MODE_CONNECTOR_HDMIA:
7120 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7121 		aconnector->base.ycbcr_420_allowed =
7122 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
7123 		break;
7124 	case DRM_MODE_CONNECTOR_DisplayPort:
7125 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7126 		link->link_enc = link_enc_cfg_get_link_enc(link);
7127 		ASSERT(link->link_enc);
7128 		if (link->link_enc)
7129 			aconnector->base.ycbcr_420_allowed =
7130 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
7131 		break;
7132 	case DRM_MODE_CONNECTOR_DVID:
7133 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7134 		break;
7135 	default:
7136 		break;
7137 	}
7138 
7139 	drm_object_attach_property(&aconnector->base.base,
7140 				dm->ddev->mode_config.scaling_mode_property,
7141 				DRM_MODE_SCALE_NONE);
7142 
7143 	drm_object_attach_property(&aconnector->base.base,
7144 				adev->mode_info.underscan_property,
7145 				UNDERSCAN_OFF);
7146 	drm_object_attach_property(&aconnector->base.base,
7147 				adev->mode_info.underscan_hborder_property,
7148 				0);
7149 	drm_object_attach_property(&aconnector->base.base,
7150 				adev->mode_info.underscan_vborder_property,
7151 				0);
7152 
7153 	if (!aconnector->mst_root)
7154 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7155 
7156 	/* This defaults to the max in the range, but we want 8bpc for non-edp. */
7157 	aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7158 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7159 
7160 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7161 	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7162 		drm_object_attach_property(&aconnector->base.base,
7163 				adev->mode_info.abm_level_property, 0);
7164 	}
7165 
7166 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7167 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7168 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
7169 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7170 
7171 		if (!aconnector->mst_root)
7172 			drm_connector_attach_vrr_capable_property(&aconnector->base);
7173 
7174 #ifdef CONFIG_DRM_AMD_DC_HDCP
7175 		if (adev->dm.hdcp_workqueue)
7176 			drm_connector_attach_content_protection_property(&aconnector->base, true);
7177 #endif
7178 	}
7179 }
7180 
7181 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7182 			      struct i2c_msg *msgs, int num)
7183 {
7184 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7185 	struct ddc_service *ddc_service = i2c->ddc_service;
7186 	struct i2c_command cmd;
7187 	int i;
7188 	int result = -EIO;
7189 
7190 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7191 
7192 	if (!cmd.payloads)
7193 		return result;
7194 
7195 	cmd.number_of_payloads = num;
7196 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7197 	cmd.speed = 100;
7198 
7199 	for (i = 0; i < num; i++) {
7200 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7201 		cmd.payloads[i].address = msgs[i].addr;
7202 		cmd.payloads[i].length = msgs[i].len;
7203 		cmd.payloads[i].data = msgs[i].buf;
7204 	}
7205 
7206 	if (dc_submit_i2c(
7207 			ddc_service->ctx->dc,
7208 			ddc_service->link->link_index,
7209 			&cmd))
7210 		result = num;
7211 
7212 	kfree(cmd.payloads);
7213 	return result;
7214 }
7215 
7216 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7217 {
7218 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7219 }
7220 
7221 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7222 	.master_xfer = amdgpu_dm_i2c_xfer,
7223 	.functionality = amdgpu_dm_i2c_func,
7224 };
7225 
7226 static struct amdgpu_i2c_adapter *
7227 create_i2c(struct ddc_service *ddc_service,
7228 	   int link_index,
7229 	   int *res)
7230 {
7231 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7232 	struct amdgpu_i2c_adapter *i2c;
7233 
7234 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7235 	if (!i2c)
7236 		return NULL;
7237 	i2c->base.owner = THIS_MODULE;
7238 	i2c->base.class = I2C_CLASS_DDC;
7239 	i2c->base.dev.parent = &adev->pdev->dev;
7240 	i2c->base.algo = &amdgpu_dm_i2c_algo;
7241 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7242 	i2c_set_adapdata(&i2c->base, i2c);
7243 	i2c->ddc_service = ddc_service;
7244 
7245 	return i2c;
7246 }
7247 
7248 
7249 /*
7250  * Note: this function assumes that dc_link_detect() was called for the
7251  * dc_link which will be represented by this aconnector.
7252  */
7253 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7254 				    struct amdgpu_dm_connector *aconnector,
7255 				    u32 link_index,
7256 				    struct amdgpu_encoder *aencoder)
7257 {
7258 	int res = 0;
7259 	int connector_type;
7260 	struct dc *dc = dm->dc;
7261 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
7262 	struct amdgpu_i2c_adapter *i2c;
7263 
7264 	link->priv = aconnector;
7265 
7266 	DRM_DEBUG_DRIVER("%s()\n", __func__);
7267 
7268 	i2c = create_i2c(link->ddc, link->link_index, &res);
7269 	if (!i2c) {
7270 		DRM_ERROR("Failed to create i2c adapter data\n");
7271 		return -ENOMEM;
7272 	}
7273 
7274 	aconnector->i2c = i2c;
7275 	res = i2c_add_adapter(&i2c->base);
7276 
7277 	if (res) {
7278 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7279 		goto out_free;
7280 	}
7281 
7282 	connector_type = to_drm_connector_type(link->connector_signal);
7283 
7284 	res = drm_connector_init_with_ddc(
7285 			dm->ddev,
7286 			&aconnector->base,
7287 			&amdgpu_dm_connector_funcs,
7288 			connector_type,
7289 			&i2c->base);
7290 
7291 	if (res) {
7292 		DRM_ERROR("connector_init failed\n");
7293 		aconnector->connector_id = -1;
7294 		goto out_free;
7295 	}
7296 
7297 	drm_connector_helper_add(
7298 			&aconnector->base,
7299 			&amdgpu_dm_connector_helper_funcs);
7300 
7301 	amdgpu_dm_connector_init_helper(
7302 		dm,
7303 		aconnector,
7304 		connector_type,
7305 		link,
7306 		link_index);
7307 
7308 	drm_connector_attach_encoder(
7309 		&aconnector->base, &aencoder->base);
7310 
7311 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7312 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
7313 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7314 
7315 out_free:
7316 	if (res) {
7317 		kfree(i2c);
7318 		aconnector->i2c = NULL;
7319 	}
7320 	return res;
7321 }
7322 
7323 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7324 {
7325 	switch (adev->mode_info.num_crtc) {
7326 	case 1:
7327 		return 0x1;
7328 	case 2:
7329 		return 0x3;
7330 	case 3:
7331 		return 0x7;
7332 	case 4:
7333 		return 0xf;
7334 	case 5:
7335 		return 0x1f;
7336 	case 6:
7337 	default:
7338 		return 0x3f;
7339 	}
7340 }
7341 
7342 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7343 				  struct amdgpu_encoder *aencoder,
7344 				  uint32_t link_index)
7345 {
7346 	struct amdgpu_device *adev = drm_to_adev(dev);
7347 
7348 	int res = drm_encoder_init(dev,
7349 				   &aencoder->base,
7350 				   &amdgpu_dm_encoder_funcs,
7351 				   DRM_MODE_ENCODER_TMDS,
7352 				   NULL);
7353 
7354 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7355 
7356 	if (!res)
7357 		aencoder->encoder_id = link_index;
7358 	else
7359 		aencoder->encoder_id = -1;
7360 
7361 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7362 
7363 	return res;
7364 }
7365 
7366 static void manage_dm_interrupts(struct amdgpu_device *adev,
7367 				 struct amdgpu_crtc *acrtc,
7368 				 bool enable)
7369 {
7370 	/*
7371 	 * We have no guarantee that the frontend index maps to the same
7372 	 * backend index - some even map to more than one.
7373 	 *
7374 	 * TODO: Use a different interrupt or check DC itself for the mapping.
7375 	 */
7376 	int irq_type =
7377 		amdgpu_display_crtc_idx_to_irq_type(
7378 			adev,
7379 			acrtc->crtc_id);
7380 
7381 	if (enable) {
7382 		drm_crtc_vblank_on(&acrtc->base);
7383 		amdgpu_irq_get(
7384 			adev,
7385 			&adev->pageflip_irq,
7386 			irq_type);
7387 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7388 		amdgpu_irq_get(
7389 			adev,
7390 			&adev->vline0_irq,
7391 			irq_type);
7392 #endif
7393 	} else {
7394 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7395 		amdgpu_irq_put(
7396 			adev,
7397 			&adev->vline0_irq,
7398 			irq_type);
7399 #endif
7400 		amdgpu_irq_put(
7401 			adev,
7402 			&adev->pageflip_irq,
7403 			irq_type);
7404 		drm_crtc_vblank_off(&acrtc->base);
7405 	}
7406 }
7407 
7408 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7409 				      struct amdgpu_crtc *acrtc)
7410 {
7411 	int irq_type =
7412 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7413 
7414 	/**
7415 	 * This reads the current state for the IRQ and force reapplies
7416 	 * the setting to hardware.
7417 	 */
7418 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7419 }
7420 
7421 static bool
7422 is_scaling_state_different(const struct dm_connector_state *dm_state,
7423 			   const struct dm_connector_state *old_dm_state)
7424 {
7425 	if (dm_state->scaling != old_dm_state->scaling)
7426 		return true;
7427 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7428 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7429 			return true;
7430 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7431 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7432 			return true;
7433 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7434 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7435 		return true;
7436 	return false;
7437 }
7438 
7439 #ifdef CONFIG_DRM_AMD_DC_HDCP
7440 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
7441 					    struct drm_crtc_state *old_crtc_state,
7442 					    struct drm_connector_state *new_conn_state,
7443 					    struct drm_connector_state *old_conn_state,
7444 					    const struct drm_connector *connector,
7445 					    struct hdcp_workqueue *hdcp_w)
7446 {
7447 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7448 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7449 
7450 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
7451 		connector->index, connector->status, connector->dpms);
7452 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
7453 		old_conn_state->content_protection, new_conn_state->content_protection);
7454 
7455 	if (old_crtc_state)
7456 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7457 		old_crtc_state->enable,
7458 		old_crtc_state->active,
7459 		old_crtc_state->mode_changed,
7460 		old_crtc_state->active_changed,
7461 		old_crtc_state->connectors_changed);
7462 
7463 	if (new_crtc_state)
7464 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7465 		new_crtc_state->enable,
7466 		new_crtc_state->active,
7467 		new_crtc_state->mode_changed,
7468 		new_crtc_state->active_changed,
7469 		new_crtc_state->connectors_changed);
7470 
7471 	/* hdcp content type change */
7472 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
7473 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7474 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7475 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
7476 		return true;
7477 	}
7478 
7479 	/* CP is being re enabled, ignore this */
7480 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7481 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7482 		if (new_crtc_state && new_crtc_state->mode_changed) {
7483 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7484 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
7485 			return true;
7486 		}
7487 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7488 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
7489 		return false;
7490 	}
7491 
7492 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7493 	 *
7494 	 * Handles:	UNDESIRED -> ENABLED
7495 	 */
7496 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7497 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7498 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7499 
7500 	/* Stream removed and re-enabled
7501 	 *
7502 	 * Can sometimes overlap with the HPD case,
7503 	 * thus set update_hdcp to false to avoid
7504 	 * setting HDCP multiple times.
7505 	 *
7506 	 * Handles:	DESIRED -> DESIRED (Special case)
7507 	 */
7508 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
7509 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
7510 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7511 		dm_con_state->update_hdcp = false;
7512 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
7513 			__func__);
7514 		return true;
7515 	}
7516 
7517 	/* Hot-plug, headless s3, dpms
7518 	 *
7519 	 * Only start HDCP if the display is connected/enabled.
7520 	 * update_hdcp flag will be set to false until the next
7521 	 * HPD comes in.
7522 	 *
7523 	 * Handles:	DESIRED -> DESIRED (Special case)
7524 	 */
7525 	if (dm_con_state->update_hdcp &&
7526 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7527 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7528 		dm_con_state->update_hdcp = false;
7529 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
7530 			__func__);
7531 		return true;
7532 	}
7533 
7534 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
7535 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7536 			if (new_crtc_state && new_crtc_state->mode_changed) {
7537 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
7538 					__func__);
7539 				return true;
7540 			}
7541 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
7542 				__func__);
7543 			return false;
7544 		}
7545 
7546 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
7547 		return false;
7548 	}
7549 
7550 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
7551 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
7552 			__func__);
7553 		return true;
7554 	}
7555 
7556 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
7557 	return false;
7558 }
7559 #endif
7560 
7561 static void remove_stream(struct amdgpu_device *adev,
7562 			  struct amdgpu_crtc *acrtc,
7563 			  struct dc_stream_state *stream)
7564 {
7565 	/* this is the update mode case */
7566 
7567 	acrtc->otg_inst = -1;
7568 	acrtc->enabled = false;
7569 }
7570 
7571 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7572 {
7573 
7574 	assert_spin_locked(&acrtc->base.dev->event_lock);
7575 	WARN_ON(acrtc->event);
7576 
7577 	acrtc->event = acrtc->base.state->event;
7578 
7579 	/* Set the flip status */
7580 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7581 
7582 	/* Mark this event as consumed */
7583 	acrtc->base.state->event = NULL;
7584 
7585 	DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7586 		     acrtc->crtc_id);
7587 }
7588 
7589 static void update_freesync_state_on_stream(
7590 	struct amdgpu_display_manager *dm,
7591 	struct dm_crtc_state *new_crtc_state,
7592 	struct dc_stream_state *new_stream,
7593 	struct dc_plane_state *surface,
7594 	u32 flip_timestamp_in_us)
7595 {
7596 	struct mod_vrr_params vrr_params;
7597 	struct dc_info_packet vrr_infopacket = {0};
7598 	struct amdgpu_device *adev = dm->adev;
7599 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7600 	unsigned long flags;
7601 	bool pack_sdp_v1_3 = false;
7602 
7603 	if (!new_stream)
7604 		return;
7605 
7606 	/*
7607 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7608 	 * For now it's sufficient to just guard against these conditions.
7609 	 */
7610 
7611 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7612 		return;
7613 
7614 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7615         vrr_params = acrtc->dm_irq_params.vrr_params;
7616 
7617 	if (surface) {
7618 		mod_freesync_handle_preflip(
7619 			dm->freesync_module,
7620 			surface,
7621 			new_stream,
7622 			flip_timestamp_in_us,
7623 			&vrr_params);
7624 
7625 		if (adev->family < AMDGPU_FAMILY_AI &&
7626 		    amdgpu_dm_vrr_active(new_crtc_state)) {
7627 			mod_freesync_handle_v_update(dm->freesync_module,
7628 						     new_stream, &vrr_params);
7629 
7630 			/* Need to call this before the frame ends. */
7631 			dc_stream_adjust_vmin_vmax(dm->dc,
7632 						   new_crtc_state->stream,
7633 						   &vrr_params.adjust);
7634 		}
7635 	}
7636 
7637 	mod_freesync_build_vrr_infopacket(
7638 		dm->freesync_module,
7639 		new_stream,
7640 		&vrr_params,
7641 		PACKET_TYPE_VRR,
7642 		TRANSFER_FUNC_UNKNOWN,
7643 		&vrr_infopacket,
7644 		pack_sdp_v1_3);
7645 
7646 	new_crtc_state->freesync_vrr_info_changed |=
7647 		(memcmp(&new_crtc_state->vrr_infopacket,
7648 			&vrr_infopacket,
7649 			sizeof(vrr_infopacket)) != 0);
7650 
7651 	acrtc->dm_irq_params.vrr_params = vrr_params;
7652 	new_crtc_state->vrr_infopacket = vrr_infopacket;
7653 
7654 	new_stream->vrr_infopacket = vrr_infopacket;
7655 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
7656 
7657 	if (new_crtc_state->freesync_vrr_info_changed)
7658 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7659 			      new_crtc_state->base.crtc->base.id,
7660 			      (int)new_crtc_state->base.vrr_enabled,
7661 			      (int)vrr_params.state);
7662 
7663 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7664 }
7665 
7666 static void update_stream_irq_parameters(
7667 	struct amdgpu_display_manager *dm,
7668 	struct dm_crtc_state *new_crtc_state)
7669 {
7670 	struct dc_stream_state *new_stream = new_crtc_state->stream;
7671 	struct mod_vrr_params vrr_params;
7672 	struct mod_freesync_config config = new_crtc_state->freesync_config;
7673 	struct amdgpu_device *adev = dm->adev;
7674 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7675 	unsigned long flags;
7676 
7677 	if (!new_stream)
7678 		return;
7679 
7680 	/*
7681 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7682 	 * For now it's sufficient to just guard against these conditions.
7683 	 */
7684 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7685 		return;
7686 
7687 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7688 	vrr_params = acrtc->dm_irq_params.vrr_params;
7689 
7690 	if (new_crtc_state->vrr_supported &&
7691 	    config.min_refresh_in_uhz &&
7692 	    config.max_refresh_in_uhz) {
7693 		/*
7694 		 * if freesync compatible mode was set, config.state will be set
7695 		 * in atomic check
7696 		 */
7697 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7698 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7699 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7700 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7701 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7702 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7703 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7704 		} else {
7705 			config.state = new_crtc_state->base.vrr_enabled ?
7706 						     VRR_STATE_ACTIVE_VARIABLE :
7707 						     VRR_STATE_INACTIVE;
7708 		}
7709 	} else {
7710 		config.state = VRR_STATE_UNSUPPORTED;
7711 	}
7712 
7713 	mod_freesync_build_vrr_params(dm->freesync_module,
7714 				      new_stream,
7715 				      &config, &vrr_params);
7716 
7717 	new_crtc_state->freesync_config = config;
7718 	/* Copy state for access from DM IRQ handler */
7719 	acrtc->dm_irq_params.freesync_config = config;
7720 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7721 	acrtc->dm_irq_params.vrr_params = vrr_params;
7722 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7723 }
7724 
7725 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7726 					    struct dm_crtc_state *new_state)
7727 {
7728 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7729 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7730 
7731 	if (!old_vrr_active && new_vrr_active) {
7732 		/* Transition VRR inactive -> active:
7733 		 * While VRR is active, we must not disable vblank irq, as a
7734 		 * reenable after disable would compute bogus vblank/pflip
7735 		 * timestamps if it likely happened inside display front-porch.
7736 		 *
7737 		 * We also need vupdate irq for the actual core vblank handling
7738 		 * at end of vblank.
7739 		 */
7740 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7741 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7742 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7743 				 __func__, new_state->base.crtc->base.id);
7744 	} else if (old_vrr_active && !new_vrr_active) {
7745 		/* Transition VRR active -> inactive:
7746 		 * Allow vblank irq disable again for fixed refresh rate.
7747 		 */
7748 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7749 		drm_crtc_vblank_put(new_state->base.crtc);
7750 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7751 				 __func__, new_state->base.crtc->base.id);
7752 	}
7753 }
7754 
7755 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7756 {
7757 	struct drm_plane *plane;
7758 	struct drm_plane_state *old_plane_state;
7759 	int i;
7760 
7761 	/*
7762 	 * TODO: Make this per-stream so we don't issue redundant updates for
7763 	 * commits with multiple streams.
7764 	 */
7765 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
7766 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
7767 			handle_cursor_update(plane, old_plane_state);
7768 }
7769 
7770 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7771 				    struct dc_state *dc_state,
7772 				    struct drm_device *dev,
7773 				    struct amdgpu_display_manager *dm,
7774 				    struct drm_crtc *pcrtc,
7775 				    bool wait_for_vblank)
7776 {
7777 	u32 i;
7778 	u64 timestamp_ns;
7779 	struct drm_plane *plane;
7780 	struct drm_plane_state *old_plane_state, *new_plane_state;
7781 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7782 	struct drm_crtc_state *new_pcrtc_state =
7783 			drm_atomic_get_new_crtc_state(state, pcrtc);
7784 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7785 	struct dm_crtc_state *dm_old_crtc_state =
7786 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7787 	int planes_count = 0, vpos, hpos;
7788 	unsigned long flags;
7789 	u32 target_vblank, last_flip_vblank;
7790 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7791 	bool cursor_update = false;
7792 	bool pflip_present = false;
7793 	struct {
7794 		struct dc_surface_update surface_updates[MAX_SURFACES];
7795 		struct dc_plane_info plane_infos[MAX_SURFACES];
7796 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
7797 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7798 		struct dc_stream_update stream_update;
7799 	} *bundle;
7800 
7801 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7802 
7803 	if (!bundle) {
7804 		dm_error("Failed to allocate update bundle\n");
7805 		goto cleanup;
7806 	}
7807 
7808 	/*
7809 	 * Disable the cursor first if we're disabling all the planes.
7810 	 * It'll remain on the screen after the planes are re-enabled
7811 	 * if we don't.
7812 	 */
7813 	if (acrtc_state->active_planes == 0)
7814 		amdgpu_dm_commit_cursors(state);
7815 
7816 	/* update planes when needed */
7817 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7818 		struct drm_crtc *crtc = new_plane_state->crtc;
7819 		struct drm_crtc_state *new_crtc_state;
7820 		struct drm_framebuffer *fb = new_plane_state->fb;
7821 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7822 		bool plane_needs_flip;
7823 		struct dc_plane_state *dc_plane;
7824 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7825 
7826 		/* Cursor plane is handled after stream updates */
7827 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7828 			if ((fb && crtc == pcrtc) ||
7829 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7830 				cursor_update = true;
7831 
7832 			continue;
7833 		}
7834 
7835 		if (!fb || !crtc || pcrtc != crtc)
7836 			continue;
7837 
7838 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7839 		if (!new_crtc_state->active)
7840 			continue;
7841 
7842 		dc_plane = dm_new_plane_state->dc_state;
7843 
7844 		bundle->surface_updates[planes_count].surface = dc_plane;
7845 		if (new_pcrtc_state->color_mgmt_changed) {
7846 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7847 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7848 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7849 		}
7850 
7851 		fill_dc_scaling_info(dm->adev, new_plane_state,
7852 				     &bundle->scaling_infos[planes_count]);
7853 
7854 		bundle->surface_updates[planes_count].scaling_info =
7855 			&bundle->scaling_infos[planes_count];
7856 
7857 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7858 
7859 		pflip_present = pflip_present || plane_needs_flip;
7860 
7861 		if (!plane_needs_flip) {
7862 			planes_count += 1;
7863 			continue;
7864 		}
7865 
7866 		fill_dc_plane_info_and_addr(
7867 			dm->adev, new_plane_state,
7868 			afb->tiling_flags,
7869 			&bundle->plane_infos[planes_count],
7870 			&bundle->flip_addrs[planes_count].address,
7871 			afb->tmz_surface, false);
7872 
7873 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7874 				 new_plane_state->plane->index,
7875 				 bundle->plane_infos[planes_count].dcc.enable);
7876 
7877 		bundle->surface_updates[planes_count].plane_info =
7878 			&bundle->plane_infos[planes_count];
7879 
7880 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7881 			fill_dc_dirty_rects(plane, old_plane_state,
7882 					    new_plane_state, new_crtc_state,
7883 					    &bundle->flip_addrs[planes_count]);
7884 
7885 		/*
7886 		 * Only allow immediate flips for fast updates that don't
7887 		 * change FB pitch, DCC state, rotation or mirroing.
7888 		 */
7889 		bundle->flip_addrs[planes_count].flip_immediate =
7890 			crtc->state->async_flip &&
7891 			acrtc_state->update_type == UPDATE_TYPE_FAST;
7892 
7893 		timestamp_ns = ktime_get_ns();
7894 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7895 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7896 		bundle->surface_updates[planes_count].surface = dc_plane;
7897 
7898 		if (!bundle->surface_updates[planes_count].surface) {
7899 			DRM_ERROR("No surface for CRTC: id=%d\n",
7900 					acrtc_attach->crtc_id);
7901 			continue;
7902 		}
7903 
7904 		if (plane == pcrtc->primary)
7905 			update_freesync_state_on_stream(
7906 				dm,
7907 				acrtc_state,
7908 				acrtc_state->stream,
7909 				dc_plane,
7910 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7911 
7912 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7913 				 __func__,
7914 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7915 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7916 
7917 		planes_count += 1;
7918 
7919 	}
7920 
7921 	if (pflip_present) {
7922 		if (!vrr_active) {
7923 			/* Use old throttling in non-vrr fixed refresh rate mode
7924 			 * to keep flip scheduling based on target vblank counts
7925 			 * working in a backwards compatible way, e.g., for
7926 			 * clients using the GLX_OML_sync_control extension or
7927 			 * DRI3/Present extension with defined target_msc.
7928 			 */
7929 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7930 		}
7931 		else {
7932 			/* For variable refresh rate mode only:
7933 			 * Get vblank of last completed flip to avoid > 1 vrr
7934 			 * flips per video frame by use of throttling, but allow
7935 			 * flip programming anywhere in the possibly large
7936 			 * variable vrr vblank interval for fine-grained flip
7937 			 * timing control and more opportunity to avoid stutter
7938 			 * on late submission of flips.
7939 			 */
7940 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7941 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
7942 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7943 		}
7944 
7945 		target_vblank = last_flip_vblank + wait_for_vblank;
7946 
7947 		/*
7948 		 * Wait until we're out of the vertical blank period before the one
7949 		 * targeted by the flip
7950 		 */
7951 		while ((acrtc_attach->enabled &&
7952 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
7953 							    0, &vpos, &hpos, NULL,
7954 							    NULL, &pcrtc->hwmode)
7955 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
7956 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
7957 			(int)(target_vblank -
7958 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
7959 			usleep_range(1000, 1100);
7960 		}
7961 
7962 		/**
7963 		 * Prepare the flip event for the pageflip interrupt to handle.
7964 		 *
7965 		 * This only works in the case where we've already turned on the
7966 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
7967 		 * from 0 -> n planes we have to skip a hardware generated event
7968 		 * and rely on sending it from software.
7969 		 */
7970 		if (acrtc_attach->base.state->event &&
7971 		    acrtc_state->active_planes > 0) {
7972 			drm_crtc_vblank_get(pcrtc);
7973 
7974 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7975 
7976 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
7977 			prepare_flip_isr(acrtc_attach);
7978 
7979 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7980 		}
7981 
7982 		if (acrtc_state->stream) {
7983 			if (acrtc_state->freesync_vrr_info_changed)
7984 				bundle->stream_update.vrr_infopacket =
7985 					&acrtc_state->stream->vrr_infopacket;
7986 		}
7987 	} else if (cursor_update && acrtc_state->active_planes > 0 &&
7988 		   acrtc_attach->base.state->event) {
7989 		drm_crtc_vblank_get(pcrtc);
7990 
7991 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7992 
7993 		acrtc_attach->event = acrtc_attach->base.state->event;
7994 		acrtc_attach->base.state->event = NULL;
7995 
7996 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7997 	}
7998 
7999 	/* Update the planes if changed or disable if we don't have any. */
8000 	if ((planes_count || acrtc_state->active_planes == 0) &&
8001 		acrtc_state->stream) {
8002 		/*
8003 		 * If PSR or idle optimizations are enabled then flush out
8004 		 * any pending work before hardware programming.
8005 		 */
8006 		if (dm->vblank_control_workqueue)
8007 			flush_workqueue(dm->vblank_control_workqueue);
8008 
8009 		bundle->stream_update.stream = acrtc_state->stream;
8010 		if (new_pcrtc_state->mode_changed) {
8011 			bundle->stream_update.src = acrtc_state->stream->src;
8012 			bundle->stream_update.dst = acrtc_state->stream->dst;
8013 		}
8014 
8015 		if (new_pcrtc_state->color_mgmt_changed) {
8016 			/*
8017 			 * TODO: This isn't fully correct since we've actually
8018 			 * already modified the stream in place.
8019 			 */
8020 			bundle->stream_update.gamut_remap =
8021 				&acrtc_state->stream->gamut_remap_matrix;
8022 			bundle->stream_update.output_csc_transform =
8023 				&acrtc_state->stream->csc_color_matrix;
8024 			bundle->stream_update.out_transfer_func =
8025 				acrtc_state->stream->out_transfer_func;
8026 		}
8027 
8028 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
8029 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
8030 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
8031 
8032 		/*
8033 		 * If FreeSync state on the stream has changed then we need to
8034 		 * re-adjust the min/max bounds now that DC doesn't handle this
8035 		 * as part of commit.
8036 		 */
8037 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
8038 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
8039 			dc_stream_adjust_vmin_vmax(
8040 				dm->dc, acrtc_state->stream,
8041 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
8042 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
8043 		}
8044 		mutex_lock(&dm->dc_lock);
8045 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8046 				acrtc_state->stream->link->psr_settings.psr_allow_active)
8047 			amdgpu_dm_psr_disable(acrtc_state->stream);
8048 
8049 		dc_commit_updates_for_stream(dm->dc,
8050 						     bundle->surface_updates,
8051 						     planes_count,
8052 						     acrtc_state->stream,
8053 						     &bundle->stream_update,
8054 						     dc_state);
8055 
8056 		/**
8057 		 * Enable or disable the interrupts on the backend.
8058 		 *
8059 		 * Most pipes are put into power gating when unused.
8060 		 *
8061 		 * When power gating is enabled on a pipe we lose the
8062 		 * interrupt enablement state when power gating is disabled.
8063 		 *
8064 		 * So we need to update the IRQ control state in hardware
8065 		 * whenever the pipe turns on (since it could be previously
8066 		 * power gated) or off (since some pipes can't be power gated
8067 		 * on some ASICs).
8068 		 */
8069 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
8070 			dm_update_pflip_irq_state(drm_to_adev(dev),
8071 						  acrtc_attach);
8072 
8073 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8074 				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
8075 				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
8076 			amdgpu_dm_link_setup_psr(acrtc_state->stream);
8077 
8078 		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
8079 		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
8080 		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
8081 			struct amdgpu_dm_connector *aconn =
8082 				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8083 
8084 			if (aconn->psr_skip_count > 0)
8085 				aconn->psr_skip_count--;
8086 
8087 			/* Allow PSR when skip count is 0. */
8088 			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
8089 
8090 			/*
8091 			 * If sink supports PSR SU, there is no need to rely on
8092 			 * a vblank event disable request to enable PSR. PSR SU
8093 			 * can be enabled immediately once OS demonstrates an
8094 			 * adequate number of fast atomic commits to notify KMD
8095 			 * of update events. See `vblank_control_worker()`.
8096 			 */
8097 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
8098 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
8099 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
8100 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
8101 #endif
8102 			    !acrtc_state->stream->link->psr_settings.psr_allow_active)
8103 				amdgpu_dm_psr_enable(acrtc_state->stream);
8104 		} else {
8105 			acrtc_attach->dm_irq_params.allow_psr_entry = false;
8106 		}
8107 
8108 		mutex_unlock(&dm->dc_lock);
8109 	}
8110 
8111 	/*
8112 	 * Update cursor state *after* programming all the planes.
8113 	 * This avoids redundant programming in the case where we're going
8114 	 * to be disabling a single plane - those pipes are being disabled.
8115 	 */
8116 	if (acrtc_state->active_planes)
8117 		amdgpu_dm_commit_cursors(state);
8118 
8119 cleanup:
8120 	kfree(bundle);
8121 }
8122 
8123 static void amdgpu_dm_commit_audio(struct drm_device *dev,
8124 				   struct drm_atomic_state *state)
8125 {
8126 	struct amdgpu_device *adev = drm_to_adev(dev);
8127 	struct amdgpu_dm_connector *aconnector;
8128 	struct drm_connector *connector;
8129 	struct drm_connector_state *old_con_state, *new_con_state;
8130 	struct drm_crtc_state *new_crtc_state;
8131 	struct dm_crtc_state *new_dm_crtc_state;
8132 	const struct dc_stream_status *status;
8133 	int i, inst;
8134 
8135 	/* Notify device removals. */
8136 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8137 		if (old_con_state->crtc != new_con_state->crtc) {
8138 			/* CRTC changes require notification. */
8139 			goto notify;
8140 		}
8141 
8142 		if (!new_con_state->crtc)
8143 			continue;
8144 
8145 		new_crtc_state = drm_atomic_get_new_crtc_state(
8146 			state, new_con_state->crtc);
8147 
8148 		if (!new_crtc_state)
8149 			continue;
8150 
8151 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8152 			continue;
8153 
8154 	notify:
8155 		aconnector = to_amdgpu_dm_connector(connector);
8156 
8157 		mutex_lock(&adev->dm.audio_lock);
8158 		inst = aconnector->audio_inst;
8159 		aconnector->audio_inst = -1;
8160 		mutex_unlock(&adev->dm.audio_lock);
8161 
8162 		amdgpu_dm_audio_eld_notify(adev, inst);
8163 	}
8164 
8165 	/* Notify audio device additions. */
8166 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8167 		if (!new_con_state->crtc)
8168 			continue;
8169 
8170 		new_crtc_state = drm_atomic_get_new_crtc_state(
8171 			state, new_con_state->crtc);
8172 
8173 		if (!new_crtc_state)
8174 			continue;
8175 
8176 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8177 			continue;
8178 
8179 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
8180 		if (!new_dm_crtc_state->stream)
8181 			continue;
8182 
8183 		status = dc_stream_get_status(new_dm_crtc_state->stream);
8184 		if (!status)
8185 			continue;
8186 
8187 		aconnector = to_amdgpu_dm_connector(connector);
8188 
8189 		mutex_lock(&adev->dm.audio_lock);
8190 		inst = status->audio_inst;
8191 		aconnector->audio_inst = inst;
8192 		mutex_unlock(&adev->dm.audio_lock);
8193 
8194 		amdgpu_dm_audio_eld_notify(adev, inst);
8195 	}
8196 }
8197 
8198 /*
8199  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8200  * @crtc_state: the DRM CRTC state
8201  * @stream_state: the DC stream state.
8202  *
8203  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8204  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8205  */
8206 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8207 						struct dc_stream_state *stream_state)
8208 {
8209 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8210 }
8211 
8212 /**
8213  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8214  * @state: The atomic state to commit
8215  *
8216  * This will tell DC to commit the constructed DC state from atomic_check,
8217  * programming the hardware. Any failures here implies a hardware failure, since
8218  * atomic check should have filtered anything non-kosher.
8219  */
8220 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8221 {
8222 	struct drm_device *dev = state->dev;
8223 	struct amdgpu_device *adev = drm_to_adev(dev);
8224 	struct amdgpu_display_manager *dm = &adev->dm;
8225 	struct dm_atomic_state *dm_state;
8226 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8227 	u32 i, j;
8228 	struct drm_crtc *crtc;
8229 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8230 	unsigned long flags;
8231 	bool wait_for_vblank = true;
8232 	struct drm_connector *connector;
8233 	struct drm_connector_state *old_con_state, *new_con_state;
8234 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8235 	int crtc_disable_count = 0;
8236 	bool mode_set_reset_required = false;
8237 	int r;
8238 
8239 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
8240 
8241 	r = drm_atomic_helper_wait_for_fences(dev, state, false);
8242 	if (unlikely(r))
8243 		DRM_ERROR("Waiting for fences timed out!");
8244 
8245 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
8246 	drm_dp_mst_atomic_wait_for_dependencies(state);
8247 
8248 	dm_state = dm_atomic_get_new_state(state);
8249 	if (dm_state && dm_state->context) {
8250 		dc_state = dm_state->context;
8251 	} else {
8252 		/* No state changes, retain current state. */
8253 		dc_state_temp = dc_create_state(dm->dc);
8254 		ASSERT(dc_state_temp);
8255 		dc_state = dc_state_temp;
8256 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
8257 	}
8258 
8259 	for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8260 				       new_crtc_state, i) {
8261 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8262 
8263 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8264 
8265 		if (old_crtc_state->active &&
8266 		    (!new_crtc_state->active ||
8267 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8268 			manage_dm_interrupts(adev, acrtc, false);
8269 			dc_stream_release(dm_old_crtc_state->stream);
8270 		}
8271 	}
8272 
8273 	drm_atomic_helper_calc_timestamping_constants(state);
8274 
8275 	/* update changed items */
8276 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8277 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8278 
8279 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8280 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8281 
8282 		drm_dbg_state(state->dev,
8283 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8284 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8285 			"connectors_changed:%d\n",
8286 			acrtc->crtc_id,
8287 			new_crtc_state->enable,
8288 			new_crtc_state->active,
8289 			new_crtc_state->planes_changed,
8290 			new_crtc_state->mode_changed,
8291 			new_crtc_state->active_changed,
8292 			new_crtc_state->connectors_changed);
8293 
8294 		/* Disable cursor if disabling crtc */
8295 		if (old_crtc_state->active && !new_crtc_state->active) {
8296 			struct dc_cursor_position position;
8297 
8298 			memset(&position, 0, sizeof(position));
8299 			mutex_lock(&dm->dc_lock);
8300 			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8301 			mutex_unlock(&dm->dc_lock);
8302 		}
8303 
8304 		/* Copy all transient state flags into dc state */
8305 		if (dm_new_crtc_state->stream) {
8306 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8307 							    dm_new_crtc_state->stream);
8308 		}
8309 
8310 		/* handles headless hotplug case, updating new_state and
8311 		 * aconnector as needed
8312 		 */
8313 
8314 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8315 
8316 			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8317 
8318 			if (!dm_new_crtc_state->stream) {
8319 				/*
8320 				 * this could happen because of issues with
8321 				 * userspace notifications delivery.
8322 				 * In this case userspace tries to set mode on
8323 				 * display which is disconnected in fact.
8324 				 * dc_sink is NULL in this case on aconnector.
8325 				 * We expect reset mode will come soon.
8326 				 *
8327 				 * This can also happen when unplug is done
8328 				 * during resume sequence ended
8329 				 *
8330 				 * In this case, we want to pretend we still
8331 				 * have a sink to keep the pipe running so that
8332 				 * hw state is consistent with the sw state
8333 				 */
8334 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8335 						__func__, acrtc->base.base.id);
8336 				continue;
8337 			}
8338 
8339 			if (dm_old_crtc_state->stream)
8340 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8341 
8342 			pm_runtime_get_noresume(dev->dev);
8343 
8344 			acrtc->enabled = true;
8345 			acrtc->hw_mode = new_crtc_state->mode;
8346 			crtc->hwmode = new_crtc_state->mode;
8347 			mode_set_reset_required = true;
8348 		} else if (modereset_required(new_crtc_state)) {
8349 			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8350 			/* i.e. reset mode */
8351 			if (dm_old_crtc_state->stream)
8352 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8353 
8354 			mode_set_reset_required = true;
8355 		}
8356 	} /* for_each_crtc_in_state() */
8357 
8358 	if (dc_state) {
8359 		/* if there mode set or reset, disable eDP PSR */
8360 		if (mode_set_reset_required) {
8361 			if (dm->vblank_control_workqueue)
8362 				flush_workqueue(dm->vblank_control_workqueue);
8363 
8364 			amdgpu_dm_psr_disable_all(dm);
8365 		}
8366 
8367 		dm_enable_per_frame_crtc_master_sync(dc_state);
8368 		mutex_lock(&dm->dc_lock);
8369 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
8370 
8371 		/* Allow idle optimization when vblank count is 0 for display off */
8372 		if (dm->active_vblank_irq_count == 0)
8373 			dc_allow_idle_optimizations(dm->dc, true);
8374 		mutex_unlock(&dm->dc_lock);
8375 	}
8376 
8377 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8378 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8379 
8380 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8381 
8382 		if (dm_new_crtc_state->stream != NULL) {
8383 			const struct dc_stream_status *status =
8384 					dc_stream_get_status(dm_new_crtc_state->stream);
8385 
8386 			if (!status)
8387 				status = dc_stream_get_status_from_state(dc_state,
8388 									 dm_new_crtc_state->stream);
8389 			if (!status)
8390 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8391 			else
8392 				acrtc->otg_inst = status->primary_otg_inst;
8393 		}
8394 	}
8395 #ifdef CONFIG_DRM_AMD_DC_HDCP
8396 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8397 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8398 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8399 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8400 
8401 		pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
8402 
8403 		if (!connector)
8404 			continue;
8405 
8406 		pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8407 			connector->index, connector->status, connector->dpms);
8408 		pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8409 			old_con_state->content_protection, new_con_state->content_protection);
8410 
8411 		if (aconnector->dc_sink) {
8412 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
8413 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
8414 				pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
8415 				aconnector->dc_sink->edid_caps.display_name);
8416 			}
8417 		}
8418 
8419 		new_crtc_state = NULL;
8420 		old_crtc_state = NULL;
8421 
8422 		if (acrtc) {
8423 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8424 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8425 		}
8426 
8427 		if (old_crtc_state)
8428 			pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8429 			old_crtc_state->enable,
8430 			old_crtc_state->active,
8431 			old_crtc_state->mode_changed,
8432 			old_crtc_state->active_changed,
8433 			old_crtc_state->connectors_changed);
8434 
8435 		if (new_crtc_state)
8436 			pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8437 			new_crtc_state->enable,
8438 			new_crtc_state->active,
8439 			new_crtc_state->mode_changed,
8440 			new_crtc_state->active_changed,
8441 			new_crtc_state->connectors_changed);
8442 	}
8443 
8444 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8445 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8446 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8447 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8448 
8449 		new_crtc_state = NULL;
8450 		old_crtc_state = NULL;
8451 
8452 		if (acrtc) {
8453 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8454 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8455 		}
8456 
8457 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8458 
8459 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8460 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8461 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8462 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8463 			dm_new_con_state->update_hdcp = true;
8464 			continue;
8465 		}
8466 
8467 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
8468 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
8469 			/* when display is unplugged from mst hub, connctor will
8470 			 * be destroyed within dm_dp_mst_connector_destroy. connector
8471 			 * hdcp perperties, like type, undesired, desired, enabled,
8472 			 * will be lost. So, save hdcp properties into hdcp_work within
8473 			 * amdgpu_dm_atomic_commit_tail. if the same display is
8474 			 * plugged back with same display index, its hdcp properties
8475 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
8476 			 */
8477 
8478 			bool enable_encryption = false;
8479 
8480 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
8481 				enable_encryption = true;
8482 
8483 			if (aconnector->dc_link && aconnector->dc_sink &&
8484 				aconnector->dc_link->type == dc_connection_mst_branch) {
8485 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
8486 				struct hdcp_workqueue *hdcp_w =
8487 					&hdcp_work[aconnector->dc_link->link_index];
8488 
8489 				hdcp_w->hdcp_content_type[connector->index] =
8490 					new_con_state->hdcp_content_type;
8491 				hdcp_w->content_protection[connector->index] =
8492 					new_con_state->content_protection;
8493 			}
8494 
8495 			if (new_crtc_state && new_crtc_state->mode_changed &&
8496 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
8497 				enable_encryption = true;
8498 
8499 			DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
8500 
8501 			hdcp_update_display(
8502 				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8503 				new_con_state->hdcp_content_type, enable_encryption);
8504 		}
8505 	}
8506 #endif
8507 
8508 	/* Handle connector state changes */
8509 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8510 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8511 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8512 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8513 		struct dc_surface_update dummy_updates[MAX_SURFACES];
8514 		struct dc_stream_update stream_update;
8515 		struct dc_info_packet hdr_packet;
8516 		struct dc_stream_status *status = NULL;
8517 		bool abm_changed, hdr_changed, scaling_changed;
8518 
8519 		memset(&dummy_updates, 0, sizeof(dummy_updates));
8520 		memset(&stream_update, 0, sizeof(stream_update));
8521 
8522 		if (acrtc) {
8523 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8524 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8525 		}
8526 
8527 		/* Skip any modesets/resets */
8528 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8529 			continue;
8530 
8531 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8532 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8533 
8534 		scaling_changed = is_scaling_state_different(dm_new_con_state,
8535 							     dm_old_con_state);
8536 
8537 		abm_changed = dm_new_crtc_state->abm_level !=
8538 			      dm_old_crtc_state->abm_level;
8539 
8540 		hdr_changed =
8541 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8542 
8543 		if (!scaling_changed && !abm_changed && !hdr_changed)
8544 			continue;
8545 
8546 		stream_update.stream = dm_new_crtc_state->stream;
8547 		if (scaling_changed) {
8548 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8549 					dm_new_con_state, dm_new_crtc_state->stream);
8550 
8551 			stream_update.src = dm_new_crtc_state->stream->src;
8552 			stream_update.dst = dm_new_crtc_state->stream->dst;
8553 		}
8554 
8555 		if (abm_changed) {
8556 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8557 
8558 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
8559 		}
8560 
8561 		if (hdr_changed) {
8562 			fill_hdr_info_packet(new_con_state, &hdr_packet);
8563 			stream_update.hdr_static_metadata = &hdr_packet;
8564 		}
8565 
8566 		status = dc_stream_get_status(dm_new_crtc_state->stream);
8567 
8568 		if (WARN_ON(!status))
8569 			continue;
8570 
8571 		WARN_ON(!status->plane_count);
8572 
8573 		/*
8574 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
8575 		 * Here we create an empty update on each plane.
8576 		 * To fix this, DC should permit updating only stream properties.
8577 		 */
8578 		for (j = 0; j < status->plane_count; j++)
8579 			dummy_updates[j].surface = status->plane_states[0];
8580 
8581 
8582 		mutex_lock(&dm->dc_lock);
8583 		dc_commit_updates_for_stream(dm->dc,
8584 						     dummy_updates,
8585 						     status->plane_count,
8586 						     dm_new_crtc_state->stream,
8587 						     &stream_update,
8588 						     dc_state);
8589 		mutex_unlock(&dm->dc_lock);
8590 	}
8591 
8592 	/**
8593 	 * Enable interrupts for CRTCs that are newly enabled or went through
8594 	 * a modeset. It was intentionally deferred until after the front end
8595 	 * state was modified to wait until the OTG was on and so the IRQ
8596 	 * handlers didn't access stale or invalid state.
8597 	 */
8598 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8599 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8600 #ifdef CONFIG_DEBUG_FS
8601 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
8602 #endif
8603 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
8604 		if (old_crtc_state->active && !new_crtc_state->active)
8605 			crtc_disable_count++;
8606 
8607 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8608 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8609 
8610 		/* For freesync config update on crtc state and params for irq */
8611 		update_stream_irq_parameters(dm, dm_new_crtc_state);
8612 
8613 #ifdef CONFIG_DEBUG_FS
8614 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8615 		cur_crc_src = acrtc->dm_irq_params.crc_src;
8616 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8617 #endif
8618 
8619 		if (new_crtc_state->active &&
8620 		    (!old_crtc_state->active ||
8621 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8622 			dc_stream_retain(dm_new_crtc_state->stream);
8623 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8624 			manage_dm_interrupts(adev, acrtc, true);
8625 		}
8626 		/* Handle vrr on->off / off->on transitions */
8627 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8628 
8629 #ifdef CONFIG_DEBUG_FS
8630 		if (new_crtc_state->active &&
8631 		    (!old_crtc_state->active ||
8632 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8633 			/**
8634 			 * Frontend may have changed so reapply the CRC capture
8635 			 * settings for the stream.
8636 			 */
8637 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8638 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8639 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
8640 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8641 					acrtc->dm_irq_params.window_param.update_win = true;
8642 
8643 					/**
8644 					 * It takes 2 frames for HW to stably generate CRC when
8645 					 * resuming from suspend, so we set skip_frame_cnt 2.
8646 					 */
8647 					acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
8648 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8649 				}
8650 #endif
8651 				if (amdgpu_dm_crtc_configure_crc_source(
8652 					crtc, dm_new_crtc_state, cur_crc_src))
8653 					DRM_DEBUG_DRIVER("Failed to configure crc source");
8654 			}
8655 		}
8656 #endif
8657 	}
8658 
8659 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8660 		if (new_crtc_state->async_flip)
8661 			wait_for_vblank = false;
8662 
8663 	/* update planes when needed per crtc*/
8664 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8665 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8666 
8667 		if (dm_new_crtc_state->stream)
8668 			amdgpu_dm_commit_planes(state, dc_state, dev,
8669 						dm, crtc, wait_for_vblank);
8670 	}
8671 
8672 	/* Update audio instances for each connector. */
8673 	amdgpu_dm_commit_audio(dev, state);
8674 
8675 	/* restore the backlight level */
8676 	for (i = 0; i < dm->num_of_edps; i++) {
8677 		if (dm->backlight_dev[i] &&
8678 		    (dm->actual_brightness[i] != dm->brightness[i]))
8679 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8680 	}
8681 
8682 	/*
8683 	 * send vblank event on all events not handled in flip and
8684 	 * mark consumed event for drm_atomic_helper_commit_hw_done
8685 	 */
8686 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8687 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8688 
8689 		if (new_crtc_state->event)
8690 			drm_send_event_locked(dev, &new_crtc_state->event->base);
8691 
8692 		new_crtc_state->event = NULL;
8693 	}
8694 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8695 
8696 	/* Signal HW programming completion */
8697 	drm_atomic_helper_commit_hw_done(state);
8698 
8699 	if (wait_for_vblank)
8700 		drm_atomic_helper_wait_for_flip_done(dev, state);
8701 
8702 	drm_atomic_helper_cleanup_planes(dev, state);
8703 
8704 	/* return the stolen vga memory back to VRAM */
8705 	if (!adev->mman.keep_stolen_vga_memory)
8706 		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8707 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8708 
8709 	/*
8710 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
8711 	 * so we can put the GPU into runtime suspend if we're not driving any
8712 	 * displays anymore
8713 	 */
8714 	for (i = 0; i < crtc_disable_count; i++)
8715 		pm_runtime_put_autosuspend(dev->dev);
8716 	pm_runtime_mark_last_busy(dev->dev);
8717 
8718 	if (dc_state_temp)
8719 		dc_release_state(dc_state_temp);
8720 }
8721 
8722 static int dm_force_atomic_commit(struct drm_connector *connector)
8723 {
8724 	int ret = 0;
8725 	struct drm_device *ddev = connector->dev;
8726 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8727 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8728 	struct drm_plane *plane = disconnected_acrtc->base.primary;
8729 	struct drm_connector_state *conn_state;
8730 	struct drm_crtc_state *crtc_state;
8731 	struct drm_plane_state *plane_state;
8732 
8733 	if (!state)
8734 		return -ENOMEM;
8735 
8736 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
8737 
8738 	/* Construct an atomic state to restore previous display setting */
8739 
8740 	/*
8741 	 * Attach connectors to drm_atomic_state
8742 	 */
8743 	conn_state = drm_atomic_get_connector_state(state, connector);
8744 
8745 	ret = PTR_ERR_OR_ZERO(conn_state);
8746 	if (ret)
8747 		goto out;
8748 
8749 	/* Attach crtc to drm_atomic_state*/
8750 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8751 
8752 	ret = PTR_ERR_OR_ZERO(crtc_state);
8753 	if (ret)
8754 		goto out;
8755 
8756 	/* force a restore */
8757 	crtc_state->mode_changed = true;
8758 
8759 	/* Attach plane to drm_atomic_state */
8760 	plane_state = drm_atomic_get_plane_state(state, plane);
8761 
8762 	ret = PTR_ERR_OR_ZERO(plane_state);
8763 	if (ret)
8764 		goto out;
8765 
8766 	/* Call commit internally with the state we just constructed */
8767 	ret = drm_atomic_commit(state);
8768 
8769 out:
8770 	drm_atomic_state_put(state);
8771 	if (ret)
8772 		DRM_ERROR("Restoring old state failed with %i\n", ret);
8773 
8774 	return ret;
8775 }
8776 
8777 /*
8778  * This function handles all cases when set mode does not come upon hotplug.
8779  * This includes when a display is unplugged then plugged back into the
8780  * same port and when running without usermode desktop manager supprot
8781  */
8782 void dm_restore_drm_connector_state(struct drm_device *dev,
8783 				    struct drm_connector *connector)
8784 {
8785 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8786 	struct amdgpu_crtc *disconnected_acrtc;
8787 	struct dm_crtc_state *acrtc_state;
8788 
8789 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8790 		return;
8791 
8792 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8793 	if (!disconnected_acrtc)
8794 		return;
8795 
8796 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8797 	if (!acrtc_state->stream)
8798 		return;
8799 
8800 	/*
8801 	 * If the previous sink is not released and different from the current,
8802 	 * we deduce we are in a state where we can not rely on usermode call
8803 	 * to turn on the display, so we do it here
8804 	 */
8805 	if (acrtc_state->stream->sink != aconnector->dc_sink)
8806 		dm_force_atomic_commit(&aconnector->base);
8807 }
8808 
8809 /*
8810  * Grabs all modesetting locks to serialize against any blocking commits,
8811  * Waits for completion of all non blocking commits.
8812  */
8813 static int do_aquire_global_lock(struct drm_device *dev,
8814 				 struct drm_atomic_state *state)
8815 {
8816 	struct drm_crtc *crtc;
8817 	struct drm_crtc_commit *commit;
8818 	long ret;
8819 
8820 	/*
8821 	 * Adding all modeset locks to aquire_ctx will
8822 	 * ensure that when the framework release it the
8823 	 * extra locks we are locking here will get released to
8824 	 */
8825 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8826 	if (ret)
8827 		return ret;
8828 
8829 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8830 		spin_lock(&crtc->commit_lock);
8831 		commit = list_first_entry_or_null(&crtc->commit_list,
8832 				struct drm_crtc_commit, commit_entry);
8833 		if (commit)
8834 			drm_crtc_commit_get(commit);
8835 		spin_unlock(&crtc->commit_lock);
8836 
8837 		if (!commit)
8838 			continue;
8839 
8840 		/*
8841 		 * Make sure all pending HW programming completed and
8842 		 * page flips done
8843 		 */
8844 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8845 
8846 		if (ret > 0)
8847 			ret = wait_for_completion_interruptible_timeout(
8848 					&commit->flip_done, 10*HZ);
8849 
8850 		if (ret == 0)
8851 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8852 				  "timed out\n", crtc->base.id, crtc->name);
8853 
8854 		drm_crtc_commit_put(commit);
8855 	}
8856 
8857 	return ret < 0 ? ret : 0;
8858 }
8859 
8860 static void get_freesync_config_for_crtc(
8861 	struct dm_crtc_state *new_crtc_state,
8862 	struct dm_connector_state *new_con_state)
8863 {
8864 	struct mod_freesync_config config = {0};
8865 	struct amdgpu_dm_connector *aconnector =
8866 			to_amdgpu_dm_connector(new_con_state->base.connector);
8867 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
8868 	int vrefresh = drm_mode_vrefresh(mode);
8869 	bool fs_vid_mode = false;
8870 
8871 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8872 					vrefresh >= aconnector->min_vfreq &&
8873 					vrefresh <= aconnector->max_vfreq;
8874 
8875 	if (new_crtc_state->vrr_supported) {
8876 		new_crtc_state->stream->ignore_msa_timing_param = true;
8877 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8878 
8879 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8880 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8881 		config.vsif_supported = true;
8882 		config.btr = true;
8883 
8884 		if (fs_vid_mode) {
8885 			config.state = VRR_STATE_ACTIVE_FIXED;
8886 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8887 			goto out;
8888 		} else if (new_crtc_state->base.vrr_enabled) {
8889 			config.state = VRR_STATE_ACTIVE_VARIABLE;
8890 		} else {
8891 			config.state = VRR_STATE_INACTIVE;
8892 		}
8893 	}
8894 out:
8895 	new_crtc_state->freesync_config = config;
8896 }
8897 
8898 static void reset_freesync_config_for_crtc(
8899 	struct dm_crtc_state *new_crtc_state)
8900 {
8901 	new_crtc_state->vrr_supported = false;
8902 
8903 	memset(&new_crtc_state->vrr_infopacket, 0,
8904 	       sizeof(new_crtc_state->vrr_infopacket));
8905 }
8906 
8907 static bool
8908 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8909 				 struct drm_crtc_state *new_crtc_state)
8910 {
8911 	const struct drm_display_mode *old_mode, *new_mode;
8912 
8913 	if (!old_crtc_state || !new_crtc_state)
8914 		return false;
8915 
8916 	old_mode = &old_crtc_state->mode;
8917 	new_mode = &new_crtc_state->mode;
8918 
8919 	if (old_mode->clock       == new_mode->clock &&
8920 	    old_mode->hdisplay    == new_mode->hdisplay &&
8921 	    old_mode->vdisplay    == new_mode->vdisplay &&
8922 	    old_mode->htotal      == new_mode->htotal &&
8923 	    old_mode->vtotal      != new_mode->vtotal &&
8924 	    old_mode->hsync_start == new_mode->hsync_start &&
8925 	    old_mode->vsync_start != new_mode->vsync_start &&
8926 	    old_mode->hsync_end   == new_mode->hsync_end &&
8927 	    old_mode->vsync_end   != new_mode->vsync_end &&
8928 	    old_mode->hskew       == new_mode->hskew &&
8929 	    old_mode->vscan       == new_mode->vscan &&
8930 	    (old_mode->vsync_end - old_mode->vsync_start) ==
8931 	    (new_mode->vsync_end - new_mode->vsync_start))
8932 		return true;
8933 
8934 	return false;
8935 }
8936 
8937 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
8938 	u64 num, den, res;
8939 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
8940 
8941 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
8942 
8943 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
8944 	den = (unsigned long long)new_crtc_state->mode.htotal *
8945 	      (unsigned long long)new_crtc_state->mode.vtotal;
8946 
8947 	res = div_u64(num, den);
8948 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
8949 }
8950 
8951 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
8952 			 struct drm_atomic_state *state,
8953 			 struct drm_crtc *crtc,
8954 			 struct drm_crtc_state *old_crtc_state,
8955 			 struct drm_crtc_state *new_crtc_state,
8956 			 bool enable,
8957 			 bool *lock_and_validation_needed)
8958 {
8959 	struct dm_atomic_state *dm_state = NULL;
8960 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8961 	struct dc_stream_state *new_stream;
8962 	int ret = 0;
8963 
8964 	/*
8965 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
8966 	 * update changed items
8967 	 */
8968 	struct amdgpu_crtc *acrtc = NULL;
8969 	struct amdgpu_dm_connector *aconnector = NULL;
8970 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
8971 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
8972 
8973 	new_stream = NULL;
8974 
8975 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8976 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8977 	acrtc = to_amdgpu_crtc(crtc);
8978 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
8979 
8980 	/* TODO This hack should go away */
8981 	if (aconnector && enable) {
8982 		/* Make sure fake sink is created in plug-in scenario */
8983 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
8984 							    &aconnector->base);
8985 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
8986 							    &aconnector->base);
8987 
8988 		if (IS_ERR(drm_new_conn_state)) {
8989 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
8990 			goto fail;
8991 		}
8992 
8993 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
8994 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
8995 
8996 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8997 			goto skip_modeset;
8998 
8999 		new_stream = create_validate_stream_for_sink(aconnector,
9000 							     &new_crtc_state->mode,
9001 							     dm_new_conn_state,
9002 							     dm_old_crtc_state->stream);
9003 
9004 		/*
9005 		 * we can have no stream on ACTION_SET if a display
9006 		 * was disconnected during S3, in this case it is not an
9007 		 * error, the OS will be updated after detection, and
9008 		 * will do the right thing on next atomic commit
9009 		 */
9010 
9011 		if (!new_stream) {
9012 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
9013 					__func__, acrtc->base.base.id);
9014 			ret = -ENOMEM;
9015 			goto fail;
9016 		}
9017 
9018 		/*
9019 		 * TODO: Check VSDB bits to decide whether this should
9020 		 * be enabled or not.
9021 		 */
9022 		new_stream->triggered_crtc_reset.enabled =
9023 			dm->force_timing_sync;
9024 
9025 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9026 
9027 		ret = fill_hdr_info_packet(drm_new_conn_state,
9028 					   &new_stream->hdr_static_metadata);
9029 		if (ret)
9030 			goto fail;
9031 
9032 		/*
9033 		 * If we already removed the old stream from the context
9034 		 * (and set the new stream to NULL) then we can't reuse
9035 		 * the old stream even if the stream and scaling are unchanged.
9036 		 * We'll hit the BUG_ON and black screen.
9037 		 *
9038 		 * TODO: Refactor this function to allow this check to work
9039 		 * in all conditions.
9040 		 */
9041 		if (amdgpu_freesync_vid_mode &&
9042 		    dm_new_crtc_state->stream &&
9043 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
9044 			goto skip_modeset;
9045 
9046 		if (dm_new_crtc_state->stream &&
9047 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9048 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
9049 			new_crtc_state->mode_changed = false;
9050 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
9051 					 new_crtc_state->mode_changed);
9052 		}
9053 	}
9054 
9055 	/* mode_changed flag may get updated above, need to check again */
9056 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9057 		goto skip_modeset;
9058 
9059 	drm_dbg_state(state->dev,
9060 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
9061 		"planes_changed:%d, mode_changed:%d,active_changed:%d,"
9062 		"connectors_changed:%d\n",
9063 		acrtc->crtc_id,
9064 		new_crtc_state->enable,
9065 		new_crtc_state->active,
9066 		new_crtc_state->planes_changed,
9067 		new_crtc_state->mode_changed,
9068 		new_crtc_state->active_changed,
9069 		new_crtc_state->connectors_changed);
9070 
9071 	/* Remove stream for any changed/disabled CRTC */
9072 	if (!enable) {
9073 
9074 		if (!dm_old_crtc_state->stream)
9075 			goto skip_modeset;
9076 
9077 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
9078 		    is_timing_unchanged_for_freesync(new_crtc_state,
9079 						     old_crtc_state)) {
9080 			new_crtc_state->mode_changed = false;
9081 			DRM_DEBUG_DRIVER(
9082 				"Mode change not required for front porch change, "
9083 				"setting mode_changed to %d",
9084 				new_crtc_state->mode_changed);
9085 
9086 			set_freesync_fixed_config(dm_new_crtc_state);
9087 
9088 			goto skip_modeset;
9089 		} else if (amdgpu_freesync_vid_mode && aconnector &&
9090 			   is_freesync_video_mode(&new_crtc_state->mode,
9091 						  aconnector)) {
9092 			struct drm_display_mode *high_mode;
9093 
9094 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
9095 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
9096 				set_freesync_fixed_config(dm_new_crtc_state);
9097 			}
9098 		}
9099 
9100 		ret = dm_atomic_get_state(state, &dm_state);
9101 		if (ret)
9102 			goto fail;
9103 
9104 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
9105 				crtc->base.id);
9106 
9107 		/* i.e. reset mode */
9108 		if (dc_remove_stream_from_ctx(
9109 				dm->dc,
9110 				dm_state->context,
9111 				dm_old_crtc_state->stream) != DC_OK) {
9112 			ret = -EINVAL;
9113 			goto fail;
9114 		}
9115 
9116 		dc_stream_release(dm_old_crtc_state->stream);
9117 		dm_new_crtc_state->stream = NULL;
9118 
9119 		reset_freesync_config_for_crtc(dm_new_crtc_state);
9120 
9121 		*lock_and_validation_needed = true;
9122 
9123 	} else {/* Add stream for any updated/enabled CRTC */
9124 		/*
9125 		 * Quick fix to prevent NULL pointer on new_stream when
9126 		 * added MST connectors not found in existing crtc_state in the chained mode
9127 		 * TODO: need to dig out the root cause of that
9128 		 */
9129 		if (!aconnector)
9130 			goto skip_modeset;
9131 
9132 		if (modereset_required(new_crtc_state))
9133 			goto skip_modeset;
9134 
9135 		if (modeset_required(new_crtc_state, new_stream,
9136 				     dm_old_crtc_state->stream)) {
9137 
9138 			WARN_ON(dm_new_crtc_state->stream);
9139 
9140 			ret = dm_atomic_get_state(state, &dm_state);
9141 			if (ret)
9142 				goto fail;
9143 
9144 			dm_new_crtc_state->stream = new_stream;
9145 
9146 			dc_stream_retain(new_stream);
9147 
9148 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
9149 					 crtc->base.id);
9150 
9151 			if (dc_add_stream_to_ctx(
9152 					dm->dc,
9153 					dm_state->context,
9154 					dm_new_crtc_state->stream) != DC_OK) {
9155 				ret = -EINVAL;
9156 				goto fail;
9157 			}
9158 
9159 			*lock_and_validation_needed = true;
9160 		}
9161 	}
9162 
9163 skip_modeset:
9164 	/* Release extra reference */
9165 	if (new_stream)
9166 		 dc_stream_release(new_stream);
9167 
9168 	/*
9169 	 * We want to do dc stream updates that do not require a
9170 	 * full modeset below.
9171 	 */
9172 	if (!(enable && aconnector && new_crtc_state->active))
9173 		return 0;
9174 	/*
9175 	 * Given above conditions, the dc state cannot be NULL because:
9176 	 * 1. We're in the process of enabling CRTCs (just been added
9177 	 *    to the dc context, or already is on the context)
9178 	 * 2. Has a valid connector attached, and
9179 	 * 3. Is currently active and enabled.
9180 	 * => The dc stream state currently exists.
9181 	 */
9182 	BUG_ON(dm_new_crtc_state->stream == NULL);
9183 
9184 	/* Scaling or underscan settings */
9185 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
9186 				drm_atomic_crtc_needs_modeset(new_crtc_state))
9187 		update_stream_scaling_settings(
9188 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
9189 
9190 	/* ABM settings */
9191 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9192 
9193 	/*
9194 	 * Color management settings. We also update color properties
9195 	 * when a modeset is needed, to ensure it gets reprogrammed.
9196 	 */
9197 	if (dm_new_crtc_state->base.color_mgmt_changed ||
9198 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9199 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
9200 		if (ret)
9201 			goto fail;
9202 	}
9203 
9204 	/* Update Freesync settings. */
9205 	get_freesync_config_for_crtc(dm_new_crtc_state,
9206 				     dm_new_conn_state);
9207 
9208 	return ret;
9209 
9210 fail:
9211 	if (new_stream)
9212 		dc_stream_release(new_stream);
9213 	return ret;
9214 }
9215 
9216 static bool should_reset_plane(struct drm_atomic_state *state,
9217 			       struct drm_plane *plane,
9218 			       struct drm_plane_state *old_plane_state,
9219 			       struct drm_plane_state *new_plane_state)
9220 {
9221 	struct drm_plane *other;
9222 	struct drm_plane_state *old_other_state, *new_other_state;
9223 	struct drm_crtc_state *new_crtc_state;
9224 	int i;
9225 
9226 	/*
9227 	 * TODO: Remove this hack once the checks below are sufficient
9228 	 * enough to determine when we need to reset all the planes on
9229 	 * the stream.
9230 	 */
9231 	if (state->allow_modeset)
9232 		return true;
9233 
9234 	/* Exit early if we know that we're adding or removing the plane. */
9235 	if (old_plane_state->crtc != new_plane_state->crtc)
9236 		return true;
9237 
9238 	/* old crtc == new_crtc == NULL, plane not in context. */
9239 	if (!new_plane_state->crtc)
9240 		return false;
9241 
9242 	new_crtc_state =
9243 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
9244 
9245 	if (!new_crtc_state)
9246 		return true;
9247 
9248 	/* CRTC Degamma changes currently require us to recreate planes. */
9249 	if (new_crtc_state->color_mgmt_changed)
9250 		return true;
9251 
9252 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
9253 		return true;
9254 
9255 	/*
9256 	 * If there are any new primary or overlay planes being added or
9257 	 * removed then the z-order can potentially change. To ensure
9258 	 * correct z-order and pipe acquisition the current DC architecture
9259 	 * requires us to remove and recreate all existing planes.
9260 	 *
9261 	 * TODO: Come up with a more elegant solution for this.
9262 	 */
9263 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9264 		struct amdgpu_framebuffer *old_afb, *new_afb;
9265 		if (other->type == DRM_PLANE_TYPE_CURSOR)
9266 			continue;
9267 
9268 		if (old_other_state->crtc != new_plane_state->crtc &&
9269 		    new_other_state->crtc != new_plane_state->crtc)
9270 			continue;
9271 
9272 		if (old_other_state->crtc != new_other_state->crtc)
9273 			return true;
9274 
9275 		/* Src/dst size and scaling updates. */
9276 		if (old_other_state->src_w != new_other_state->src_w ||
9277 		    old_other_state->src_h != new_other_state->src_h ||
9278 		    old_other_state->crtc_w != new_other_state->crtc_w ||
9279 		    old_other_state->crtc_h != new_other_state->crtc_h)
9280 			return true;
9281 
9282 		/* Rotation / mirroring updates. */
9283 		if (old_other_state->rotation != new_other_state->rotation)
9284 			return true;
9285 
9286 		/* Blending updates. */
9287 		if (old_other_state->pixel_blend_mode !=
9288 		    new_other_state->pixel_blend_mode)
9289 			return true;
9290 
9291 		/* Alpha updates. */
9292 		if (old_other_state->alpha != new_other_state->alpha)
9293 			return true;
9294 
9295 		/* Colorspace changes. */
9296 		if (old_other_state->color_range != new_other_state->color_range ||
9297 		    old_other_state->color_encoding != new_other_state->color_encoding)
9298 			return true;
9299 
9300 		/* Framebuffer checks fall at the end. */
9301 		if (!old_other_state->fb || !new_other_state->fb)
9302 			continue;
9303 
9304 		/* Pixel format changes can require bandwidth updates. */
9305 		if (old_other_state->fb->format != new_other_state->fb->format)
9306 			return true;
9307 
9308 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9309 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9310 
9311 		/* Tiling and DCC changes also require bandwidth updates. */
9312 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
9313 		    old_afb->base.modifier != new_afb->base.modifier)
9314 			return true;
9315 	}
9316 
9317 	return false;
9318 }
9319 
9320 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9321 			      struct drm_plane_state *new_plane_state,
9322 			      struct drm_framebuffer *fb)
9323 {
9324 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9325 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9326 	unsigned int pitch;
9327 	bool linear;
9328 
9329 	if (fb->width > new_acrtc->max_cursor_width ||
9330 	    fb->height > new_acrtc->max_cursor_height) {
9331 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9332 				 new_plane_state->fb->width,
9333 				 new_plane_state->fb->height);
9334 		return -EINVAL;
9335 	}
9336 	if (new_plane_state->src_w != fb->width << 16 ||
9337 	    new_plane_state->src_h != fb->height << 16) {
9338 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9339 		return -EINVAL;
9340 	}
9341 
9342 	/* Pitch in pixels */
9343 	pitch = fb->pitches[0] / fb->format->cpp[0];
9344 
9345 	if (fb->width != pitch) {
9346 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9347 				 fb->width, pitch);
9348 		return -EINVAL;
9349 	}
9350 
9351 	switch (pitch) {
9352 	case 64:
9353 	case 128:
9354 	case 256:
9355 		/* FB pitch is supported by cursor plane */
9356 		break;
9357 	default:
9358 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9359 		return -EINVAL;
9360 	}
9361 
9362 	/* Core DRM takes care of checking FB modifiers, so we only need to
9363 	 * check tiling flags when the FB doesn't have a modifier. */
9364 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9365 		if (adev->family < AMDGPU_FAMILY_AI) {
9366 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9367 			         AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9368 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9369 		} else {
9370 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9371 		}
9372 		if (!linear) {
9373 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
9374 			return -EINVAL;
9375 		}
9376 	}
9377 
9378 	return 0;
9379 }
9380 
9381 static int dm_update_plane_state(struct dc *dc,
9382 				 struct drm_atomic_state *state,
9383 				 struct drm_plane *plane,
9384 				 struct drm_plane_state *old_plane_state,
9385 				 struct drm_plane_state *new_plane_state,
9386 				 bool enable,
9387 				 bool *lock_and_validation_needed)
9388 {
9389 
9390 	struct dm_atomic_state *dm_state = NULL;
9391 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9392 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9393 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9394 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9395 	struct amdgpu_crtc *new_acrtc;
9396 	bool needs_reset;
9397 	int ret = 0;
9398 
9399 
9400 	new_plane_crtc = new_plane_state->crtc;
9401 	old_plane_crtc = old_plane_state->crtc;
9402 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
9403 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
9404 
9405 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9406 		if (!enable || !new_plane_crtc ||
9407 			drm_atomic_plane_disabling(plane->state, new_plane_state))
9408 			return 0;
9409 
9410 		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9411 
9412 		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9413 			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9414 			return -EINVAL;
9415 		}
9416 
9417 		if (new_plane_state->fb) {
9418 			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9419 						 new_plane_state->fb);
9420 			if (ret)
9421 				return ret;
9422 		}
9423 
9424 		return 0;
9425 	}
9426 
9427 	needs_reset = should_reset_plane(state, plane, old_plane_state,
9428 					 new_plane_state);
9429 
9430 	/* Remove any changed/removed planes */
9431 	if (!enable) {
9432 		if (!needs_reset)
9433 			return 0;
9434 
9435 		if (!old_plane_crtc)
9436 			return 0;
9437 
9438 		old_crtc_state = drm_atomic_get_old_crtc_state(
9439 				state, old_plane_crtc);
9440 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9441 
9442 		if (!dm_old_crtc_state->stream)
9443 			return 0;
9444 
9445 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9446 				plane->base.id, old_plane_crtc->base.id);
9447 
9448 		ret = dm_atomic_get_state(state, &dm_state);
9449 		if (ret)
9450 			return ret;
9451 
9452 		if (!dc_remove_plane_from_context(
9453 				dc,
9454 				dm_old_crtc_state->stream,
9455 				dm_old_plane_state->dc_state,
9456 				dm_state->context)) {
9457 
9458 			return -EINVAL;
9459 		}
9460 
9461 
9462 		dc_plane_state_release(dm_old_plane_state->dc_state);
9463 		dm_new_plane_state->dc_state = NULL;
9464 
9465 		*lock_and_validation_needed = true;
9466 
9467 	} else { /* Add new planes */
9468 		struct dc_plane_state *dc_new_plane_state;
9469 
9470 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9471 			return 0;
9472 
9473 		if (!new_plane_crtc)
9474 			return 0;
9475 
9476 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9477 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9478 
9479 		if (!dm_new_crtc_state->stream)
9480 			return 0;
9481 
9482 		if (!needs_reset)
9483 			return 0;
9484 
9485 		ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9486 		if (ret)
9487 			return ret;
9488 
9489 		WARN_ON(dm_new_plane_state->dc_state);
9490 
9491 		dc_new_plane_state = dc_create_plane_state(dc);
9492 		if (!dc_new_plane_state)
9493 			return -ENOMEM;
9494 
9495 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9496 				 plane->base.id, new_plane_crtc->base.id);
9497 
9498 		ret = fill_dc_plane_attributes(
9499 			drm_to_adev(new_plane_crtc->dev),
9500 			dc_new_plane_state,
9501 			new_plane_state,
9502 			new_crtc_state);
9503 		if (ret) {
9504 			dc_plane_state_release(dc_new_plane_state);
9505 			return ret;
9506 		}
9507 
9508 		ret = dm_atomic_get_state(state, &dm_state);
9509 		if (ret) {
9510 			dc_plane_state_release(dc_new_plane_state);
9511 			return ret;
9512 		}
9513 
9514 		/*
9515 		 * Any atomic check errors that occur after this will
9516 		 * not need a release. The plane state will be attached
9517 		 * to the stream, and therefore part of the atomic
9518 		 * state. It'll be released when the atomic state is
9519 		 * cleaned.
9520 		 */
9521 		if (!dc_add_plane_to_context(
9522 				dc,
9523 				dm_new_crtc_state->stream,
9524 				dc_new_plane_state,
9525 				dm_state->context)) {
9526 
9527 			dc_plane_state_release(dc_new_plane_state);
9528 			return -EINVAL;
9529 		}
9530 
9531 		dm_new_plane_state->dc_state = dc_new_plane_state;
9532 
9533 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9534 
9535 		/* Tell DC to do a full surface update every time there
9536 		 * is a plane change. Inefficient, but works for now.
9537 		 */
9538 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9539 
9540 		*lock_and_validation_needed = true;
9541 	}
9542 
9543 
9544 	return ret;
9545 }
9546 
9547 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9548 				       int *src_w, int *src_h)
9549 {
9550 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9551 	case DRM_MODE_ROTATE_90:
9552 	case DRM_MODE_ROTATE_270:
9553 		*src_w = plane_state->src_h >> 16;
9554 		*src_h = plane_state->src_w >> 16;
9555 		break;
9556 	case DRM_MODE_ROTATE_0:
9557 	case DRM_MODE_ROTATE_180:
9558 	default:
9559 		*src_w = plane_state->src_w >> 16;
9560 		*src_h = plane_state->src_h >> 16;
9561 		break;
9562 	}
9563 }
9564 
9565 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9566 				struct drm_crtc *crtc,
9567 				struct drm_crtc_state *new_crtc_state)
9568 {
9569 	struct drm_plane *cursor = crtc->cursor, *underlying;
9570 	struct drm_plane_state *new_cursor_state, *new_underlying_state;
9571 	int i;
9572 	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9573 	int cursor_src_w, cursor_src_h;
9574 	int underlying_src_w, underlying_src_h;
9575 
9576 	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9577 	 * cursor per pipe but it's going to inherit the scaling and
9578 	 * positioning from the underlying pipe. Check the cursor plane's
9579 	 * blending properties match the underlying planes'. */
9580 
9581 	new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9582 	if (!new_cursor_state || !new_cursor_state->fb) {
9583 		return 0;
9584 	}
9585 
9586 	dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9587 	cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9588 	cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9589 
9590 	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9591 		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
9592 		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9593 			continue;
9594 
9595 		/* Ignore disabled planes */
9596 		if (!new_underlying_state->fb)
9597 			continue;
9598 
9599 		dm_get_oriented_plane_size(new_underlying_state,
9600 					   &underlying_src_w, &underlying_src_h);
9601 		underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9602 		underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9603 
9604 		if (cursor_scale_w != underlying_scale_w ||
9605 		    cursor_scale_h != underlying_scale_h) {
9606 			drm_dbg_atomic(crtc->dev,
9607 				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9608 				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9609 			return -EINVAL;
9610 		}
9611 
9612 		/* If this plane covers the whole CRTC, no need to check planes underneath */
9613 		if (new_underlying_state->crtc_x <= 0 &&
9614 		    new_underlying_state->crtc_y <= 0 &&
9615 		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9616 		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9617 			break;
9618 	}
9619 
9620 	return 0;
9621 }
9622 
9623 #if defined(CONFIG_DRM_AMD_DC_DCN)
9624 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9625 {
9626 	struct drm_connector *connector;
9627 	struct drm_connector_state *conn_state, *old_conn_state;
9628 	struct amdgpu_dm_connector *aconnector = NULL;
9629 	int i;
9630 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9631 		if (!conn_state->crtc)
9632 			conn_state = old_conn_state;
9633 
9634 		if (conn_state->crtc != crtc)
9635 			continue;
9636 
9637 		aconnector = to_amdgpu_dm_connector(connector);
9638 		if (!aconnector->mst_output_port || !aconnector->mst_root)
9639 			aconnector = NULL;
9640 		else
9641 			break;
9642 	}
9643 
9644 	if (!aconnector)
9645 		return 0;
9646 
9647 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
9648 }
9649 #endif
9650 
9651 /**
9652  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9653  *
9654  * @dev: The DRM device
9655  * @state: The atomic state to commit
9656  *
9657  * Validate that the given atomic state is programmable by DC into hardware.
9658  * This involves constructing a &struct dc_state reflecting the new hardware
9659  * state we wish to commit, then querying DC to see if it is programmable. It's
9660  * important not to modify the existing DC state. Otherwise, atomic_check
9661  * may unexpectedly commit hardware changes.
9662  *
9663  * When validating the DC state, it's important that the right locks are
9664  * acquired. For full updates case which removes/adds/updates streams on one
9665  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9666  * that any such full update commit will wait for completion of any outstanding
9667  * flip using DRMs synchronization events.
9668  *
9669  * Note that DM adds the affected connectors for all CRTCs in state, when that
9670  * might not seem necessary. This is because DC stream creation requires the
9671  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9672  * be possible but non-trivial - a possible TODO item.
9673  *
9674  * Return: -Error code if validation failed.
9675  */
9676 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9677 				  struct drm_atomic_state *state)
9678 {
9679 	struct amdgpu_device *adev = drm_to_adev(dev);
9680 	struct dm_atomic_state *dm_state = NULL;
9681 	struct dc *dc = adev->dm.dc;
9682 	struct drm_connector *connector;
9683 	struct drm_connector_state *old_con_state, *new_con_state;
9684 	struct drm_crtc *crtc;
9685 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9686 	struct drm_dp_mst_topology_mgr *mgr;
9687 	struct drm_dp_mst_topology_state *mst_state;
9688 	struct drm_plane *plane;
9689 	struct drm_plane_state *old_plane_state, *new_plane_state;
9690 	enum dc_status status;
9691 	int ret, i;
9692 	bool lock_and_validation_needed = false;
9693 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9694 #if defined(CONFIG_DRM_AMD_DC_DCN)
9695 	struct dsc_mst_fairness_vars vars[MAX_PIPES];
9696 #endif
9697 
9698 	trace_amdgpu_dm_atomic_check_begin(state);
9699 
9700 	ret = drm_atomic_helper_check_modeset(dev, state);
9701 	if (ret) {
9702 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9703 		goto fail;
9704 	}
9705 
9706 	/* Check connector changes */
9707 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9708 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9709 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9710 
9711 		/* Skip connectors that are disabled or part of modeset already. */
9712 		if (!new_con_state->crtc)
9713 			continue;
9714 
9715 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9716 		if (IS_ERR(new_crtc_state)) {
9717 			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9718 			ret = PTR_ERR(new_crtc_state);
9719 			goto fail;
9720 		}
9721 
9722 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
9723 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
9724 			new_crtc_state->connectors_changed = true;
9725 	}
9726 
9727 #if defined(CONFIG_DRM_AMD_DC_DCN)
9728 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9729 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9730 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9731 				ret = add_affected_mst_dsc_crtcs(state, crtc);
9732 				if (ret) {
9733 					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9734 					goto fail;
9735 				}
9736 			}
9737 		}
9738 	}
9739 #endif
9740 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9741 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9742 
9743 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9744 		    !new_crtc_state->color_mgmt_changed &&
9745 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9746 			dm_old_crtc_state->dsc_force_changed == false)
9747 			continue;
9748 
9749 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9750 		if (ret) {
9751 			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9752 			goto fail;
9753 		}
9754 
9755 		if (!new_crtc_state->enable)
9756 			continue;
9757 
9758 		ret = drm_atomic_add_affected_connectors(state, crtc);
9759 		if (ret) {
9760 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9761 			goto fail;
9762 		}
9763 
9764 		ret = drm_atomic_add_affected_planes(state, crtc);
9765 		if (ret) {
9766 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9767 			goto fail;
9768 		}
9769 
9770 		if (dm_old_crtc_state->dsc_force_changed)
9771 			new_crtc_state->mode_changed = true;
9772 	}
9773 
9774 	/*
9775 	 * Add all primary and overlay planes on the CRTC to the state
9776 	 * whenever a plane is enabled to maintain correct z-ordering
9777 	 * and to enable fast surface updates.
9778 	 */
9779 	drm_for_each_crtc(crtc, dev) {
9780 		bool modified = false;
9781 
9782 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9783 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9784 				continue;
9785 
9786 			if (new_plane_state->crtc == crtc ||
9787 			    old_plane_state->crtc == crtc) {
9788 				modified = true;
9789 				break;
9790 			}
9791 		}
9792 
9793 		if (!modified)
9794 			continue;
9795 
9796 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9797 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9798 				continue;
9799 
9800 			new_plane_state =
9801 				drm_atomic_get_plane_state(state, plane);
9802 
9803 			if (IS_ERR(new_plane_state)) {
9804 				ret = PTR_ERR(new_plane_state);
9805 				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9806 				goto fail;
9807 			}
9808 		}
9809 	}
9810 
9811 	/*
9812 	 * DC consults the zpos (layer_index in DC terminology) to determine the
9813 	 * hw plane on which to enable the hw cursor (see
9814 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9815 	 * atomic state, so call drm helper to normalize zpos.
9816 	 */
9817 	drm_atomic_normalize_zpos(dev, state);
9818 
9819 	/* Remove exiting planes if they are modified */
9820 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9821 		ret = dm_update_plane_state(dc, state, plane,
9822 					    old_plane_state,
9823 					    new_plane_state,
9824 					    false,
9825 					    &lock_and_validation_needed);
9826 		if (ret) {
9827 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9828 			goto fail;
9829 		}
9830 	}
9831 
9832 	/* Disable all crtcs which require disable */
9833 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9834 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9835 					   old_crtc_state,
9836 					   new_crtc_state,
9837 					   false,
9838 					   &lock_and_validation_needed);
9839 		if (ret) {
9840 			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9841 			goto fail;
9842 		}
9843 	}
9844 
9845 	/* Enable all crtcs which require enable */
9846 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9847 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9848 					   old_crtc_state,
9849 					   new_crtc_state,
9850 					   true,
9851 					   &lock_and_validation_needed);
9852 		if (ret) {
9853 			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9854 			goto fail;
9855 		}
9856 	}
9857 
9858 	/* Add new/modified planes */
9859 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9860 		ret = dm_update_plane_state(dc, state, plane,
9861 					    old_plane_state,
9862 					    new_plane_state,
9863 					    true,
9864 					    &lock_and_validation_needed);
9865 		if (ret) {
9866 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9867 			goto fail;
9868 		}
9869 	}
9870 
9871 #if defined(CONFIG_DRM_AMD_DC_DCN)
9872 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9873 		ret = pre_validate_dsc(state, &dm_state, vars);
9874 		if (ret != 0)
9875 			goto fail;
9876 	}
9877 #endif
9878 
9879 	/* Run this here since we want to validate the streams we created */
9880 	ret = drm_atomic_helper_check_planes(dev, state);
9881 	if (ret) {
9882 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
9883 		goto fail;
9884 	}
9885 
9886 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9887 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9888 		if (dm_new_crtc_state->mpo_requested)
9889 			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
9890 	}
9891 
9892 	/* Check cursor planes scaling */
9893 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9894 		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
9895 		if (ret) {
9896 			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
9897 			goto fail;
9898 		}
9899 	}
9900 
9901 	if (state->legacy_cursor_update) {
9902 		/*
9903 		 * This is a fast cursor update coming from the plane update
9904 		 * helper, check if it can be done asynchronously for better
9905 		 * performance.
9906 		 */
9907 		state->async_update =
9908 			!drm_atomic_helper_async_check(dev, state);
9909 
9910 		/*
9911 		 * Skip the remaining global validation if this is an async
9912 		 * update. Cursor updates can be done without affecting
9913 		 * state or bandwidth calcs and this avoids the performance
9914 		 * penalty of locking the private state object and
9915 		 * allocating a new dc_state.
9916 		 */
9917 		if (state->async_update)
9918 			return 0;
9919 	}
9920 
9921 	/* Check scaling and underscan changes*/
9922 	/* TODO Removed scaling changes validation due to inability to commit
9923 	 * new stream into context w\o causing full reset. Need to
9924 	 * decide how to handle.
9925 	 */
9926 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9927 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9928 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9929 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9930 
9931 		/* Skip any modesets/resets */
9932 		if (!acrtc || drm_atomic_crtc_needs_modeset(
9933 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
9934 			continue;
9935 
9936 		/* Skip any thing not scale or underscan changes */
9937 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
9938 			continue;
9939 
9940 		lock_and_validation_needed = true;
9941 	}
9942 
9943 #if defined(CONFIG_DRM_AMD_DC_DCN)
9944 	/* set the slot info for each mst_state based on the link encoding format */
9945 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
9946 		struct amdgpu_dm_connector *aconnector;
9947 		struct drm_connector *connector;
9948 		struct drm_connector_list_iter iter;
9949 		u8 link_coding_cap;
9950 
9951 		drm_connector_list_iter_begin(dev, &iter);
9952 		drm_for_each_connector_iter(connector, &iter) {
9953 			if (connector->index == mst_state->mgr->conn_base_id) {
9954 				aconnector = to_amdgpu_dm_connector(connector);
9955 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
9956 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
9957 
9958 				break;
9959 			}
9960 		}
9961 		drm_connector_list_iter_end(&iter);
9962 	}
9963 #endif
9964 
9965 	/**
9966 	 * Streams and planes are reset when there are changes that affect
9967 	 * bandwidth. Anything that affects bandwidth needs to go through
9968 	 * DC global validation to ensure that the configuration can be applied
9969 	 * to hardware.
9970 	 *
9971 	 * We have to currently stall out here in atomic_check for outstanding
9972 	 * commits to finish in this case because our IRQ handlers reference
9973 	 * DRM state directly - we can end up disabling interrupts too early
9974 	 * if we don't.
9975 	 *
9976 	 * TODO: Remove this stall and drop DM state private objects.
9977 	 */
9978 	if (lock_and_validation_needed) {
9979 		ret = dm_atomic_get_state(state, &dm_state);
9980 		if (ret) {
9981 			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
9982 			goto fail;
9983 		}
9984 
9985 		ret = do_aquire_global_lock(dev, state);
9986 		if (ret) {
9987 			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
9988 			goto fail;
9989 		}
9990 
9991 #if defined(CONFIG_DRM_AMD_DC_DCN)
9992 		ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
9993 		if (ret) {
9994 			DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
9995 			goto fail;
9996 		}
9997 
9998 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
9999 		if (ret) {
10000 			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
10001 			goto fail;
10002 		}
10003 #endif
10004 
10005 		/*
10006 		 * Perform validation of MST topology in the state:
10007 		 * We need to perform MST atomic check before calling
10008 		 * dc_validate_global_state(), or there is a chance
10009 		 * to get stuck in an infinite loop and hang eventually.
10010 		 */
10011 		ret = drm_dp_mst_atomic_check(state);
10012 		if (ret) {
10013 			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
10014 			goto fail;
10015 		}
10016 		status = dc_validate_global_state(dc, dm_state->context, true);
10017 		if (status != DC_OK) {
10018 			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
10019 				       dc_status_to_str(status), status);
10020 			ret = -EINVAL;
10021 			goto fail;
10022 		}
10023 	} else {
10024 		/*
10025 		 * The commit is a fast update. Fast updates shouldn't change
10026 		 * the DC context, affect global validation, and can have their
10027 		 * commit work done in parallel with other commits not touching
10028 		 * the same resource. If we have a new DC context as part of
10029 		 * the DM atomic state from validation we need to free it and
10030 		 * retain the existing one instead.
10031 		 *
10032 		 * Furthermore, since the DM atomic state only contains the DC
10033 		 * context and can safely be annulled, we can free the state
10034 		 * and clear the associated private object now to free
10035 		 * some memory and avoid a possible use-after-free later.
10036 		 */
10037 
10038 		for (i = 0; i < state->num_private_objs; i++) {
10039 			struct drm_private_obj *obj = state->private_objs[i].ptr;
10040 
10041 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
10042 				int j = state->num_private_objs-1;
10043 
10044 				dm_atomic_destroy_state(obj,
10045 						state->private_objs[i].state);
10046 
10047 				/* If i is not at the end of the array then the
10048 				 * last element needs to be moved to where i was
10049 				 * before the array can safely be truncated.
10050 				 */
10051 				if (i != j)
10052 					state->private_objs[i] =
10053 						state->private_objs[j];
10054 
10055 				state->private_objs[j].ptr = NULL;
10056 				state->private_objs[j].state = NULL;
10057 				state->private_objs[j].old_state = NULL;
10058 				state->private_objs[j].new_state = NULL;
10059 
10060 				state->num_private_objs = j;
10061 				break;
10062 			}
10063 		}
10064 	}
10065 
10066 	/* Store the overall update type for use later in atomic check. */
10067 	for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
10068 		struct dm_crtc_state *dm_new_crtc_state =
10069 			to_dm_crtc_state(new_crtc_state);
10070 
10071 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
10072 							 UPDATE_TYPE_FULL :
10073 							 UPDATE_TYPE_FAST;
10074 	}
10075 
10076 	/* Must be success */
10077 	WARN_ON(ret);
10078 
10079 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10080 
10081 	return ret;
10082 
10083 fail:
10084 	if (ret == -EDEADLK)
10085 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10086 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10087 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10088 	else
10089 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
10090 
10091 	trace_amdgpu_dm_atomic_check_finish(state, ret);
10092 
10093 	return ret;
10094 }
10095 
10096 static bool is_dp_capable_without_timing_msa(struct dc *dc,
10097 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
10098 {
10099 	u8 dpcd_data;
10100 	bool capable = false;
10101 
10102 	if (amdgpu_dm_connector->dc_link &&
10103 		dm_helpers_dp_read_dpcd(
10104 				NULL,
10105 				amdgpu_dm_connector->dc_link,
10106 				DP_DOWN_STREAM_PORT_COUNT,
10107 				&dpcd_data,
10108 				sizeof(dpcd_data))) {
10109 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10110 	}
10111 
10112 	return capable;
10113 }
10114 
10115 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10116 		unsigned int offset,
10117 		unsigned int total_length,
10118 		u8 *data,
10119 		unsigned int length,
10120 		struct amdgpu_hdmi_vsdb_info *vsdb)
10121 {
10122 	bool res;
10123 	union dmub_rb_cmd cmd;
10124 	struct dmub_cmd_send_edid_cea *input;
10125 	struct dmub_cmd_edid_cea_output *output;
10126 
10127 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10128 		return false;
10129 
10130 	memset(&cmd, 0, sizeof(cmd));
10131 
10132 	input = &cmd.edid_cea.data.input;
10133 
10134 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10135 	cmd.edid_cea.header.sub_type = 0;
10136 	cmd.edid_cea.header.payload_bytes =
10137 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10138 	input->offset = offset;
10139 	input->length = length;
10140 	input->cea_total_length = total_length;
10141 	memcpy(input->payload, data, length);
10142 
10143 	res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
10144 	if (!res) {
10145 		DRM_ERROR("EDID CEA parser failed\n");
10146 		return false;
10147 	}
10148 
10149 	output = &cmd.edid_cea.data.output;
10150 
10151 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10152 		if (!output->ack.success) {
10153 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
10154 					output->ack.offset);
10155 		}
10156 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10157 		if (!output->amd_vsdb.vsdb_found)
10158 			return false;
10159 
10160 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10161 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10162 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10163 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10164 	} else {
10165 		DRM_WARN("Unknown EDID CEA parser results\n");
10166 		return false;
10167 	}
10168 
10169 	return true;
10170 }
10171 
10172 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10173 		u8 *edid_ext, int len,
10174 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10175 {
10176 	int i;
10177 
10178 	/* send extension block to DMCU for parsing */
10179 	for (i = 0; i < len; i += 8) {
10180 		bool res;
10181 		int offset;
10182 
10183 		/* send 8 bytes a time */
10184 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10185 			return false;
10186 
10187 		if (i+8 == len) {
10188 			/* EDID block sent completed, expect result */
10189 			int version, min_rate, max_rate;
10190 
10191 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10192 			if (res) {
10193 				/* amd vsdb found */
10194 				vsdb_info->freesync_supported = 1;
10195 				vsdb_info->amd_vsdb_version = version;
10196 				vsdb_info->min_refresh_rate_hz = min_rate;
10197 				vsdb_info->max_refresh_rate_hz = max_rate;
10198 				return true;
10199 			}
10200 			/* not amd vsdb */
10201 			return false;
10202 		}
10203 
10204 		/* check for ack*/
10205 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10206 		if (!res)
10207 			return false;
10208 	}
10209 
10210 	return false;
10211 }
10212 
10213 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10214 		u8 *edid_ext, int len,
10215 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10216 {
10217 	int i;
10218 
10219 	/* send extension block to DMCU for parsing */
10220 	for (i = 0; i < len; i += 8) {
10221 		/* send 8 bytes a time */
10222 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10223 			return false;
10224 	}
10225 
10226 	return vsdb_info->freesync_supported;
10227 }
10228 
10229 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
10230 		u8 *edid_ext, int len,
10231 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10232 {
10233 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
10234 	bool ret;
10235 
10236 	mutex_lock(&adev->dm.dc_lock);
10237 	if (adev->dm.dmub_srv)
10238 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
10239 	else
10240 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
10241 	mutex_unlock(&adev->dm.dc_lock);
10242 	return ret;
10243 }
10244 
10245 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
10246 		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
10247 {
10248 	u8 *edid_ext = NULL;
10249 	int i;
10250 	bool valid_vsdb_found = false;
10251 
10252 	/*----- drm_find_cea_extension() -----*/
10253 	/* No EDID or EDID extensions */
10254 	if (edid == NULL || edid->extensions == 0)
10255 		return -ENODEV;
10256 
10257 	/* Find CEA extension */
10258 	for (i = 0; i < edid->extensions; i++) {
10259 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
10260 		if (edid_ext[0] == CEA_EXT)
10261 			break;
10262 	}
10263 
10264 	if (i == edid->extensions)
10265 		return -ENODEV;
10266 
10267 	/*----- cea_db_offsets() -----*/
10268 	if (edid_ext[0] != CEA_EXT)
10269 		return -ENODEV;
10270 
10271 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
10272 
10273 	return valid_vsdb_found ? i : -ENODEV;
10274 }
10275 
10276 /**
10277  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
10278  *
10279  * @connector: Connector to query.
10280  * @edid: EDID from monitor
10281  *
10282  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
10283  * track of some of the display information in the internal data struct used by
10284  * amdgpu_dm. This function checks which type of connector we need to set the
10285  * FreeSync parameters.
10286  */
10287 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
10288 				    struct edid *edid)
10289 {
10290 	int i = 0;
10291 	struct detailed_timing *timing;
10292 	struct detailed_non_pixel *data;
10293 	struct detailed_data_monitor_range *range;
10294 	struct amdgpu_dm_connector *amdgpu_dm_connector =
10295 			to_amdgpu_dm_connector(connector);
10296 	struct dm_connector_state *dm_con_state = NULL;
10297 	struct dc_sink *sink;
10298 
10299 	struct drm_device *dev = connector->dev;
10300 	struct amdgpu_device *adev = drm_to_adev(dev);
10301 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10302 	bool freesync_capable = false;
10303 
10304 	if (!connector->state) {
10305 		DRM_ERROR("%s - Connector has no state", __func__);
10306 		goto update;
10307 	}
10308 
10309 	sink = amdgpu_dm_connector->dc_sink ?
10310 		amdgpu_dm_connector->dc_sink :
10311 		amdgpu_dm_connector->dc_em_sink;
10312 
10313 	if (!edid || !sink) {
10314 		dm_con_state = to_dm_connector_state(connector->state);
10315 
10316 		amdgpu_dm_connector->min_vfreq = 0;
10317 		amdgpu_dm_connector->max_vfreq = 0;
10318 		amdgpu_dm_connector->pixel_clock_mhz = 0;
10319 		connector->display_info.monitor_range.min_vfreq = 0;
10320 		connector->display_info.monitor_range.max_vfreq = 0;
10321 		freesync_capable = false;
10322 
10323 		goto update;
10324 	}
10325 
10326 	dm_con_state = to_dm_connector_state(connector->state);
10327 
10328 	if (!adev->dm.freesync_module)
10329 		goto update;
10330 
10331 	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10332 		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
10333 		bool edid_check_required = false;
10334 
10335 		if (edid) {
10336 			edid_check_required = is_dp_capable_without_timing_msa(
10337 						adev->dm.dc,
10338 						amdgpu_dm_connector);
10339 		}
10340 
10341 		if (edid_check_required == true && (edid->version > 1 ||
10342 		   (edid->version == 1 && edid->revision > 1))) {
10343 			for (i = 0; i < 4; i++) {
10344 
10345 				timing	= &edid->detailed_timings[i];
10346 				data	= &timing->data.other_data;
10347 				range	= &data->data.range;
10348 				/*
10349 				 * Check if monitor has continuous frequency mode
10350 				 */
10351 				if (data->type != EDID_DETAIL_MONITOR_RANGE)
10352 					continue;
10353 				/*
10354 				 * Check for flag range limits only. If flag == 1 then
10355 				 * no additional timing information provided.
10356 				 * Default GTF, GTF Secondary curve and CVT are not
10357 				 * supported
10358 				 */
10359 				if (range->flags != 1)
10360 					continue;
10361 
10362 				amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10363 				amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10364 				amdgpu_dm_connector->pixel_clock_mhz =
10365 					range->pixel_clock_mhz * 10;
10366 
10367 				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10368 				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10369 
10370 				break;
10371 			}
10372 
10373 			if (amdgpu_dm_connector->max_vfreq -
10374 			    amdgpu_dm_connector->min_vfreq > 10) {
10375 
10376 				freesync_capable = true;
10377 			}
10378 		}
10379 	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10380 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10381 		if (i >= 0 && vsdb_info.freesync_supported) {
10382 			timing  = &edid->detailed_timings[i];
10383 			data    = &timing->data.other_data;
10384 
10385 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10386 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10387 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10388 				freesync_capable = true;
10389 
10390 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10391 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10392 		}
10393 	}
10394 
10395 update:
10396 	if (dm_con_state)
10397 		dm_con_state->freesync_capable = freesync_capable;
10398 
10399 	if (connector->vrr_capable_property)
10400 		drm_connector_set_vrr_capable_property(connector,
10401 						       freesync_capable);
10402 }
10403 
10404 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10405 {
10406 	struct amdgpu_device *adev = drm_to_adev(dev);
10407 	struct dc *dc = adev->dm.dc;
10408 	int i;
10409 
10410 	mutex_lock(&adev->dm.dc_lock);
10411 	if (dc->current_state) {
10412 		for (i = 0; i < dc->current_state->stream_count; ++i)
10413 			dc->current_state->streams[i]
10414 				->triggered_crtc_reset.enabled =
10415 				adev->dm.force_timing_sync;
10416 
10417 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
10418 		dc_trigger_sync(dc, dc->current_state);
10419 	}
10420 	mutex_unlock(&adev->dm.dc_lock);
10421 }
10422 
10423 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10424 		       u32 value, const char *func_name)
10425 {
10426 #ifdef DM_CHECK_ADDR_0
10427 	if (address == 0) {
10428 		DC_ERR("invalid register write. address = 0");
10429 		return;
10430 	}
10431 #endif
10432 	cgs_write_register(ctx->cgs_device, address, value);
10433 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10434 }
10435 
10436 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10437 			  const char *func_name)
10438 {
10439 	u32 value;
10440 #ifdef DM_CHECK_ADDR_0
10441 	if (address == 0) {
10442 		DC_ERR("invalid register read; address = 0\n");
10443 		return 0;
10444 	}
10445 #endif
10446 
10447 	if (ctx->dmub_srv &&
10448 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10449 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10450 		ASSERT(false);
10451 		return 0;
10452 	}
10453 
10454 	value = cgs_read_register(ctx->cgs_device, address);
10455 
10456 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10457 
10458 	return value;
10459 }
10460 
10461 int amdgpu_dm_process_dmub_aux_transfer_sync(
10462 		struct dc_context *ctx,
10463 		unsigned int link_index,
10464 		struct aux_payload *payload,
10465 		enum aux_return_code_type *operation_result)
10466 {
10467 	struct amdgpu_device *adev = ctx->driver_context;
10468 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
10469 	int ret = -1;
10470 
10471 	mutex_lock(&adev->dm.dpia_aux_lock);
10472 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
10473 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10474 		goto out;
10475  	}
10476 
10477 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10478 		DRM_ERROR("wait_for_completion_timeout timeout!");
10479 		*operation_result = AUX_RET_ERROR_TIMEOUT;
10480 		goto out;
10481 	}
10482 
10483 	if (p_notify->result != AUX_RET_SUCCESS) {
10484 		/*
10485 		 * Transient states before tunneling is enabled could
10486 		 * lead to this error. We can ignore this for now.
10487 		 */
10488 		if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
10489 			DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
10490 					payload->address, payload->length,
10491 					p_notify->result);
10492 		}
10493 		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10494 		goto out;
10495 	}
10496 
10497 
10498 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10499 	if (!payload->write && p_notify->aux_reply.length &&
10500 			(payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
10501 
10502 		if (payload->length != p_notify->aux_reply.length) {
10503 			DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
10504 				p_notify->aux_reply.length,
10505 					payload->address, payload->length);
10506 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10507 			goto out;
10508 		}
10509 
10510 		memcpy(payload->data, p_notify->aux_reply.data,
10511 				p_notify->aux_reply.length);
10512 	}
10513 
10514 	/* success */
10515 	ret = p_notify->aux_reply.length;
10516 	*operation_result = p_notify->result;
10517 out:
10518 	mutex_unlock(&adev->dm.dpia_aux_lock);
10519 	return ret;
10520 }
10521 
10522 int amdgpu_dm_process_dmub_set_config_sync(
10523 		struct dc_context *ctx,
10524 		unsigned int link_index,
10525 		struct set_config_cmd_payload *payload,
10526 		enum set_config_status *operation_result)
10527 {
10528 	struct amdgpu_device *adev = ctx->driver_context;
10529 	bool is_cmd_complete;
10530 	int ret;
10531 
10532 	mutex_lock(&adev->dm.dpia_aux_lock);
10533 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
10534 			link_index, payload, adev->dm.dmub_notify);
10535 
10536 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10537 		ret = 0;
10538 		*operation_result = adev->dm.dmub_notify->sc_status;
10539 	} else {
10540 		DRM_ERROR("wait_for_completion_timeout timeout!");
10541 		ret = -1;
10542 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
10543 	}
10544 
10545 	mutex_unlock(&adev->dm.dpia_aux_lock);
10546 	return ret;
10547 }
10548 
10549 /*
10550  * Check whether seamless boot is supported.
10551  *
10552  * So far we only support seamless boot on CHIP_VANGOGH.
10553  * If everything goes well, we may consider expanding
10554  * seamless boot to other ASICs.
10555  */
10556 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10557 {
10558 	switch (adev->ip_versions[DCE_HWIP][0]) {
10559 	case IP_VERSION(3, 0, 1):
10560 		if (!adev->mman.keep_stolen_vga_memory)
10561 			return true;
10562 		break;
10563 	default:
10564 		break;
10565 	}
10566 
10567 	return false;
10568 }
10569