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