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