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