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