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