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