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