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