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