xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 5b5a56d9a2d64e8395dfbaddecb3e5149d7ecae8)
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 				   const struct drm_display_mode *mode)
7476 {
7477 	int result = MODE_ERROR;
7478 	struct dc_sink *dc_sink;
7479 	struct drm_display_mode *test_mode;
7480 	/* TODO: Unhardcode stream count */
7481 	struct dc_stream_state *stream;
7482 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7483 
7484 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
7485 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
7486 		return result;
7487 
7488 	/*
7489 	 * Only run this the first time mode_valid is called to initilialize
7490 	 * EDID mgmt
7491 	 */
7492 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
7493 		!aconnector->dc_em_sink)
7494 		handle_edid_mgmt(aconnector);
7495 
7496 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
7497 
7498 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
7499 				aconnector->base.force != DRM_FORCE_ON) {
7500 		DRM_ERROR("dc_sink is NULL!\n");
7501 		goto fail;
7502 	}
7503 
7504 	test_mode = drm_mode_duplicate(connector->dev, mode);
7505 	if (!test_mode)
7506 		goto fail;
7507 
7508 	drm_mode_set_crtcinfo(test_mode, 0);
7509 
7510 	stream = create_validate_stream_for_sink(aconnector, test_mode,
7511 						 to_dm_connector_state(connector->state),
7512 						 NULL);
7513 	drm_mode_destroy(connector->dev, test_mode);
7514 	if (stream) {
7515 		dc_stream_release(stream);
7516 		result = MODE_OK;
7517 	}
7518 
7519 fail:
7520 	/* TODO: error handling*/
7521 	return result;
7522 }
7523 
7524 static int fill_hdr_info_packet(const struct drm_connector_state *state,
7525 				struct dc_info_packet *out)
7526 {
7527 	struct hdmi_drm_infoframe frame;
7528 	unsigned char buf[30]; /* 26 + 4 */
7529 	ssize_t len;
7530 	int ret, i;
7531 
7532 	memset(out, 0, sizeof(*out));
7533 
7534 	if (!state->hdr_output_metadata)
7535 		return 0;
7536 
7537 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
7538 	if (ret)
7539 		return ret;
7540 
7541 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
7542 	if (len < 0)
7543 		return (int)len;
7544 
7545 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
7546 	if (len != 30)
7547 		return -EINVAL;
7548 
7549 	/* Prepare the infopacket for DC. */
7550 	switch (state->connector->connector_type) {
7551 	case DRM_MODE_CONNECTOR_HDMIA:
7552 		out->hb0 = 0x87; /* type */
7553 		out->hb1 = 0x01; /* version */
7554 		out->hb2 = 0x1A; /* length */
7555 		out->sb[0] = buf[3]; /* checksum */
7556 		i = 1;
7557 		break;
7558 
7559 	case DRM_MODE_CONNECTOR_DisplayPort:
7560 	case DRM_MODE_CONNECTOR_eDP:
7561 		out->hb0 = 0x00; /* sdp id, zero */
7562 		out->hb1 = 0x87; /* type */
7563 		out->hb2 = 0x1D; /* payload len - 1 */
7564 		out->hb3 = (0x13 << 2); /* sdp version */
7565 		out->sb[0] = 0x01; /* version */
7566 		out->sb[1] = 0x1A; /* length */
7567 		i = 2;
7568 		break;
7569 
7570 	default:
7571 		return -EINVAL;
7572 	}
7573 
7574 	memcpy(&out->sb[i], &buf[4], 26);
7575 	out->valid = true;
7576 
7577 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
7578 		       sizeof(out->sb), false);
7579 
7580 	return 0;
7581 }
7582 
7583 static int
7584 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
7585 				 struct drm_atomic_state *state)
7586 {
7587 	struct drm_connector_state *new_con_state =
7588 		drm_atomic_get_new_connector_state(state, conn);
7589 	struct drm_connector_state *old_con_state =
7590 		drm_atomic_get_old_connector_state(state, conn);
7591 	struct drm_crtc *crtc = new_con_state->crtc;
7592 	struct drm_crtc_state *new_crtc_state;
7593 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
7594 	int ret;
7595 
7596 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
7597 
7598 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
7599 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
7600 		if (ret < 0)
7601 			return ret;
7602 	}
7603 
7604 	if (!crtc)
7605 		return 0;
7606 
7607 	if (new_con_state->colorspace != old_con_state->colorspace) {
7608 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7609 		if (IS_ERR(new_crtc_state))
7610 			return PTR_ERR(new_crtc_state);
7611 
7612 		new_crtc_state->mode_changed = true;
7613 	}
7614 
7615 	if (new_con_state->content_type != old_con_state->content_type) {
7616 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7617 		if (IS_ERR(new_crtc_state))
7618 			return PTR_ERR(new_crtc_state);
7619 
7620 		new_crtc_state->mode_changed = true;
7621 	}
7622 
7623 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
7624 		struct dc_info_packet hdr_infopacket;
7625 
7626 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
7627 		if (ret)
7628 			return ret;
7629 
7630 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7631 		if (IS_ERR(new_crtc_state))
7632 			return PTR_ERR(new_crtc_state);
7633 
7634 		/*
7635 		 * DC considers the stream backends changed if the
7636 		 * static metadata changes. Forcing the modeset also
7637 		 * gives a simple way for userspace to switch from
7638 		 * 8bpc to 10bpc when setting the metadata to enter
7639 		 * or exit HDR.
7640 		 *
7641 		 * Changing the static metadata after it's been
7642 		 * set is permissible, however. So only force a
7643 		 * modeset if we're entering or exiting HDR.
7644 		 */
7645 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
7646 			!old_con_state->hdr_output_metadata ||
7647 			!new_con_state->hdr_output_metadata;
7648 	}
7649 
7650 	return 0;
7651 }
7652 
7653 static const struct drm_connector_helper_funcs
7654 amdgpu_dm_connector_helper_funcs = {
7655 	/*
7656 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
7657 	 * modes will be filtered by drm_mode_validate_size(), and those modes
7658 	 * are missing after user start lightdm. So we need to renew modes list.
7659 	 * in get_modes call back, not just return the modes count
7660 	 */
7661 	.get_modes = get_modes,
7662 	.mode_valid = amdgpu_dm_connector_mode_valid,
7663 	.atomic_check = amdgpu_dm_connector_atomic_check,
7664 };
7665 
7666 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
7667 {
7668 
7669 }
7670 
7671 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
7672 {
7673 	switch (display_color_depth) {
7674 	case COLOR_DEPTH_666:
7675 		return 6;
7676 	case COLOR_DEPTH_888:
7677 		return 8;
7678 	case COLOR_DEPTH_101010:
7679 		return 10;
7680 	case COLOR_DEPTH_121212:
7681 		return 12;
7682 	case COLOR_DEPTH_141414:
7683 		return 14;
7684 	case COLOR_DEPTH_161616:
7685 		return 16;
7686 	default:
7687 		break;
7688 	}
7689 	return 0;
7690 }
7691 
7692 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
7693 					  struct drm_crtc_state *crtc_state,
7694 					  struct drm_connector_state *conn_state)
7695 {
7696 	struct drm_atomic_state *state = crtc_state->state;
7697 	struct drm_connector *connector = conn_state->connector;
7698 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7699 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
7700 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
7701 	struct drm_dp_mst_topology_mgr *mst_mgr;
7702 	struct drm_dp_mst_port *mst_port;
7703 	struct drm_dp_mst_topology_state *mst_state;
7704 	enum dc_color_depth color_depth;
7705 	int clock, bpp = 0;
7706 	bool is_y420 = false;
7707 
7708 	if (!aconnector->mst_output_port)
7709 		return 0;
7710 
7711 	mst_port = aconnector->mst_output_port;
7712 	mst_mgr = &aconnector->mst_root->mst_mgr;
7713 
7714 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
7715 		return 0;
7716 
7717 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
7718 	if (IS_ERR(mst_state))
7719 		return PTR_ERR(mst_state);
7720 
7721 	mst_state->pbn_div.full = dfixed_const(dm_mst_get_pbn_divider(aconnector->mst_root->dc_link));
7722 
7723 	if (!state->duplicated) {
7724 		int max_bpc = conn_state->max_requested_bpc;
7725 
7726 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
7727 			  aconnector->force_yuv420_output;
7728 		color_depth = convert_color_depth_from_display_info(connector,
7729 								    is_y420,
7730 								    max_bpc);
7731 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
7732 		clock = adjusted_mode->clock;
7733 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
7734 	}
7735 
7736 	dm_new_connector_state->vcpi_slots =
7737 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
7738 					      dm_new_connector_state->pbn);
7739 	if (dm_new_connector_state->vcpi_slots < 0) {
7740 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
7741 		return dm_new_connector_state->vcpi_slots;
7742 	}
7743 	return 0;
7744 }
7745 
7746 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
7747 	.disable = dm_encoder_helper_disable,
7748 	.atomic_check = dm_encoder_helper_atomic_check
7749 };
7750 
7751 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
7752 					    struct dc_state *dc_state,
7753 					    struct dsc_mst_fairness_vars *vars)
7754 {
7755 	struct dc_stream_state *stream = NULL;
7756 	struct drm_connector *connector;
7757 	struct drm_connector_state *new_con_state;
7758 	struct amdgpu_dm_connector *aconnector;
7759 	struct dm_connector_state *dm_conn_state;
7760 	int i, j, ret;
7761 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
7762 
7763 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
7764 
7765 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7766 			continue;
7767 
7768 		aconnector = to_amdgpu_dm_connector(connector);
7769 
7770 		if (!aconnector->mst_output_port)
7771 			continue;
7772 
7773 		if (!new_con_state || !new_con_state->crtc)
7774 			continue;
7775 
7776 		dm_conn_state = to_dm_connector_state(new_con_state);
7777 
7778 		for (j = 0; j < dc_state->stream_count; j++) {
7779 			stream = dc_state->streams[j];
7780 			if (!stream)
7781 				continue;
7782 
7783 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
7784 				break;
7785 
7786 			stream = NULL;
7787 		}
7788 
7789 		if (!stream)
7790 			continue;
7791 
7792 		pbn_div = dm_mst_get_pbn_divider(stream->link);
7793 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
7794 		for (j = 0; j < dc_state->stream_count; j++) {
7795 			if (vars[j].aconnector == aconnector) {
7796 				pbn = vars[j].pbn;
7797 				break;
7798 			}
7799 		}
7800 
7801 		if (j == dc_state->stream_count || pbn_div == 0)
7802 			continue;
7803 
7804 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
7805 
7806 		if (stream->timing.flags.DSC != 1) {
7807 			dm_conn_state->pbn = pbn;
7808 			dm_conn_state->vcpi_slots = slot_num;
7809 
7810 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
7811 							   dm_conn_state->pbn, false);
7812 			if (ret < 0)
7813 				return ret;
7814 
7815 			continue;
7816 		}
7817 
7818 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
7819 		if (vcpi < 0)
7820 			return vcpi;
7821 
7822 		dm_conn_state->pbn = pbn;
7823 		dm_conn_state->vcpi_slots = vcpi;
7824 	}
7825 	return 0;
7826 }
7827 
7828 static int to_drm_connector_type(enum signal_type st)
7829 {
7830 	switch (st) {
7831 	case SIGNAL_TYPE_HDMI_TYPE_A:
7832 		return DRM_MODE_CONNECTOR_HDMIA;
7833 	case SIGNAL_TYPE_EDP:
7834 		return DRM_MODE_CONNECTOR_eDP;
7835 	case SIGNAL_TYPE_LVDS:
7836 		return DRM_MODE_CONNECTOR_LVDS;
7837 	case SIGNAL_TYPE_RGB:
7838 		return DRM_MODE_CONNECTOR_VGA;
7839 	case SIGNAL_TYPE_DISPLAY_PORT:
7840 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
7841 		return DRM_MODE_CONNECTOR_DisplayPort;
7842 	case SIGNAL_TYPE_DVI_DUAL_LINK:
7843 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
7844 		return DRM_MODE_CONNECTOR_DVID;
7845 	case SIGNAL_TYPE_VIRTUAL:
7846 		return DRM_MODE_CONNECTOR_VIRTUAL;
7847 
7848 	default:
7849 		return DRM_MODE_CONNECTOR_Unknown;
7850 	}
7851 }
7852 
7853 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
7854 {
7855 	struct drm_encoder *encoder;
7856 
7857 	/* There is only one encoder per connector */
7858 	drm_connector_for_each_possible_encoder(connector, encoder)
7859 		return encoder;
7860 
7861 	return NULL;
7862 }
7863 
7864 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
7865 {
7866 	struct drm_encoder *encoder;
7867 	struct amdgpu_encoder *amdgpu_encoder;
7868 
7869 	encoder = amdgpu_dm_connector_to_encoder(connector);
7870 
7871 	if (encoder == NULL)
7872 		return;
7873 
7874 	amdgpu_encoder = to_amdgpu_encoder(encoder);
7875 
7876 	amdgpu_encoder->native_mode.clock = 0;
7877 
7878 	if (!list_empty(&connector->probed_modes)) {
7879 		struct drm_display_mode *preferred_mode = NULL;
7880 
7881 		list_for_each_entry(preferred_mode,
7882 				    &connector->probed_modes,
7883 				    head) {
7884 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
7885 				amdgpu_encoder->native_mode = *preferred_mode;
7886 
7887 			break;
7888 		}
7889 
7890 	}
7891 }
7892 
7893 static struct drm_display_mode *
7894 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
7895 			     char *name,
7896 			     int hdisplay, int vdisplay)
7897 {
7898 	struct drm_device *dev = encoder->dev;
7899 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
7900 	struct drm_display_mode *mode = NULL;
7901 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
7902 
7903 	mode = drm_mode_duplicate(dev, native_mode);
7904 
7905 	if (mode == NULL)
7906 		return NULL;
7907 
7908 	mode->hdisplay = hdisplay;
7909 	mode->vdisplay = vdisplay;
7910 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
7911 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
7912 
7913 	return mode;
7914 
7915 }
7916 
7917 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
7918 						 struct drm_connector *connector)
7919 {
7920 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
7921 	struct drm_display_mode *mode = NULL;
7922 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
7923 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7924 				to_amdgpu_dm_connector(connector);
7925 	int i;
7926 	int n;
7927 	struct mode_size {
7928 		char name[DRM_DISPLAY_MODE_LEN];
7929 		int w;
7930 		int h;
7931 	} common_modes[] = {
7932 		{  "640x480",  640,  480},
7933 		{  "800x600",  800,  600},
7934 		{ "1024x768", 1024,  768},
7935 		{ "1280x720", 1280,  720},
7936 		{ "1280x800", 1280,  800},
7937 		{"1280x1024", 1280, 1024},
7938 		{ "1440x900", 1440,  900},
7939 		{"1680x1050", 1680, 1050},
7940 		{"1600x1200", 1600, 1200},
7941 		{"1920x1080", 1920, 1080},
7942 		{"1920x1200", 1920, 1200}
7943 	};
7944 
7945 	n = ARRAY_SIZE(common_modes);
7946 
7947 	for (i = 0; i < n; i++) {
7948 		struct drm_display_mode *curmode = NULL;
7949 		bool mode_existed = false;
7950 
7951 		if (common_modes[i].w > native_mode->hdisplay ||
7952 		    common_modes[i].h > native_mode->vdisplay ||
7953 		   (common_modes[i].w == native_mode->hdisplay &&
7954 		    common_modes[i].h == native_mode->vdisplay))
7955 			continue;
7956 
7957 		list_for_each_entry(curmode, &connector->probed_modes, head) {
7958 			if (common_modes[i].w == curmode->hdisplay &&
7959 			    common_modes[i].h == curmode->vdisplay) {
7960 				mode_existed = true;
7961 				break;
7962 			}
7963 		}
7964 
7965 		if (mode_existed)
7966 			continue;
7967 
7968 		mode = amdgpu_dm_create_common_mode(encoder,
7969 				common_modes[i].name, common_modes[i].w,
7970 				common_modes[i].h);
7971 		if (!mode)
7972 			continue;
7973 
7974 		drm_mode_probed_add(connector, mode);
7975 		amdgpu_dm_connector->num_modes++;
7976 	}
7977 }
7978 
7979 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
7980 {
7981 	struct drm_encoder *encoder;
7982 	struct amdgpu_encoder *amdgpu_encoder;
7983 	const struct drm_display_mode *native_mode;
7984 
7985 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
7986 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
7987 		return;
7988 
7989 	mutex_lock(&connector->dev->mode_config.mutex);
7990 	amdgpu_dm_connector_get_modes(connector);
7991 	mutex_unlock(&connector->dev->mode_config.mutex);
7992 
7993 	encoder = amdgpu_dm_connector_to_encoder(connector);
7994 	if (!encoder)
7995 		return;
7996 
7997 	amdgpu_encoder = to_amdgpu_encoder(encoder);
7998 
7999 	native_mode = &amdgpu_encoder->native_mode;
8000 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8001 		return;
8002 
8003 	drm_connector_set_panel_orientation_with_quirk(connector,
8004 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8005 						       native_mode->hdisplay,
8006 						       native_mode->vdisplay);
8007 }
8008 
8009 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8010 					      const struct drm_edid *drm_edid)
8011 {
8012 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8013 			to_amdgpu_dm_connector(connector);
8014 
8015 	if (drm_edid) {
8016 		/* empty probed_modes */
8017 		INIT_LIST_HEAD(&connector->probed_modes);
8018 		amdgpu_dm_connector->num_modes =
8019 				drm_edid_connector_add_modes(connector);
8020 
8021 		/* sorting the probed modes before calling function
8022 		 * amdgpu_dm_get_native_mode() since EDID can have
8023 		 * more than one preferred mode. The modes that are
8024 		 * later in the probed mode list could be of higher
8025 		 * and preferred resolution. For example, 3840x2160
8026 		 * resolution in base EDID preferred timing and 4096x2160
8027 		 * preferred resolution in DID extension block later.
8028 		 */
8029 		drm_mode_sort(&connector->probed_modes);
8030 		amdgpu_dm_get_native_mode(connector);
8031 
8032 		/* Freesync capabilities are reset by calling
8033 		 * drm_edid_connector_add_modes() and need to be
8034 		 * restored here.
8035 		 */
8036 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8037 	} else {
8038 		amdgpu_dm_connector->num_modes = 0;
8039 	}
8040 }
8041 
8042 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8043 			      struct drm_display_mode *mode)
8044 {
8045 	struct drm_display_mode *m;
8046 
8047 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8048 		if (drm_mode_equal(m, mode))
8049 			return true;
8050 	}
8051 
8052 	return false;
8053 }
8054 
8055 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8056 {
8057 	const struct drm_display_mode *m;
8058 	struct drm_display_mode *new_mode;
8059 	uint i;
8060 	u32 new_modes_count = 0;
8061 
8062 	/* Standard FPS values
8063 	 *
8064 	 * 23.976       - TV/NTSC
8065 	 * 24           - Cinema
8066 	 * 25           - TV/PAL
8067 	 * 29.97        - TV/NTSC
8068 	 * 30           - TV/NTSC
8069 	 * 48           - Cinema HFR
8070 	 * 50           - TV/PAL
8071 	 * 60           - Commonly used
8072 	 * 48,72,96,120 - Multiples of 24
8073 	 */
8074 	static const u32 common_rates[] = {
8075 		23976, 24000, 25000, 29970, 30000,
8076 		48000, 50000, 60000, 72000, 96000, 120000
8077 	};
8078 
8079 	/*
8080 	 * Find mode with highest refresh rate with the same resolution
8081 	 * as the preferred mode. Some monitors report a preferred mode
8082 	 * with lower resolution than the highest refresh rate supported.
8083 	 */
8084 
8085 	m = get_highest_refresh_rate_mode(aconnector, true);
8086 	if (!m)
8087 		return 0;
8088 
8089 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8090 		u64 target_vtotal, target_vtotal_diff;
8091 		u64 num, den;
8092 
8093 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8094 			continue;
8095 
8096 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8097 		    common_rates[i] > aconnector->max_vfreq * 1000)
8098 			continue;
8099 
8100 		num = (unsigned long long)m->clock * 1000 * 1000;
8101 		den = common_rates[i] * (unsigned long long)m->htotal;
8102 		target_vtotal = div_u64(num, den);
8103 		target_vtotal_diff = target_vtotal - m->vtotal;
8104 
8105 		/* Check for illegal modes */
8106 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8107 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8108 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8109 			continue;
8110 
8111 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8112 		if (!new_mode)
8113 			goto out;
8114 
8115 		new_mode->vtotal += (u16)target_vtotal_diff;
8116 		new_mode->vsync_start += (u16)target_vtotal_diff;
8117 		new_mode->vsync_end += (u16)target_vtotal_diff;
8118 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8119 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8120 
8121 		if (!is_duplicate_mode(aconnector, new_mode)) {
8122 			drm_mode_probed_add(&aconnector->base, new_mode);
8123 			new_modes_count += 1;
8124 		} else
8125 			drm_mode_destroy(aconnector->base.dev, new_mode);
8126 	}
8127  out:
8128 	return new_modes_count;
8129 }
8130 
8131 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8132 						   const struct drm_edid *drm_edid)
8133 {
8134 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8135 		to_amdgpu_dm_connector(connector);
8136 
8137 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8138 		return;
8139 
8140 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8141 		amdgpu_dm_connector->num_modes +=
8142 			add_fs_modes(amdgpu_dm_connector);
8143 }
8144 
8145 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8146 {
8147 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8148 			to_amdgpu_dm_connector(connector);
8149 	struct drm_encoder *encoder;
8150 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8151 	struct dc_link_settings *verified_link_cap =
8152 			&amdgpu_dm_connector->dc_link->verified_link_cap;
8153 	const struct dc *dc = amdgpu_dm_connector->dc_link->dc;
8154 
8155 	encoder = amdgpu_dm_connector_to_encoder(connector);
8156 
8157 	if (!drm_edid) {
8158 		amdgpu_dm_connector->num_modes =
8159 				drm_add_modes_noedid(connector, 640, 480);
8160 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8161 			amdgpu_dm_connector->num_modes +=
8162 				drm_add_modes_noedid(connector, 1920, 1080);
8163 	} else {
8164 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8165 		if (encoder)
8166 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8167 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8168 	}
8169 	amdgpu_dm_fbc_init(connector);
8170 
8171 	return amdgpu_dm_connector->num_modes;
8172 }
8173 
8174 static const u32 supported_colorspaces =
8175 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8176 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8177 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8178 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8179 
8180 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8181 				     struct amdgpu_dm_connector *aconnector,
8182 				     int connector_type,
8183 				     struct dc_link *link,
8184 				     int link_index)
8185 {
8186 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8187 
8188 	/*
8189 	 * Some of the properties below require access to state, like bpc.
8190 	 * Allocate some default initial connector state with our reset helper.
8191 	 */
8192 	if (aconnector->base.funcs->reset)
8193 		aconnector->base.funcs->reset(&aconnector->base);
8194 
8195 	aconnector->connector_id = link_index;
8196 	aconnector->bl_idx = -1;
8197 	aconnector->dc_link = link;
8198 	aconnector->base.interlace_allowed = false;
8199 	aconnector->base.doublescan_allowed = false;
8200 	aconnector->base.stereo_allowed = false;
8201 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8202 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8203 	aconnector->audio_inst = -1;
8204 	aconnector->pack_sdp_v1_3 = false;
8205 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8206 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8207 	mutex_init(&aconnector->hpd_lock);
8208 	mutex_init(&aconnector->handle_mst_msg_ready);
8209 
8210 	/*
8211 	 * configure support HPD hot plug connector_>polled default value is 0
8212 	 * which means HPD hot plug not supported
8213 	 */
8214 	switch (connector_type) {
8215 	case DRM_MODE_CONNECTOR_HDMIA:
8216 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8217 		aconnector->base.ycbcr_420_allowed =
8218 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
8219 		break;
8220 	case DRM_MODE_CONNECTOR_DisplayPort:
8221 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8222 		link->link_enc = link_enc_cfg_get_link_enc(link);
8223 		ASSERT(link->link_enc);
8224 		if (link->link_enc)
8225 			aconnector->base.ycbcr_420_allowed =
8226 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
8227 		break;
8228 	case DRM_MODE_CONNECTOR_DVID:
8229 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8230 		break;
8231 	default:
8232 		break;
8233 	}
8234 
8235 	drm_object_attach_property(&aconnector->base.base,
8236 				dm->ddev->mode_config.scaling_mode_property,
8237 				DRM_MODE_SCALE_NONE);
8238 
8239 	drm_object_attach_property(&aconnector->base.base,
8240 				adev->mode_info.underscan_property,
8241 				UNDERSCAN_OFF);
8242 	drm_object_attach_property(&aconnector->base.base,
8243 				adev->mode_info.underscan_hborder_property,
8244 				0);
8245 	drm_object_attach_property(&aconnector->base.base,
8246 				adev->mode_info.underscan_vborder_property,
8247 				0);
8248 
8249 	if (!aconnector->mst_root)
8250 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
8251 
8252 	aconnector->base.state->max_bpc = 16;
8253 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
8254 
8255 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8256 		/* Content Type is currently only implemented for HDMI. */
8257 		drm_connector_attach_content_type_property(&aconnector->base);
8258 	}
8259 
8260 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8261 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
8262 			drm_connector_attach_colorspace_property(&aconnector->base);
8263 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
8264 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
8265 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
8266 			drm_connector_attach_colorspace_property(&aconnector->base);
8267 	}
8268 
8269 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
8270 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
8271 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
8272 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
8273 
8274 		if (!aconnector->mst_root)
8275 			drm_connector_attach_vrr_capable_property(&aconnector->base);
8276 
8277 		if (adev->dm.hdcp_workqueue)
8278 			drm_connector_attach_content_protection_property(&aconnector->base, true);
8279 	}
8280 }
8281 
8282 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
8283 			      struct i2c_msg *msgs, int num)
8284 {
8285 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
8286 	struct ddc_service *ddc_service = i2c->ddc_service;
8287 	struct i2c_command cmd;
8288 	int i;
8289 	int result = -EIO;
8290 
8291 	if (!ddc_service->ddc_pin || !ddc_service->ddc_pin->hw_info.hw_supported)
8292 		return result;
8293 
8294 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
8295 
8296 	if (!cmd.payloads)
8297 		return result;
8298 
8299 	cmd.number_of_payloads = num;
8300 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
8301 	cmd.speed = 100;
8302 
8303 	for (i = 0; i < num; i++) {
8304 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
8305 		cmd.payloads[i].address = msgs[i].addr;
8306 		cmd.payloads[i].length = msgs[i].len;
8307 		cmd.payloads[i].data = msgs[i].buf;
8308 	}
8309 
8310 	if (dc_submit_i2c(
8311 			ddc_service->ctx->dc,
8312 			ddc_service->link->link_index,
8313 			&cmd))
8314 		result = num;
8315 
8316 	kfree(cmd.payloads);
8317 	return result;
8318 }
8319 
8320 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
8321 {
8322 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
8323 }
8324 
8325 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
8326 	.master_xfer = amdgpu_dm_i2c_xfer,
8327 	.functionality = amdgpu_dm_i2c_func,
8328 };
8329 
8330 static struct amdgpu_i2c_adapter *
8331 create_i2c(struct ddc_service *ddc_service,
8332 	   int link_index,
8333 	   int *res)
8334 {
8335 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
8336 	struct amdgpu_i2c_adapter *i2c;
8337 
8338 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
8339 	if (!i2c)
8340 		return NULL;
8341 	i2c->base.owner = THIS_MODULE;
8342 	i2c->base.dev.parent = &adev->pdev->dev;
8343 	i2c->base.algo = &amdgpu_dm_i2c_algo;
8344 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
8345 	i2c_set_adapdata(&i2c->base, i2c);
8346 	i2c->ddc_service = ddc_service;
8347 
8348 	return i2c;
8349 }
8350 
8351 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
8352 {
8353 	struct cec_connector_info conn_info;
8354 	struct drm_device *ddev = aconnector->base.dev;
8355 	struct device *hdmi_dev = ddev->dev;
8356 
8357 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
8358 		drm_info(ddev, "HDMI-CEC feature masked\n");
8359 		return -EINVAL;
8360 	}
8361 
8362 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
8363 	aconnector->notifier =
8364 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
8365 	if (!aconnector->notifier) {
8366 		drm_err(ddev, "Failed to create cec notifier\n");
8367 		return -ENOMEM;
8368 	}
8369 
8370 	return 0;
8371 }
8372 
8373 /*
8374  * Note: this function assumes that dc_link_detect() was called for the
8375  * dc_link which will be represented by this aconnector.
8376  */
8377 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
8378 				    struct amdgpu_dm_connector *aconnector,
8379 				    u32 link_index,
8380 				    struct amdgpu_encoder *aencoder)
8381 {
8382 	int res = 0;
8383 	int connector_type;
8384 	struct dc *dc = dm->dc;
8385 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
8386 	struct amdgpu_i2c_adapter *i2c;
8387 
8388 	/* Not needed for writeback connector */
8389 	link->priv = aconnector;
8390 
8391 
8392 	i2c = create_i2c(link->ddc, link->link_index, &res);
8393 	if (!i2c) {
8394 		DRM_ERROR("Failed to create i2c adapter data\n");
8395 		return -ENOMEM;
8396 	}
8397 
8398 	aconnector->i2c = i2c;
8399 	res = i2c_add_adapter(&i2c->base);
8400 
8401 	if (res) {
8402 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
8403 		goto out_free;
8404 	}
8405 
8406 	connector_type = to_drm_connector_type(link->connector_signal);
8407 
8408 	res = drm_connector_init_with_ddc(
8409 			dm->ddev,
8410 			&aconnector->base,
8411 			&amdgpu_dm_connector_funcs,
8412 			connector_type,
8413 			&i2c->base);
8414 
8415 	if (res) {
8416 		DRM_ERROR("connector_init failed\n");
8417 		aconnector->connector_id = -1;
8418 		goto out_free;
8419 	}
8420 
8421 	drm_connector_helper_add(
8422 			&aconnector->base,
8423 			&amdgpu_dm_connector_helper_funcs);
8424 
8425 	amdgpu_dm_connector_init_helper(
8426 		dm,
8427 		aconnector,
8428 		connector_type,
8429 		link,
8430 		link_index);
8431 
8432 	drm_connector_attach_encoder(
8433 		&aconnector->base, &aencoder->base);
8434 
8435 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
8436 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
8437 		amdgpu_dm_initialize_hdmi_connector(aconnector);
8438 
8439 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
8440 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
8441 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
8442 
8443 out_free:
8444 	if (res) {
8445 		kfree(i2c);
8446 		aconnector->i2c = NULL;
8447 	}
8448 	return res;
8449 }
8450 
8451 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
8452 {
8453 	switch (adev->mode_info.num_crtc) {
8454 	case 1:
8455 		return 0x1;
8456 	case 2:
8457 		return 0x3;
8458 	case 3:
8459 		return 0x7;
8460 	case 4:
8461 		return 0xf;
8462 	case 5:
8463 		return 0x1f;
8464 	case 6:
8465 	default:
8466 		return 0x3f;
8467 	}
8468 }
8469 
8470 static int amdgpu_dm_encoder_init(struct drm_device *dev,
8471 				  struct amdgpu_encoder *aencoder,
8472 				  uint32_t link_index)
8473 {
8474 	struct amdgpu_device *adev = drm_to_adev(dev);
8475 
8476 	int res = drm_encoder_init(dev,
8477 				   &aencoder->base,
8478 				   &amdgpu_dm_encoder_funcs,
8479 				   DRM_MODE_ENCODER_TMDS,
8480 				   NULL);
8481 
8482 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
8483 
8484 	if (!res)
8485 		aencoder->encoder_id = link_index;
8486 	else
8487 		aencoder->encoder_id = -1;
8488 
8489 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
8490 
8491 	return res;
8492 }
8493 
8494 static void manage_dm_interrupts(struct amdgpu_device *adev,
8495 				 struct amdgpu_crtc *acrtc,
8496 				 struct dm_crtc_state *acrtc_state)
8497 {
8498 	struct drm_vblank_crtc_config config = {0};
8499 	struct dc_crtc_timing *timing;
8500 	int offdelay;
8501 
8502 	if (acrtc_state) {
8503 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
8504 		    IP_VERSION(3, 5, 0) ||
8505 		    acrtc_state->stream->link->psr_settings.psr_version <
8506 		    DC_PSR_VERSION_UNSUPPORTED ||
8507 		    !(adev->flags & AMD_IS_APU)) {
8508 			timing = &acrtc_state->stream->timing;
8509 
8510 			/* at least 2 frames */
8511 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
8512 						      timing->v_total *
8513 						      timing->h_total,
8514 						      timing->pix_clk_100hz);
8515 
8516 			config.offdelay_ms = offdelay ?: 30;
8517 		} else {
8518 			config.disable_immediate = true;
8519 		}
8520 
8521 		drm_crtc_vblank_on_config(&acrtc->base,
8522 					  &config);
8523 	} else {
8524 		drm_crtc_vblank_off(&acrtc->base);
8525 	}
8526 }
8527 
8528 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
8529 				      struct amdgpu_crtc *acrtc)
8530 {
8531 	int irq_type =
8532 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
8533 
8534 	/**
8535 	 * This reads the current state for the IRQ and force reapplies
8536 	 * the setting to hardware.
8537 	 */
8538 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
8539 }
8540 
8541 static bool
8542 is_scaling_state_different(const struct dm_connector_state *dm_state,
8543 			   const struct dm_connector_state *old_dm_state)
8544 {
8545 	if (dm_state->scaling != old_dm_state->scaling)
8546 		return true;
8547 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
8548 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
8549 			return true;
8550 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
8551 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
8552 			return true;
8553 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
8554 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
8555 		return true;
8556 	return false;
8557 }
8558 
8559 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
8560 					    struct drm_crtc_state *old_crtc_state,
8561 					    struct drm_connector_state *new_conn_state,
8562 					    struct drm_connector_state *old_conn_state,
8563 					    const struct drm_connector *connector,
8564 					    struct hdcp_workqueue *hdcp_w)
8565 {
8566 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8567 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
8568 
8569 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8570 		connector->index, connector->status, connector->dpms);
8571 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8572 		old_conn_state->content_protection, new_conn_state->content_protection);
8573 
8574 	if (old_crtc_state)
8575 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8576 		old_crtc_state->enable,
8577 		old_crtc_state->active,
8578 		old_crtc_state->mode_changed,
8579 		old_crtc_state->active_changed,
8580 		old_crtc_state->connectors_changed);
8581 
8582 	if (new_crtc_state)
8583 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8584 		new_crtc_state->enable,
8585 		new_crtc_state->active,
8586 		new_crtc_state->mode_changed,
8587 		new_crtc_state->active_changed,
8588 		new_crtc_state->connectors_changed);
8589 
8590 	/* hdcp content type change */
8591 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
8592 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
8593 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8594 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
8595 		return true;
8596 	}
8597 
8598 	/* CP is being re enabled, ignore this */
8599 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
8600 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
8601 		if (new_crtc_state && new_crtc_state->mode_changed) {
8602 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8603 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
8604 			return true;
8605 		}
8606 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
8607 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
8608 		return false;
8609 	}
8610 
8611 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
8612 	 *
8613 	 * Handles:	UNDESIRED -> ENABLED
8614 	 */
8615 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
8616 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
8617 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8618 
8619 	/* Stream removed and re-enabled
8620 	 *
8621 	 * Can sometimes overlap with the HPD case,
8622 	 * thus set update_hdcp to false to avoid
8623 	 * setting HDCP multiple times.
8624 	 *
8625 	 * Handles:	DESIRED -> DESIRED (Special case)
8626 	 */
8627 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
8628 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
8629 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
8630 		dm_con_state->update_hdcp = false;
8631 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
8632 			__func__);
8633 		return true;
8634 	}
8635 
8636 	/* Hot-plug, headless s3, dpms
8637 	 *
8638 	 * Only start HDCP if the display is connected/enabled.
8639 	 * update_hdcp flag will be set to false until the next
8640 	 * HPD comes in.
8641 	 *
8642 	 * Handles:	DESIRED -> DESIRED (Special case)
8643 	 */
8644 	if (dm_con_state->update_hdcp &&
8645 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
8646 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
8647 		dm_con_state->update_hdcp = false;
8648 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
8649 			__func__);
8650 		return true;
8651 	}
8652 
8653 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
8654 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
8655 			if (new_crtc_state && new_crtc_state->mode_changed) {
8656 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
8657 					__func__);
8658 				return true;
8659 			}
8660 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
8661 				__func__);
8662 			return false;
8663 		}
8664 
8665 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
8666 		return false;
8667 	}
8668 
8669 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8670 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
8671 			__func__);
8672 		return true;
8673 	}
8674 
8675 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
8676 	return false;
8677 }
8678 
8679 static void remove_stream(struct amdgpu_device *adev,
8680 			  struct amdgpu_crtc *acrtc,
8681 			  struct dc_stream_state *stream)
8682 {
8683 	/* this is the update mode case */
8684 
8685 	acrtc->otg_inst = -1;
8686 	acrtc->enabled = false;
8687 }
8688 
8689 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
8690 {
8691 
8692 	assert_spin_locked(&acrtc->base.dev->event_lock);
8693 	WARN_ON(acrtc->event);
8694 
8695 	acrtc->event = acrtc->base.state->event;
8696 
8697 	/* Set the flip status */
8698 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
8699 
8700 	/* Mark this event as consumed */
8701 	acrtc->base.state->event = NULL;
8702 
8703 	drm_dbg_state(acrtc->base.dev,
8704 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
8705 		      acrtc->crtc_id);
8706 }
8707 
8708 static void update_freesync_state_on_stream(
8709 	struct amdgpu_display_manager *dm,
8710 	struct dm_crtc_state *new_crtc_state,
8711 	struct dc_stream_state *new_stream,
8712 	struct dc_plane_state *surface,
8713 	u32 flip_timestamp_in_us)
8714 {
8715 	struct mod_vrr_params vrr_params;
8716 	struct dc_info_packet vrr_infopacket = {0};
8717 	struct amdgpu_device *adev = dm->adev;
8718 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
8719 	unsigned long flags;
8720 	bool pack_sdp_v1_3 = false;
8721 	struct amdgpu_dm_connector *aconn;
8722 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
8723 
8724 	if (!new_stream)
8725 		return;
8726 
8727 	/*
8728 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
8729 	 * For now it's sufficient to just guard against these conditions.
8730 	 */
8731 
8732 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
8733 		return;
8734 
8735 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8736 	vrr_params = acrtc->dm_irq_params.vrr_params;
8737 
8738 	if (surface) {
8739 		mod_freesync_handle_preflip(
8740 			dm->freesync_module,
8741 			surface,
8742 			new_stream,
8743 			flip_timestamp_in_us,
8744 			&vrr_params);
8745 
8746 		if (adev->family < AMDGPU_FAMILY_AI &&
8747 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
8748 			mod_freesync_handle_v_update(dm->freesync_module,
8749 						     new_stream, &vrr_params);
8750 
8751 			/* Need to call this before the frame ends. */
8752 			dc_stream_adjust_vmin_vmax(dm->dc,
8753 						   new_crtc_state->stream,
8754 						   &vrr_params.adjust);
8755 		}
8756 	}
8757 
8758 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
8759 
8760 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
8761 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
8762 
8763 		if (aconn->vsdb_info.amd_vsdb_version == 1)
8764 			packet_type = PACKET_TYPE_FS_V1;
8765 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
8766 			packet_type = PACKET_TYPE_FS_V2;
8767 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
8768 			packet_type = PACKET_TYPE_FS_V3;
8769 
8770 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
8771 					&new_stream->adaptive_sync_infopacket);
8772 	}
8773 
8774 	mod_freesync_build_vrr_infopacket(
8775 		dm->freesync_module,
8776 		new_stream,
8777 		&vrr_params,
8778 		packet_type,
8779 		TRANSFER_FUNC_UNKNOWN,
8780 		&vrr_infopacket,
8781 		pack_sdp_v1_3);
8782 
8783 	new_crtc_state->freesync_vrr_info_changed |=
8784 		(memcmp(&new_crtc_state->vrr_infopacket,
8785 			&vrr_infopacket,
8786 			sizeof(vrr_infopacket)) != 0);
8787 
8788 	acrtc->dm_irq_params.vrr_params = vrr_params;
8789 	new_crtc_state->vrr_infopacket = vrr_infopacket;
8790 
8791 	new_stream->vrr_infopacket = vrr_infopacket;
8792 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
8793 
8794 	if (new_crtc_state->freesync_vrr_info_changed)
8795 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
8796 			      new_crtc_state->base.crtc->base.id,
8797 			      (int)new_crtc_state->base.vrr_enabled,
8798 			      (int)vrr_params.state);
8799 
8800 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8801 }
8802 
8803 static void update_stream_irq_parameters(
8804 	struct amdgpu_display_manager *dm,
8805 	struct dm_crtc_state *new_crtc_state)
8806 {
8807 	struct dc_stream_state *new_stream = new_crtc_state->stream;
8808 	struct mod_vrr_params vrr_params;
8809 	struct mod_freesync_config config = new_crtc_state->freesync_config;
8810 	struct amdgpu_device *adev = dm->adev;
8811 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
8812 	unsigned long flags;
8813 
8814 	if (!new_stream)
8815 		return;
8816 
8817 	/*
8818 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
8819 	 * For now it's sufficient to just guard against these conditions.
8820 	 */
8821 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
8822 		return;
8823 
8824 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8825 	vrr_params = acrtc->dm_irq_params.vrr_params;
8826 
8827 	if (new_crtc_state->vrr_supported &&
8828 	    config.min_refresh_in_uhz &&
8829 	    config.max_refresh_in_uhz) {
8830 		/*
8831 		 * if freesync compatible mode was set, config.state will be set
8832 		 * in atomic check
8833 		 */
8834 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
8835 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
8836 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
8837 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
8838 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
8839 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
8840 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
8841 		} else {
8842 			config.state = new_crtc_state->base.vrr_enabled ?
8843 						     VRR_STATE_ACTIVE_VARIABLE :
8844 						     VRR_STATE_INACTIVE;
8845 		}
8846 	} else {
8847 		config.state = VRR_STATE_UNSUPPORTED;
8848 	}
8849 
8850 	mod_freesync_build_vrr_params(dm->freesync_module,
8851 				      new_stream,
8852 				      &config, &vrr_params);
8853 
8854 	new_crtc_state->freesync_config = config;
8855 	/* Copy state for access from DM IRQ handler */
8856 	acrtc->dm_irq_params.freesync_config = config;
8857 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
8858 	acrtc->dm_irq_params.vrr_params = vrr_params;
8859 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8860 }
8861 
8862 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
8863 					    struct dm_crtc_state *new_state)
8864 {
8865 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
8866 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
8867 
8868 	if (!old_vrr_active && new_vrr_active) {
8869 		/* Transition VRR inactive -> active:
8870 		 * While VRR is active, we must not disable vblank irq, as a
8871 		 * reenable after disable would compute bogus vblank/pflip
8872 		 * timestamps if it likely happened inside display front-porch.
8873 		 *
8874 		 * We also need vupdate irq for the actual core vblank handling
8875 		 * at end of vblank.
8876 		 */
8877 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
8878 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
8879 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
8880 				 __func__, new_state->base.crtc->base.id);
8881 	} else if (old_vrr_active && !new_vrr_active) {
8882 		/* Transition VRR active -> inactive:
8883 		 * Allow vblank irq disable again for fixed refresh rate.
8884 		 */
8885 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
8886 		drm_crtc_vblank_put(new_state->base.crtc);
8887 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
8888 				 __func__, new_state->base.crtc->base.id);
8889 	}
8890 }
8891 
8892 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
8893 {
8894 	struct drm_plane *plane;
8895 	struct drm_plane_state *old_plane_state;
8896 	int i;
8897 
8898 	/*
8899 	 * TODO: Make this per-stream so we don't issue redundant updates for
8900 	 * commits with multiple streams.
8901 	 */
8902 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
8903 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
8904 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
8905 }
8906 
8907 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
8908 {
8909 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
8910 
8911 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
8912 }
8913 
8914 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
8915 				    struct drm_plane_state *old_plane_state,
8916 				    struct dc_stream_update *update)
8917 {
8918 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
8919 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
8920 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
8921 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
8922 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
8923 	uint64_t address = afb ? afb->address : 0;
8924 	struct dc_cursor_position position = {0};
8925 	struct dc_cursor_attributes attributes;
8926 	int ret;
8927 
8928 	if (!plane->state->fb && !old_plane_state->fb)
8929 		return;
8930 
8931 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
8932 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
8933 		       plane->state->crtc_h);
8934 
8935 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
8936 	if (ret)
8937 		return;
8938 
8939 	if (!position.enable) {
8940 		/* turn off cursor */
8941 		if (crtc_state && crtc_state->stream) {
8942 			dc_stream_set_cursor_position(crtc_state->stream,
8943 						      &position);
8944 			update->cursor_position = &crtc_state->stream->cursor_position;
8945 		}
8946 		return;
8947 	}
8948 
8949 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
8950 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
8951 
8952 	memset(&attributes, 0, sizeof(attributes));
8953 	attributes.address.high_part = upper_32_bits(address);
8954 	attributes.address.low_part  = lower_32_bits(address);
8955 	attributes.width             = plane->state->crtc_w;
8956 	attributes.height            = plane->state->crtc_h;
8957 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
8958 	attributes.rotation_angle    = 0;
8959 	attributes.attribute_flags.value = 0;
8960 
8961 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
8962 	 * legacy gamma setup.
8963 	 */
8964 	if (crtc_state->cm_is_degamma_srgb &&
8965 	    adev->dm.dc->caps.color.dpp.gamma_corr)
8966 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
8967 
8968 	if (afb)
8969 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
8970 
8971 	if (crtc_state->stream) {
8972 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
8973 						     &attributes))
8974 			DRM_ERROR("DC failed to set cursor attributes\n");
8975 
8976 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
8977 
8978 		if (!dc_stream_set_cursor_position(crtc_state->stream,
8979 						   &position))
8980 			DRM_ERROR("DC failed to set cursor position\n");
8981 
8982 		update->cursor_position = &crtc_state->stream->cursor_position;
8983 	}
8984 }
8985 
8986 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
8987 					  const struct dm_crtc_state *acrtc_state,
8988 					  const u64 current_ts)
8989 {
8990 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
8991 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
8992 	struct amdgpu_dm_connector *aconn =
8993 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8994 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
8995 
8996 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
8997 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
8998 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
8999 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9000 			     !psr->psr_feature_enabled)
9001 			if (!aconn->disallow_edp_enter_psr)
9002 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9003 	}
9004 
9005 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9006 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9007 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9008 		if (aconn->sr_skip_count > 0)
9009 			aconn->sr_skip_count--;
9010 
9011 		/* Allow SR when skip count is 0. */
9012 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9013 
9014 		/*
9015 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9016 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9017 		 * can be enabled immediately once OS demonstrates an
9018 		 * adequate number of fast atomic commits to notify KMD
9019 		 * of update events. See `vblank_control_worker()`.
9020 		 */
9021 		if (!vrr_active &&
9022 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9023 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9024 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9025 #endif
9026 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9027 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9028 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9029 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9030 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9031 				amdgpu_dm_psr_enable(acrtc_state->stream);
9032 		}
9033 	} else {
9034 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9035 	}
9036 }
9037 
9038 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9039 				    struct drm_device *dev,
9040 				    struct amdgpu_display_manager *dm,
9041 				    struct drm_crtc *pcrtc,
9042 				    bool wait_for_vblank)
9043 {
9044 	u32 i;
9045 	u64 timestamp_ns = ktime_get_ns();
9046 	struct drm_plane *plane;
9047 	struct drm_plane_state *old_plane_state, *new_plane_state;
9048 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9049 	struct drm_crtc_state *new_pcrtc_state =
9050 			drm_atomic_get_new_crtc_state(state, pcrtc);
9051 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9052 	struct dm_crtc_state *dm_old_crtc_state =
9053 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9054 	int planes_count = 0, vpos, hpos;
9055 	unsigned long flags;
9056 	u32 target_vblank, last_flip_vblank;
9057 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9058 	bool cursor_update = false;
9059 	bool pflip_present = false;
9060 	bool dirty_rects_changed = false;
9061 	bool updated_planes_and_streams = false;
9062 	struct {
9063 		struct dc_surface_update surface_updates[MAX_SURFACES];
9064 		struct dc_plane_info plane_infos[MAX_SURFACES];
9065 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9066 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9067 		struct dc_stream_update stream_update;
9068 	} *bundle;
9069 
9070 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
9071 
9072 	if (!bundle) {
9073 		drm_err(dev, "Failed to allocate update bundle\n");
9074 		goto cleanup;
9075 	}
9076 
9077 	/*
9078 	 * Disable the cursor first if we're disabling all the planes.
9079 	 * It'll remain on the screen after the planes are re-enabled
9080 	 * if we don't.
9081 	 *
9082 	 * If the cursor is transitioning from native to overlay mode, the
9083 	 * native cursor needs to be disabled first.
9084 	 */
9085 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9086 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9087 		struct dc_cursor_position cursor_position = {0};
9088 
9089 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9090 						   &cursor_position))
9091 			drm_err(dev, "DC failed to disable native cursor\n");
9092 
9093 		bundle->stream_update.cursor_position =
9094 				&acrtc_state->stream->cursor_position;
9095 	}
9096 
9097 	if (acrtc_state->active_planes == 0 &&
9098 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9099 		amdgpu_dm_commit_cursors(state);
9100 
9101 	/* update planes when needed */
9102 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9103 		struct drm_crtc *crtc = new_plane_state->crtc;
9104 		struct drm_crtc_state *new_crtc_state;
9105 		struct drm_framebuffer *fb = new_plane_state->fb;
9106 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9107 		bool plane_needs_flip;
9108 		struct dc_plane_state *dc_plane;
9109 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9110 
9111 		/* Cursor plane is handled after stream updates */
9112 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9113 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9114 			if ((fb && crtc == pcrtc) ||
9115 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9116 				cursor_update = true;
9117 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
9118 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
9119 			}
9120 
9121 			continue;
9122 		}
9123 
9124 		if (!fb || !crtc || pcrtc != crtc)
9125 			continue;
9126 
9127 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
9128 		if (!new_crtc_state->active)
9129 			continue;
9130 
9131 		dc_plane = dm_new_plane_state->dc_state;
9132 		if (!dc_plane)
9133 			continue;
9134 
9135 		bundle->surface_updates[planes_count].surface = dc_plane;
9136 		if (new_pcrtc_state->color_mgmt_changed) {
9137 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
9138 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
9139 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
9140 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
9141 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
9142 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
9143 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
9144 		}
9145 
9146 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
9147 				     &bundle->scaling_infos[planes_count]);
9148 
9149 		bundle->surface_updates[planes_count].scaling_info =
9150 			&bundle->scaling_infos[planes_count];
9151 
9152 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
9153 
9154 		pflip_present = pflip_present || plane_needs_flip;
9155 
9156 		if (!plane_needs_flip) {
9157 			planes_count += 1;
9158 			continue;
9159 		}
9160 
9161 		fill_dc_plane_info_and_addr(
9162 			dm->adev, new_plane_state,
9163 			afb->tiling_flags,
9164 			&bundle->plane_infos[planes_count],
9165 			&bundle->flip_addrs[planes_count].address,
9166 			afb->tmz_surface);
9167 
9168 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
9169 				 new_plane_state->plane->index,
9170 				 bundle->plane_infos[planes_count].dcc.enable);
9171 
9172 		bundle->surface_updates[planes_count].plane_info =
9173 			&bundle->plane_infos[planes_count];
9174 
9175 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
9176 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
9177 			fill_dc_dirty_rects(plane, old_plane_state,
9178 					    new_plane_state, new_crtc_state,
9179 					    &bundle->flip_addrs[planes_count],
9180 					    acrtc_state->stream->link->psr_settings.psr_version ==
9181 					    DC_PSR_VERSION_SU_1,
9182 					    &dirty_rects_changed);
9183 
9184 			/*
9185 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
9186 			 * and enabled it again after dirty regions are stable to avoid video glitch.
9187 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
9188 			 * during the PSR-SU was disabled.
9189 			 */
9190 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
9191 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
9192 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9193 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9194 #endif
9195 			    dirty_rects_changed) {
9196 				mutex_lock(&dm->dc_lock);
9197 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
9198 				timestamp_ns;
9199 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
9200 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
9201 				mutex_unlock(&dm->dc_lock);
9202 			}
9203 		}
9204 
9205 		/*
9206 		 * Only allow immediate flips for fast updates that don't
9207 		 * change memory domain, FB pitch, DCC state, rotation or
9208 		 * mirroring.
9209 		 *
9210 		 * dm_crtc_helper_atomic_check() only accepts async flips with
9211 		 * fast updates.
9212 		 */
9213 		if (crtc->state->async_flip &&
9214 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
9215 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
9216 			drm_warn_once(state->dev,
9217 				      "[PLANE:%d:%s] async flip with non-fast update\n",
9218 				      plane->base.id, plane->name);
9219 
9220 		bundle->flip_addrs[planes_count].flip_immediate =
9221 			crtc->state->async_flip &&
9222 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
9223 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
9224 
9225 		timestamp_ns = ktime_get_ns();
9226 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
9227 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
9228 		bundle->surface_updates[planes_count].surface = dc_plane;
9229 
9230 		if (!bundle->surface_updates[planes_count].surface) {
9231 			DRM_ERROR("No surface for CRTC: id=%d\n",
9232 					acrtc_attach->crtc_id);
9233 			continue;
9234 		}
9235 
9236 		if (plane == pcrtc->primary)
9237 			update_freesync_state_on_stream(
9238 				dm,
9239 				acrtc_state,
9240 				acrtc_state->stream,
9241 				dc_plane,
9242 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
9243 
9244 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
9245 				 __func__,
9246 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
9247 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
9248 
9249 		planes_count += 1;
9250 
9251 	}
9252 
9253 	if (pflip_present) {
9254 		if (!vrr_active) {
9255 			/* Use old throttling in non-vrr fixed refresh rate mode
9256 			 * to keep flip scheduling based on target vblank counts
9257 			 * working in a backwards compatible way, e.g., for
9258 			 * clients using the GLX_OML_sync_control extension or
9259 			 * DRI3/Present extension with defined target_msc.
9260 			 */
9261 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
9262 		} else {
9263 			/* For variable refresh rate mode only:
9264 			 * Get vblank of last completed flip to avoid > 1 vrr
9265 			 * flips per video frame by use of throttling, but allow
9266 			 * flip programming anywhere in the possibly large
9267 			 * variable vrr vblank interval for fine-grained flip
9268 			 * timing control and more opportunity to avoid stutter
9269 			 * on late submission of flips.
9270 			 */
9271 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9272 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
9273 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9274 		}
9275 
9276 		target_vblank = last_flip_vblank + wait_for_vblank;
9277 
9278 		/*
9279 		 * Wait until we're out of the vertical blank period before the one
9280 		 * targeted by the flip
9281 		 */
9282 		while ((acrtc_attach->enabled &&
9283 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
9284 							    0, &vpos, &hpos, NULL,
9285 							    NULL, &pcrtc->hwmode)
9286 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
9287 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
9288 			(int)(target_vblank -
9289 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
9290 			usleep_range(1000, 1100);
9291 		}
9292 
9293 		/**
9294 		 * Prepare the flip event for the pageflip interrupt to handle.
9295 		 *
9296 		 * This only works in the case where we've already turned on the
9297 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
9298 		 * from 0 -> n planes we have to skip a hardware generated event
9299 		 * and rely on sending it from software.
9300 		 */
9301 		if (acrtc_attach->base.state->event &&
9302 		    acrtc_state->active_planes > 0) {
9303 			drm_crtc_vblank_get(pcrtc);
9304 
9305 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9306 
9307 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
9308 			prepare_flip_isr(acrtc_attach);
9309 
9310 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9311 		}
9312 
9313 		if (acrtc_state->stream) {
9314 			if (acrtc_state->freesync_vrr_info_changed)
9315 				bundle->stream_update.vrr_infopacket =
9316 					&acrtc_state->stream->vrr_infopacket;
9317 		}
9318 	} else if (cursor_update && acrtc_state->active_planes > 0) {
9319 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9320 		if (acrtc_attach->base.state->event) {
9321 			drm_crtc_vblank_get(pcrtc);
9322 			acrtc_attach->event = acrtc_attach->base.state->event;
9323 			acrtc_attach->base.state->event = NULL;
9324 		}
9325 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9326 	}
9327 
9328 	/* Update the planes if changed or disable if we don't have any. */
9329 	if ((planes_count || acrtc_state->active_planes == 0) &&
9330 		acrtc_state->stream) {
9331 		/*
9332 		 * If PSR or idle optimizations are enabled then flush out
9333 		 * any pending work before hardware programming.
9334 		 */
9335 		if (dm->vblank_control_workqueue)
9336 			flush_workqueue(dm->vblank_control_workqueue);
9337 
9338 		bundle->stream_update.stream = acrtc_state->stream;
9339 		if (new_pcrtc_state->mode_changed) {
9340 			bundle->stream_update.src = acrtc_state->stream->src;
9341 			bundle->stream_update.dst = acrtc_state->stream->dst;
9342 		}
9343 
9344 		if (new_pcrtc_state->color_mgmt_changed) {
9345 			/*
9346 			 * TODO: This isn't fully correct since we've actually
9347 			 * already modified the stream in place.
9348 			 */
9349 			bundle->stream_update.gamut_remap =
9350 				&acrtc_state->stream->gamut_remap_matrix;
9351 			bundle->stream_update.output_csc_transform =
9352 				&acrtc_state->stream->csc_color_matrix;
9353 			bundle->stream_update.out_transfer_func =
9354 				&acrtc_state->stream->out_transfer_func;
9355 			bundle->stream_update.lut3d_func =
9356 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
9357 			bundle->stream_update.func_shaper =
9358 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
9359 		}
9360 
9361 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
9362 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
9363 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
9364 
9365 		mutex_lock(&dm->dc_lock);
9366 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
9367 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
9368 				amdgpu_dm_replay_disable(acrtc_state->stream);
9369 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
9370 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
9371 		}
9372 		mutex_unlock(&dm->dc_lock);
9373 
9374 		/*
9375 		 * If FreeSync state on the stream has changed then we need to
9376 		 * re-adjust the min/max bounds now that DC doesn't handle this
9377 		 * as part of commit.
9378 		 */
9379 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
9380 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9381 			dc_stream_adjust_vmin_vmax(
9382 				dm->dc, acrtc_state->stream,
9383 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
9384 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9385 		}
9386 		mutex_lock(&dm->dc_lock);
9387 		update_planes_and_stream_adapter(dm->dc,
9388 					 acrtc_state->update_type,
9389 					 planes_count,
9390 					 acrtc_state->stream,
9391 					 &bundle->stream_update,
9392 					 bundle->surface_updates);
9393 		updated_planes_and_streams = true;
9394 
9395 		/**
9396 		 * Enable or disable the interrupts on the backend.
9397 		 *
9398 		 * Most pipes are put into power gating when unused.
9399 		 *
9400 		 * When power gating is enabled on a pipe we lose the
9401 		 * interrupt enablement state when power gating is disabled.
9402 		 *
9403 		 * So we need to update the IRQ control state in hardware
9404 		 * whenever the pipe turns on (since it could be previously
9405 		 * power gated) or off (since some pipes can't be power gated
9406 		 * on some ASICs).
9407 		 */
9408 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
9409 			dm_update_pflip_irq_state(drm_to_adev(dev),
9410 						  acrtc_attach);
9411 
9412 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
9413 		mutex_unlock(&dm->dc_lock);
9414 	}
9415 
9416 	/*
9417 	 * Update cursor state *after* programming all the planes.
9418 	 * This avoids redundant programming in the case where we're going
9419 	 * to be disabling a single plane - those pipes are being disabled.
9420 	 */
9421 	if (acrtc_state->active_planes &&
9422 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
9423 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9424 		amdgpu_dm_commit_cursors(state);
9425 
9426 cleanup:
9427 	kfree(bundle);
9428 }
9429 
9430 static void amdgpu_dm_commit_audio(struct drm_device *dev,
9431 				   struct drm_atomic_state *state)
9432 {
9433 	struct amdgpu_device *adev = drm_to_adev(dev);
9434 	struct amdgpu_dm_connector *aconnector;
9435 	struct drm_connector *connector;
9436 	struct drm_connector_state *old_con_state, *new_con_state;
9437 	struct drm_crtc_state *new_crtc_state;
9438 	struct dm_crtc_state *new_dm_crtc_state;
9439 	const struct dc_stream_status *status;
9440 	int i, inst;
9441 
9442 	/* Notify device removals. */
9443 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9444 		if (old_con_state->crtc != new_con_state->crtc) {
9445 			/* CRTC changes require notification. */
9446 			goto notify;
9447 		}
9448 
9449 		if (!new_con_state->crtc)
9450 			continue;
9451 
9452 		new_crtc_state = drm_atomic_get_new_crtc_state(
9453 			state, new_con_state->crtc);
9454 
9455 		if (!new_crtc_state)
9456 			continue;
9457 
9458 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9459 			continue;
9460 
9461 notify:
9462 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
9463 			continue;
9464 
9465 		aconnector = to_amdgpu_dm_connector(connector);
9466 
9467 		mutex_lock(&adev->dm.audio_lock);
9468 		inst = aconnector->audio_inst;
9469 		aconnector->audio_inst = -1;
9470 		mutex_unlock(&adev->dm.audio_lock);
9471 
9472 		amdgpu_dm_audio_eld_notify(adev, inst);
9473 	}
9474 
9475 	/* Notify audio device additions. */
9476 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
9477 		if (!new_con_state->crtc)
9478 			continue;
9479 
9480 		new_crtc_state = drm_atomic_get_new_crtc_state(
9481 			state, new_con_state->crtc);
9482 
9483 		if (!new_crtc_state)
9484 			continue;
9485 
9486 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9487 			continue;
9488 
9489 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
9490 		if (!new_dm_crtc_state->stream)
9491 			continue;
9492 
9493 		status = dc_stream_get_status(new_dm_crtc_state->stream);
9494 		if (!status)
9495 			continue;
9496 
9497 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
9498 			continue;
9499 
9500 		aconnector = to_amdgpu_dm_connector(connector);
9501 
9502 		mutex_lock(&adev->dm.audio_lock);
9503 		inst = status->audio_inst;
9504 		aconnector->audio_inst = inst;
9505 		mutex_unlock(&adev->dm.audio_lock);
9506 
9507 		amdgpu_dm_audio_eld_notify(adev, inst);
9508 	}
9509 }
9510 
9511 /*
9512  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
9513  * @crtc_state: the DRM CRTC state
9514  * @stream_state: the DC stream state.
9515  *
9516  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
9517  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
9518  */
9519 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
9520 						struct dc_stream_state *stream_state)
9521 {
9522 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
9523 }
9524 
9525 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
9526 			      struct dm_crtc_state *crtc_state)
9527 {
9528 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
9529 }
9530 
9531 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
9532 					struct dc_state *dc_state)
9533 {
9534 	struct drm_device *dev = state->dev;
9535 	struct amdgpu_device *adev = drm_to_adev(dev);
9536 	struct amdgpu_display_manager *dm = &adev->dm;
9537 	struct drm_crtc *crtc;
9538 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9539 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9540 	struct drm_connector_state *old_con_state;
9541 	struct drm_connector *connector;
9542 	bool mode_set_reset_required = false;
9543 	u32 i;
9544 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
9545 	bool set_backlight_level = false;
9546 
9547 	/* Disable writeback */
9548 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
9549 		struct dm_connector_state *dm_old_con_state;
9550 		struct amdgpu_crtc *acrtc;
9551 
9552 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
9553 			continue;
9554 
9555 		old_crtc_state = NULL;
9556 
9557 		dm_old_con_state = to_dm_connector_state(old_con_state);
9558 		if (!dm_old_con_state->base.crtc)
9559 			continue;
9560 
9561 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
9562 		if (acrtc)
9563 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
9564 
9565 		if (!acrtc || !acrtc->wb_enabled)
9566 			continue;
9567 
9568 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9569 
9570 		dm_clear_writeback(dm, dm_old_crtc_state);
9571 		acrtc->wb_enabled = false;
9572 	}
9573 
9574 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
9575 				      new_crtc_state, i) {
9576 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
9577 
9578 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9579 
9580 		if (old_crtc_state->active &&
9581 		    (!new_crtc_state->active ||
9582 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
9583 			manage_dm_interrupts(adev, acrtc, NULL);
9584 			dc_stream_release(dm_old_crtc_state->stream);
9585 		}
9586 	}
9587 
9588 	drm_atomic_helper_calc_timestamping_constants(state);
9589 
9590 	/* update changed items */
9591 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9592 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
9593 
9594 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9595 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9596 
9597 		drm_dbg_state(state->dev,
9598 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
9599 			acrtc->crtc_id,
9600 			new_crtc_state->enable,
9601 			new_crtc_state->active,
9602 			new_crtc_state->planes_changed,
9603 			new_crtc_state->mode_changed,
9604 			new_crtc_state->active_changed,
9605 			new_crtc_state->connectors_changed);
9606 
9607 		/* Disable cursor if disabling crtc */
9608 		if (old_crtc_state->active && !new_crtc_state->active) {
9609 			struct dc_cursor_position position;
9610 
9611 			memset(&position, 0, sizeof(position));
9612 			mutex_lock(&dm->dc_lock);
9613 			dc_exit_ips_for_hw_access(dm->dc);
9614 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
9615 			mutex_unlock(&dm->dc_lock);
9616 		}
9617 
9618 		/* Copy all transient state flags into dc state */
9619 		if (dm_new_crtc_state->stream) {
9620 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
9621 							    dm_new_crtc_state->stream);
9622 		}
9623 
9624 		/* handles headless hotplug case, updating new_state and
9625 		 * aconnector as needed
9626 		 */
9627 
9628 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
9629 
9630 			drm_dbg_atomic(dev,
9631 				       "Atomic commit: SET crtc id %d: [%p]\n",
9632 				       acrtc->crtc_id, acrtc);
9633 
9634 			if (!dm_new_crtc_state->stream) {
9635 				/*
9636 				 * this could happen because of issues with
9637 				 * userspace notifications delivery.
9638 				 * In this case userspace tries to set mode on
9639 				 * display which is disconnected in fact.
9640 				 * dc_sink is NULL in this case on aconnector.
9641 				 * We expect reset mode will come soon.
9642 				 *
9643 				 * This can also happen when unplug is done
9644 				 * during resume sequence ended
9645 				 *
9646 				 * In this case, we want to pretend we still
9647 				 * have a sink to keep the pipe running so that
9648 				 * hw state is consistent with the sw state
9649 				 */
9650 				drm_dbg_atomic(dev,
9651 					       "Failed to create new stream for crtc %d\n",
9652 						acrtc->base.base.id);
9653 				continue;
9654 			}
9655 
9656 			if (dm_old_crtc_state->stream)
9657 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
9658 
9659 			pm_runtime_get_noresume(dev->dev);
9660 
9661 			acrtc->enabled = true;
9662 			acrtc->hw_mode = new_crtc_state->mode;
9663 			crtc->hwmode = new_crtc_state->mode;
9664 			mode_set_reset_required = true;
9665 			set_backlight_level = true;
9666 		} else if (modereset_required(new_crtc_state)) {
9667 			drm_dbg_atomic(dev,
9668 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
9669 				       acrtc->crtc_id, acrtc);
9670 			/* i.e. reset mode */
9671 			if (dm_old_crtc_state->stream)
9672 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
9673 
9674 			mode_set_reset_required = true;
9675 		}
9676 	} /* for_each_crtc_in_state() */
9677 
9678 	/* if there mode set or reset, disable eDP PSR, Replay */
9679 	if (mode_set_reset_required) {
9680 		if (dm->vblank_control_workqueue)
9681 			flush_workqueue(dm->vblank_control_workqueue);
9682 
9683 		amdgpu_dm_replay_disable_all(dm);
9684 		amdgpu_dm_psr_disable_all(dm);
9685 	}
9686 
9687 	dm_enable_per_frame_crtc_master_sync(dc_state);
9688 	mutex_lock(&dm->dc_lock);
9689 	dc_exit_ips_for_hw_access(dm->dc);
9690 	WARN_ON(!dc_commit_streams(dm->dc, &params));
9691 
9692 	/* Allow idle optimization when vblank count is 0 for display off */
9693 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
9694 		dc_allow_idle_optimizations(dm->dc, true);
9695 	mutex_unlock(&dm->dc_lock);
9696 
9697 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9698 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
9699 
9700 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9701 
9702 		if (dm_new_crtc_state->stream != NULL) {
9703 			const struct dc_stream_status *status =
9704 					dc_stream_get_status(dm_new_crtc_state->stream);
9705 
9706 			if (!status)
9707 				status = dc_state_get_stream_status(dc_state,
9708 									 dm_new_crtc_state->stream);
9709 			if (!status)
9710 				drm_err(dev,
9711 					"got no status for stream %p on acrtc%p\n",
9712 					dm_new_crtc_state->stream, acrtc);
9713 			else
9714 				acrtc->otg_inst = status->primary_otg_inst;
9715 		}
9716 	}
9717 
9718 	/* During boot up and resume the DC layer will reset the panel brightness
9719 	 * to fix a flicker issue.
9720 	 * It will cause the dm->actual_brightness is not the current panel brightness
9721 	 * level. (the dm->brightness is the correct panel level)
9722 	 * So we set the backlight level with dm->brightness value after set mode
9723 	 */
9724 	if (set_backlight_level) {
9725 		for (i = 0; i < dm->num_of_edps; i++) {
9726 			if (dm->backlight_dev[i])
9727 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
9728 		}
9729 	}
9730 }
9731 
9732 static void dm_set_writeback(struct amdgpu_display_manager *dm,
9733 			      struct dm_crtc_state *crtc_state,
9734 			      struct drm_connector *connector,
9735 			      struct drm_connector_state *new_con_state)
9736 {
9737 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
9738 	struct amdgpu_device *adev = dm->adev;
9739 	struct amdgpu_crtc *acrtc;
9740 	struct dc_writeback_info *wb_info;
9741 	struct pipe_ctx *pipe = NULL;
9742 	struct amdgpu_framebuffer *afb;
9743 	int i = 0;
9744 
9745 	wb_info = kzalloc(sizeof(*wb_info), GFP_KERNEL);
9746 	if (!wb_info) {
9747 		DRM_ERROR("Failed to allocate wb_info\n");
9748 		return;
9749 	}
9750 
9751 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
9752 	if (!acrtc) {
9753 		DRM_ERROR("no amdgpu_crtc found\n");
9754 		kfree(wb_info);
9755 		return;
9756 	}
9757 
9758 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
9759 	if (!afb) {
9760 		DRM_ERROR("No amdgpu_framebuffer found\n");
9761 		kfree(wb_info);
9762 		return;
9763 	}
9764 
9765 	for (i = 0; i < MAX_PIPES; i++) {
9766 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
9767 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
9768 			break;
9769 		}
9770 	}
9771 
9772 	/* fill in wb_info */
9773 	wb_info->wb_enabled = true;
9774 
9775 	wb_info->dwb_pipe_inst = 0;
9776 	wb_info->dwb_params.dwbscl_black_color = 0;
9777 	wb_info->dwb_params.hdr_mult = 0x1F000;
9778 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
9779 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
9780 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
9781 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
9782 
9783 	/* width & height from crtc */
9784 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
9785 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
9786 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
9787 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
9788 
9789 	wb_info->dwb_params.cnv_params.crop_en = false;
9790 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
9791 
9792 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
9793 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
9794 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
9795 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
9796 
9797 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
9798 
9799 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
9800 
9801 	wb_info->dwb_params.scaler_taps.h_taps = 4;
9802 	wb_info->dwb_params.scaler_taps.v_taps = 4;
9803 	wb_info->dwb_params.scaler_taps.h_taps_c = 2;
9804 	wb_info->dwb_params.scaler_taps.v_taps_c = 2;
9805 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
9806 
9807 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
9808 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
9809 
9810 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
9811 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
9812 		wb_info->mcif_buf_params.chroma_address[i] = 0;
9813 	}
9814 
9815 	wb_info->mcif_buf_params.p_vmid = 1;
9816 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
9817 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
9818 		wb_info->mcif_warmup_params.region_size =
9819 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
9820 	}
9821 	wb_info->mcif_warmup_params.p_vmid = 1;
9822 	wb_info->writeback_source_plane = pipe->plane_state;
9823 
9824 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
9825 
9826 	acrtc->wb_pending = true;
9827 	acrtc->wb_conn = wb_conn;
9828 	drm_writeback_queue_job(wb_conn, new_con_state);
9829 }
9830 
9831 /**
9832  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
9833  * @state: The atomic state to commit
9834  *
9835  * This will tell DC to commit the constructed DC state from atomic_check,
9836  * programming the hardware. Any failures here implies a hardware failure, since
9837  * atomic check should have filtered anything non-kosher.
9838  */
9839 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
9840 {
9841 	struct drm_device *dev = state->dev;
9842 	struct amdgpu_device *adev = drm_to_adev(dev);
9843 	struct amdgpu_display_manager *dm = &adev->dm;
9844 	struct dm_atomic_state *dm_state;
9845 	struct dc_state *dc_state = NULL;
9846 	u32 i, j;
9847 	struct drm_crtc *crtc;
9848 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9849 	unsigned long flags;
9850 	bool wait_for_vblank = true;
9851 	struct drm_connector *connector;
9852 	struct drm_connector_state *old_con_state, *new_con_state;
9853 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9854 	int crtc_disable_count = 0;
9855 
9856 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
9857 
9858 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
9859 	drm_dp_mst_atomic_wait_for_dependencies(state);
9860 
9861 	dm_state = dm_atomic_get_new_state(state);
9862 	if (dm_state && dm_state->context) {
9863 		dc_state = dm_state->context;
9864 		amdgpu_dm_commit_streams(state, dc_state);
9865 	}
9866 
9867 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9868 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9869 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9870 		struct amdgpu_dm_connector *aconnector;
9871 
9872 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
9873 			continue;
9874 
9875 		aconnector = to_amdgpu_dm_connector(connector);
9876 
9877 		if (!adev->dm.hdcp_workqueue)
9878 			continue;
9879 
9880 		pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
9881 
9882 		if (!connector)
9883 			continue;
9884 
9885 		pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9886 			connector->index, connector->status, connector->dpms);
9887 		pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9888 			old_con_state->content_protection, new_con_state->content_protection);
9889 
9890 		if (aconnector->dc_sink) {
9891 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
9892 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
9893 				pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
9894 				aconnector->dc_sink->edid_caps.display_name);
9895 			}
9896 		}
9897 
9898 		new_crtc_state = NULL;
9899 		old_crtc_state = NULL;
9900 
9901 		if (acrtc) {
9902 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
9903 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
9904 		}
9905 
9906 		if (old_crtc_state)
9907 			pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9908 			old_crtc_state->enable,
9909 			old_crtc_state->active,
9910 			old_crtc_state->mode_changed,
9911 			old_crtc_state->active_changed,
9912 			old_crtc_state->connectors_changed);
9913 
9914 		if (new_crtc_state)
9915 			pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9916 			new_crtc_state->enable,
9917 			new_crtc_state->active,
9918 			new_crtc_state->mode_changed,
9919 			new_crtc_state->active_changed,
9920 			new_crtc_state->connectors_changed);
9921 	}
9922 
9923 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9924 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9925 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9926 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9927 
9928 		if (!adev->dm.hdcp_workqueue)
9929 			continue;
9930 
9931 		new_crtc_state = NULL;
9932 		old_crtc_state = NULL;
9933 
9934 		if (acrtc) {
9935 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
9936 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
9937 		}
9938 
9939 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9940 
9941 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
9942 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9943 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
9944 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9945 			dm_new_con_state->update_hdcp = true;
9946 			continue;
9947 		}
9948 
9949 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
9950 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
9951 			/* when display is unplugged from mst hub, connctor will
9952 			 * be destroyed within dm_dp_mst_connector_destroy. connector
9953 			 * hdcp perperties, like type, undesired, desired, enabled,
9954 			 * will be lost. So, save hdcp properties into hdcp_work within
9955 			 * amdgpu_dm_atomic_commit_tail. if the same display is
9956 			 * plugged back with same display index, its hdcp properties
9957 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
9958 			 */
9959 
9960 			bool enable_encryption = false;
9961 
9962 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
9963 				enable_encryption = true;
9964 
9965 			if (aconnector->dc_link && aconnector->dc_sink &&
9966 				aconnector->dc_link->type == dc_connection_mst_branch) {
9967 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
9968 				struct hdcp_workqueue *hdcp_w =
9969 					&hdcp_work[aconnector->dc_link->link_index];
9970 
9971 				hdcp_w->hdcp_content_type[connector->index] =
9972 					new_con_state->hdcp_content_type;
9973 				hdcp_w->content_protection[connector->index] =
9974 					new_con_state->content_protection;
9975 			}
9976 
9977 			if (new_crtc_state && new_crtc_state->mode_changed &&
9978 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
9979 				enable_encryption = true;
9980 
9981 			DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
9982 
9983 			if (aconnector->dc_link)
9984 				hdcp_update_display(
9985 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
9986 					new_con_state->hdcp_content_type, enable_encryption);
9987 		}
9988 	}
9989 
9990 	/* Handle connector state changes */
9991 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9992 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9993 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9994 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9995 		struct dc_surface_update *dummy_updates;
9996 		struct dc_stream_update stream_update;
9997 		struct dc_info_packet hdr_packet;
9998 		struct dc_stream_status *status = NULL;
9999 		bool abm_changed, hdr_changed, scaling_changed;
10000 
10001 		memset(&stream_update, 0, sizeof(stream_update));
10002 
10003 		if (acrtc) {
10004 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10005 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10006 		}
10007 
10008 		/* Skip any modesets/resets */
10009 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10010 			continue;
10011 
10012 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10013 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10014 
10015 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10016 							     dm_old_con_state);
10017 
10018 		abm_changed = dm_new_crtc_state->abm_level !=
10019 			      dm_old_crtc_state->abm_level;
10020 
10021 		hdr_changed =
10022 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10023 
10024 		if (!scaling_changed && !abm_changed && !hdr_changed)
10025 			continue;
10026 
10027 		stream_update.stream = dm_new_crtc_state->stream;
10028 		if (scaling_changed) {
10029 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
10030 					dm_new_con_state, dm_new_crtc_state->stream);
10031 
10032 			stream_update.src = dm_new_crtc_state->stream->src;
10033 			stream_update.dst = dm_new_crtc_state->stream->dst;
10034 		}
10035 
10036 		if (abm_changed) {
10037 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10038 
10039 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10040 		}
10041 
10042 		if (hdr_changed) {
10043 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10044 			stream_update.hdr_static_metadata = &hdr_packet;
10045 		}
10046 
10047 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10048 
10049 		if (WARN_ON(!status))
10050 			continue;
10051 
10052 		WARN_ON(!status->plane_count);
10053 
10054 		/*
10055 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10056 		 * Here we create an empty update on each plane.
10057 		 * To fix this, DC should permit updating only stream properties.
10058 		 */
10059 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_ATOMIC);
10060 		if (!dummy_updates) {
10061 			DRM_ERROR("Failed to allocate memory for dummy_updates.\n");
10062 			continue;
10063 		}
10064 		for (j = 0; j < status->plane_count; j++)
10065 			dummy_updates[j].surface = status->plane_states[0];
10066 
10067 		sort(dummy_updates, status->plane_count,
10068 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10069 
10070 		mutex_lock(&dm->dc_lock);
10071 		dc_exit_ips_for_hw_access(dm->dc);
10072 		dc_update_planes_and_stream(dm->dc,
10073 					    dummy_updates,
10074 					    status->plane_count,
10075 					    dm_new_crtc_state->stream,
10076 					    &stream_update);
10077 		mutex_unlock(&dm->dc_lock);
10078 		kfree(dummy_updates);
10079 	}
10080 
10081 	/**
10082 	 * Enable interrupts for CRTCs that are newly enabled or went through
10083 	 * a modeset. It was intentionally deferred until after the front end
10084 	 * state was modified to wait until the OTG was on and so the IRQ
10085 	 * handlers didn't access stale or invalid state.
10086 	 */
10087 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10088 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10089 #ifdef CONFIG_DEBUG_FS
10090 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
10091 #endif
10092 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
10093 		if (old_crtc_state->active && !new_crtc_state->active)
10094 			crtc_disable_count++;
10095 
10096 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10097 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10098 
10099 		/* For freesync config update on crtc state and params for irq */
10100 		update_stream_irq_parameters(dm, dm_new_crtc_state);
10101 
10102 #ifdef CONFIG_DEBUG_FS
10103 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10104 		cur_crc_src = acrtc->dm_irq_params.crc_src;
10105 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10106 #endif
10107 
10108 		if (new_crtc_state->active &&
10109 		    (!old_crtc_state->active ||
10110 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10111 			dc_stream_retain(dm_new_crtc_state->stream);
10112 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
10113 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
10114 		}
10115 		/* Handle vrr on->off / off->on transitions */
10116 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
10117 
10118 #ifdef CONFIG_DEBUG_FS
10119 		if (new_crtc_state->active &&
10120 		    (!old_crtc_state->active ||
10121 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10122 			/**
10123 			 * Frontend may have changed so reapply the CRC capture
10124 			 * settings for the stream.
10125 			 */
10126 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
10127 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
10128 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
10129 					uint8_t cnt;
10130 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10131 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
10132 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
10133 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
10134 
10135 							/**
10136 							 * It takes 2 frames for HW to stably generate CRC when
10137 							 * resuming from suspend, so we set skip_frame_cnt 2.
10138 							 */
10139 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
10140 						}
10141 					}
10142 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10143 				}
10144 #endif
10145 				if (amdgpu_dm_crtc_configure_crc_source(
10146 					crtc, dm_new_crtc_state, cur_crc_src))
10147 					drm_dbg_atomic(dev, "Failed to configure crc source");
10148 			}
10149 		}
10150 #endif
10151 	}
10152 
10153 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
10154 		if (new_crtc_state->async_flip)
10155 			wait_for_vblank = false;
10156 
10157 	/* update planes when needed per crtc*/
10158 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
10159 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10160 
10161 		if (dm_new_crtc_state->stream)
10162 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
10163 	}
10164 
10165 	/* Enable writeback */
10166 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10167 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10168 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10169 
10170 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10171 			continue;
10172 
10173 		if (!new_con_state->writeback_job)
10174 			continue;
10175 
10176 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10177 
10178 		if (!new_crtc_state)
10179 			continue;
10180 
10181 		if (acrtc->wb_enabled)
10182 			continue;
10183 
10184 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10185 
10186 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
10187 		acrtc->wb_enabled = true;
10188 	}
10189 
10190 	/* Update audio instances for each connector. */
10191 	amdgpu_dm_commit_audio(dev, state);
10192 
10193 	/* restore the backlight level */
10194 	for (i = 0; i < dm->num_of_edps; i++) {
10195 		if (dm->backlight_dev[i] &&
10196 		    (dm->actual_brightness[i] != dm->brightness[i]))
10197 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10198 	}
10199 
10200 	/*
10201 	 * send vblank event on all events not handled in flip and
10202 	 * mark consumed event for drm_atomic_helper_commit_hw_done
10203 	 */
10204 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10205 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10206 
10207 		if (new_crtc_state->event)
10208 			drm_send_event_locked(dev, &new_crtc_state->event->base);
10209 
10210 		new_crtc_state->event = NULL;
10211 	}
10212 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10213 
10214 	/* Signal HW programming completion */
10215 	drm_atomic_helper_commit_hw_done(state);
10216 
10217 	if (wait_for_vblank)
10218 		drm_atomic_helper_wait_for_flip_done(dev, state);
10219 
10220 	drm_atomic_helper_cleanup_planes(dev, state);
10221 
10222 	/* Don't free the memory if we are hitting this as part of suspend.
10223 	 * This way we don't free any memory during suspend; see
10224 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
10225 	 * non-suspend modeset or when the driver is torn down.
10226 	 */
10227 	if (!adev->in_suspend) {
10228 		/* return the stolen vga memory back to VRAM */
10229 		if (!adev->mman.keep_stolen_vga_memory)
10230 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
10231 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
10232 	}
10233 
10234 	/*
10235 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
10236 	 * so we can put the GPU into runtime suspend if we're not driving any
10237 	 * displays anymore
10238 	 */
10239 	for (i = 0; i < crtc_disable_count; i++)
10240 		pm_runtime_put_autosuspend(dev->dev);
10241 	pm_runtime_mark_last_busy(dev->dev);
10242 
10243 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
10244 }
10245 
10246 static int dm_force_atomic_commit(struct drm_connector *connector)
10247 {
10248 	int ret = 0;
10249 	struct drm_device *ddev = connector->dev;
10250 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
10251 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
10252 	struct drm_plane *plane = disconnected_acrtc->base.primary;
10253 	struct drm_connector_state *conn_state;
10254 	struct drm_crtc_state *crtc_state;
10255 	struct drm_plane_state *plane_state;
10256 
10257 	if (!state)
10258 		return -ENOMEM;
10259 
10260 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
10261 
10262 	/* Construct an atomic state to restore previous display setting */
10263 
10264 	/*
10265 	 * Attach connectors to drm_atomic_state
10266 	 */
10267 	conn_state = drm_atomic_get_connector_state(state, connector);
10268 
10269 	ret = PTR_ERR_OR_ZERO(conn_state);
10270 	if (ret)
10271 		goto out;
10272 
10273 	/* Attach crtc to drm_atomic_state*/
10274 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
10275 
10276 	ret = PTR_ERR_OR_ZERO(crtc_state);
10277 	if (ret)
10278 		goto out;
10279 
10280 	/* force a restore */
10281 	crtc_state->mode_changed = true;
10282 
10283 	/* Attach plane to drm_atomic_state */
10284 	plane_state = drm_atomic_get_plane_state(state, plane);
10285 
10286 	ret = PTR_ERR_OR_ZERO(plane_state);
10287 	if (ret)
10288 		goto out;
10289 
10290 	/* Call commit internally with the state we just constructed */
10291 	ret = drm_atomic_commit(state);
10292 
10293 out:
10294 	drm_atomic_state_put(state);
10295 	if (ret)
10296 		DRM_ERROR("Restoring old state failed with %i\n", ret);
10297 
10298 	return ret;
10299 }
10300 
10301 /*
10302  * This function handles all cases when set mode does not come upon hotplug.
10303  * This includes when a display is unplugged then plugged back into the
10304  * same port and when running without usermode desktop manager supprot
10305  */
10306 void dm_restore_drm_connector_state(struct drm_device *dev,
10307 				    struct drm_connector *connector)
10308 {
10309 	struct amdgpu_dm_connector *aconnector;
10310 	struct amdgpu_crtc *disconnected_acrtc;
10311 	struct dm_crtc_state *acrtc_state;
10312 
10313 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10314 		return;
10315 
10316 	aconnector = to_amdgpu_dm_connector(connector);
10317 
10318 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
10319 		return;
10320 
10321 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
10322 	if (!disconnected_acrtc)
10323 		return;
10324 
10325 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
10326 	if (!acrtc_state->stream)
10327 		return;
10328 
10329 	/*
10330 	 * If the previous sink is not released and different from the current,
10331 	 * we deduce we are in a state where we can not rely on usermode call
10332 	 * to turn on the display, so we do it here
10333 	 */
10334 	if (acrtc_state->stream->sink != aconnector->dc_sink)
10335 		dm_force_atomic_commit(&aconnector->base);
10336 }
10337 
10338 /*
10339  * Grabs all modesetting locks to serialize against any blocking commits,
10340  * Waits for completion of all non blocking commits.
10341  */
10342 static int do_aquire_global_lock(struct drm_device *dev,
10343 				 struct drm_atomic_state *state)
10344 {
10345 	struct drm_crtc *crtc;
10346 	struct drm_crtc_commit *commit;
10347 	long ret;
10348 
10349 	/*
10350 	 * Adding all modeset locks to aquire_ctx will
10351 	 * ensure that when the framework release it the
10352 	 * extra locks we are locking here will get released to
10353 	 */
10354 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
10355 	if (ret)
10356 		return ret;
10357 
10358 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
10359 		spin_lock(&crtc->commit_lock);
10360 		commit = list_first_entry_or_null(&crtc->commit_list,
10361 				struct drm_crtc_commit, commit_entry);
10362 		if (commit)
10363 			drm_crtc_commit_get(commit);
10364 		spin_unlock(&crtc->commit_lock);
10365 
10366 		if (!commit)
10367 			continue;
10368 
10369 		/*
10370 		 * Make sure all pending HW programming completed and
10371 		 * page flips done
10372 		 */
10373 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
10374 
10375 		if (ret > 0)
10376 			ret = wait_for_completion_interruptible_timeout(
10377 					&commit->flip_done, 10*HZ);
10378 
10379 		if (ret == 0)
10380 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done timed out\n",
10381 				  crtc->base.id, crtc->name);
10382 
10383 		drm_crtc_commit_put(commit);
10384 	}
10385 
10386 	return ret < 0 ? ret : 0;
10387 }
10388 
10389 static void get_freesync_config_for_crtc(
10390 	struct dm_crtc_state *new_crtc_state,
10391 	struct dm_connector_state *new_con_state)
10392 {
10393 	struct mod_freesync_config config = {0};
10394 	struct amdgpu_dm_connector *aconnector;
10395 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
10396 	int vrefresh = drm_mode_vrefresh(mode);
10397 	bool fs_vid_mode = false;
10398 
10399 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10400 		return;
10401 
10402 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
10403 
10404 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
10405 					vrefresh >= aconnector->min_vfreq &&
10406 					vrefresh <= aconnector->max_vfreq;
10407 
10408 	if (new_crtc_state->vrr_supported) {
10409 		new_crtc_state->stream->ignore_msa_timing_param = true;
10410 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
10411 
10412 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
10413 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
10414 		config.vsif_supported = true;
10415 		config.btr = true;
10416 
10417 		if (fs_vid_mode) {
10418 			config.state = VRR_STATE_ACTIVE_FIXED;
10419 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
10420 			goto out;
10421 		} else if (new_crtc_state->base.vrr_enabled) {
10422 			config.state = VRR_STATE_ACTIVE_VARIABLE;
10423 		} else {
10424 			config.state = VRR_STATE_INACTIVE;
10425 		}
10426 	}
10427 out:
10428 	new_crtc_state->freesync_config = config;
10429 }
10430 
10431 static void reset_freesync_config_for_crtc(
10432 	struct dm_crtc_state *new_crtc_state)
10433 {
10434 	new_crtc_state->vrr_supported = false;
10435 
10436 	memset(&new_crtc_state->vrr_infopacket, 0,
10437 	       sizeof(new_crtc_state->vrr_infopacket));
10438 }
10439 
10440 static bool
10441 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
10442 				 struct drm_crtc_state *new_crtc_state)
10443 {
10444 	const struct drm_display_mode *old_mode, *new_mode;
10445 
10446 	if (!old_crtc_state || !new_crtc_state)
10447 		return false;
10448 
10449 	old_mode = &old_crtc_state->mode;
10450 	new_mode = &new_crtc_state->mode;
10451 
10452 	if (old_mode->clock       == new_mode->clock &&
10453 	    old_mode->hdisplay    == new_mode->hdisplay &&
10454 	    old_mode->vdisplay    == new_mode->vdisplay &&
10455 	    old_mode->htotal      == new_mode->htotal &&
10456 	    old_mode->vtotal      != new_mode->vtotal &&
10457 	    old_mode->hsync_start == new_mode->hsync_start &&
10458 	    old_mode->vsync_start != new_mode->vsync_start &&
10459 	    old_mode->hsync_end   == new_mode->hsync_end &&
10460 	    old_mode->vsync_end   != new_mode->vsync_end &&
10461 	    old_mode->hskew       == new_mode->hskew &&
10462 	    old_mode->vscan       == new_mode->vscan &&
10463 	    (old_mode->vsync_end - old_mode->vsync_start) ==
10464 	    (new_mode->vsync_end - new_mode->vsync_start))
10465 		return true;
10466 
10467 	return false;
10468 }
10469 
10470 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
10471 {
10472 	u64 num, den, res;
10473 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
10474 
10475 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
10476 
10477 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
10478 	den = (unsigned long long)new_crtc_state->mode.htotal *
10479 	      (unsigned long long)new_crtc_state->mode.vtotal;
10480 
10481 	res = div_u64(num, den);
10482 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
10483 }
10484 
10485 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
10486 			 struct drm_atomic_state *state,
10487 			 struct drm_crtc *crtc,
10488 			 struct drm_crtc_state *old_crtc_state,
10489 			 struct drm_crtc_state *new_crtc_state,
10490 			 bool enable,
10491 			 bool *lock_and_validation_needed)
10492 {
10493 	struct dm_atomic_state *dm_state = NULL;
10494 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10495 	struct dc_stream_state *new_stream;
10496 	int ret = 0;
10497 
10498 	/*
10499 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
10500 	 * update changed items
10501 	 */
10502 	struct amdgpu_crtc *acrtc = NULL;
10503 	struct drm_connector *connector = NULL;
10504 	struct amdgpu_dm_connector *aconnector = NULL;
10505 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
10506 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
10507 
10508 	new_stream = NULL;
10509 
10510 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10511 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10512 	acrtc = to_amdgpu_crtc(crtc);
10513 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
10514 	if (connector)
10515 		aconnector = to_amdgpu_dm_connector(connector);
10516 
10517 	/* TODO This hack should go away */
10518 	if (connector && enable) {
10519 		/* Make sure fake sink is created in plug-in scenario */
10520 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
10521 									connector);
10522 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
10523 									connector);
10524 
10525 		if (IS_ERR(drm_new_conn_state)) {
10526 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
10527 			goto fail;
10528 		}
10529 
10530 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
10531 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
10532 
10533 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10534 			goto skip_modeset;
10535 
10536 		new_stream = create_validate_stream_for_sink(aconnector,
10537 							     &new_crtc_state->mode,
10538 							     dm_new_conn_state,
10539 							     dm_old_crtc_state->stream);
10540 
10541 		/*
10542 		 * we can have no stream on ACTION_SET if a display
10543 		 * was disconnected during S3, in this case it is not an
10544 		 * error, the OS will be updated after detection, and
10545 		 * will do the right thing on next atomic commit
10546 		 */
10547 
10548 		if (!new_stream) {
10549 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
10550 					__func__, acrtc->base.base.id);
10551 			ret = -ENOMEM;
10552 			goto fail;
10553 		}
10554 
10555 		/*
10556 		 * TODO: Check VSDB bits to decide whether this should
10557 		 * be enabled or not.
10558 		 */
10559 		new_stream->triggered_crtc_reset.enabled =
10560 			dm->force_timing_sync;
10561 
10562 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
10563 
10564 		ret = fill_hdr_info_packet(drm_new_conn_state,
10565 					   &new_stream->hdr_static_metadata);
10566 		if (ret)
10567 			goto fail;
10568 
10569 		/*
10570 		 * If we already removed the old stream from the context
10571 		 * (and set the new stream to NULL) then we can't reuse
10572 		 * the old stream even if the stream and scaling are unchanged.
10573 		 * We'll hit the BUG_ON and black screen.
10574 		 *
10575 		 * TODO: Refactor this function to allow this check to work
10576 		 * in all conditions.
10577 		 */
10578 		if (amdgpu_freesync_vid_mode &&
10579 		    dm_new_crtc_state->stream &&
10580 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
10581 			goto skip_modeset;
10582 
10583 		if (dm_new_crtc_state->stream &&
10584 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10585 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
10586 			new_crtc_state->mode_changed = false;
10587 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
10588 					 new_crtc_state->mode_changed);
10589 		}
10590 	}
10591 
10592 	/* mode_changed flag may get updated above, need to check again */
10593 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10594 		goto skip_modeset;
10595 
10596 	drm_dbg_state(state->dev,
10597 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10598 		acrtc->crtc_id,
10599 		new_crtc_state->enable,
10600 		new_crtc_state->active,
10601 		new_crtc_state->planes_changed,
10602 		new_crtc_state->mode_changed,
10603 		new_crtc_state->active_changed,
10604 		new_crtc_state->connectors_changed);
10605 
10606 	/* Remove stream for any changed/disabled CRTC */
10607 	if (!enable) {
10608 
10609 		if (!dm_old_crtc_state->stream)
10610 			goto skip_modeset;
10611 
10612 		/* Unset freesync video if it was active before */
10613 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
10614 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
10615 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
10616 		}
10617 
10618 		/* Now check if we should set freesync video mode */
10619 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
10620 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10621 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
10622 		    is_timing_unchanged_for_freesync(new_crtc_state,
10623 						     old_crtc_state)) {
10624 			new_crtc_state->mode_changed = false;
10625 			DRM_DEBUG_DRIVER(
10626 				"Mode change not required for front porch change, setting mode_changed to %d",
10627 				new_crtc_state->mode_changed);
10628 
10629 			set_freesync_fixed_config(dm_new_crtc_state);
10630 
10631 			goto skip_modeset;
10632 		} else if (amdgpu_freesync_vid_mode && aconnector &&
10633 			   is_freesync_video_mode(&new_crtc_state->mode,
10634 						  aconnector)) {
10635 			struct drm_display_mode *high_mode;
10636 
10637 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
10638 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
10639 				set_freesync_fixed_config(dm_new_crtc_state);
10640 		}
10641 
10642 		ret = dm_atomic_get_state(state, &dm_state);
10643 		if (ret)
10644 			goto fail;
10645 
10646 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
10647 				crtc->base.id);
10648 
10649 		/* i.e. reset mode */
10650 		if (dc_state_remove_stream(
10651 				dm->dc,
10652 				dm_state->context,
10653 				dm_old_crtc_state->stream) != DC_OK) {
10654 			ret = -EINVAL;
10655 			goto fail;
10656 		}
10657 
10658 		dc_stream_release(dm_old_crtc_state->stream);
10659 		dm_new_crtc_state->stream = NULL;
10660 
10661 		reset_freesync_config_for_crtc(dm_new_crtc_state);
10662 
10663 		*lock_and_validation_needed = true;
10664 
10665 	} else {/* Add stream for any updated/enabled CRTC */
10666 		/*
10667 		 * Quick fix to prevent NULL pointer on new_stream when
10668 		 * added MST connectors not found in existing crtc_state in the chained mode
10669 		 * TODO: need to dig out the root cause of that
10670 		 */
10671 		if (!connector)
10672 			goto skip_modeset;
10673 
10674 		if (modereset_required(new_crtc_state))
10675 			goto skip_modeset;
10676 
10677 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
10678 				     dm_old_crtc_state->stream)) {
10679 
10680 			WARN_ON(dm_new_crtc_state->stream);
10681 
10682 			ret = dm_atomic_get_state(state, &dm_state);
10683 			if (ret)
10684 				goto fail;
10685 
10686 			dm_new_crtc_state->stream = new_stream;
10687 
10688 			dc_stream_retain(new_stream);
10689 
10690 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
10691 					 crtc->base.id);
10692 
10693 			if (dc_state_add_stream(
10694 					dm->dc,
10695 					dm_state->context,
10696 					dm_new_crtc_state->stream) != DC_OK) {
10697 				ret = -EINVAL;
10698 				goto fail;
10699 			}
10700 
10701 			*lock_and_validation_needed = true;
10702 		}
10703 	}
10704 
10705 skip_modeset:
10706 	/* Release extra reference */
10707 	if (new_stream)
10708 		dc_stream_release(new_stream);
10709 
10710 	/*
10711 	 * We want to do dc stream updates that do not require a
10712 	 * full modeset below.
10713 	 */
10714 	if (!(enable && connector && new_crtc_state->active))
10715 		return 0;
10716 	/*
10717 	 * Given above conditions, the dc state cannot be NULL because:
10718 	 * 1. We're in the process of enabling CRTCs (just been added
10719 	 *    to the dc context, or already is on the context)
10720 	 * 2. Has a valid connector attached, and
10721 	 * 3. Is currently active and enabled.
10722 	 * => The dc stream state currently exists.
10723 	 */
10724 	BUG_ON(dm_new_crtc_state->stream == NULL);
10725 
10726 	/* Scaling or underscan settings */
10727 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
10728 				drm_atomic_crtc_needs_modeset(new_crtc_state))
10729 		update_stream_scaling_settings(
10730 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
10731 
10732 	/* ABM settings */
10733 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
10734 
10735 	/*
10736 	 * Color management settings. We also update color properties
10737 	 * when a modeset is needed, to ensure it gets reprogrammed.
10738 	 */
10739 	if (dm_new_crtc_state->base.color_mgmt_changed ||
10740 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10741 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
10742 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10743 		if (ret)
10744 			goto fail;
10745 	}
10746 
10747 	/* Update Freesync settings. */
10748 	get_freesync_config_for_crtc(dm_new_crtc_state,
10749 				     dm_new_conn_state);
10750 
10751 	return ret;
10752 
10753 fail:
10754 	if (new_stream)
10755 		dc_stream_release(new_stream);
10756 	return ret;
10757 }
10758 
10759 static bool should_reset_plane(struct drm_atomic_state *state,
10760 			       struct drm_plane *plane,
10761 			       struct drm_plane_state *old_plane_state,
10762 			       struct drm_plane_state *new_plane_state)
10763 {
10764 	struct drm_plane *other;
10765 	struct drm_plane_state *old_other_state, *new_other_state;
10766 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10767 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
10768 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10769 	int i;
10770 
10771 	/*
10772 	 * TODO: Remove this hack for all asics once it proves that the
10773 	 * fast updates works fine on DCN3.2+.
10774 	 */
10775 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
10776 	    state->allow_modeset)
10777 		return true;
10778 
10779 	/* Exit early if we know that we're adding or removing the plane. */
10780 	if (old_plane_state->crtc != new_plane_state->crtc)
10781 		return true;
10782 
10783 	/* old crtc == new_crtc == NULL, plane not in context. */
10784 	if (!new_plane_state->crtc)
10785 		return false;
10786 
10787 	new_crtc_state =
10788 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
10789 	old_crtc_state =
10790 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
10791 
10792 	if (!new_crtc_state)
10793 		return true;
10794 
10795 	/*
10796 	 * A change in cursor mode means a new dc pipe needs to be acquired or
10797 	 * released from the state
10798 	 */
10799 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
10800 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10801 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10802 	    old_dm_crtc_state != NULL &&
10803 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
10804 		return true;
10805 	}
10806 
10807 	/* CRTC Degamma changes currently require us to recreate planes. */
10808 	if (new_crtc_state->color_mgmt_changed)
10809 		return true;
10810 
10811 	/*
10812 	 * On zpos change, planes need to be reordered by removing and re-adding
10813 	 * them one by one to the dc state, in order of descending zpos.
10814 	 *
10815 	 * TODO: We can likely skip bandwidth validation if the only thing that
10816 	 * changed about the plane was it'z z-ordering.
10817 	 */
10818 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
10819 		return true;
10820 
10821 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
10822 		return true;
10823 
10824 	/*
10825 	 * If there are any new primary or overlay planes being added or
10826 	 * removed then the z-order can potentially change. To ensure
10827 	 * correct z-order and pipe acquisition the current DC architecture
10828 	 * requires us to remove and recreate all existing planes.
10829 	 *
10830 	 * TODO: Come up with a more elegant solution for this.
10831 	 */
10832 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
10833 		struct amdgpu_framebuffer *old_afb, *new_afb;
10834 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
10835 
10836 		dm_new_other_state = to_dm_plane_state(new_other_state);
10837 		dm_old_other_state = to_dm_plane_state(old_other_state);
10838 
10839 		if (other->type == DRM_PLANE_TYPE_CURSOR)
10840 			continue;
10841 
10842 		if (old_other_state->crtc != new_plane_state->crtc &&
10843 		    new_other_state->crtc != new_plane_state->crtc)
10844 			continue;
10845 
10846 		if (old_other_state->crtc != new_other_state->crtc)
10847 			return true;
10848 
10849 		/* Src/dst size and scaling updates. */
10850 		if (old_other_state->src_w != new_other_state->src_w ||
10851 		    old_other_state->src_h != new_other_state->src_h ||
10852 		    old_other_state->crtc_w != new_other_state->crtc_w ||
10853 		    old_other_state->crtc_h != new_other_state->crtc_h)
10854 			return true;
10855 
10856 		/* Rotation / mirroring updates. */
10857 		if (old_other_state->rotation != new_other_state->rotation)
10858 			return true;
10859 
10860 		/* Blending updates. */
10861 		if (old_other_state->pixel_blend_mode !=
10862 		    new_other_state->pixel_blend_mode)
10863 			return true;
10864 
10865 		/* Alpha updates. */
10866 		if (old_other_state->alpha != new_other_state->alpha)
10867 			return true;
10868 
10869 		/* Colorspace changes. */
10870 		if (old_other_state->color_range != new_other_state->color_range ||
10871 		    old_other_state->color_encoding != new_other_state->color_encoding)
10872 			return true;
10873 
10874 		/* HDR/Transfer Function changes. */
10875 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
10876 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
10877 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
10878 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
10879 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
10880 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
10881 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
10882 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
10883 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
10884 			return true;
10885 
10886 		/* Framebuffer checks fall at the end. */
10887 		if (!old_other_state->fb || !new_other_state->fb)
10888 			continue;
10889 
10890 		/* Pixel format changes can require bandwidth updates. */
10891 		if (old_other_state->fb->format != new_other_state->fb->format)
10892 			return true;
10893 
10894 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
10895 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
10896 
10897 		/* Tiling and DCC changes also require bandwidth updates. */
10898 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
10899 		    old_afb->base.modifier != new_afb->base.modifier)
10900 			return true;
10901 	}
10902 
10903 	return false;
10904 }
10905 
10906 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
10907 			      struct drm_plane_state *new_plane_state,
10908 			      struct drm_framebuffer *fb)
10909 {
10910 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
10911 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
10912 	unsigned int pitch;
10913 	bool linear;
10914 
10915 	if (fb->width > new_acrtc->max_cursor_width ||
10916 	    fb->height > new_acrtc->max_cursor_height) {
10917 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
10918 				 new_plane_state->fb->width,
10919 				 new_plane_state->fb->height);
10920 		return -EINVAL;
10921 	}
10922 	if (new_plane_state->src_w != fb->width << 16 ||
10923 	    new_plane_state->src_h != fb->height << 16) {
10924 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
10925 		return -EINVAL;
10926 	}
10927 
10928 	/* Pitch in pixels */
10929 	pitch = fb->pitches[0] / fb->format->cpp[0];
10930 
10931 	if (fb->width != pitch) {
10932 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
10933 				 fb->width, pitch);
10934 		return -EINVAL;
10935 	}
10936 
10937 	switch (pitch) {
10938 	case 64:
10939 	case 128:
10940 	case 256:
10941 		/* FB pitch is supported by cursor plane */
10942 		break;
10943 	default:
10944 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
10945 		return -EINVAL;
10946 	}
10947 
10948 	/* Core DRM takes care of checking FB modifiers, so we only need to
10949 	 * check tiling flags when the FB doesn't have a modifier.
10950 	 */
10951 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
10952 		if (adev->family >= AMDGPU_FAMILY_GC_12_0_0) {
10953 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
10954 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
10955 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
10956 		} else {
10957 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
10958 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
10959 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
10960 		}
10961 		if (!linear) {
10962 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
10963 			return -EINVAL;
10964 		}
10965 	}
10966 
10967 	return 0;
10968 }
10969 
10970 /*
10971  * Helper function for checking the cursor in native mode
10972  */
10973 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
10974 					struct drm_plane *plane,
10975 					struct drm_plane_state *new_plane_state,
10976 					bool enable)
10977 {
10978 
10979 	struct amdgpu_crtc *new_acrtc;
10980 	int ret;
10981 
10982 	if (!enable || !new_plane_crtc ||
10983 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
10984 		return 0;
10985 
10986 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
10987 
10988 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
10989 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
10990 		return -EINVAL;
10991 	}
10992 
10993 	if (new_plane_state->fb) {
10994 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
10995 						new_plane_state->fb);
10996 		if (ret)
10997 			return ret;
10998 	}
10999 
11000 	return 0;
11001 }
11002 
11003 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11004 					   struct drm_crtc *old_plane_crtc,
11005 					   struct drm_crtc *new_plane_crtc,
11006 					   bool enable)
11007 {
11008 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11009 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11010 
11011 	if (!enable) {
11012 		if (old_plane_crtc == NULL)
11013 			return true;
11014 
11015 		old_crtc_state = drm_atomic_get_old_crtc_state(
11016 			state, old_plane_crtc);
11017 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11018 
11019 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11020 	} else {
11021 		if (new_plane_crtc == NULL)
11022 			return true;
11023 
11024 		new_crtc_state = drm_atomic_get_new_crtc_state(
11025 			state, new_plane_crtc);
11026 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11027 
11028 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11029 	}
11030 }
11031 
11032 static int dm_update_plane_state(struct dc *dc,
11033 				 struct drm_atomic_state *state,
11034 				 struct drm_plane *plane,
11035 				 struct drm_plane_state *old_plane_state,
11036 				 struct drm_plane_state *new_plane_state,
11037 				 bool enable,
11038 				 bool *lock_and_validation_needed,
11039 				 bool *is_top_most_overlay)
11040 {
11041 
11042 	struct dm_atomic_state *dm_state = NULL;
11043 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11044 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11045 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11046 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11047 	bool needs_reset, update_native_cursor;
11048 	int ret = 0;
11049 
11050 
11051 	new_plane_crtc = new_plane_state->crtc;
11052 	old_plane_crtc = old_plane_state->crtc;
11053 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11054 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11055 
11056 	update_native_cursor = dm_should_update_native_cursor(state,
11057 							      old_plane_crtc,
11058 							      new_plane_crtc,
11059 							      enable);
11060 
11061 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11062 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11063 						    new_plane_state, enable);
11064 		if (ret)
11065 			return ret;
11066 
11067 		return 0;
11068 	}
11069 
11070 	needs_reset = should_reset_plane(state, plane, old_plane_state,
11071 					 new_plane_state);
11072 
11073 	/* Remove any changed/removed planes */
11074 	if (!enable) {
11075 		if (!needs_reset)
11076 			return 0;
11077 
11078 		if (!old_plane_crtc)
11079 			return 0;
11080 
11081 		old_crtc_state = drm_atomic_get_old_crtc_state(
11082 				state, old_plane_crtc);
11083 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11084 
11085 		if (!dm_old_crtc_state->stream)
11086 			return 0;
11087 
11088 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
11089 				plane->base.id, old_plane_crtc->base.id);
11090 
11091 		ret = dm_atomic_get_state(state, &dm_state);
11092 		if (ret)
11093 			return ret;
11094 
11095 		if (!dc_state_remove_plane(
11096 				dc,
11097 				dm_old_crtc_state->stream,
11098 				dm_old_plane_state->dc_state,
11099 				dm_state->context)) {
11100 
11101 			return -EINVAL;
11102 		}
11103 
11104 		if (dm_old_plane_state->dc_state)
11105 			dc_plane_state_release(dm_old_plane_state->dc_state);
11106 
11107 		dm_new_plane_state->dc_state = NULL;
11108 
11109 		*lock_and_validation_needed = true;
11110 
11111 	} else { /* Add new planes */
11112 		struct dc_plane_state *dc_new_plane_state;
11113 
11114 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
11115 			return 0;
11116 
11117 		if (!new_plane_crtc)
11118 			return 0;
11119 
11120 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
11121 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11122 
11123 		if (!dm_new_crtc_state->stream)
11124 			return 0;
11125 
11126 		if (!needs_reset)
11127 			return 0;
11128 
11129 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
11130 		if (ret)
11131 			goto out;
11132 
11133 		WARN_ON(dm_new_plane_state->dc_state);
11134 
11135 		dc_new_plane_state = dc_create_plane_state(dc);
11136 		if (!dc_new_plane_state) {
11137 			ret = -ENOMEM;
11138 			goto out;
11139 		}
11140 
11141 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
11142 				 plane->base.id, new_plane_crtc->base.id);
11143 
11144 		ret = fill_dc_plane_attributes(
11145 			drm_to_adev(new_plane_crtc->dev),
11146 			dc_new_plane_state,
11147 			new_plane_state,
11148 			new_crtc_state);
11149 		if (ret) {
11150 			dc_plane_state_release(dc_new_plane_state);
11151 			goto out;
11152 		}
11153 
11154 		ret = dm_atomic_get_state(state, &dm_state);
11155 		if (ret) {
11156 			dc_plane_state_release(dc_new_plane_state);
11157 			goto out;
11158 		}
11159 
11160 		/*
11161 		 * Any atomic check errors that occur after this will
11162 		 * not need a release. The plane state will be attached
11163 		 * to the stream, and therefore part of the atomic
11164 		 * state. It'll be released when the atomic state is
11165 		 * cleaned.
11166 		 */
11167 		if (!dc_state_add_plane(
11168 				dc,
11169 				dm_new_crtc_state->stream,
11170 				dc_new_plane_state,
11171 				dm_state->context)) {
11172 
11173 			dc_plane_state_release(dc_new_plane_state);
11174 			ret = -EINVAL;
11175 			goto out;
11176 		}
11177 
11178 		dm_new_plane_state->dc_state = dc_new_plane_state;
11179 
11180 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
11181 
11182 		/* Tell DC to do a full surface update every time there
11183 		 * is a plane change. Inefficient, but works for now.
11184 		 */
11185 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
11186 
11187 		*lock_and_validation_needed = true;
11188 	}
11189 
11190 out:
11191 	/* If enabling cursor overlay failed, attempt fallback to native mode */
11192 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
11193 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11194 						    new_plane_state, enable);
11195 		if (ret)
11196 			return ret;
11197 
11198 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
11199 	}
11200 
11201 	return ret;
11202 }
11203 
11204 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
11205 				       int *src_w, int *src_h)
11206 {
11207 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
11208 	case DRM_MODE_ROTATE_90:
11209 	case DRM_MODE_ROTATE_270:
11210 		*src_w = plane_state->src_h >> 16;
11211 		*src_h = plane_state->src_w >> 16;
11212 		break;
11213 	case DRM_MODE_ROTATE_0:
11214 	case DRM_MODE_ROTATE_180:
11215 	default:
11216 		*src_w = plane_state->src_w >> 16;
11217 		*src_h = plane_state->src_h >> 16;
11218 		break;
11219 	}
11220 }
11221 
11222 static void
11223 dm_get_plane_scale(struct drm_plane_state *plane_state,
11224 		   int *out_plane_scale_w, int *out_plane_scale_h)
11225 {
11226 	int plane_src_w, plane_src_h;
11227 
11228 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
11229 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
11230 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
11231 }
11232 
11233 /*
11234  * The normalized_zpos value cannot be used by this iterator directly. It's only
11235  * calculated for enabled planes, potentially causing normalized_zpos collisions
11236  * between enabled/disabled planes in the atomic state. We need a unique value
11237  * so that the iterator will not generate the same object twice, or loop
11238  * indefinitely.
11239  */
11240 static inline struct __drm_planes_state *__get_next_zpos(
11241 	struct drm_atomic_state *state,
11242 	struct __drm_planes_state *prev)
11243 {
11244 	unsigned int highest_zpos = 0, prev_zpos = 256;
11245 	uint32_t highest_id = 0, prev_id = UINT_MAX;
11246 	struct drm_plane_state *new_plane_state;
11247 	struct drm_plane *plane;
11248 	int i, highest_i = -1;
11249 
11250 	if (prev != NULL) {
11251 		prev_zpos = prev->new_state->zpos;
11252 		prev_id = prev->ptr->base.id;
11253 	}
11254 
11255 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
11256 		/* Skip planes with higher zpos than the previously returned */
11257 		if (new_plane_state->zpos > prev_zpos ||
11258 		    (new_plane_state->zpos == prev_zpos &&
11259 		     plane->base.id >= prev_id))
11260 			continue;
11261 
11262 		/* Save the index of the plane with highest zpos */
11263 		if (new_plane_state->zpos > highest_zpos ||
11264 		    (new_plane_state->zpos == highest_zpos &&
11265 		     plane->base.id > highest_id)) {
11266 			highest_zpos = new_plane_state->zpos;
11267 			highest_id = plane->base.id;
11268 			highest_i = i;
11269 		}
11270 	}
11271 
11272 	if (highest_i < 0)
11273 		return NULL;
11274 
11275 	return &state->planes[highest_i];
11276 }
11277 
11278 /*
11279  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
11280  * by descending zpos, as read from the new plane state. This is the same
11281  * ordering as defined by drm_atomic_normalize_zpos().
11282  */
11283 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
11284 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
11285 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
11286 		for_each_if(((plane) = __i->ptr,				\
11287 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
11288 			     (old_plane_state) = __i->old_state,		\
11289 			     (new_plane_state) = __i->new_state, 1))
11290 
11291 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
11292 {
11293 	struct drm_connector *connector;
11294 	struct drm_connector_state *conn_state, *old_conn_state;
11295 	struct amdgpu_dm_connector *aconnector = NULL;
11296 	int i;
11297 
11298 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
11299 		if (!conn_state->crtc)
11300 			conn_state = old_conn_state;
11301 
11302 		if (conn_state->crtc != crtc)
11303 			continue;
11304 
11305 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11306 			continue;
11307 
11308 		aconnector = to_amdgpu_dm_connector(connector);
11309 		if (!aconnector->mst_output_port || !aconnector->mst_root)
11310 			aconnector = NULL;
11311 		else
11312 			break;
11313 	}
11314 
11315 	if (!aconnector)
11316 		return 0;
11317 
11318 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
11319 }
11320 
11321 /**
11322  * DOC: Cursor Modes - Native vs Overlay
11323  *
11324  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
11325  * plane. It does not require a dedicated hw plane to enable, but it is
11326  * subjected to the same z-order and scaling as the hw plane. It also has format
11327  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
11328  * hw plane.
11329  *
11330  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
11331  * own scaling and z-pos. It also has no blending restrictions. It lends to a
11332  * cursor behavior more akin to a DRM client's expectations. However, it does
11333  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
11334  * available.
11335  */
11336 
11337 /**
11338  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
11339  * @adev: amdgpu device
11340  * @state: DRM atomic state
11341  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
11342  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
11343  *
11344  * Get whether the cursor should be enabled in native mode, or overlay mode, on
11345  * the dm_crtc_state.
11346  *
11347  * The cursor should be enabled in overlay mode if there exists an underlying
11348  * plane - on which the cursor may be blended - that is either YUV formatted, or
11349  * scaled differently from the cursor.
11350  *
11351  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
11352  * calling this function.
11353  *
11354  * Return: 0 on success, or an error code if getting the cursor plane state
11355  * failed.
11356  */
11357 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
11358 				   struct drm_atomic_state *state,
11359 				   struct dm_crtc_state *dm_crtc_state,
11360 				   enum amdgpu_dm_cursor_mode *cursor_mode)
11361 {
11362 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
11363 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
11364 	struct drm_plane *plane;
11365 	bool consider_mode_change = false;
11366 	bool entire_crtc_covered = false;
11367 	bool cursor_changed = false;
11368 	int underlying_scale_w, underlying_scale_h;
11369 	int cursor_scale_w, cursor_scale_h;
11370 	int i;
11371 
11372 	/* Overlay cursor not supported on HW before DCN
11373 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
11374 	 * as previous DCN generations, so enable native mode on DCN401 in addition to DCE
11375 	 */
11376 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0 ||
11377 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
11378 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11379 		return 0;
11380 	}
11381 
11382 	/* Init cursor_mode to be the same as current */
11383 	*cursor_mode = dm_crtc_state->cursor_mode;
11384 
11385 	/*
11386 	 * Cursor mode can change if a plane's format changes, scale changes, is
11387 	 * enabled/disabled, or z-order changes.
11388 	 */
11389 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
11390 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
11391 
11392 		/* Only care about planes on this CRTC */
11393 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
11394 			continue;
11395 
11396 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
11397 			cursor_changed = true;
11398 
11399 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
11400 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
11401 		    old_plane_state->fb->format != plane_state->fb->format) {
11402 			consider_mode_change = true;
11403 			break;
11404 		}
11405 
11406 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
11407 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
11408 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
11409 			consider_mode_change = true;
11410 			break;
11411 		}
11412 	}
11413 
11414 	if (!consider_mode_change && !crtc_state->zpos_changed)
11415 		return 0;
11416 
11417 	/*
11418 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
11419 	 * no need to set cursor mode. This avoids needlessly locking the cursor
11420 	 * state.
11421 	 */
11422 	if (!cursor_changed &&
11423 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
11424 		return 0;
11425 	}
11426 
11427 	cursor_state = drm_atomic_get_plane_state(state,
11428 						  crtc_state->crtc->cursor);
11429 	if (IS_ERR(cursor_state))
11430 		return PTR_ERR(cursor_state);
11431 
11432 	/* Cursor is disabled */
11433 	if (!cursor_state->fb)
11434 		return 0;
11435 
11436 	/* For all planes in descending z-order (all of which are below cursor
11437 	 * as per zpos definitions), check their scaling and format
11438 	 */
11439 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
11440 
11441 		/* Only care about non-cursor planes on this CRTC */
11442 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
11443 		    plane->type == DRM_PLANE_TYPE_CURSOR)
11444 			continue;
11445 
11446 		/* Underlying plane is YUV format - use overlay cursor */
11447 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
11448 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11449 			return 0;
11450 		}
11451 
11452 		dm_get_plane_scale(plane_state,
11453 				   &underlying_scale_w, &underlying_scale_h);
11454 		dm_get_plane_scale(cursor_state,
11455 				   &cursor_scale_w, &cursor_scale_h);
11456 
11457 		/* Underlying plane has different scale - use overlay cursor */
11458 		if (cursor_scale_w != underlying_scale_w &&
11459 		    cursor_scale_h != underlying_scale_h) {
11460 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11461 			return 0;
11462 		}
11463 
11464 		/* If this plane covers the whole CRTC, no need to check planes underneath */
11465 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
11466 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
11467 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
11468 			entire_crtc_covered = true;
11469 			break;
11470 		}
11471 	}
11472 
11473 	/* If planes do not cover the entire CRTC, use overlay mode to enable
11474 	 * cursor over holes
11475 	 */
11476 	if (entire_crtc_covered)
11477 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11478 	else
11479 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11480 
11481 	return 0;
11482 }
11483 
11484 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
11485 					    struct drm_atomic_state *state,
11486 					    struct drm_crtc_state *crtc_state)
11487 {
11488 	struct drm_plane *plane;
11489 	struct drm_plane_state *new_plane_state, *old_plane_state;
11490 
11491 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
11492 		new_plane_state = drm_atomic_get_plane_state(state, plane);
11493 		old_plane_state = drm_atomic_get_plane_state(state, plane);
11494 
11495 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
11496 			DRM_ERROR("Failed to get plane state for plane %s\n", plane->name);
11497 			return false;
11498 		}
11499 
11500 		if (old_plane_state->fb && new_plane_state->fb &&
11501 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
11502 			return true;
11503 	}
11504 
11505 	return false;
11506 }
11507 
11508 /**
11509  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
11510  *
11511  * @dev: The DRM device
11512  * @state: The atomic state to commit
11513  *
11514  * Validate that the given atomic state is programmable by DC into hardware.
11515  * This involves constructing a &struct dc_state reflecting the new hardware
11516  * state we wish to commit, then querying DC to see if it is programmable. It's
11517  * important not to modify the existing DC state. Otherwise, atomic_check
11518  * may unexpectedly commit hardware changes.
11519  *
11520  * When validating the DC state, it's important that the right locks are
11521  * acquired. For full updates case which removes/adds/updates streams on one
11522  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
11523  * that any such full update commit will wait for completion of any outstanding
11524  * flip using DRMs synchronization events.
11525  *
11526  * Note that DM adds the affected connectors for all CRTCs in state, when that
11527  * might not seem necessary. This is because DC stream creation requires the
11528  * DC sink, which is tied to the DRM connector state. Cleaning this up should
11529  * be possible but non-trivial - a possible TODO item.
11530  *
11531  * Return: -Error code if validation failed.
11532  */
11533 static int amdgpu_dm_atomic_check(struct drm_device *dev,
11534 				  struct drm_atomic_state *state)
11535 {
11536 	struct amdgpu_device *adev = drm_to_adev(dev);
11537 	struct dm_atomic_state *dm_state = NULL;
11538 	struct dc *dc = adev->dm.dc;
11539 	struct drm_connector *connector;
11540 	struct drm_connector_state *old_con_state, *new_con_state;
11541 	struct drm_crtc *crtc;
11542 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11543 	struct drm_plane *plane;
11544 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
11545 	enum dc_status status;
11546 	int ret, i;
11547 	bool lock_and_validation_needed = false;
11548 	bool is_top_most_overlay = true;
11549 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11550 	struct drm_dp_mst_topology_mgr *mgr;
11551 	struct drm_dp_mst_topology_state *mst_state;
11552 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
11553 
11554 	trace_amdgpu_dm_atomic_check_begin(state);
11555 
11556 	ret = drm_atomic_helper_check_modeset(dev, state);
11557 	if (ret) {
11558 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
11559 		goto fail;
11560 	}
11561 
11562 	/* Check connector changes */
11563 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11564 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11565 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11566 
11567 		/* Skip connectors that are disabled or part of modeset already. */
11568 		if (!new_con_state->crtc)
11569 			continue;
11570 
11571 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
11572 		if (IS_ERR(new_crtc_state)) {
11573 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
11574 			ret = PTR_ERR(new_crtc_state);
11575 			goto fail;
11576 		}
11577 
11578 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
11579 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
11580 			new_crtc_state->connectors_changed = true;
11581 	}
11582 
11583 	if (dc_resource_is_dsc_encoding_supported(dc)) {
11584 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11585 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11586 				ret = add_affected_mst_dsc_crtcs(state, crtc);
11587 				if (ret) {
11588 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
11589 					goto fail;
11590 				}
11591 			}
11592 		}
11593 	}
11594 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11595 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11596 
11597 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
11598 		    !new_crtc_state->color_mgmt_changed &&
11599 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
11600 			dm_old_crtc_state->dsc_force_changed == false)
11601 			continue;
11602 
11603 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
11604 		if (ret) {
11605 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
11606 			goto fail;
11607 		}
11608 
11609 		if (!new_crtc_state->enable)
11610 			continue;
11611 
11612 		ret = drm_atomic_add_affected_connectors(state, crtc);
11613 		if (ret) {
11614 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
11615 			goto fail;
11616 		}
11617 
11618 		ret = drm_atomic_add_affected_planes(state, crtc);
11619 		if (ret) {
11620 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
11621 			goto fail;
11622 		}
11623 
11624 		if (dm_old_crtc_state->dsc_force_changed)
11625 			new_crtc_state->mode_changed = true;
11626 	}
11627 
11628 	/*
11629 	 * Add all primary and overlay planes on the CRTC to the state
11630 	 * whenever a plane is enabled to maintain correct z-ordering
11631 	 * and to enable fast surface updates.
11632 	 */
11633 	drm_for_each_crtc(crtc, dev) {
11634 		bool modified = false;
11635 
11636 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
11637 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
11638 				continue;
11639 
11640 			if (new_plane_state->crtc == crtc ||
11641 			    old_plane_state->crtc == crtc) {
11642 				modified = true;
11643 				break;
11644 			}
11645 		}
11646 
11647 		if (!modified)
11648 			continue;
11649 
11650 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
11651 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
11652 				continue;
11653 
11654 			new_plane_state =
11655 				drm_atomic_get_plane_state(state, plane);
11656 
11657 			if (IS_ERR(new_plane_state)) {
11658 				ret = PTR_ERR(new_plane_state);
11659 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
11660 				goto fail;
11661 			}
11662 		}
11663 	}
11664 
11665 	/*
11666 	 * DC consults the zpos (layer_index in DC terminology) to determine the
11667 	 * hw plane on which to enable the hw cursor (see
11668 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
11669 	 * atomic state, so call drm helper to normalize zpos.
11670 	 */
11671 	ret = drm_atomic_normalize_zpos(dev, state);
11672 	if (ret) {
11673 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
11674 		goto fail;
11675 	}
11676 
11677 	/*
11678 	 * Determine whether cursors on each CRTC should be enabled in native or
11679 	 * overlay mode.
11680 	 */
11681 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11682 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11683 
11684 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
11685 					      &dm_new_crtc_state->cursor_mode);
11686 		if (ret) {
11687 			drm_dbg(dev, "Failed to determine cursor mode\n");
11688 			goto fail;
11689 		}
11690 
11691 		/*
11692 		 * If overlay cursor is needed, DC cannot go through the
11693 		 * native cursor update path. All enabled planes on the CRTC
11694 		 * need to be added for DC to not disable a plane by mistake
11695 		 */
11696 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
11697 			ret = drm_atomic_add_affected_planes(state, crtc);
11698 			if (ret)
11699 				goto fail;
11700 		}
11701 	}
11702 
11703 	/* Remove exiting planes if they are modified */
11704 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
11705 
11706 		ret = dm_update_plane_state(dc, state, plane,
11707 					    old_plane_state,
11708 					    new_plane_state,
11709 					    false,
11710 					    &lock_and_validation_needed,
11711 					    &is_top_most_overlay);
11712 		if (ret) {
11713 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
11714 			goto fail;
11715 		}
11716 	}
11717 
11718 	/* Disable all crtcs which require disable */
11719 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11720 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
11721 					   old_crtc_state,
11722 					   new_crtc_state,
11723 					   false,
11724 					   &lock_and_validation_needed);
11725 		if (ret) {
11726 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
11727 			goto fail;
11728 		}
11729 	}
11730 
11731 	/* Enable all crtcs which require enable */
11732 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11733 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
11734 					   old_crtc_state,
11735 					   new_crtc_state,
11736 					   true,
11737 					   &lock_and_validation_needed);
11738 		if (ret) {
11739 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
11740 			goto fail;
11741 		}
11742 	}
11743 
11744 	/* Add new/modified planes */
11745 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
11746 		ret = dm_update_plane_state(dc, state, plane,
11747 					    old_plane_state,
11748 					    new_plane_state,
11749 					    true,
11750 					    &lock_and_validation_needed,
11751 					    &is_top_most_overlay);
11752 		if (ret) {
11753 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
11754 			goto fail;
11755 		}
11756 	}
11757 
11758 #if defined(CONFIG_DRM_AMD_DC_FP)
11759 	if (dc_resource_is_dsc_encoding_supported(dc)) {
11760 		ret = pre_validate_dsc(state, &dm_state, vars);
11761 		if (ret != 0)
11762 			goto fail;
11763 	}
11764 #endif
11765 
11766 	/* Run this here since we want to validate the streams we created */
11767 	ret = drm_atomic_helper_check_planes(dev, state);
11768 	if (ret) {
11769 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
11770 		goto fail;
11771 	}
11772 
11773 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11774 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11775 		if (dm_new_crtc_state->mpo_requested)
11776 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
11777 	}
11778 
11779 	/* Check cursor restrictions */
11780 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11781 		enum amdgpu_dm_cursor_mode required_cursor_mode;
11782 		int is_rotated, is_scaled;
11783 
11784 		/* Overlay cusor not subject to native cursor restrictions */
11785 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11786 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
11787 			continue;
11788 
11789 		/* Check if rotation or scaling is enabled on DCN401 */
11790 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
11791 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
11792 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
11793 
11794 			is_rotated = new_cursor_state &&
11795 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
11796 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
11797 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
11798 
11799 			if (is_rotated || is_scaled) {
11800 				drm_dbg_driver(
11801 					crtc->dev,
11802 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
11803 					crtc->base.id, crtc->name);
11804 				ret = -EINVAL;
11805 				goto fail;
11806 			}
11807 		}
11808 
11809 		/* If HW can only do native cursor, check restrictions again */
11810 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
11811 					      &required_cursor_mode);
11812 		if (ret) {
11813 			drm_dbg_driver(crtc->dev,
11814 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
11815 				       crtc->base.id, crtc->name);
11816 			goto fail;
11817 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
11818 			drm_dbg_driver(crtc->dev,
11819 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
11820 				       crtc->base.id, crtc->name);
11821 			ret = -EINVAL;
11822 			goto fail;
11823 		}
11824 	}
11825 
11826 	if (state->legacy_cursor_update) {
11827 		/*
11828 		 * This is a fast cursor update coming from the plane update
11829 		 * helper, check if it can be done asynchronously for better
11830 		 * performance.
11831 		 */
11832 		state->async_update =
11833 			!drm_atomic_helper_async_check(dev, state);
11834 
11835 		/*
11836 		 * Skip the remaining global validation if this is an async
11837 		 * update. Cursor updates can be done without affecting
11838 		 * state or bandwidth calcs and this avoids the performance
11839 		 * penalty of locking the private state object and
11840 		 * allocating a new dc_state.
11841 		 */
11842 		if (state->async_update)
11843 			return 0;
11844 	}
11845 
11846 	/* Check scaling and underscan changes*/
11847 	/* TODO Removed scaling changes validation due to inability to commit
11848 	 * new stream into context w\o causing full reset. Need to
11849 	 * decide how to handle.
11850 	 */
11851 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11852 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11853 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11854 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11855 
11856 		/* Skip any modesets/resets */
11857 		if (!acrtc || drm_atomic_crtc_needs_modeset(
11858 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
11859 			continue;
11860 
11861 		/* Skip any thing not scale or underscan changes */
11862 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
11863 			continue;
11864 
11865 		lock_and_validation_needed = true;
11866 	}
11867 
11868 	/* set the slot info for each mst_state based on the link encoding format */
11869 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
11870 		struct amdgpu_dm_connector *aconnector;
11871 		struct drm_connector *connector;
11872 		struct drm_connector_list_iter iter;
11873 		u8 link_coding_cap;
11874 
11875 		drm_connector_list_iter_begin(dev, &iter);
11876 		drm_for_each_connector_iter(connector, &iter) {
11877 			if (connector->index == mst_state->mgr->conn_base_id) {
11878 				aconnector = to_amdgpu_dm_connector(connector);
11879 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
11880 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
11881 
11882 				break;
11883 			}
11884 		}
11885 		drm_connector_list_iter_end(&iter);
11886 	}
11887 
11888 	/**
11889 	 * Streams and planes are reset when there are changes that affect
11890 	 * bandwidth. Anything that affects bandwidth needs to go through
11891 	 * DC global validation to ensure that the configuration can be applied
11892 	 * to hardware.
11893 	 *
11894 	 * We have to currently stall out here in atomic_check for outstanding
11895 	 * commits to finish in this case because our IRQ handlers reference
11896 	 * DRM state directly - we can end up disabling interrupts too early
11897 	 * if we don't.
11898 	 *
11899 	 * TODO: Remove this stall and drop DM state private objects.
11900 	 */
11901 	if (lock_and_validation_needed) {
11902 		ret = dm_atomic_get_state(state, &dm_state);
11903 		if (ret) {
11904 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
11905 			goto fail;
11906 		}
11907 
11908 		ret = do_aquire_global_lock(dev, state);
11909 		if (ret) {
11910 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
11911 			goto fail;
11912 		}
11913 
11914 #if defined(CONFIG_DRM_AMD_DC_FP)
11915 		if (dc_resource_is_dsc_encoding_supported(dc)) {
11916 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
11917 			if (ret) {
11918 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
11919 				ret = -EINVAL;
11920 				goto fail;
11921 			}
11922 		}
11923 #endif
11924 
11925 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
11926 		if (ret) {
11927 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
11928 			goto fail;
11929 		}
11930 
11931 		/*
11932 		 * Perform validation of MST topology in the state:
11933 		 * We need to perform MST atomic check before calling
11934 		 * dc_validate_global_state(), or there is a chance
11935 		 * to get stuck in an infinite loop and hang eventually.
11936 		 */
11937 		ret = drm_dp_mst_atomic_check(state);
11938 		if (ret) {
11939 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
11940 			goto fail;
11941 		}
11942 		status = dc_validate_global_state(dc, dm_state->context, true);
11943 		if (status != DC_OK) {
11944 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
11945 				       dc_status_to_str(status), status);
11946 			ret = -EINVAL;
11947 			goto fail;
11948 		}
11949 	} else {
11950 		/*
11951 		 * The commit is a fast update. Fast updates shouldn't change
11952 		 * the DC context, affect global validation, and can have their
11953 		 * commit work done in parallel with other commits not touching
11954 		 * the same resource. If we have a new DC context as part of
11955 		 * the DM atomic state from validation we need to free it and
11956 		 * retain the existing one instead.
11957 		 *
11958 		 * Furthermore, since the DM atomic state only contains the DC
11959 		 * context and can safely be annulled, we can free the state
11960 		 * and clear the associated private object now to free
11961 		 * some memory and avoid a possible use-after-free later.
11962 		 */
11963 
11964 		for (i = 0; i < state->num_private_objs; i++) {
11965 			struct drm_private_obj *obj = state->private_objs[i].ptr;
11966 
11967 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
11968 				int j = state->num_private_objs-1;
11969 
11970 				dm_atomic_destroy_state(obj,
11971 						state->private_objs[i].state);
11972 
11973 				/* If i is not at the end of the array then the
11974 				 * last element needs to be moved to where i was
11975 				 * before the array can safely be truncated.
11976 				 */
11977 				if (i != j)
11978 					state->private_objs[i] =
11979 						state->private_objs[j];
11980 
11981 				state->private_objs[j].ptr = NULL;
11982 				state->private_objs[j].state = NULL;
11983 				state->private_objs[j].old_state = NULL;
11984 				state->private_objs[j].new_state = NULL;
11985 
11986 				state->num_private_objs = j;
11987 				break;
11988 			}
11989 		}
11990 	}
11991 
11992 	/* Store the overall update type for use later in atomic check. */
11993 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11994 		struct dm_crtc_state *dm_new_crtc_state =
11995 			to_dm_crtc_state(new_crtc_state);
11996 
11997 		/*
11998 		 * Only allow async flips for fast updates that don't change
11999 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12000 		 */
12001 		if (new_crtc_state->async_flip &&
12002 		    (lock_and_validation_needed ||
12003 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12004 			drm_dbg_atomic(crtc->dev,
12005 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12006 				       crtc->base.id, crtc->name);
12007 			ret = -EINVAL;
12008 			goto fail;
12009 		}
12010 
12011 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12012 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12013 	}
12014 
12015 	/* Must be success */
12016 	WARN_ON(ret);
12017 
12018 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12019 
12020 	return ret;
12021 
12022 fail:
12023 	if (ret == -EDEADLK)
12024 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12025 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12026 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12027 	else
12028 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12029 
12030 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12031 
12032 	return ret;
12033 }
12034 
12035 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12036 		unsigned int offset,
12037 		unsigned int total_length,
12038 		u8 *data,
12039 		unsigned int length,
12040 		struct amdgpu_hdmi_vsdb_info *vsdb)
12041 {
12042 	bool res;
12043 	union dmub_rb_cmd cmd;
12044 	struct dmub_cmd_send_edid_cea *input;
12045 	struct dmub_cmd_edid_cea_output *output;
12046 
12047 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12048 		return false;
12049 
12050 	memset(&cmd, 0, sizeof(cmd));
12051 
12052 	input = &cmd.edid_cea.data.input;
12053 
12054 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12055 	cmd.edid_cea.header.sub_type = 0;
12056 	cmd.edid_cea.header.payload_bytes =
12057 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12058 	input->offset = offset;
12059 	input->length = length;
12060 	input->cea_total_length = total_length;
12061 	memcpy(input->payload, data, length);
12062 
12063 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12064 	if (!res) {
12065 		DRM_ERROR("EDID CEA parser failed\n");
12066 		return false;
12067 	}
12068 
12069 	output = &cmd.edid_cea.data.output;
12070 
12071 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
12072 		if (!output->ack.success) {
12073 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
12074 					output->ack.offset);
12075 		}
12076 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
12077 		if (!output->amd_vsdb.vsdb_found)
12078 			return false;
12079 
12080 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
12081 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
12082 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
12083 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
12084 	} else {
12085 		DRM_WARN("Unknown EDID CEA parser results\n");
12086 		return false;
12087 	}
12088 
12089 	return true;
12090 }
12091 
12092 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
12093 		u8 *edid_ext, int len,
12094 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12095 {
12096 	int i;
12097 
12098 	/* send extension block to DMCU for parsing */
12099 	for (i = 0; i < len; i += 8) {
12100 		bool res;
12101 		int offset;
12102 
12103 		/* send 8 bytes a time */
12104 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
12105 			return false;
12106 
12107 		if (i+8 == len) {
12108 			/* EDID block sent completed, expect result */
12109 			int version, min_rate, max_rate;
12110 
12111 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
12112 			if (res) {
12113 				/* amd vsdb found */
12114 				vsdb_info->freesync_supported = 1;
12115 				vsdb_info->amd_vsdb_version = version;
12116 				vsdb_info->min_refresh_rate_hz = min_rate;
12117 				vsdb_info->max_refresh_rate_hz = max_rate;
12118 				return true;
12119 			}
12120 			/* not amd vsdb */
12121 			return false;
12122 		}
12123 
12124 		/* check for ack*/
12125 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
12126 		if (!res)
12127 			return false;
12128 	}
12129 
12130 	return false;
12131 }
12132 
12133 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
12134 		u8 *edid_ext, int len,
12135 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12136 {
12137 	int i;
12138 
12139 	/* send extension block to DMCU for parsing */
12140 	for (i = 0; i < len; i += 8) {
12141 		/* send 8 bytes a time */
12142 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
12143 			return false;
12144 	}
12145 
12146 	return vsdb_info->freesync_supported;
12147 }
12148 
12149 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
12150 		u8 *edid_ext, int len,
12151 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12152 {
12153 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
12154 	bool ret;
12155 
12156 	mutex_lock(&adev->dm.dc_lock);
12157 	if (adev->dm.dmub_srv)
12158 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
12159 	else
12160 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
12161 	mutex_unlock(&adev->dm.dc_lock);
12162 	return ret;
12163 }
12164 
12165 static void parse_edid_displayid_vrr(struct drm_connector *connector,
12166 				     const struct edid *edid)
12167 {
12168 	u8 *edid_ext = NULL;
12169 	int i;
12170 	int j = 0;
12171 	u16 min_vfreq;
12172 	u16 max_vfreq;
12173 
12174 	if (edid == NULL || edid->extensions == 0)
12175 		return;
12176 
12177 	/* Find DisplayID extension */
12178 	for (i = 0; i < edid->extensions; i++) {
12179 		edid_ext = (void *)(edid + (i + 1));
12180 		if (edid_ext[0] == DISPLAYID_EXT)
12181 			break;
12182 	}
12183 
12184 	if (edid_ext == NULL)
12185 		return;
12186 
12187 	while (j < EDID_LENGTH) {
12188 		/* Get dynamic video timing range from DisplayID if available */
12189 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
12190 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
12191 			min_vfreq = edid_ext[j+9];
12192 			if (edid_ext[j+1] & 7)
12193 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
12194 			else
12195 				max_vfreq = edid_ext[j+10];
12196 
12197 			if (max_vfreq && min_vfreq) {
12198 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
12199 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
12200 
12201 				return;
12202 			}
12203 		}
12204 		j++;
12205 	}
12206 }
12207 
12208 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12209 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
12210 {
12211 	u8 *edid_ext = NULL;
12212 	int i;
12213 	int j = 0;
12214 
12215 	if (edid == NULL || edid->extensions == 0)
12216 		return -ENODEV;
12217 
12218 	/* Find DisplayID extension */
12219 	for (i = 0; i < edid->extensions; i++) {
12220 		edid_ext = (void *)(edid + (i + 1));
12221 		if (edid_ext[0] == DISPLAYID_EXT)
12222 			break;
12223 	}
12224 
12225 	while (j < EDID_LENGTH - sizeof(struct amd_vsdb_block)) {
12226 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
12227 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
12228 
12229 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
12230 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
12231 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
12232 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
12233 			DRM_DEBUG_KMS("Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
12234 
12235 			return true;
12236 		}
12237 		j++;
12238 	}
12239 
12240 	return false;
12241 }
12242 
12243 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12244 			       const struct edid *edid,
12245 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
12246 {
12247 	u8 *edid_ext = NULL;
12248 	int i;
12249 	bool valid_vsdb_found = false;
12250 
12251 	/*----- drm_find_cea_extension() -----*/
12252 	/* No EDID or EDID extensions */
12253 	if (edid == NULL || edid->extensions == 0)
12254 		return -ENODEV;
12255 
12256 	/* Find CEA extension */
12257 	for (i = 0; i < edid->extensions; i++) {
12258 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
12259 		if (edid_ext[0] == CEA_EXT)
12260 			break;
12261 	}
12262 
12263 	if (i == edid->extensions)
12264 		return -ENODEV;
12265 
12266 	/*----- cea_db_offsets() -----*/
12267 	if (edid_ext[0] != CEA_EXT)
12268 		return -ENODEV;
12269 
12270 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
12271 
12272 	return valid_vsdb_found ? i : -ENODEV;
12273 }
12274 
12275 /**
12276  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
12277  *
12278  * @connector: Connector to query.
12279  * @drm_edid: DRM EDID from monitor
12280  *
12281  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
12282  * track of some of the display information in the internal data struct used by
12283  * amdgpu_dm. This function checks which type of connector we need to set the
12284  * FreeSync parameters.
12285  */
12286 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
12287 				    const struct drm_edid *drm_edid)
12288 {
12289 	int i = 0;
12290 	struct amdgpu_dm_connector *amdgpu_dm_connector =
12291 			to_amdgpu_dm_connector(connector);
12292 	struct dm_connector_state *dm_con_state = NULL;
12293 	struct dc_sink *sink;
12294 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
12295 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
12296 	const struct edid *edid;
12297 	bool freesync_capable = false;
12298 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
12299 
12300 	if (!connector->state) {
12301 		DRM_ERROR("%s - Connector has no state", __func__);
12302 		goto update;
12303 	}
12304 
12305 	sink = amdgpu_dm_connector->dc_sink ?
12306 		amdgpu_dm_connector->dc_sink :
12307 		amdgpu_dm_connector->dc_em_sink;
12308 
12309 	drm_edid_connector_update(connector, drm_edid);
12310 
12311 	if (!drm_edid || !sink) {
12312 		dm_con_state = to_dm_connector_state(connector->state);
12313 
12314 		amdgpu_dm_connector->min_vfreq = 0;
12315 		amdgpu_dm_connector->max_vfreq = 0;
12316 		freesync_capable = false;
12317 
12318 		goto update;
12319 	}
12320 
12321 	dm_con_state = to_dm_connector_state(connector->state);
12322 
12323 	if (!adev->dm.freesync_module)
12324 		goto update;
12325 
12326 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
12327 
12328 	/* Some eDP panels only have the refresh rate range info in DisplayID */
12329 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
12330 	     connector->display_info.monitor_range.max_vfreq == 0))
12331 		parse_edid_displayid_vrr(connector, edid);
12332 
12333 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
12334 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
12335 		if (amdgpu_dm_connector->dc_link &&
12336 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
12337 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
12338 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
12339 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12340 				freesync_capable = true;
12341 		}
12342 
12343 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12344 
12345 		if (vsdb_info.replay_mode) {
12346 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
12347 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
12348 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
12349 		}
12350 
12351 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
12352 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12353 		if (i >= 0 && vsdb_info.freesync_supported) {
12354 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12355 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12356 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12357 				freesync_capable = true;
12358 
12359 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12360 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12361 		}
12362 	}
12363 
12364 	if (amdgpu_dm_connector->dc_link)
12365 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
12366 
12367 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
12368 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12369 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
12370 
12371 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
12372 			amdgpu_dm_connector->as_type = as_type;
12373 			amdgpu_dm_connector->vsdb_info = vsdb_info;
12374 
12375 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12376 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12377 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12378 				freesync_capable = true;
12379 
12380 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12381 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12382 		}
12383 	}
12384 
12385 update:
12386 	if (dm_con_state)
12387 		dm_con_state->freesync_capable = freesync_capable;
12388 
12389 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
12390 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
12391 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
12392 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
12393 	}
12394 
12395 	if (connector->vrr_capable_property)
12396 		drm_connector_set_vrr_capable_property(connector,
12397 						       freesync_capable);
12398 }
12399 
12400 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
12401 {
12402 	struct amdgpu_device *adev = drm_to_adev(dev);
12403 	struct dc *dc = adev->dm.dc;
12404 	int i;
12405 
12406 	mutex_lock(&adev->dm.dc_lock);
12407 	if (dc->current_state) {
12408 		for (i = 0; i < dc->current_state->stream_count; ++i)
12409 			dc->current_state->streams[i]
12410 				->triggered_crtc_reset.enabled =
12411 				adev->dm.force_timing_sync;
12412 
12413 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
12414 		dc_trigger_sync(dc, dc->current_state);
12415 	}
12416 	mutex_unlock(&adev->dm.dc_lock);
12417 }
12418 
12419 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
12420 {
12421 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
12422 		dc_exit_ips_for_hw_access(dc);
12423 }
12424 
12425 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
12426 		       u32 value, const char *func_name)
12427 {
12428 #ifdef DM_CHECK_ADDR_0
12429 	if (address == 0) {
12430 		drm_err(adev_to_drm(ctx->driver_context),
12431 			"invalid register write. address = 0");
12432 		return;
12433 	}
12434 #endif
12435 
12436 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12437 	cgs_write_register(ctx->cgs_device, address, value);
12438 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
12439 }
12440 
12441 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
12442 			  const char *func_name)
12443 {
12444 	u32 value;
12445 #ifdef DM_CHECK_ADDR_0
12446 	if (address == 0) {
12447 		drm_err(adev_to_drm(ctx->driver_context),
12448 			"invalid register read; address = 0\n");
12449 		return 0;
12450 	}
12451 #endif
12452 
12453 	if (ctx->dmub_srv &&
12454 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
12455 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
12456 		ASSERT(false);
12457 		return 0;
12458 	}
12459 
12460 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12461 
12462 	value = cgs_read_register(ctx->cgs_device, address);
12463 
12464 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
12465 
12466 	return value;
12467 }
12468 
12469 int amdgpu_dm_process_dmub_aux_transfer_sync(
12470 		struct dc_context *ctx,
12471 		unsigned int link_index,
12472 		struct aux_payload *payload,
12473 		enum aux_return_code_type *operation_result)
12474 {
12475 	struct amdgpu_device *adev = ctx->driver_context;
12476 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
12477 	int ret = -1;
12478 
12479 	mutex_lock(&adev->dm.dpia_aux_lock);
12480 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
12481 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
12482 		goto out;
12483 	}
12484 
12485 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12486 		DRM_ERROR("wait_for_completion_timeout timeout!");
12487 		*operation_result = AUX_RET_ERROR_TIMEOUT;
12488 		goto out;
12489 	}
12490 
12491 	if (p_notify->result != AUX_RET_SUCCESS) {
12492 		/*
12493 		 * Transient states before tunneling is enabled could
12494 		 * lead to this error. We can ignore this for now.
12495 		 */
12496 		if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
12497 			DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
12498 					payload->address, payload->length,
12499 					p_notify->result);
12500 		}
12501 		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
12502 		goto out;
12503 	}
12504 
12505 
12506 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
12507 	if (!payload->write && p_notify->aux_reply.length &&
12508 			(payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
12509 
12510 		if (payload->length != p_notify->aux_reply.length) {
12511 			DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
12512 				p_notify->aux_reply.length,
12513 					payload->address, payload->length);
12514 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
12515 			goto out;
12516 		}
12517 
12518 		memcpy(payload->data, p_notify->aux_reply.data,
12519 				p_notify->aux_reply.length);
12520 	}
12521 
12522 	/* success */
12523 	ret = p_notify->aux_reply.length;
12524 	*operation_result = p_notify->result;
12525 out:
12526 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
12527 	mutex_unlock(&adev->dm.dpia_aux_lock);
12528 	return ret;
12529 }
12530 
12531 int amdgpu_dm_process_dmub_set_config_sync(
12532 		struct dc_context *ctx,
12533 		unsigned int link_index,
12534 		struct set_config_cmd_payload *payload,
12535 		enum set_config_status *operation_result)
12536 {
12537 	struct amdgpu_device *adev = ctx->driver_context;
12538 	bool is_cmd_complete;
12539 	int ret;
12540 
12541 	mutex_lock(&adev->dm.dpia_aux_lock);
12542 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
12543 			link_index, payload, adev->dm.dmub_notify);
12544 
12545 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12546 		ret = 0;
12547 		*operation_result = adev->dm.dmub_notify->sc_status;
12548 	} else {
12549 		DRM_ERROR("wait_for_completion_timeout timeout!");
12550 		ret = -1;
12551 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
12552 	}
12553 
12554 	if (!is_cmd_complete)
12555 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
12556 	mutex_unlock(&adev->dm.dpia_aux_lock);
12557 	return ret;
12558 }
12559 
12560 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
12561 {
12562 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
12563 }
12564 
12565 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)
12566 {
12567 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
12568 }
12569