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