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