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