xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 53c271b9a06ca307c2ce6994877d8d084d031962)
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 static void dm_oem_i2c_hw_fini(struct amdgpu_device *adev)
2961 {
2962 	struct amdgpu_display_manager *dm = &adev->dm;
2963 
2964 	if (dm->oem_i2c) {
2965 		i2c_del_adapter(&dm->oem_i2c->base);
2966 		kfree(dm->oem_i2c);
2967 		dm->oem_i2c = NULL;
2968 	}
2969 }
2970 
2971 /**
2972  * dm_hw_init() - Initialize DC device
2973  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
2974  *
2975  * Initialize the &struct amdgpu_display_manager device. This involves calling
2976  * the initializers of each DM component, then populating the struct with them.
2977  *
2978  * Although the function implies hardware initialization, both hardware and
2979  * software are initialized here. Splitting them out to their relevant init
2980  * hooks is a future TODO item.
2981  *
2982  * Some notable things that are initialized here:
2983  *
2984  * - Display Core, both software and hardware
2985  * - DC modules that we need (freesync and color management)
2986  * - DRM software states
2987  * - Interrupt sources and handlers
2988  * - Vblank support
2989  * - Debug FS entries, if enabled
2990  */
2991 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
2992 {
2993 	struct amdgpu_device *adev = ip_block->adev;
2994 	int r;
2995 
2996 	/* Create DAL display manager */
2997 	r = amdgpu_dm_init(adev);
2998 	if (r)
2999 		return r;
3000 	amdgpu_dm_hpd_init(adev);
3001 
3002 	r = dm_oem_i2c_hw_init(adev);
3003 	if (r)
3004 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3005 
3006 	return 0;
3007 }
3008 
3009 /**
3010  * dm_hw_fini() - Teardown DC device
3011  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3012  *
3013  * Teardown components within &struct amdgpu_display_manager that require
3014  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3015  * were loaded. Also flush IRQ workqueues and disable them.
3016  */
3017 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3018 {
3019 	struct amdgpu_device *adev = ip_block->adev;
3020 
3021 	dm_oem_i2c_hw_fini(adev);
3022 
3023 	amdgpu_dm_hpd_fini(adev);
3024 
3025 	amdgpu_dm_irq_fini(adev);
3026 	amdgpu_dm_fini(adev);
3027 	return 0;
3028 }
3029 
3030 
3031 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3032 				 struct dc_state *state, bool enable)
3033 {
3034 	enum dc_irq_source irq_source;
3035 	struct amdgpu_crtc *acrtc;
3036 	int rc = -EBUSY;
3037 	int i = 0;
3038 
3039 	for (i = 0; i < state->stream_count; i++) {
3040 		acrtc = get_crtc_by_otg_inst(
3041 				adev, state->stream_status[i].primary_otg_inst);
3042 
3043 		if (acrtc && state->stream_status[i].plane_count != 0) {
3044 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3045 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3046 			if (rc)
3047 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3048 					 enable ? "enable" : "disable");
3049 
3050 			if (enable) {
3051 				if (amdgpu_dm_crtc_vrr_active(to_dm_crtc_state(acrtc->base.state)))
3052 					rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, true);
3053 			} else
3054 				rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, false);
3055 
3056 			if (rc)
3057 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n", enable ? "en" : "dis");
3058 
3059 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3060 			/* During gpu-reset we disable and then enable vblank irq, so
3061 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3062 			 */
3063 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3064 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3065 		}
3066 	}
3067 
3068 }
3069 
3070 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3071 
3072 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3073 {
3074 	struct dc_state *context __free(state_release) = NULL;
3075 	int i;
3076 	struct dc_stream_state *del_streams[MAX_PIPES];
3077 	int del_streams_count = 0;
3078 	struct dc_commit_streams_params params = {};
3079 
3080 	memset(del_streams, 0, sizeof(del_streams));
3081 
3082 	context = dc_state_create_current_copy(dc);
3083 	if (context == NULL)
3084 		return DC_ERROR_UNEXPECTED;
3085 
3086 	/* First remove from context all streams */
3087 	for (i = 0; i < context->stream_count; i++) {
3088 		struct dc_stream_state *stream = context->streams[i];
3089 
3090 		del_streams[del_streams_count++] = stream;
3091 	}
3092 
3093 	/* Remove all planes for removed streams and then remove the streams */
3094 	for (i = 0; i < del_streams_count; i++) {
3095 		enum dc_status res;
3096 
3097 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3098 			return DC_FAIL_DETACH_SURFACES;
3099 
3100 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3101 		if (res != DC_OK)
3102 			return res;
3103 	}
3104 
3105 	params.streams = context->streams;
3106 	params.stream_count = context->stream_count;
3107 
3108 	return dc_commit_streams(dc, &params);
3109 }
3110 
3111 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3112 {
3113 	int i;
3114 
3115 	if (dm->hpd_rx_offload_wq) {
3116 		for (i = 0; i < dm->dc->caps.max_links; i++)
3117 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3118 	}
3119 }
3120 
3121 static int dm_cache_state(struct amdgpu_device *adev)
3122 {
3123 	int r;
3124 
3125 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3126 	if (IS_ERR(adev->dm.cached_state)) {
3127 		r = PTR_ERR(adev->dm.cached_state);
3128 		adev->dm.cached_state = NULL;
3129 	}
3130 
3131 	return adev->dm.cached_state ? 0 : r;
3132 }
3133 
3134 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3135 {
3136 	struct amdgpu_display_manager *dm = &adev->dm;
3137 	struct drm_device *ddev = adev_to_drm(adev);
3138 	struct dm_plane_state *dm_new_plane_state;
3139 	struct drm_plane_state *new_plane_state;
3140 	struct dm_crtc_state *dm_new_crtc_state;
3141 	struct drm_crtc_state *new_crtc_state;
3142 	struct drm_plane *plane;
3143 	struct drm_crtc *crtc;
3144 	int i;
3145 
3146 	if (!dm->cached_state)
3147 		return;
3148 
3149 	/* Force mode set in atomic commit */
3150 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3151 		new_crtc_state->active_changed = true;
3152 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3153 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3154 	}
3155 
3156 	/*
3157 	 * atomic_check is expected to create the dc states. We need to release
3158 	 * them here, since they were duplicated as part of the suspend
3159 	 * procedure.
3160 	 */
3161 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3162 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3163 		if (dm_new_crtc_state->stream) {
3164 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3165 			dc_stream_release(dm_new_crtc_state->stream);
3166 			dm_new_crtc_state->stream = NULL;
3167 		}
3168 		dm_new_crtc_state->base.color_mgmt_changed = true;
3169 	}
3170 
3171 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3172 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3173 		if (dm_new_plane_state->dc_state) {
3174 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3175 			dc_plane_state_release(dm_new_plane_state->dc_state);
3176 			dm_new_plane_state->dc_state = NULL;
3177 		}
3178 	}
3179 
3180 	drm_atomic_helper_resume(ddev, dm->cached_state);
3181 
3182 	dm->cached_state = NULL;
3183 }
3184 
3185 static void dm_complete(struct amdgpu_ip_block *ip_block)
3186 {
3187 	struct amdgpu_device *adev = ip_block->adev;
3188 
3189 	dm_destroy_cached_state(adev);
3190 }
3191 
3192 static int dm_prepare_suspend(struct amdgpu_ip_block *ip_block)
3193 {
3194 	struct amdgpu_device *adev = ip_block->adev;
3195 
3196 	if (amdgpu_in_reset(adev))
3197 		return 0;
3198 
3199 	WARN_ON(adev->dm.cached_state);
3200 
3201 	return dm_cache_state(adev);
3202 }
3203 
3204 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3205 {
3206 	struct amdgpu_device *adev = ip_block->adev;
3207 	struct amdgpu_display_manager *dm = &adev->dm;
3208 
3209 	if (amdgpu_in_reset(adev)) {
3210 		enum dc_status res;
3211 
3212 		mutex_lock(&dm->dc_lock);
3213 
3214 		dc_allow_idle_optimizations(adev->dm.dc, false);
3215 
3216 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3217 
3218 		if (dm->cached_dc_state)
3219 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3220 
3221 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3222 		if (res != DC_OK) {
3223 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3224 			return -EINVAL;
3225 		}
3226 
3227 		amdgpu_dm_irq_suspend(adev);
3228 
3229 		hpd_rx_irq_work_suspend(dm);
3230 
3231 		return 0;
3232 	}
3233 
3234 	if (!adev->dm.cached_state) {
3235 		int r = dm_cache_state(adev);
3236 
3237 		if (r)
3238 			return r;
3239 	}
3240 
3241 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3242 
3243 	s3_handle_mst(adev_to_drm(adev), true);
3244 
3245 	amdgpu_dm_irq_suspend(adev);
3246 
3247 	hpd_rx_irq_work_suspend(dm);
3248 
3249 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3250 
3251 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3252 		dc_allow_idle_optimizations(dm->dc, true);
3253 
3254 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3255 
3256 	return 0;
3257 }
3258 
3259 struct drm_connector *
3260 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3261 					     struct drm_crtc *crtc)
3262 {
3263 	u32 i;
3264 	struct drm_connector_state *new_con_state;
3265 	struct drm_connector *connector;
3266 	struct drm_crtc *crtc_from_state;
3267 
3268 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3269 		crtc_from_state = new_con_state->crtc;
3270 
3271 		if (crtc_from_state == crtc)
3272 			return connector;
3273 	}
3274 
3275 	return NULL;
3276 }
3277 
3278 static void emulated_link_detect(struct dc_link *link)
3279 {
3280 	struct dc_sink_init_data sink_init_data = { 0 };
3281 	struct display_sink_capability sink_caps = { 0 };
3282 	enum dc_edid_status edid_status;
3283 	struct dc_context *dc_ctx = link->ctx;
3284 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3285 	struct dc_sink *sink = NULL;
3286 	struct dc_sink *prev_sink = NULL;
3287 
3288 	link->type = dc_connection_none;
3289 	prev_sink = link->local_sink;
3290 
3291 	if (prev_sink)
3292 		dc_sink_release(prev_sink);
3293 
3294 	switch (link->connector_signal) {
3295 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3296 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3297 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3298 		break;
3299 	}
3300 
3301 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3302 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3303 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3304 		break;
3305 	}
3306 
3307 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3308 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3309 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3310 		break;
3311 	}
3312 
3313 	case SIGNAL_TYPE_LVDS: {
3314 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3315 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3316 		break;
3317 	}
3318 
3319 	case SIGNAL_TYPE_EDP: {
3320 		sink_caps.transaction_type =
3321 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3322 		sink_caps.signal = SIGNAL_TYPE_EDP;
3323 		break;
3324 	}
3325 
3326 	case SIGNAL_TYPE_DISPLAY_PORT: {
3327 		sink_caps.transaction_type =
3328 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3329 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3330 		break;
3331 	}
3332 
3333 	default:
3334 		drm_err(dev, "Invalid connector type! signal:%d\n",
3335 			link->connector_signal);
3336 		return;
3337 	}
3338 
3339 	sink_init_data.link = link;
3340 	sink_init_data.sink_signal = sink_caps.signal;
3341 
3342 	sink = dc_sink_create(&sink_init_data);
3343 	if (!sink) {
3344 		drm_err(dev, "Failed to create sink!\n");
3345 		return;
3346 	}
3347 
3348 	/* dc_sink_create returns a new reference */
3349 	link->local_sink = sink;
3350 
3351 	edid_status = dm_helpers_read_local_edid(
3352 			link->ctx,
3353 			link,
3354 			sink);
3355 
3356 	if (edid_status != EDID_OK)
3357 		drm_err(dev, "Failed to read EDID\n");
3358 
3359 }
3360 
3361 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3362 				     struct amdgpu_display_manager *dm)
3363 {
3364 	struct {
3365 		struct dc_surface_update surface_updates[MAX_SURFACES];
3366 		struct dc_plane_info plane_infos[MAX_SURFACES];
3367 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3368 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3369 		struct dc_stream_update stream_update;
3370 	} *bundle __free(kfree);
3371 	int k, m;
3372 
3373 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
3374 
3375 	if (!bundle) {
3376 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3377 		return;
3378 	}
3379 
3380 	for (k = 0; k < dc_state->stream_count; k++) {
3381 		bundle->stream_update.stream = dc_state->streams[k];
3382 
3383 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3384 			bundle->surface_updates[m].surface =
3385 				dc_state->stream_status[k].plane_states[m];
3386 			bundle->surface_updates[m].surface->force_full_update =
3387 				true;
3388 		}
3389 
3390 		update_planes_and_stream_adapter(dm->dc,
3391 					 UPDATE_TYPE_FULL,
3392 					 dc_state->stream_status[k].plane_count,
3393 					 dc_state->streams[k],
3394 					 &bundle->stream_update,
3395 					 bundle->surface_updates);
3396 	}
3397 }
3398 
3399 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3400 					    struct dc_sink *sink)
3401 {
3402 	struct dc_panel_patch *ppatch = NULL;
3403 
3404 	if (!sink)
3405 		return;
3406 
3407 	ppatch = &sink->edid_caps.panel_patch;
3408 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3409 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3410 		drm_dbg_driver(adev_to_drm(adev),
3411 			       "%s: adding a %ds delay as w/a for panel\n",
3412 			       __func__,
3413 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3414 	}
3415 }
3416 
3417 static int dm_resume(struct amdgpu_ip_block *ip_block)
3418 {
3419 	struct amdgpu_device *adev = ip_block->adev;
3420 	struct drm_device *ddev = adev_to_drm(adev);
3421 	struct amdgpu_display_manager *dm = &adev->dm;
3422 	struct amdgpu_dm_connector *aconnector;
3423 	struct drm_connector *connector;
3424 	struct drm_connector_list_iter iter;
3425 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3426 	enum dc_connection_type new_connection_type = dc_connection_none;
3427 	struct dc_state *dc_state;
3428 	int i, r, j;
3429 	struct dc_commit_streams_params commit_params = {};
3430 
3431 	if (dm->dc->caps.ips_support) {
3432 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3433 	}
3434 
3435 	if (amdgpu_in_reset(adev)) {
3436 		dc_state = dm->cached_dc_state;
3437 
3438 		/*
3439 		 * The dc->current_state is backed up into dm->cached_dc_state
3440 		 * before we commit 0 streams.
3441 		 *
3442 		 * DC will clear link encoder assignments on the real state
3443 		 * but the changes won't propagate over to the copy we made
3444 		 * before the 0 streams commit.
3445 		 *
3446 		 * DC expects that link encoder assignments are *not* valid
3447 		 * when committing a state, so as a workaround we can copy
3448 		 * off of the current state.
3449 		 *
3450 		 * We lose the previous assignments, but we had already
3451 		 * commit 0 streams anyway.
3452 		 */
3453 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3454 
3455 		r = dm_dmub_hw_init(adev);
3456 		if (r) {
3457 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3458 			return r;
3459 		}
3460 
3461 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3462 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3463 
3464 		dc_resume(dm->dc);
3465 
3466 		amdgpu_dm_irq_resume_early(adev);
3467 
3468 		for (i = 0; i < dc_state->stream_count; i++) {
3469 			dc_state->streams[i]->mode_changed = true;
3470 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3471 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3472 					= 0xffffffff;
3473 			}
3474 		}
3475 
3476 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3477 			amdgpu_dm_outbox_init(adev);
3478 			dc_enable_dmub_outbox(adev->dm.dc);
3479 		}
3480 
3481 		commit_params.streams = dc_state->streams;
3482 		commit_params.stream_count = dc_state->stream_count;
3483 		dc_exit_ips_for_hw_access(dm->dc);
3484 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3485 
3486 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3487 
3488 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3489 
3490 		dc_state_release(dm->cached_dc_state);
3491 		dm->cached_dc_state = NULL;
3492 
3493 		amdgpu_dm_irq_resume_late(adev);
3494 
3495 		mutex_unlock(&dm->dc_lock);
3496 
3497 		/* set the backlight after a reset */
3498 		for (i = 0; i < dm->num_of_edps; i++) {
3499 			if (dm->backlight_dev[i])
3500 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3501 		}
3502 
3503 		return 0;
3504 	}
3505 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3506 	dc_state_release(dm_state->context);
3507 	dm_state->context = dc_state_create(dm->dc, NULL);
3508 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3509 
3510 	/* Before powering on DC we need to re-initialize DMUB. */
3511 	dm_dmub_hw_resume(adev);
3512 
3513 	/* Re-enable outbox interrupts for DPIA. */
3514 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3515 		amdgpu_dm_outbox_init(adev);
3516 		dc_enable_dmub_outbox(adev->dm.dc);
3517 	}
3518 
3519 	/* power on hardware */
3520 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3521 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3522 
3523 	/* program HPD filter */
3524 	dc_resume(dm->dc);
3525 
3526 	/*
3527 	 * early enable HPD Rx IRQ, should be done before set mode as short
3528 	 * pulse interrupts are used for MST
3529 	 */
3530 	amdgpu_dm_irq_resume_early(adev);
3531 
3532 	s3_handle_hdmi_cec(ddev, false);
3533 
3534 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3535 	s3_handle_mst(ddev, false);
3536 
3537 	/* Do detection*/
3538 	drm_connector_list_iter_begin(ddev, &iter);
3539 	drm_for_each_connector_iter(connector, &iter) {
3540 		bool ret;
3541 
3542 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3543 			continue;
3544 
3545 		aconnector = to_amdgpu_dm_connector(connector);
3546 
3547 		if (!aconnector->dc_link)
3548 			continue;
3549 
3550 		/*
3551 		 * this is the case when traversing through already created end sink
3552 		 * MST connectors, should be skipped
3553 		 */
3554 		if (aconnector->mst_root)
3555 			continue;
3556 
3557 		guard(mutex)(&aconnector->hpd_lock);
3558 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3559 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3560 
3561 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3562 			emulated_link_detect(aconnector->dc_link);
3563 		} else {
3564 			guard(mutex)(&dm->dc_lock);
3565 			dc_exit_ips_for_hw_access(dm->dc);
3566 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3567 			if (ret) {
3568 				/* w/a delay for certain panels */
3569 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3570 			}
3571 		}
3572 
3573 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3574 			aconnector->fake_enable = false;
3575 
3576 		if (aconnector->dc_sink)
3577 			dc_sink_release(aconnector->dc_sink);
3578 		aconnector->dc_sink = NULL;
3579 		amdgpu_dm_update_connector_after_detect(aconnector);
3580 	}
3581 	drm_connector_list_iter_end(&iter);
3582 
3583 	dm_destroy_cached_state(adev);
3584 
3585 	/* Do mst topology probing after resuming cached state*/
3586 	drm_connector_list_iter_begin(ddev, &iter);
3587 	drm_for_each_connector_iter(connector, &iter) {
3588 
3589 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3590 			continue;
3591 
3592 		aconnector = to_amdgpu_dm_connector(connector);
3593 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3594 		    aconnector->mst_root)
3595 			continue;
3596 
3597 		drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3598 	}
3599 	drm_connector_list_iter_end(&iter);
3600 
3601 	amdgpu_dm_irq_resume_late(adev);
3602 
3603 	amdgpu_dm_smu_write_watermarks_table(adev);
3604 
3605 	drm_kms_helper_hotplug_event(ddev);
3606 
3607 	return 0;
3608 }
3609 
3610 /**
3611  * DOC: DM Lifecycle
3612  *
3613  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3614  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3615  * the base driver's device list to be initialized and torn down accordingly.
3616  *
3617  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3618  */
3619 
3620 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3621 	.name = "dm",
3622 	.early_init = dm_early_init,
3623 	.late_init = dm_late_init,
3624 	.sw_init = dm_sw_init,
3625 	.sw_fini = dm_sw_fini,
3626 	.early_fini = amdgpu_dm_early_fini,
3627 	.hw_init = dm_hw_init,
3628 	.hw_fini = dm_hw_fini,
3629 	.prepare_suspend = dm_prepare_suspend,
3630 	.suspend = dm_suspend,
3631 	.resume = dm_resume,
3632 	.complete = dm_complete,
3633 	.is_idle = dm_is_idle,
3634 	.wait_for_idle = dm_wait_for_idle,
3635 	.check_soft_reset = dm_check_soft_reset,
3636 	.soft_reset = dm_soft_reset,
3637 	.set_clockgating_state = dm_set_clockgating_state,
3638 	.set_powergating_state = dm_set_powergating_state,
3639 };
3640 
3641 const struct amdgpu_ip_block_version dm_ip_block = {
3642 	.type = AMD_IP_BLOCK_TYPE_DCE,
3643 	.major = 1,
3644 	.minor = 0,
3645 	.rev = 0,
3646 	.funcs = &amdgpu_dm_funcs,
3647 };
3648 
3649 
3650 /**
3651  * DOC: atomic
3652  *
3653  * *WIP*
3654  */
3655 
3656 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3657 	.fb_create = amdgpu_display_user_framebuffer_create,
3658 	.get_format_info = amdgpu_dm_plane_get_format_info,
3659 	.atomic_check = amdgpu_dm_atomic_check,
3660 	.atomic_commit = drm_atomic_helper_commit,
3661 };
3662 
3663 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3664 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3665 	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
3666 };
3667 
3668 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3669 {
3670 	struct amdgpu_dm_backlight_caps *caps;
3671 	struct drm_connector *conn_base;
3672 	struct amdgpu_device *adev;
3673 	struct drm_luminance_range_info *luminance_range;
3674 	int min_input_signal_override;
3675 
3676 	if (aconnector->bl_idx == -1 ||
3677 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3678 		return;
3679 
3680 	conn_base = &aconnector->base;
3681 	adev = drm_to_adev(conn_base->dev);
3682 
3683 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3684 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3685 	caps->aux_support = false;
3686 
3687 	if (caps->ext_caps->bits.oled == 1
3688 	    /*
3689 	     * ||
3690 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3691 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3692 	     */)
3693 		caps->aux_support = true;
3694 
3695 	if (amdgpu_backlight == 0)
3696 		caps->aux_support = false;
3697 	else if (amdgpu_backlight == 1)
3698 		caps->aux_support = true;
3699 	if (caps->aux_support)
3700 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3701 
3702 	luminance_range = &conn_base->display_info.luminance_range;
3703 
3704 	if (luminance_range->max_luminance)
3705 		caps->aux_max_input_signal = luminance_range->max_luminance;
3706 	else
3707 		caps->aux_max_input_signal = 512;
3708 
3709 	if (luminance_range->min_luminance)
3710 		caps->aux_min_input_signal = luminance_range->min_luminance;
3711 	else
3712 		caps->aux_min_input_signal = 1;
3713 
3714 	min_input_signal_override = drm_get_panel_min_brightness_quirk(aconnector->drm_edid);
3715 	if (min_input_signal_override >= 0)
3716 		caps->min_input_signal = min_input_signal_override;
3717 }
3718 
3719 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3720 
3721 void amdgpu_dm_update_connector_after_detect(
3722 		struct amdgpu_dm_connector *aconnector)
3723 {
3724 	struct drm_connector *connector = &aconnector->base;
3725 	struct dc_sink *sink __free(sink_release) = NULL;
3726 	struct drm_device *dev = connector->dev;
3727 
3728 	/* MST handled by drm_mst framework */
3729 	if (aconnector->mst_mgr.mst_state == true)
3730 		return;
3731 
3732 	sink = aconnector->dc_link->local_sink;
3733 	if (sink)
3734 		dc_sink_retain(sink);
3735 
3736 	/*
3737 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3738 	 * the connector sink is set to either fake or physical sink depends on link status.
3739 	 * Skip if already done during boot.
3740 	 */
3741 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3742 			&& aconnector->dc_em_sink) {
3743 
3744 		/*
3745 		 * For S3 resume with headless use eml_sink to fake stream
3746 		 * because on resume connector->sink is set to NULL
3747 		 */
3748 		guard(mutex)(&dev->mode_config.mutex);
3749 
3750 		if (sink) {
3751 			if (aconnector->dc_sink) {
3752 				amdgpu_dm_update_freesync_caps(connector, NULL);
3753 				/*
3754 				 * retain and release below are used to
3755 				 * bump up refcount for sink because the link doesn't point
3756 				 * to it anymore after disconnect, so on next crtc to connector
3757 				 * reshuffle by UMD we will get into unwanted dc_sink release
3758 				 */
3759 				dc_sink_release(aconnector->dc_sink);
3760 			}
3761 			aconnector->dc_sink = sink;
3762 			dc_sink_retain(aconnector->dc_sink);
3763 			amdgpu_dm_update_freesync_caps(connector,
3764 					aconnector->drm_edid);
3765 		} else {
3766 			amdgpu_dm_update_freesync_caps(connector, NULL);
3767 			if (!aconnector->dc_sink) {
3768 				aconnector->dc_sink = aconnector->dc_em_sink;
3769 				dc_sink_retain(aconnector->dc_sink);
3770 			}
3771 		}
3772 
3773 		return;
3774 	}
3775 
3776 	/*
3777 	 * TODO: temporary guard to look for proper fix
3778 	 * if this sink is MST sink, we should not do anything
3779 	 */
3780 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
3781 		return;
3782 
3783 	if (aconnector->dc_sink == sink) {
3784 		/*
3785 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3786 		 * Do nothing!!
3787 		 */
3788 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
3789 				 aconnector->connector_id);
3790 		return;
3791 	}
3792 
3793 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3794 		    aconnector->connector_id, aconnector->dc_sink, sink);
3795 
3796 	guard(mutex)(&dev->mode_config.mutex);
3797 
3798 	/*
3799 	 * 1. Update status of the drm connector
3800 	 * 2. Send an event and let userspace tell us what to do
3801 	 */
3802 	if (sink) {
3803 		/*
3804 		 * TODO: check if we still need the S3 mode update workaround.
3805 		 * If yes, put it here.
3806 		 */
3807 		if (aconnector->dc_sink) {
3808 			amdgpu_dm_update_freesync_caps(connector, NULL);
3809 			dc_sink_release(aconnector->dc_sink);
3810 		}
3811 
3812 		aconnector->dc_sink = sink;
3813 		dc_sink_retain(aconnector->dc_sink);
3814 		if (sink->dc_edid.length == 0) {
3815 			aconnector->drm_edid = NULL;
3816 			hdmi_cec_unset_edid(aconnector);
3817 			if (aconnector->dc_link->aux_mode) {
3818 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3819 			}
3820 		} else {
3821 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
3822 
3823 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
3824 			drm_edid_connector_update(connector, aconnector->drm_edid);
3825 
3826 			hdmi_cec_set_edid(aconnector);
3827 			if (aconnector->dc_link->aux_mode)
3828 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
3829 						  connector->display_info.source_physical_address);
3830 		}
3831 
3832 		if (!aconnector->timing_requested) {
3833 			aconnector->timing_requested =
3834 				kzalloc(sizeof(struct dc_crtc_timing), GFP_KERNEL);
3835 			if (!aconnector->timing_requested)
3836 				drm_err(dev,
3837 					"failed to create aconnector->requested_timing\n");
3838 		}
3839 
3840 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid);
3841 		update_connector_ext_caps(aconnector);
3842 	} else {
3843 		hdmi_cec_unset_edid(aconnector);
3844 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3845 		amdgpu_dm_update_freesync_caps(connector, NULL);
3846 		aconnector->num_modes = 0;
3847 		dc_sink_release(aconnector->dc_sink);
3848 		aconnector->dc_sink = NULL;
3849 		drm_edid_free(aconnector->drm_edid);
3850 		aconnector->drm_edid = NULL;
3851 		kfree(aconnector->timing_requested);
3852 		aconnector->timing_requested = NULL;
3853 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3854 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3855 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3856 	}
3857 
3858 	update_subconnector_property(aconnector);
3859 }
3860 
3861 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3862 {
3863 	struct drm_connector *connector = &aconnector->base;
3864 	struct drm_device *dev = connector->dev;
3865 	enum dc_connection_type new_connection_type = dc_connection_none;
3866 	struct amdgpu_device *adev = drm_to_adev(dev);
3867 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3868 	struct dc *dc = aconnector->dc_link->ctx->dc;
3869 	bool ret = false;
3870 
3871 	if (adev->dm.disable_hpd_irq)
3872 		return;
3873 
3874 	/*
3875 	 * In case of failure or MST no need to update connector status or notify the OS
3876 	 * since (for MST case) MST does this in its own context.
3877 	 */
3878 	guard(mutex)(&aconnector->hpd_lock);
3879 
3880 	if (adev->dm.hdcp_workqueue) {
3881 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3882 		dm_con_state->update_hdcp = true;
3883 	}
3884 	if (aconnector->fake_enable)
3885 		aconnector->fake_enable = false;
3886 
3887 	aconnector->timing_changed = false;
3888 
3889 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3890 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3891 
3892 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
3893 		emulated_link_detect(aconnector->dc_link);
3894 
3895 		drm_modeset_lock_all(dev);
3896 		dm_restore_drm_connector_state(dev, connector);
3897 		drm_modeset_unlock_all(dev);
3898 
3899 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3900 			drm_kms_helper_connector_hotplug_event(connector);
3901 	} else {
3902 		scoped_guard(mutex, &adev->dm.dc_lock) {
3903 			dc_exit_ips_for_hw_access(dc);
3904 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3905 		}
3906 		if (ret) {
3907 			/* w/a delay for certain panels */
3908 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3909 			amdgpu_dm_update_connector_after_detect(aconnector);
3910 
3911 			drm_modeset_lock_all(dev);
3912 			dm_restore_drm_connector_state(dev, connector);
3913 			drm_modeset_unlock_all(dev);
3914 
3915 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3916 				drm_kms_helper_connector_hotplug_event(connector);
3917 		}
3918 	}
3919 }
3920 
3921 static void handle_hpd_irq(void *param)
3922 {
3923 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3924 
3925 	handle_hpd_irq_helper(aconnector);
3926 
3927 }
3928 
3929 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
3930 							union hpd_irq_data hpd_irq_data)
3931 {
3932 	struct hpd_rx_irq_offload_work *offload_work =
3933 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
3934 
3935 	if (!offload_work) {
3936 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
3937 		return;
3938 	}
3939 
3940 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3941 	offload_work->data = hpd_irq_data;
3942 	offload_work->offload_wq = offload_wq;
3943 	offload_work->adev = adev;
3944 
3945 	queue_work(offload_wq->wq, &offload_work->work);
3946 	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3947 }
3948 
3949 static void handle_hpd_rx_irq(void *param)
3950 {
3951 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3952 	struct drm_connector *connector = &aconnector->base;
3953 	struct drm_device *dev = connector->dev;
3954 	struct dc_link *dc_link = aconnector->dc_link;
3955 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3956 	bool result = false;
3957 	enum dc_connection_type new_connection_type = dc_connection_none;
3958 	struct amdgpu_device *adev = drm_to_adev(dev);
3959 	union hpd_irq_data hpd_irq_data;
3960 	bool link_loss = false;
3961 	bool has_left_work = false;
3962 	int idx = dc_link->link_index;
3963 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3964 	struct dc *dc = aconnector->dc_link->ctx->dc;
3965 
3966 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3967 
3968 	if (adev->dm.disable_hpd_irq)
3969 		return;
3970 
3971 	/*
3972 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3973 	 * conflict, after implement i2c helper, this mutex should be
3974 	 * retired.
3975 	 */
3976 	mutex_lock(&aconnector->hpd_lock);
3977 
3978 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3979 						&link_loss, true, &has_left_work);
3980 
3981 	if (!has_left_work)
3982 		goto out;
3983 
3984 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3985 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
3986 		goto out;
3987 	}
3988 
3989 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3990 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3991 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3992 			bool skip = false;
3993 
3994 			/*
3995 			 * DOWN_REP_MSG_RDY is also handled by polling method
3996 			 * mgr->cbs->poll_hpd_irq()
3997 			 */
3998 			spin_lock(&offload_wq->offload_lock);
3999 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4000 
4001 			if (!skip)
4002 				offload_wq->is_handling_mst_msg_rdy_event = true;
4003 
4004 			spin_unlock(&offload_wq->offload_lock);
4005 
4006 			if (!skip)
4007 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4008 
4009 			goto out;
4010 		}
4011 
4012 		if (link_loss) {
4013 			bool skip = false;
4014 
4015 			spin_lock(&offload_wq->offload_lock);
4016 			skip = offload_wq->is_handling_link_loss;
4017 
4018 			if (!skip)
4019 				offload_wq->is_handling_link_loss = true;
4020 
4021 			spin_unlock(&offload_wq->offload_lock);
4022 
4023 			if (!skip)
4024 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4025 
4026 			goto out;
4027 		}
4028 	}
4029 
4030 out:
4031 	if (result && !is_mst_root_connector) {
4032 		/* Downstream Port status changed. */
4033 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4034 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4035 
4036 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4037 			emulated_link_detect(dc_link);
4038 
4039 			if (aconnector->fake_enable)
4040 				aconnector->fake_enable = false;
4041 
4042 			amdgpu_dm_update_connector_after_detect(aconnector);
4043 
4044 
4045 			drm_modeset_lock_all(dev);
4046 			dm_restore_drm_connector_state(dev, connector);
4047 			drm_modeset_unlock_all(dev);
4048 
4049 			drm_kms_helper_connector_hotplug_event(connector);
4050 		} else {
4051 			bool ret = false;
4052 
4053 			mutex_lock(&adev->dm.dc_lock);
4054 			dc_exit_ips_for_hw_access(dc);
4055 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4056 			mutex_unlock(&adev->dm.dc_lock);
4057 
4058 			if (ret) {
4059 				if (aconnector->fake_enable)
4060 					aconnector->fake_enable = false;
4061 
4062 				amdgpu_dm_update_connector_after_detect(aconnector);
4063 
4064 				drm_modeset_lock_all(dev);
4065 				dm_restore_drm_connector_state(dev, connector);
4066 				drm_modeset_unlock_all(dev);
4067 
4068 				drm_kms_helper_connector_hotplug_event(connector);
4069 			}
4070 		}
4071 	}
4072 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4073 		if (adev->dm.hdcp_workqueue)
4074 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4075 	}
4076 
4077 	if (dc_link->type != dc_connection_mst_branch)
4078 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4079 
4080 	mutex_unlock(&aconnector->hpd_lock);
4081 }
4082 
4083 static int register_hpd_handlers(struct amdgpu_device *adev)
4084 {
4085 	struct drm_device *dev = adev_to_drm(adev);
4086 	struct drm_connector *connector;
4087 	struct amdgpu_dm_connector *aconnector;
4088 	const struct dc_link *dc_link;
4089 	struct dc_interrupt_params int_params = {0};
4090 
4091 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4092 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4093 
4094 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4095 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4096 			dmub_hpd_callback, true)) {
4097 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4098 			return -EINVAL;
4099 		}
4100 
4101 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4102 			dmub_hpd_callback, true)) {
4103 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4104 			return -EINVAL;
4105 		}
4106 
4107 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4108 			dmub_hpd_sense_callback, true)) {
4109 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4110 			return -EINVAL;
4111 		}
4112 	}
4113 
4114 	list_for_each_entry(connector,
4115 			&dev->mode_config.connector_list, head)	{
4116 
4117 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4118 			continue;
4119 
4120 		aconnector = to_amdgpu_dm_connector(connector);
4121 		dc_link = aconnector->dc_link;
4122 
4123 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4124 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4125 			int_params.irq_source = dc_link->irq_source_hpd;
4126 
4127 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4128 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4129 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4130 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4131 				return -EINVAL;
4132 			}
4133 
4134 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4135 				handle_hpd_irq, (void *) aconnector))
4136 				return -ENOMEM;
4137 		}
4138 
4139 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4140 
4141 			/* Also register for DP short pulse (hpd_rx). */
4142 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4143 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4144 
4145 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4146 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4147 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4148 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4149 				return -EINVAL;
4150 			}
4151 
4152 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4153 				handle_hpd_rx_irq, (void *) aconnector))
4154 				return -ENOMEM;
4155 		}
4156 	}
4157 	return 0;
4158 }
4159 
4160 #if defined(CONFIG_DRM_AMD_DC_SI)
4161 /* Register IRQ sources and initialize IRQ callbacks */
4162 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
4163 {
4164 	struct dc *dc = adev->dm.dc;
4165 	struct common_irq_params *c_irq_params;
4166 	struct dc_interrupt_params int_params = {0};
4167 	int r;
4168 	int i;
4169 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4170 
4171 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4172 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4173 
4174 	/*
4175 	 * Actions of amdgpu_irq_add_id():
4176 	 * 1. Register a set() function with base driver.
4177 	 *    Base driver will call set() function to enable/disable an
4178 	 *    interrupt in DC hardware.
4179 	 * 2. Register amdgpu_dm_irq_handler().
4180 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4181 	 *    coming from DC hardware.
4182 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4183 	 *    for acknowledging and handling.
4184 	 */
4185 
4186 	/* Use VBLANK interrupt */
4187 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4188 		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
4189 		if (r) {
4190 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4191 			return r;
4192 		}
4193 
4194 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4195 		int_params.irq_source =
4196 			dc_interrupt_to_irq_source(dc, i + 1, 0);
4197 
4198 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4199 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4200 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4201 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4202 			return -EINVAL;
4203 		}
4204 
4205 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4206 
4207 		c_irq_params->adev = adev;
4208 		c_irq_params->irq_src = int_params.irq_source;
4209 
4210 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4211 			dm_crtc_high_irq, c_irq_params))
4212 			return -ENOMEM;
4213 	}
4214 
4215 	/* Use GRPH_PFLIP interrupt */
4216 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4217 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4218 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4219 		if (r) {
4220 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4221 			return r;
4222 		}
4223 
4224 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4225 		int_params.irq_source =
4226 			dc_interrupt_to_irq_source(dc, i, 0);
4227 
4228 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4229 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4230 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4231 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4232 			return -EINVAL;
4233 		}
4234 
4235 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4236 
4237 		c_irq_params->adev = adev;
4238 		c_irq_params->irq_src = int_params.irq_source;
4239 
4240 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4241 			dm_pflip_high_irq, c_irq_params))
4242 			return -ENOMEM;
4243 	}
4244 
4245 	/* HPD */
4246 	r = amdgpu_irq_add_id(adev, client_id,
4247 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4248 	if (r) {
4249 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4250 		return r;
4251 	}
4252 
4253 	r = register_hpd_handlers(adev);
4254 
4255 	return r;
4256 }
4257 #endif
4258 
4259 /* Register IRQ sources and initialize IRQ callbacks */
4260 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4261 {
4262 	struct dc *dc = adev->dm.dc;
4263 	struct common_irq_params *c_irq_params;
4264 	struct dc_interrupt_params int_params = {0};
4265 	int r;
4266 	int i;
4267 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4268 
4269 	if (adev->family >= AMDGPU_FAMILY_AI)
4270 		client_id = SOC15_IH_CLIENTID_DCE;
4271 
4272 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4273 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4274 
4275 	/*
4276 	 * Actions of amdgpu_irq_add_id():
4277 	 * 1. Register a set() function with base driver.
4278 	 *    Base driver will call set() function to enable/disable an
4279 	 *    interrupt in DC hardware.
4280 	 * 2. Register amdgpu_dm_irq_handler().
4281 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4282 	 *    coming from DC hardware.
4283 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4284 	 *    for acknowledging and handling.
4285 	 */
4286 
4287 	/* Use VBLANK interrupt */
4288 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
4289 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
4290 		if (r) {
4291 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4292 			return r;
4293 		}
4294 
4295 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4296 		int_params.irq_source =
4297 			dc_interrupt_to_irq_source(dc, i, 0);
4298 
4299 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4300 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4301 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4302 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4303 			return -EINVAL;
4304 		}
4305 
4306 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4307 
4308 		c_irq_params->adev = adev;
4309 		c_irq_params->irq_src = int_params.irq_source;
4310 
4311 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4312 			dm_crtc_high_irq, c_irq_params))
4313 			return -ENOMEM;
4314 	}
4315 
4316 	/* Use VUPDATE interrupt */
4317 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
4318 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
4319 		if (r) {
4320 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4321 			return r;
4322 		}
4323 
4324 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4325 		int_params.irq_source =
4326 			dc_interrupt_to_irq_source(dc, i, 0);
4327 
4328 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4329 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4330 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4331 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4332 			return -EINVAL;
4333 		}
4334 
4335 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4336 
4337 		c_irq_params->adev = adev;
4338 		c_irq_params->irq_src = int_params.irq_source;
4339 
4340 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4341 			dm_vupdate_high_irq, c_irq_params))
4342 			return -ENOMEM;
4343 	}
4344 
4345 	/* Use GRPH_PFLIP interrupt */
4346 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4347 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4348 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4349 		if (r) {
4350 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4351 			return r;
4352 		}
4353 
4354 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4355 		int_params.irq_source =
4356 			dc_interrupt_to_irq_source(dc, i, 0);
4357 
4358 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4359 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4360 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4361 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4362 			return -EINVAL;
4363 		}
4364 
4365 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4366 
4367 		c_irq_params->adev = adev;
4368 		c_irq_params->irq_src = int_params.irq_source;
4369 
4370 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4371 			dm_pflip_high_irq, c_irq_params))
4372 			return -ENOMEM;
4373 	}
4374 
4375 	/* HPD */
4376 	r = amdgpu_irq_add_id(adev, client_id,
4377 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4378 	if (r) {
4379 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4380 		return r;
4381 	}
4382 
4383 	r = register_hpd_handlers(adev);
4384 
4385 	return r;
4386 }
4387 
4388 /* Register IRQ sources and initialize IRQ callbacks */
4389 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4390 {
4391 	struct dc *dc = adev->dm.dc;
4392 	struct common_irq_params *c_irq_params;
4393 	struct dc_interrupt_params int_params = {0};
4394 	int r;
4395 	int i;
4396 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4397 	static const unsigned int vrtl_int_srcid[] = {
4398 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4399 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4400 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4401 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4402 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4403 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4404 	};
4405 #endif
4406 
4407 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4408 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4409 
4410 	/*
4411 	 * Actions of amdgpu_irq_add_id():
4412 	 * 1. Register a set() function with base driver.
4413 	 *    Base driver will call set() function to enable/disable an
4414 	 *    interrupt in DC hardware.
4415 	 * 2. Register amdgpu_dm_irq_handler().
4416 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4417 	 *    coming from DC hardware.
4418 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4419 	 *    for acknowledging and handling.
4420 	 */
4421 
4422 	/* Use VSTARTUP interrupt */
4423 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4424 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4425 			i++) {
4426 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4427 
4428 		if (r) {
4429 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4430 			return r;
4431 		}
4432 
4433 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4434 		int_params.irq_source =
4435 			dc_interrupt_to_irq_source(dc, i, 0);
4436 
4437 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4438 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4439 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4440 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4441 			return -EINVAL;
4442 		}
4443 
4444 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4445 
4446 		c_irq_params->adev = adev;
4447 		c_irq_params->irq_src = int_params.irq_source;
4448 
4449 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4450 			dm_crtc_high_irq, c_irq_params))
4451 			return -ENOMEM;
4452 	}
4453 
4454 	/* Use otg vertical line interrupt */
4455 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4456 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4457 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4458 				vrtl_int_srcid[i], &adev->vline0_irq);
4459 
4460 		if (r) {
4461 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4462 			return r;
4463 		}
4464 
4465 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4466 		int_params.irq_source =
4467 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4468 
4469 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4470 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4471 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4472 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4473 			return -EINVAL;
4474 		}
4475 
4476 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4477 					- DC_IRQ_SOURCE_DC1_VLINE0];
4478 
4479 		c_irq_params->adev = adev;
4480 		c_irq_params->irq_src = int_params.irq_source;
4481 
4482 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4483 			dm_dcn_vertical_interrupt0_high_irq,
4484 			c_irq_params))
4485 			return -ENOMEM;
4486 	}
4487 #endif
4488 
4489 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4490 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4491 	 * to trigger at end of each vblank, regardless of state of the lock,
4492 	 * matching DCE behaviour.
4493 	 */
4494 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4495 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4496 	     i++) {
4497 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4498 
4499 		if (r) {
4500 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4501 			return r;
4502 		}
4503 
4504 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4505 		int_params.irq_source =
4506 			dc_interrupt_to_irq_source(dc, i, 0);
4507 
4508 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4509 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4510 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4511 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4512 			return -EINVAL;
4513 		}
4514 
4515 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4516 
4517 		c_irq_params->adev = adev;
4518 		c_irq_params->irq_src = int_params.irq_source;
4519 
4520 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4521 			dm_vupdate_high_irq, c_irq_params))
4522 			return -ENOMEM;
4523 	}
4524 
4525 	/* Use GRPH_PFLIP interrupt */
4526 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4527 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4528 			i++) {
4529 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4530 		if (r) {
4531 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4532 			return r;
4533 		}
4534 
4535 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4536 		int_params.irq_source =
4537 			dc_interrupt_to_irq_source(dc, i, 0);
4538 
4539 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4540 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4541 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4542 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4543 			return -EINVAL;
4544 		}
4545 
4546 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4547 
4548 		c_irq_params->adev = adev;
4549 		c_irq_params->irq_src = int_params.irq_source;
4550 
4551 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4552 			dm_pflip_high_irq, c_irq_params))
4553 			return -ENOMEM;
4554 	}
4555 
4556 	/* HPD */
4557 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4558 			&adev->hpd_irq);
4559 	if (r) {
4560 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4561 		return r;
4562 	}
4563 
4564 	r = register_hpd_handlers(adev);
4565 
4566 	return r;
4567 }
4568 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4569 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4570 {
4571 	struct dc *dc = adev->dm.dc;
4572 	struct common_irq_params *c_irq_params;
4573 	struct dc_interrupt_params int_params = {0};
4574 	int r, i;
4575 
4576 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4577 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4578 
4579 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4580 			&adev->dmub_outbox_irq);
4581 	if (r) {
4582 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4583 		return r;
4584 	}
4585 
4586 	if (dc->ctx->dmub_srv) {
4587 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4588 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4589 		int_params.irq_source =
4590 		dc_interrupt_to_irq_source(dc, i, 0);
4591 
4592 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4593 
4594 		c_irq_params->adev = adev;
4595 		c_irq_params->irq_src = int_params.irq_source;
4596 
4597 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4598 			dm_dmub_outbox1_low_irq, c_irq_params))
4599 			return -ENOMEM;
4600 	}
4601 
4602 	return 0;
4603 }
4604 
4605 /*
4606  * Acquires the lock for the atomic state object and returns
4607  * the new atomic state.
4608  *
4609  * This should only be called during atomic check.
4610  */
4611 int dm_atomic_get_state(struct drm_atomic_state *state,
4612 			struct dm_atomic_state **dm_state)
4613 {
4614 	struct drm_device *dev = state->dev;
4615 	struct amdgpu_device *adev = drm_to_adev(dev);
4616 	struct amdgpu_display_manager *dm = &adev->dm;
4617 	struct drm_private_state *priv_state;
4618 
4619 	if (*dm_state)
4620 		return 0;
4621 
4622 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4623 	if (IS_ERR(priv_state))
4624 		return PTR_ERR(priv_state);
4625 
4626 	*dm_state = to_dm_atomic_state(priv_state);
4627 
4628 	return 0;
4629 }
4630 
4631 static struct dm_atomic_state *
4632 dm_atomic_get_new_state(struct drm_atomic_state *state)
4633 {
4634 	struct drm_device *dev = state->dev;
4635 	struct amdgpu_device *adev = drm_to_adev(dev);
4636 	struct amdgpu_display_manager *dm = &adev->dm;
4637 	struct drm_private_obj *obj;
4638 	struct drm_private_state *new_obj_state;
4639 	int i;
4640 
4641 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4642 		if (obj->funcs == dm->atomic_obj.funcs)
4643 			return to_dm_atomic_state(new_obj_state);
4644 	}
4645 
4646 	return NULL;
4647 }
4648 
4649 static struct drm_private_state *
4650 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4651 {
4652 	struct dm_atomic_state *old_state, *new_state;
4653 
4654 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
4655 	if (!new_state)
4656 		return NULL;
4657 
4658 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4659 
4660 	old_state = to_dm_atomic_state(obj->state);
4661 
4662 	if (old_state && old_state->context)
4663 		new_state->context = dc_state_create_copy(old_state->context);
4664 
4665 	if (!new_state->context) {
4666 		kfree(new_state);
4667 		return NULL;
4668 	}
4669 
4670 	return &new_state->base;
4671 }
4672 
4673 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4674 				    struct drm_private_state *state)
4675 {
4676 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4677 
4678 	if (dm_state && dm_state->context)
4679 		dc_state_release(dm_state->context);
4680 
4681 	kfree(dm_state);
4682 }
4683 
4684 static struct drm_private_state_funcs dm_atomic_state_funcs = {
4685 	.atomic_duplicate_state = dm_atomic_duplicate_state,
4686 	.atomic_destroy_state = dm_atomic_destroy_state,
4687 };
4688 
4689 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
4690 {
4691 	struct dm_atomic_state *state;
4692 	int r;
4693 
4694 	adev->mode_info.mode_config_initialized = true;
4695 
4696 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4697 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4698 
4699 	adev_to_drm(adev)->mode_config.max_width = 16384;
4700 	adev_to_drm(adev)->mode_config.max_height = 16384;
4701 
4702 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4703 	if (adev->asic_type == CHIP_HAWAII)
4704 		/* disable prefer shadow for now due to hibernation issues */
4705 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4706 	else
4707 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4708 	/* indicates support for immediate flip */
4709 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4710 
4711 	state = kzalloc(sizeof(*state), GFP_KERNEL);
4712 	if (!state)
4713 		return -ENOMEM;
4714 
4715 	state->context = dc_state_create_current_copy(adev->dm.dc);
4716 	if (!state->context) {
4717 		kfree(state);
4718 		return -ENOMEM;
4719 	}
4720 
4721 	drm_atomic_private_obj_init(adev_to_drm(adev),
4722 				    &adev->dm.atomic_obj,
4723 				    &state->base,
4724 				    &dm_atomic_state_funcs);
4725 
4726 	r = amdgpu_display_modeset_create_props(adev);
4727 	if (r) {
4728 		dc_state_release(state->context);
4729 		kfree(state);
4730 		return r;
4731 	}
4732 
4733 #ifdef AMD_PRIVATE_COLOR
4734 	if (amdgpu_dm_create_color_properties(adev)) {
4735 		dc_state_release(state->context);
4736 		kfree(state);
4737 		return -ENOMEM;
4738 	}
4739 #endif
4740 
4741 	r = amdgpu_dm_audio_init(adev);
4742 	if (r) {
4743 		dc_state_release(state->context);
4744 		kfree(state);
4745 		return r;
4746 	}
4747 
4748 	return 0;
4749 }
4750 
4751 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4752 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4753 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
4754 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4755 
4756 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4757 					    int bl_idx)
4758 {
4759 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
4760 
4761 	if (caps->caps_valid)
4762 		return;
4763 
4764 #if defined(CONFIG_ACPI)
4765 	amdgpu_acpi_get_backlight_caps(caps);
4766 
4767 	/* validate the firmware value is sane */
4768 	if (caps->caps_valid) {
4769 		int spread = caps->max_input_signal - caps->min_input_signal;
4770 
4771 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4772 		    caps->min_input_signal < 0 ||
4773 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4774 		    spread < AMDGPU_DM_MIN_SPREAD) {
4775 			DRM_DEBUG_KMS("DM: Invalid backlight caps: min=%d, max=%d\n",
4776 				      caps->min_input_signal, caps->max_input_signal);
4777 			caps->caps_valid = false;
4778 		}
4779 	}
4780 
4781 	if (!caps->caps_valid) {
4782 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4783 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4784 		caps->caps_valid = true;
4785 	}
4786 #else
4787 	if (caps->aux_support)
4788 		return;
4789 
4790 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
4791 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
4792 	caps->caps_valid = true;
4793 #endif
4794 }
4795 
4796 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
4797 				unsigned int *min, unsigned int *max)
4798 {
4799 	if (!caps)
4800 		return 0;
4801 
4802 	if (caps->aux_support) {
4803 		// Firmware limits are in nits, DC API wants millinits.
4804 		*max = 1000 * caps->aux_max_input_signal;
4805 		*min = 1000 * caps->aux_min_input_signal;
4806 	} else {
4807 		// Firmware limits are 8-bit, PWM control is 16-bit.
4808 		*max = 0x101 * caps->max_input_signal;
4809 		*min = 0x101 * caps->min_input_signal;
4810 	}
4811 	return 1;
4812 }
4813 
4814 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
4815 static inline u32 scale_input_to_fw(int min, int max, u64 input)
4816 {
4817 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
4818 }
4819 
4820 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
4821 static inline u32 scale_fw_to_input(int min, int max, u64 input)
4822 {
4823 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
4824 }
4825 
4826 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
4827 				      unsigned int min, unsigned int max,
4828 				      uint32_t *user_brightness)
4829 {
4830 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
4831 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
4832 	int left, right;
4833 
4834 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
4835 		return;
4836 
4837 	if (!caps->data_points)
4838 		return;
4839 
4840 	left = 0;
4841 	right = caps->data_points - 1;
4842 	while (left <= right) {
4843 		int mid = left + (right - left) / 2;
4844 		u8 signal = caps->luminance_data[mid].input_signal;
4845 
4846 		/* Exact match found */
4847 		if (signal == brightness) {
4848 			lum = caps->luminance_data[mid].luminance;
4849 			goto scale;
4850 		}
4851 
4852 		if (signal < brightness)
4853 			left = mid + 1;
4854 		else
4855 			right = mid - 1;
4856 	}
4857 
4858 	/* verify bound */
4859 	if (left >= caps->data_points)
4860 		left = caps->data_points - 1;
4861 
4862 	/* At this point, left > right */
4863 	lower_signal = caps->luminance_data[right].input_signal;
4864 	upper_signal = caps->luminance_data[left].input_signal;
4865 	lower_lum = caps->luminance_data[right].luminance;
4866 	upper_lum = caps->luminance_data[left].luminance;
4867 
4868 	/* interpolate */
4869 	if (right == left || !lower_lum)
4870 		lum = upper_lum;
4871 	else
4872 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
4873 						    (brightness - lower_signal),
4874 						    upper_signal - lower_signal);
4875 scale:
4876 	*user_brightness = scale_fw_to_input(min, max,
4877 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
4878 }
4879 
4880 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
4881 					uint32_t brightness)
4882 {
4883 	unsigned int min, max;
4884 
4885 	if (!get_brightness_range(caps, &min, &max))
4886 		return brightness;
4887 
4888 	convert_custom_brightness(caps, min, max, &brightness);
4889 
4890 	// Rescale 0..max to min..max
4891 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
4892 }
4893 
4894 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
4895 				      uint32_t brightness)
4896 {
4897 	unsigned int min, max;
4898 
4899 	if (!get_brightness_range(caps, &min, &max))
4900 		return brightness;
4901 
4902 	if (brightness < min)
4903 		return 0;
4904 	// Rescale min..max to 0..max
4905 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
4906 				 max - min);
4907 }
4908 
4909 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
4910 					 int bl_idx,
4911 					 u32 user_brightness)
4912 {
4913 	struct amdgpu_dm_backlight_caps *caps;
4914 	struct dc_link *link;
4915 	u32 brightness;
4916 	bool rc, reallow_idle = false;
4917 
4918 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4919 	caps = &dm->backlight_caps[bl_idx];
4920 
4921 	dm->brightness[bl_idx] = user_brightness;
4922 	/* update scratch register */
4923 	if (bl_idx == 0)
4924 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
4925 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
4926 	link = (struct dc_link *)dm->backlight_link[bl_idx];
4927 
4928 	/* Change brightness based on AUX property */
4929 	mutex_lock(&dm->dc_lock);
4930 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
4931 		dc_allow_idle_optimizations(dm->dc, false);
4932 		reallow_idle = true;
4933 	}
4934 
4935 	if (trace_amdgpu_dm_brightness_enabled()) {
4936 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
4937 					   user_brightness,
4938 					   brightness,
4939 					   caps->aux_support,
4940 					   power_supply_is_system_supplied() > 0);
4941 	}
4942 
4943 	if (caps->aux_support) {
4944 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
4945 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
4946 		if (!rc)
4947 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
4948 	} else {
4949 		struct set_backlight_level_params backlight_level_params = { 0 };
4950 
4951 		backlight_level_params.backlight_pwm_u16_16 = brightness;
4952 		backlight_level_params.transition_time_in_ms = 0;
4953 
4954 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
4955 		if (!rc)
4956 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
4957 	}
4958 
4959 	if (dm->dc->caps.ips_support && reallow_idle)
4960 		dc_allow_idle_optimizations(dm->dc, true);
4961 
4962 	mutex_unlock(&dm->dc_lock);
4963 
4964 	if (rc)
4965 		dm->actual_brightness[bl_idx] = user_brightness;
4966 }
4967 
4968 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
4969 {
4970 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4971 	int i;
4972 
4973 	for (i = 0; i < dm->num_of_edps; i++) {
4974 		if (bd == dm->backlight_dev[i])
4975 			break;
4976 	}
4977 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4978 		i = 0;
4979 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
4980 
4981 	return 0;
4982 }
4983 
4984 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
4985 					 int bl_idx)
4986 {
4987 	int ret;
4988 	struct amdgpu_dm_backlight_caps caps;
4989 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
4990 
4991 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4992 	caps = dm->backlight_caps[bl_idx];
4993 
4994 	if (caps.aux_support) {
4995 		u32 avg, peak;
4996 
4997 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
4998 			return dm->brightness[bl_idx];
4999 		return convert_brightness_to_user(&caps, avg);
5000 	}
5001 
5002 	ret = dc_link_get_backlight_level(link);
5003 
5004 	if (ret == DC_ERROR_UNEXPECTED)
5005 		return dm->brightness[bl_idx];
5006 
5007 	return convert_brightness_to_user(&caps, ret);
5008 }
5009 
5010 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5011 {
5012 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5013 	int i;
5014 
5015 	for (i = 0; i < dm->num_of_edps; i++) {
5016 		if (bd == dm->backlight_dev[i])
5017 			break;
5018 	}
5019 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5020 		i = 0;
5021 	return amdgpu_dm_backlight_get_level(dm, i);
5022 }
5023 
5024 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5025 	.options = BL_CORE_SUSPENDRESUME,
5026 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5027 	.update_status	= amdgpu_dm_backlight_update_status,
5028 };
5029 
5030 static void
5031 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5032 {
5033 	struct drm_device *drm = aconnector->base.dev;
5034 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5035 	struct backlight_properties props = { 0 };
5036 	struct amdgpu_dm_backlight_caps *caps;
5037 	char bl_name[16];
5038 	int min, max;
5039 
5040 	if (aconnector->bl_idx == -1)
5041 		return;
5042 
5043 	if (!acpi_video_backlight_use_native()) {
5044 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5045 		/* Try registering an ACPI video backlight device instead. */
5046 		acpi_video_register_backlight();
5047 		return;
5048 	}
5049 
5050 	caps = &dm->backlight_caps[aconnector->bl_idx];
5051 	if (get_brightness_range(caps, &min, &max)) {
5052 		if (power_supply_is_system_supplied() > 0)
5053 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5054 		else
5055 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5056 		/* min is zero, so max needs to be adjusted */
5057 		props.max_brightness = max - min;
5058 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5059 			caps->ac_level, caps->dc_level);
5060 	} else
5061 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5062 
5063 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE))
5064 		drm_info(drm, "Using custom brightness curve\n");
5065 	props.type = BACKLIGHT_RAW;
5066 
5067 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5068 		 drm->primary->index + aconnector->bl_idx);
5069 
5070 	dm->backlight_dev[aconnector->bl_idx] =
5071 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5072 					  &amdgpu_dm_backlight_ops, &props);
5073 	dm->brightness[aconnector->bl_idx] = props.brightness;
5074 
5075 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5076 		drm_err(drm, "DM: Backlight registration failed!\n");
5077 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5078 	} else
5079 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5080 }
5081 
5082 static int initialize_plane(struct amdgpu_display_manager *dm,
5083 			    struct amdgpu_mode_info *mode_info, int plane_id,
5084 			    enum drm_plane_type plane_type,
5085 			    const struct dc_plane_cap *plane_cap)
5086 {
5087 	struct drm_plane *plane;
5088 	unsigned long possible_crtcs;
5089 	int ret = 0;
5090 
5091 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
5092 	if (!plane) {
5093 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5094 		return -ENOMEM;
5095 	}
5096 	plane->type = plane_type;
5097 
5098 	/*
5099 	 * HACK: IGT tests expect that the primary plane for a CRTC
5100 	 * can only have one possible CRTC. Only expose support for
5101 	 * any CRTC if they're not going to be used as a primary plane
5102 	 * for a CRTC - like overlay or underlay planes.
5103 	 */
5104 	possible_crtcs = 1 << plane_id;
5105 	if (plane_id >= dm->dc->caps.max_streams)
5106 		possible_crtcs = 0xff;
5107 
5108 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5109 
5110 	if (ret) {
5111 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5112 		kfree(plane);
5113 		return ret;
5114 	}
5115 
5116 	if (mode_info)
5117 		mode_info->planes[plane_id] = plane;
5118 
5119 	return ret;
5120 }
5121 
5122 
5123 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5124 				   struct amdgpu_dm_connector *aconnector)
5125 {
5126 	struct dc_link *link = aconnector->dc_link;
5127 	int bl_idx = dm->num_of_edps;
5128 
5129 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5130 	    link->type == dc_connection_none)
5131 		return;
5132 
5133 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5134 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5135 		return;
5136 	}
5137 
5138 	aconnector->bl_idx = bl_idx;
5139 
5140 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5141 	dm->backlight_link[bl_idx] = link;
5142 	dm->num_of_edps++;
5143 
5144 	update_connector_ext_caps(aconnector);
5145 }
5146 
5147 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5148 
5149 /*
5150  * In this architecture, the association
5151  * connector -> encoder -> crtc
5152  * id not really requried. The crtc and connector will hold the
5153  * display_index as an abstraction to use with DAL component
5154  *
5155  * Returns 0 on success
5156  */
5157 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5158 {
5159 	struct amdgpu_display_manager *dm = &adev->dm;
5160 	s32 i;
5161 	struct amdgpu_dm_connector *aconnector = NULL;
5162 	struct amdgpu_encoder *aencoder = NULL;
5163 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5164 	u32 link_cnt;
5165 	s32 primary_planes;
5166 	enum dc_connection_type new_connection_type = dc_connection_none;
5167 	const struct dc_plane_cap *plane;
5168 	bool psr_feature_enabled = false;
5169 	bool replay_feature_enabled = false;
5170 	int max_overlay = dm->dc->caps.max_slave_planes;
5171 
5172 	dm->display_indexes_num = dm->dc->caps.max_streams;
5173 	/* Update the actual used number of crtc */
5174 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5175 
5176 	amdgpu_dm_set_irq_funcs(adev);
5177 
5178 	link_cnt = dm->dc->caps.max_links;
5179 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5180 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5181 		return -EINVAL;
5182 	}
5183 
5184 	/* There is one primary plane per CRTC */
5185 	primary_planes = dm->dc->caps.max_streams;
5186 	if (primary_planes > AMDGPU_MAX_PLANES) {
5187 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5188 		return -EINVAL;
5189 	}
5190 
5191 	/*
5192 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5193 	 * Order is reversed to match iteration order in atomic check.
5194 	 */
5195 	for (i = (primary_planes - 1); i >= 0; i--) {
5196 		plane = &dm->dc->caps.planes[i];
5197 
5198 		if (initialize_plane(dm, mode_info, i,
5199 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5200 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5201 			goto fail;
5202 		}
5203 	}
5204 
5205 	/*
5206 	 * Initialize overlay planes, index starting after primary planes.
5207 	 * These planes have a higher DRM index than the primary planes since
5208 	 * they should be considered as having a higher z-order.
5209 	 * Order is reversed to match iteration order in atomic check.
5210 	 *
5211 	 * Only support DCN for now, and only expose one so we don't encourage
5212 	 * userspace to use up all the pipes.
5213 	 */
5214 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5215 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5216 
5217 		/* Do not create overlay if MPO disabled */
5218 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5219 			break;
5220 
5221 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5222 			continue;
5223 
5224 		if (!plane->pixel_format_support.argb8888)
5225 			continue;
5226 
5227 		if (max_overlay-- == 0)
5228 			break;
5229 
5230 		if (initialize_plane(dm, NULL, primary_planes + i,
5231 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5232 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5233 			goto fail;
5234 		}
5235 	}
5236 
5237 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5238 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5239 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5240 			goto fail;
5241 		}
5242 
5243 	/* Use Outbox interrupt */
5244 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5245 	case IP_VERSION(3, 0, 0):
5246 	case IP_VERSION(3, 1, 2):
5247 	case IP_VERSION(3, 1, 3):
5248 	case IP_VERSION(3, 1, 4):
5249 	case IP_VERSION(3, 1, 5):
5250 	case IP_VERSION(3, 1, 6):
5251 	case IP_VERSION(3, 2, 0):
5252 	case IP_VERSION(3, 2, 1):
5253 	case IP_VERSION(2, 1, 0):
5254 	case IP_VERSION(3, 5, 0):
5255 	case IP_VERSION(3, 5, 1):
5256 	case IP_VERSION(3, 6, 0):
5257 	case IP_VERSION(4, 0, 1):
5258 		if (register_outbox_irq_handlers(dm->adev)) {
5259 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5260 			goto fail;
5261 		}
5262 		break;
5263 	default:
5264 		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
5265 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5266 	}
5267 
5268 	/* Determine whether to enable PSR support by default. */
5269 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5270 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5271 		case IP_VERSION(3, 1, 2):
5272 		case IP_VERSION(3, 1, 3):
5273 		case IP_VERSION(3, 1, 4):
5274 		case IP_VERSION(3, 1, 5):
5275 		case IP_VERSION(3, 1, 6):
5276 		case IP_VERSION(3, 2, 0):
5277 		case IP_VERSION(3, 2, 1):
5278 		case IP_VERSION(3, 5, 0):
5279 		case IP_VERSION(3, 5, 1):
5280 		case IP_VERSION(3, 6, 0):
5281 		case IP_VERSION(4, 0, 1):
5282 			psr_feature_enabled = true;
5283 			break;
5284 		default:
5285 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5286 			break;
5287 		}
5288 	}
5289 
5290 	/* Determine whether to enable Replay support by default. */
5291 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5292 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5293 		case IP_VERSION(3, 1, 4):
5294 		case IP_VERSION(3, 2, 0):
5295 		case IP_VERSION(3, 2, 1):
5296 		case IP_VERSION(3, 5, 0):
5297 		case IP_VERSION(3, 5, 1):
5298 		case IP_VERSION(3, 6, 0):
5299 			replay_feature_enabled = true;
5300 			break;
5301 
5302 		default:
5303 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5304 			break;
5305 		}
5306 	}
5307 
5308 	if (link_cnt > MAX_LINKS) {
5309 		drm_err(adev_to_drm(adev),
5310 			"KMS: Cannot support more than %d display indexes\n",
5311 				MAX_LINKS);
5312 		goto fail;
5313 	}
5314 
5315 	/* loops over all connectors on the board */
5316 	for (i = 0; i < link_cnt; i++) {
5317 		struct dc_link *link = NULL;
5318 
5319 		link = dc_get_link_at_index(dm->dc, i);
5320 
5321 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5322 			struct amdgpu_dm_wb_connector *wbcon = kzalloc(sizeof(*wbcon), GFP_KERNEL);
5323 
5324 			if (!wbcon) {
5325 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5326 				continue;
5327 			}
5328 
5329 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5330 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5331 				kfree(wbcon);
5332 				continue;
5333 			}
5334 
5335 			link->psr_settings.psr_feature_enabled = false;
5336 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5337 
5338 			continue;
5339 		}
5340 
5341 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
5342 		if (!aconnector)
5343 			goto fail;
5344 
5345 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
5346 		if (!aencoder)
5347 			goto fail;
5348 
5349 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5350 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5351 			goto fail;
5352 		}
5353 
5354 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5355 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5356 			goto fail;
5357 		}
5358 
5359 		if (dm->hpd_rx_offload_wq)
5360 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5361 				aconnector;
5362 
5363 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5364 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5365 
5366 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5367 			emulated_link_detect(link);
5368 			amdgpu_dm_update_connector_after_detect(aconnector);
5369 		} else {
5370 			bool ret = false;
5371 
5372 			mutex_lock(&dm->dc_lock);
5373 			dc_exit_ips_for_hw_access(dm->dc);
5374 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5375 			mutex_unlock(&dm->dc_lock);
5376 
5377 			if (ret) {
5378 				amdgpu_dm_update_connector_after_detect(aconnector);
5379 				setup_backlight_device(dm, aconnector);
5380 
5381 				/* Disable PSR if Replay can be enabled */
5382 				if (replay_feature_enabled)
5383 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5384 						psr_feature_enabled = false;
5385 
5386 				if (psr_feature_enabled) {
5387 					amdgpu_dm_set_psr_caps(link);
5388 					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",
5389 						 link->psr_settings.psr_feature_enabled,
5390 						 link->psr_settings.psr_version,
5391 						 link->dpcd_caps.psr_info.psr_version,
5392 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5393 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5394 				}
5395 			}
5396 		}
5397 		amdgpu_set_panel_orientation(&aconnector->base);
5398 	}
5399 
5400 	/* Software is initialized. Now we can register interrupt handlers. */
5401 	switch (adev->asic_type) {
5402 #if defined(CONFIG_DRM_AMD_DC_SI)
5403 	case CHIP_TAHITI:
5404 	case CHIP_PITCAIRN:
5405 	case CHIP_VERDE:
5406 	case CHIP_OLAND:
5407 		if (dce60_register_irq_handlers(dm->adev)) {
5408 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5409 			goto fail;
5410 		}
5411 		break;
5412 #endif
5413 	case CHIP_BONAIRE:
5414 	case CHIP_HAWAII:
5415 	case CHIP_KAVERI:
5416 	case CHIP_KABINI:
5417 	case CHIP_MULLINS:
5418 	case CHIP_TONGA:
5419 	case CHIP_FIJI:
5420 	case CHIP_CARRIZO:
5421 	case CHIP_STONEY:
5422 	case CHIP_POLARIS11:
5423 	case CHIP_POLARIS10:
5424 	case CHIP_POLARIS12:
5425 	case CHIP_VEGAM:
5426 	case CHIP_VEGA10:
5427 	case CHIP_VEGA12:
5428 	case CHIP_VEGA20:
5429 		if (dce110_register_irq_handlers(dm->adev)) {
5430 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5431 			goto fail;
5432 		}
5433 		break;
5434 	default:
5435 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5436 		case IP_VERSION(1, 0, 0):
5437 		case IP_VERSION(1, 0, 1):
5438 		case IP_VERSION(2, 0, 2):
5439 		case IP_VERSION(2, 0, 3):
5440 		case IP_VERSION(2, 0, 0):
5441 		case IP_VERSION(2, 1, 0):
5442 		case IP_VERSION(3, 0, 0):
5443 		case IP_VERSION(3, 0, 2):
5444 		case IP_VERSION(3, 0, 3):
5445 		case IP_VERSION(3, 0, 1):
5446 		case IP_VERSION(3, 1, 2):
5447 		case IP_VERSION(3, 1, 3):
5448 		case IP_VERSION(3, 1, 4):
5449 		case IP_VERSION(3, 1, 5):
5450 		case IP_VERSION(3, 1, 6):
5451 		case IP_VERSION(3, 2, 0):
5452 		case IP_VERSION(3, 2, 1):
5453 		case IP_VERSION(3, 5, 0):
5454 		case IP_VERSION(3, 5, 1):
5455 		case IP_VERSION(3, 6, 0):
5456 		case IP_VERSION(4, 0, 1):
5457 			if (dcn10_register_irq_handlers(dm->adev)) {
5458 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5459 				goto fail;
5460 			}
5461 			break;
5462 		default:
5463 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5464 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5465 			goto fail;
5466 		}
5467 		break;
5468 	}
5469 
5470 	return 0;
5471 fail:
5472 	kfree(aencoder);
5473 	kfree(aconnector);
5474 
5475 	return -EINVAL;
5476 }
5477 
5478 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5479 {
5480 	if (dm->atomic_obj.state)
5481 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5482 }
5483 
5484 /******************************************************************************
5485  * amdgpu_display_funcs functions
5486  *****************************************************************************/
5487 
5488 /*
5489  * dm_bandwidth_update - program display watermarks
5490  *
5491  * @adev: amdgpu_device pointer
5492  *
5493  * Calculate and program the display watermarks and line buffer allocation.
5494  */
5495 static void dm_bandwidth_update(struct amdgpu_device *adev)
5496 {
5497 	/* TODO: implement later */
5498 }
5499 
5500 static const struct amdgpu_display_funcs dm_display_funcs = {
5501 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5502 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5503 	.backlight_set_level = NULL, /* never called for DC */
5504 	.backlight_get_level = NULL, /* never called for DC */
5505 	.hpd_sense = NULL,/* called unconditionally */
5506 	.hpd_set_polarity = NULL, /* called unconditionally */
5507 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5508 	.page_flip_get_scanoutpos =
5509 		dm_crtc_get_scanoutpos,/* called unconditionally */
5510 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5511 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5512 };
5513 
5514 #if defined(CONFIG_DEBUG_KERNEL_DC)
5515 
5516 static ssize_t s3_debug_store(struct device *device,
5517 			      struct device_attribute *attr,
5518 			      const char *buf,
5519 			      size_t count)
5520 {
5521 	int ret;
5522 	int s3_state;
5523 	struct drm_device *drm_dev = dev_get_drvdata(device);
5524 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5525 	struct amdgpu_ip_block *ip_block;
5526 
5527 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5528 	if (!ip_block)
5529 		return -EINVAL;
5530 
5531 	ret = kstrtoint(buf, 0, &s3_state);
5532 
5533 	if (ret == 0) {
5534 		if (s3_state) {
5535 			dm_resume(ip_block);
5536 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5537 		} else
5538 			dm_suspend(ip_block);
5539 	}
5540 
5541 	return ret == 0 ? count : 0;
5542 }
5543 
5544 DEVICE_ATTR_WO(s3_debug);
5545 
5546 #endif
5547 
5548 static int dm_init_microcode(struct amdgpu_device *adev)
5549 {
5550 	char *fw_name_dmub;
5551 	int r;
5552 
5553 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5554 	case IP_VERSION(2, 1, 0):
5555 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5556 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5557 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5558 		break;
5559 	case IP_VERSION(3, 0, 0):
5560 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5561 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5562 		else
5563 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5564 		break;
5565 	case IP_VERSION(3, 0, 1):
5566 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5567 		break;
5568 	case IP_VERSION(3, 0, 2):
5569 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5570 		break;
5571 	case IP_VERSION(3, 0, 3):
5572 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5573 		break;
5574 	case IP_VERSION(3, 1, 2):
5575 	case IP_VERSION(3, 1, 3):
5576 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5577 		break;
5578 	case IP_VERSION(3, 1, 4):
5579 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5580 		break;
5581 	case IP_VERSION(3, 1, 5):
5582 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5583 		break;
5584 	case IP_VERSION(3, 1, 6):
5585 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5586 		break;
5587 	case IP_VERSION(3, 2, 0):
5588 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5589 		break;
5590 	case IP_VERSION(3, 2, 1):
5591 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5592 		break;
5593 	case IP_VERSION(3, 5, 0):
5594 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5595 		break;
5596 	case IP_VERSION(3, 5, 1):
5597 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5598 		break;
5599 	case IP_VERSION(3, 6, 0):
5600 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5601 		break;
5602 	case IP_VERSION(4, 0, 1):
5603 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5604 		break;
5605 	default:
5606 		/* ASIC doesn't support DMUB. */
5607 		return 0;
5608 	}
5609 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5610 				 "%s", fw_name_dmub);
5611 	return r;
5612 }
5613 
5614 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5615 {
5616 	struct amdgpu_device *adev = ip_block->adev;
5617 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5618 	struct atom_context *ctx = mode_info->atom_context;
5619 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5620 	u16 data_offset;
5621 
5622 	/* if there is no object header, skip DM */
5623 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5624 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5625 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5626 		return -ENOENT;
5627 	}
5628 
5629 	switch (adev->asic_type) {
5630 #if defined(CONFIG_DRM_AMD_DC_SI)
5631 	case CHIP_TAHITI:
5632 	case CHIP_PITCAIRN:
5633 	case CHIP_VERDE:
5634 		adev->mode_info.num_crtc = 6;
5635 		adev->mode_info.num_hpd = 6;
5636 		adev->mode_info.num_dig = 6;
5637 		break;
5638 	case CHIP_OLAND:
5639 		adev->mode_info.num_crtc = 2;
5640 		adev->mode_info.num_hpd = 2;
5641 		adev->mode_info.num_dig = 2;
5642 		break;
5643 #endif
5644 	case CHIP_BONAIRE:
5645 	case CHIP_HAWAII:
5646 		adev->mode_info.num_crtc = 6;
5647 		adev->mode_info.num_hpd = 6;
5648 		adev->mode_info.num_dig = 6;
5649 		break;
5650 	case CHIP_KAVERI:
5651 		adev->mode_info.num_crtc = 4;
5652 		adev->mode_info.num_hpd = 6;
5653 		adev->mode_info.num_dig = 7;
5654 		break;
5655 	case CHIP_KABINI:
5656 	case CHIP_MULLINS:
5657 		adev->mode_info.num_crtc = 2;
5658 		adev->mode_info.num_hpd = 6;
5659 		adev->mode_info.num_dig = 6;
5660 		break;
5661 	case CHIP_FIJI:
5662 	case CHIP_TONGA:
5663 		adev->mode_info.num_crtc = 6;
5664 		adev->mode_info.num_hpd = 6;
5665 		adev->mode_info.num_dig = 7;
5666 		break;
5667 	case CHIP_CARRIZO:
5668 		adev->mode_info.num_crtc = 3;
5669 		adev->mode_info.num_hpd = 6;
5670 		adev->mode_info.num_dig = 9;
5671 		break;
5672 	case CHIP_STONEY:
5673 		adev->mode_info.num_crtc = 2;
5674 		adev->mode_info.num_hpd = 6;
5675 		adev->mode_info.num_dig = 9;
5676 		break;
5677 	case CHIP_POLARIS11:
5678 	case CHIP_POLARIS12:
5679 		adev->mode_info.num_crtc = 5;
5680 		adev->mode_info.num_hpd = 5;
5681 		adev->mode_info.num_dig = 5;
5682 		break;
5683 	case CHIP_POLARIS10:
5684 	case CHIP_VEGAM:
5685 		adev->mode_info.num_crtc = 6;
5686 		adev->mode_info.num_hpd = 6;
5687 		adev->mode_info.num_dig = 6;
5688 		break;
5689 	case CHIP_VEGA10:
5690 	case CHIP_VEGA12:
5691 	case CHIP_VEGA20:
5692 		adev->mode_info.num_crtc = 6;
5693 		adev->mode_info.num_hpd = 6;
5694 		adev->mode_info.num_dig = 6;
5695 		break;
5696 	default:
5697 
5698 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5699 		case IP_VERSION(2, 0, 2):
5700 		case IP_VERSION(3, 0, 0):
5701 			adev->mode_info.num_crtc = 6;
5702 			adev->mode_info.num_hpd = 6;
5703 			adev->mode_info.num_dig = 6;
5704 			break;
5705 		case IP_VERSION(2, 0, 0):
5706 		case IP_VERSION(3, 0, 2):
5707 			adev->mode_info.num_crtc = 5;
5708 			adev->mode_info.num_hpd = 5;
5709 			adev->mode_info.num_dig = 5;
5710 			break;
5711 		case IP_VERSION(2, 0, 3):
5712 		case IP_VERSION(3, 0, 3):
5713 			adev->mode_info.num_crtc = 2;
5714 			adev->mode_info.num_hpd = 2;
5715 			adev->mode_info.num_dig = 2;
5716 			break;
5717 		case IP_VERSION(1, 0, 0):
5718 		case IP_VERSION(1, 0, 1):
5719 		case IP_VERSION(3, 0, 1):
5720 		case IP_VERSION(2, 1, 0):
5721 		case IP_VERSION(3, 1, 2):
5722 		case IP_VERSION(3, 1, 3):
5723 		case IP_VERSION(3, 1, 4):
5724 		case IP_VERSION(3, 1, 5):
5725 		case IP_VERSION(3, 1, 6):
5726 		case IP_VERSION(3, 2, 0):
5727 		case IP_VERSION(3, 2, 1):
5728 		case IP_VERSION(3, 5, 0):
5729 		case IP_VERSION(3, 5, 1):
5730 		case IP_VERSION(3, 6, 0):
5731 		case IP_VERSION(4, 0, 1):
5732 			adev->mode_info.num_crtc = 4;
5733 			adev->mode_info.num_hpd = 4;
5734 			adev->mode_info.num_dig = 4;
5735 			break;
5736 		default:
5737 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
5738 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5739 			return -EINVAL;
5740 		}
5741 		break;
5742 	}
5743 
5744 	if (adev->mode_info.funcs == NULL)
5745 		adev->mode_info.funcs = &dm_display_funcs;
5746 
5747 	/*
5748 	 * Note: Do NOT change adev->audio_endpt_rreg and
5749 	 * adev->audio_endpt_wreg because they are initialised in
5750 	 * amdgpu_device_init()
5751 	 */
5752 #if defined(CONFIG_DEBUG_KERNEL_DC)
5753 	device_create_file(
5754 		adev_to_drm(adev)->dev,
5755 		&dev_attr_s3_debug);
5756 #endif
5757 	adev->dc_enabled = true;
5758 
5759 	return dm_init_microcode(adev);
5760 }
5761 
5762 static bool modereset_required(struct drm_crtc_state *crtc_state)
5763 {
5764 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
5765 }
5766 
5767 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
5768 {
5769 	drm_encoder_cleanup(encoder);
5770 	kfree(encoder);
5771 }
5772 
5773 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
5774 	.destroy = amdgpu_dm_encoder_destroy,
5775 };
5776 
5777 static int
5778 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
5779 			    const enum surface_pixel_format format,
5780 			    enum dc_color_space *color_space)
5781 {
5782 	bool full_range;
5783 
5784 	*color_space = COLOR_SPACE_SRGB;
5785 
5786 	/* DRM color properties only affect non-RGB formats. */
5787 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
5788 		return 0;
5789 
5790 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
5791 
5792 	switch (plane_state->color_encoding) {
5793 	case DRM_COLOR_YCBCR_BT601:
5794 		if (full_range)
5795 			*color_space = COLOR_SPACE_YCBCR601;
5796 		else
5797 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
5798 		break;
5799 
5800 	case DRM_COLOR_YCBCR_BT709:
5801 		if (full_range)
5802 			*color_space = COLOR_SPACE_YCBCR709;
5803 		else
5804 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
5805 		break;
5806 
5807 	case DRM_COLOR_YCBCR_BT2020:
5808 		if (full_range)
5809 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
5810 		else
5811 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
5812 		break;
5813 
5814 	default:
5815 		return -EINVAL;
5816 	}
5817 
5818 	return 0;
5819 }
5820 
5821 static int
5822 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
5823 			    const struct drm_plane_state *plane_state,
5824 			    const u64 tiling_flags,
5825 			    struct dc_plane_info *plane_info,
5826 			    struct dc_plane_address *address,
5827 			    bool tmz_surface)
5828 {
5829 	const struct drm_framebuffer *fb = plane_state->fb;
5830 	const struct amdgpu_framebuffer *afb =
5831 		to_amdgpu_framebuffer(plane_state->fb);
5832 	int ret;
5833 
5834 	memset(plane_info, 0, sizeof(*plane_info));
5835 
5836 	switch (fb->format->format) {
5837 	case DRM_FORMAT_C8:
5838 		plane_info->format =
5839 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
5840 		break;
5841 	case DRM_FORMAT_RGB565:
5842 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
5843 		break;
5844 	case DRM_FORMAT_XRGB8888:
5845 	case DRM_FORMAT_ARGB8888:
5846 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
5847 		break;
5848 	case DRM_FORMAT_XRGB2101010:
5849 	case DRM_FORMAT_ARGB2101010:
5850 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
5851 		break;
5852 	case DRM_FORMAT_XBGR2101010:
5853 	case DRM_FORMAT_ABGR2101010:
5854 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
5855 		break;
5856 	case DRM_FORMAT_XBGR8888:
5857 	case DRM_FORMAT_ABGR8888:
5858 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
5859 		break;
5860 	case DRM_FORMAT_NV21:
5861 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
5862 		break;
5863 	case DRM_FORMAT_NV12:
5864 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
5865 		break;
5866 	case DRM_FORMAT_P010:
5867 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
5868 		break;
5869 	case DRM_FORMAT_XRGB16161616F:
5870 	case DRM_FORMAT_ARGB16161616F:
5871 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
5872 		break;
5873 	case DRM_FORMAT_XBGR16161616F:
5874 	case DRM_FORMAT_ABGR16161616F:
5875 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
5876 		break;
5877 	case DRM_FORMAT_XRGB16161616:
5878 	case DRM_FORMAT_ARGB16161616:
5879 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
5880 		break;
5881 	case DRM_FORMAT_XBGR16161616:
5882 	case DRM_FORMAT_ABGR16161616:
5883 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
5884 		break;
5885 	default:
5886 		drm_err(adev_to_drm(adev),
5887 			"Unsupported screen format %p4cc\n",
5888 			&fb->format->format);
5889 		return -EINVAL;
5890 	}
5891 
5892 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
5893 	case DRM_MODE_ROTATE_0:
5894 		plane_info->rotation = ROTATION_ANGLE_0;
5895 		break;
5896 	case DRM_MODE_ROTATE_90:
5897 		plane_info->rotation = ROTATION_ANGLE_90;
5898 		break;
5899 	case DRM_MODE_ROTATE_180:
5900 		plane_info->rotation = ROTATION_ANGLE_180;
5901 		break;
5902 	case DRM_MODE_ROTATE_270:
5903 		plane_info->rotation = ROTATION_ANGLE_270;
5904 		break;
5905 	default:
5906 		plane_info->rotation = ROTATION_ANGLE_0;
5907 		break;
5908 	}
5909 
5910 
5911 	plane_info->visible = true;
5912 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
5913 
5914 	plane_info->layer_index = plane_state->normalized_zpos;
5915 
5916 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
5917 					  &plane_info->color_space);
5918 	if (ret)
5919 		return ret;
5920 
5921 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
5922 					   plane_info->rotation, tiling_flags,
5923 					   &plane_info->tiling_info,
5924 					   &plane_info->plane_size,
5925 					   &plane_info->dcc, address,
5926 					   tmz_surface);
5927 	if (ret)
5928 		return ret;
5929 
5930 	amdgpu_dm_plane_fill_blending_from_plane_state(
5931 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
5932 		&plane_info->global_alpha, &plane_info->global_alpha_value);
5933 
5934 	return 0;
5935 }
5936 
5937 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
5938 				    struct dc_plane_state *dc_plane_state,
5939 				    struct drm_plane_state *plane_state,
5940 				    struct drm_crtc_state *crtc_state)
5941 {
5942 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
5943 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
5944 	struct dc_scaling_info scaling_info;
5945 	struct dc_plane_info plane_info;
5946 	int ret;
5947 
5948 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
5949 	if (ret)
5950 		return ret;
5951 
5952 	dc_plane_state->src_rect = scaling_info.src_rect;
5953 	dc_plane_state->dst_rect = scaling_info.dst_rect;
5954 	dc_plane_state->clip_rect = scaling_info.clip_rect;
5955 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
5956 
5957 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
5958 					  afb->tiling_flags,
5959 					  &plane_info,
5960 					  &dc_plane_state->address,
5961 					  afb->tmz_surface);
5962 	if (ret)
5963 		return ret;
5964 
5965 	dc_plane_state->format = plane_info.format;
5966 	dc_plane_state->color_space = plane_info.color_space;
5967 	dc_plane_state->format = plane_info.format;
5968 	dc_plane_state->plane_size = plane_info.plane_size;
5969 	dc_plane_state->rotation = plane_info.rotation;
5970 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
5971 	dc_plane_state->stereo_format = plane_info.stereo_format;
5972 	dc_plane_state->tiling_info = plane_info.tiling_info;
5973 	dc_plane_state->visible = plane_info.visible;
5974 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
5975 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
5976 	dc_plane_state->global_alpha = plane_info.global_alpha;
5977 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
5978 	dc_plane_state->dcc = plane_info.dcc;
5979 	dc_plane_state->layer_index = plane_info.layer_index;
5980 	dc_plane_state->flip_int_enabled = true;
5981 
5982 	/*
5983 	 * Always set input transfer function, since plane state is refreshed
5984 	 * every time.
5985 	 */
5986 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
5987 						plane_state,
5988 						dc_plane_state);
5989 	if (ret)
5990 		return ret;
5991 
5992 	return 0;
5993 }
5994 
5995 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
5996 				      struct rect *dirty_rect, int32_t x,
5997 				      s32 y, s32 width, s32 height,
5998 				      int *i, bool ffu)
5999 {
6000 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6001 
6002 	dirty_rect->x = x;
6003 	dirty_rect->y = y;
6004 	dirty_rect->width = width;
6005 	dirty_rect->height = height;
6006 
6007 	if (ffu)
6008 		drm_dbg(plane->dev,
6009 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6010 			plane->base.id, width, height);
6011 	else
6012 		drm_dbg(plane->dev,
6013 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6014 			plane->base.id, x, y, width, height);
6015 
6016 	(*i)++;
6017 }
6018 
6019 /**
6020  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6021  *
6022  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6023  *         remote fb
6024  * @old_plane_state: Old state of @plane
6025  * @new_plane_state: New state of @plane
6026  * @crtc_state: New state of CRTC connected to the @plane
6027  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6028  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6029  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6030  *             that have changed will be updated. If PSR SU is not enabled,
6031  *             or if damage clips are not available, the entire screen will be updated.
6032  * @dirty_regions_changed: dirty regions changed
6033  *
6034  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6035  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6036  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6037  * amdgpu_dm's.
6038  *
6039  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6040  * plane with regions that require flushing to the eDP remote buffer. In
6041  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6042  * implicitly provide damage clips without any client support via the plane
6043  * bounds.
6044  */
6045 static void fill_dc_dirty_rects(struct drm_plane *plane,
6046 				struct drm_plane_state *old_plane_state,
6047 				struct drm_plane_state *new_plane_state,
6048 				struct drm_crtc_state *crtc_state,
6049 				struct dc_flip_addrs *flip_addrs,
6050 				bool is_psr_su,
6051 				bool *dirty_regions_changed)
6052 {
6053 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6054 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6055 	u32 num_clips;
6056 	struct drm_mode_rect *clips;
6057 	bool bb_changed;
6058 	bool fb_changed;
6059 	u32 i = 0;
6060 	*dirty_regions_changed = false;
6061 
6062 	/*
6063 	 * Cursor plane has it's own dirty rect update interface. See
6064 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6065 	 */
6066 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6067 		return;
6068 
6069 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6070 		goto ffu;
6071 
6072 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6073 	clips = drm_plane_get_damage_clips(new_plane_state);
6074 
6075 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6076 						   is_psr_su)))
6077 		goto ffu;
6078 
6079 	if (!dm_crtc_state->mpo_requested) {
6080 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6081 			goto ffu;
6082 
6083 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6084 			fill_dc_dirty_rect(new_plane_state->plane,
6085 					   &dirty_rects[flip_addrs->dirty_rect_count],
6086 					   clips->x1, clips->y1,
6087 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6088 					   &flip_addrs->dirty_rect_count,
6089 					   false);
6090 		return;
6091 	}
6092 
6093 	/*
6094 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6095 	 * flipped to or damaged.
6096 	 *
6097 	 * If plane is moved or resized, also add old bounding box to dirty
6098 	 * rects.
6099 	 */
6100 	fb_changed = old_plane_state->fb->base.id !=
6101 		     new_plane_state->fb->base.id;
6102 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6103 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6104 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6105 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6106 
6107 	drm_dbg(plane->dev,
6108 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6109 		new_plane_state->plane->base.id,
6110 		bb_changed, fb_changed, num_clips);
6111 
6112 	*dirty_regions_changed = bb_changed;
6113 
6114 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6115 		goto ffu;
6116 
6117 	if (bb_changed) {
6118 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6119 				   new_plane_state->crtc_x,
6120 				   new_plane_state->crtc_y,
6121 				   new_plane_state->crtc_w,
6122 				   new_plane_state->crtc_h, &i, false);
6123 
6124 		/* Add old plane bounding-box if plane is moved or resized */
6125 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6126 				   old_plane_state->crtc_x,
6127 				   old_plane_state->crtc_y,
6128 				   old_plane_state->crtc_w,
6129 				   old_plane_state->crtc_h, &i, false);
6130 	}
6131 
6132 	if (num_clips) {
6133 		for (; i < num_clips; clips++)
6134 			fill_dc_dirty_rect(new_plane_state->plane,
6135 					   &dirty_rects[i], clips->x1,
6136 					   clips->y1, clips->x2 - clips->x1,
6137 					   clips->y2 - clips->y1, &i, false);
6138 	} else if (fb_changed && !bb_changed) {
6139 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6140 				   new_plane_state->crtc_x,
6141 				   new_plane_state->crtc_y,
6142 				   new_plane_state->crtc_w,
6143 				   new_plane_state->crtc_h, &i, false);
6144 	}
6145 
6146 	flip_addrs->dirty_rect_count = i;
6147 	return;
6148 
6149 ffu:
6150 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6151 			   dm_crtc_state->base.mode.crtc_hdisplay,
6152 			   dm_crtc_state->base.mode.crtc_vdisplay,
6153 			   &flip_addrs->dirty_rect_count, true);
6154 }
6155 
6156 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
6157 					   const struct dm_connector_state *dm_state,
6158 					   struct dc_stream_state *stream)
6159 {
6160 	enum amdgpu_rmx_type rmx_type;
6161 
6162 	struct rect src = { 0 }; /* viewport in composition space*/
6163 	struct rect dst = { 0 }; /* stream addressable area */
6164 
6165 	/* no mode. nothing to be done */
6166 	if (!mode)
6167 		return;
6168 
6169 	/* Full screen scaling by default */
6170 	src.width = mode->hdisplay;
6171 	src.height = mode->vdisplay;
6172 	dst.width = stream->timing.h_addressable;
6173 	dst.height = stream->timing.v_addressable;
6174 
6175 	if (dm_state) {
6176 		rmx_type = dm_state->scaling;
6177 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6178 			if (src.width * dst.height <
6179 					src.height * dst.width) {
6180 				/* height needs less upscaling/more downscaling */
6181 				dst.width = src.width *
6182 						dst.height / src.height;
6183 			} else {
6184 				/* width needs less upscaling/more downscaling */
6185 				dst.height = src.height *
6186 						dst.width / src.width;
6187 			}
6188 		} else if (rmx_type == RMX_CENTER) {
6189 			dst = src;
6190 		}
6191 
6192 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6193 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6194 
6195 		if (dm_state->underscan_enable) {
6196 			dst.x += dm_state->underscan_hborder / 2;
6197 			dst.y += dm_state->underscan_vborder / 2;
6198 			dst.width -= dm_state->underscan_hborder;
6199 			dst.height -= dm_state->underscan_vborder;
6200 		}
6201 	}
6202 
6203 	stream->src = src;
6204 	stream->dst = dst;
6205 
6206 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6207 		      dst.x, dst.y, dst.width, dst.height);
6208 
6209 }
6210 
6211 static enum dc_color_depth
6212 convert_color_depth_from_display_info(const struct drm_connector *connector,
6213 				      bool is_y420, int requested_bpc)
6214 {
6215 	u8 bpc;
6216 
6217 	if (is_y420) {
6218 		bpc = 8;
6219 
6220 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6221 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6222 			bpc = 16;
6223 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6224 			bpc = 12;
6225 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6226 			bpc = 10;
6227 	} else {
6228 		bpc = (uint8_t)connector->display_info.bpc;
6229 		/* Assume 8 bpc by default if no bpc is specified. */
6230 		bpc = bpc ? bpc : 8;
6231 	}
6232 
6233 	if (requested_bpc > 0) {
6234 		/*
6235 		 * Cap display bpc based on the user requested value.
6236 		 *
6237 		 * The value for state->max_bpc may not correctly updated
6238 		 * depending on when the connector gets added to the state
6239 		 * or if this was called outside of atomic check, so it
6240 		 * can't be used directly.
6241 		 */
6242 		bpc = min_t(u8, bpc, requested_bpc);
6243 
6244 		/* Round down to the nearest even number. */
6245 		bpc = bpc - (bpc & 1);
6246 	}
6247 
6248 	switch (bpc) {
6249 	case 0:
6250 		/*
6251 		 * Temporary Work around, DRM doesn't parse color depth for
6252 		 * EDID revision before 1.4
6253 		 * TODO: Fix edid parsing
6254 		 */
6255 		return COLOR_DEPTH_888;
6256 	case 6:
6257 		return COLOR_DEPTH_666;
6258 	case 8:
6259 		return COLOR_DEPTH_888;
6260 	case 10:
6261 		return COLOR_DEPTH_101010;
6262 	case 12:
6263 		return COLOR_DEPTH_121212;
6264 	case 14:
6265 		return COLOR_DEPTH_141414;
6266 	case 16:
6267 		return COLOR_DEPTH_161616;
6268 	default:
6269 		return COLOR_DEPTH_UNDEFINED;
6270 	}
6271 }
6272 
6273 static enum dc_aspect_ratio
6274 get_aspect_ratio(const struct drm_display_mode *mode_in)
6275 {
6276 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6277 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6278 }
6279 
6280 static enum dc_color_space
6281 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6282 		       const struct drm_connector_state *connector_state)
6283 {
6284 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6285 
6286 	switch (connector_state->colorspace) {
6287 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6288 		if (dc_crtc_timing->flags.Y_ONLY)
6289 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6290 		else
6291 			color_space = COLOR_SPACE_YCBCR601;
6292 		break;
6293 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6294 		if (dc_crtc_timing->flags.Y_ONLY)
6295 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6296 		else
6297 			color_space = COLOR_SPACE_YCBCR709;
6298 		break;
6299 	case DRM_MODE_COLORIMETRY_OPRGB:
6300 		color_space = COLOR_SPACE_ADOBERGB;
6301 		break;
6302 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6303 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6304 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6305 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6306 		else
6307 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6308 		break;
6309 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6310 	default:
6311 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6312 			color_space = COLOR_SPACE_SRGB;
6313 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6314 				color_space = COLOR_SPACE_SRGB_LIMITED;
6315 		/*
6316 		 * 27030khz is the separation point between HDTV and SDTV
6317 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6318 		 * respectively
6319 		 */
6320 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6321 			if (dc_crtc_timing->flags.Y_ONLY)
6322 				color_space =
6323 					COLOR_SPACE_YCBCR709_LIMITED;
6324 			else
6325 				color_space = COLOR_SPACE_YCBCR709;
6326 		} else {
6327 			if (dc_crtc_timing->flags.Y_ONLY)
6328 				color_space =
6329 					COLOR_SPACE_YCBCR601_LIMITED;
6330 			else
6331 				color_space = COLOR_SPACE_YCBCR601;
6332 		}
6333 		break;
6334 	}
6335 
6336 	return color_space;
6337 }
6338 
6339 static enum display_content_type
6340 get_output_content_type(const struct drm_connector_state *connector_state)
6341 {
6342 	switch (connector_state->content_type) {
6343 	default:
6344 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6345 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6346 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6347 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6348 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6349 		return DISPLAY_CONTENT_TYPE_PHOTO;
6350 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6351 		return DISPLAY_CONTENT_TYPE_CINEMA;
6352 	case DRM_MODE_CONTENT_TYPE_GAME:
6353 		return DISPLAY_CONTENT_TYPE_GAME;
6354 	}
6355 }
6356 
6357 static bool adjust_colour_depth_from_display_info(
6358 	struct dc_crtc_timing *timing_out,
6359 	const struct drm_display_info *info)
6360 {
6361 	enum dc_color_depth depth = timing_out->display_color_depth;
6362 	int normalized_clk;
6363 
6364 	do {
6365 		normalized_clk = timing_out->pix_clk_100hz / 10;
6366 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6367 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6368 			normalized_clk /= 2;
6369 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6370 		switch (depth) {
6371 		case COLOR_DEPTH_888:
6372 			break;
6373 		case COLOR_DEPTH_101010:
6374 			normalized_clk = (normalized_clk * 30) / 24;
6375 			break;
6376 		case COLOR_DEPTH_121212:
6377 			normalized_clk = (normalized_clk * 36) / 24;
6378 			break;
6379 		case COLOR_DEPTH_161616:
6380 			normalized_clk = (normalized_clk * 48) / 24;
6381 			break;
6382 		default:
6383 			/* The above depths are the only ones valid for HDMI. */
6384 			return false;
6385 		}
6386 		if (normalized_clk <= info->max_tmds_clock) {
6387 			timing_out->display_color_depth = depth;
6388 			return true;
6389 		}
6390 	} while (--depth > COLOR_DEPTH_666);
6391 	return false;
6392 }
6393 
6394 static void fill_stream_properties_from_drm_display_mode(
6395 	struct dc_stream_state *stream,
6396 	const struct drm_display_mode *mode_in,
6397 	const struct drm_connector *connector,
6398 	const struct drm_connector_state *connector_state,
6399 	const struct dc_stream_state *old_stream,
6400 	int requested_bpc)
6401 {
6402 	struct dc_crtc_timing *timing_out = &stream->timing;
6403 	const struct drm_display_info *info = &connector->display_info;
6404 	struct amdgpu_dm_connector *aconnector = NULL;
6405 	struct hdmi_vendor_infoframe hv_frame;
6406 	struct hdmi_avi_infoframe avi_frame;
6407 	ssize_t err;
6408 
6409 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6410 		aconnector = to_amdgpu_dm_connector(connector);
6411 
6412 	memset(&hv_frame, 0, sizeof(hv_frame));
6413 	memset(&avi_frame, 0, sizeof(avi_frame));
6414 
6415 	timing_out->h_border_left = 0;
6416 	timing_out->h_border_right = 0;
6417 	timing_out->v_border_top = 0;
6418 	timing_out->v_border_bottom = 0;
6419 	/* TODO: un-hardcode */
6420 	if (drm_mode_is_420_only(info, mode_in)
6421 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6422 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6423 	else if (drm_mode_is_420_also(info, mode_in)
6424 			&& aconnector
6425 			&& aconnector->force_yuv420_output)
6426 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6427 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
6428 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6429 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6430 	else
6431 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6432 
6433 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6434 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6435 		connector,
6436 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6437 		requested_bpc);
6438 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6439 	timing_out->hdmi_vic = 0;
6440 
6441 	if (old_stream) {
6442 		timing_out->vic = old_stream->timing.vic;
6443 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6444 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6445 	} else {
6446 		timing_out->vic = drm_match_cea_mode(mode_in);
6447 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6448 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6449 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6450 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6451 	}
6452 
6453 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6454 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6455 							       (struct drm_connector *)connector,
6456 							       mode_in);
6457 		if (err < 0)
6458 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6459 				      connector->name, err);
6460 		timing_out->vic = avi_frame.video_code;
6461 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6462 								  (struct drm_connector *)connector,
6463 								  mode_in);
6464 		if (err < 0)
6465 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6466 				      connector->name, err);
6467 		timing_out->hdmi_vic = hv_frame.vic;
6468 	}
6469 
6470 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6471 		timing_out->h_addressable = mode_in->hdisplay;
6472 		timing_out->h_total = mode_in->htotal;
6473 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6474 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6475 		timing_out->v_total = mode_in->vtotal;
6476 		timing_out->v_addressable = mode_in->vdisplay;
6477 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6478 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6479 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6480 	} else {
6481 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6482 		timing_out->h_total = mode_in->crtc_htotal;
6483 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6484 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6485 		timing_out->v_total = mode_in->crtc_vtotal;
6486 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6487 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6488 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6489 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6490 	}
6491 
6492 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6493 
6494 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6495 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6496 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6497 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6498 		    drm_mode_is_420_also(info, mode_in) &&
6499 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6500 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6501 			adjust_colour_depth_from_display_info(timing_out, info);
6502 		}
6503 	}
6504 
6505 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6506 	stream->content_type = get_output_content_type(connector_state);
6507 }
6508 
6509 static void fill_audio_info(struct audio_info *audio_info,
6510 			    const struct drm_connector *drm_connector,
6511 			    const struct dc_sink *dc_sink)
6512 {
6513 	int i = 0;
6514 	int cea_revision = 0;
6515 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6516 
6517 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6518 	audio_info->product_id = edid_caps->product_id;
6519 
6520 	cea_revision = drm_connector->display_info.cea_rev;
6521 
6522 	strscpy(audio_info->display_name,
6523 		edid_caps->display_name,
6524 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6525 
6526 	if (cea_revision >= 3) {
6527 		audio_info->mode_count = edid_caps->audio_mode_count;
6528 
6529 		for (i = 0; i < audio_info->mode_count; ++i) {
6530 			audio_info->modes[i].format_code =
6531 					(enum audio_format_code)
6532 					(edid_caps->audio_modes[i].format_code);
6533 			audio_info->modes[i].channel_count =
6534 					edid_caps->audio_modes[i].channel_count;
6535 			audio_info->modes[i].sample_rates.all =
6536 					edid_caps->audio_modes[i].sample_rate;
6537 			audio_info->modes[i].sample_size =
6538 					edid_caps->audio_modes[i].sample_size;
6539 		}
6540 	}
6541 
6542 	audio_info->flags.all = edid_caps->speaker_flags;
6543 
6544 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6545 	if (drm_connector->latency_present[0]) {
6546 		audio_info->video_latency = drm_connector->video_latency[0];
6547 		audio_info->audio_latency = drm_connector->audio_latency[0];
6548 	}
6549 
6550 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6551 
6552 }
6553 
6554 static void
6555 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6556 				      struct drm_display_mode *dst_mode)
6557 {
6558 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6559 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6560 	dst_mode->crtc_clock = src_mode->crtc_clock;
6561 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6562 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6563 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6564 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6565 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6566 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6567 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6568 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6569 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6570 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6571 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6572 }
6573 
6574 static void
6575 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6576 					const struct drm_display_mode *native_mode,
6577 					bool scale_enabled)
6578 {
6579 	if (scale_enabled || (
6580 	    native_mode->clock == drm_mode->clock &&
6581 	    native_mode->htotal == drm_mode->htotal &&
6582 	    native_mode->vtotal == drm_mode->vtotal)) {
6583 		if (native_mode->crtc_clock)
6584 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6585 	} else {
6586 		/* no scaling nor amdgpu inserted, no need to patch */
6587 	}
6588 }
6589 
6590 static struct dc_sink *
6591 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6592 {
6593 	struct dc_sink_init_data sink_init_data = { 0 };
6594 	struct dc_sink *sink = NULL;
6595 
6596 	sink_init_data.link = link;
6597 	sink_init_data.sink_signal = link->connector_signal;
6598 
6599 	sink = dc_sink_create(&sink_init_data);
6600 	if (!sink) {
6601 		drm_err(dev, "Failed to create sink!\n");
6602 		return NULL;
6603 	}
6604 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6605 
6606 	return sink;
6607 }
6608 
6609 static void set_multisync_trigger_params(
6610 		struct dc_stream_state *stream)
6611 {
6612 	struct dc_stream_state *master = NULL;
6613 
6614 	if (stream->triggered_crtc_reset.enabled) {
6615 		master = stream->triggered_crtc_reset.event_source;
6616 		stream->triggered_crtc_reset.event =
6617 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6618 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6619 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6620 	}
6621 }
6622 
6623 static void set_master_stream(struct dc_stream_state *stream_set[],
6624 			      int stream_count)
6625 {
6626 	int j, highest_rfr = 0, master_stream = 0;
6627 
6628 	for (j = 0;  j < stream_count; j++) {
6629 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
6630 			int refresh_rate = 0;
6631 
6632 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
6633 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
6634 			if (refresh_rate > highest_rfr) {
6635 				highest_rfr = refresh_rate;
6636 				master_stream = j;
6637 			}
6638 		}
6639 	}
6640 	for (j = 0;  j < stream_count; j++) {
6641 		if (stream_set[j])
6642 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
6643 	}
6644 }
6645 
6646 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
6647 {
6648 	int i = 0;
6649 	struct dc_stream_state *stream;
6650 
6651 	if (context->stream_count < 2)
6652 		return;
6653 	for (i = 0; i < context->stream_count ; i++) {
6654 		if (!context->streams[i])
6655 			continue;
6656 		/*
6657 		 * TODO: add a function to read AMD VSDB bits and set
6658 		 * crtc_sync_master.multi_sync_enabled flag
6659 		 * For now it's set to false
6660 		 */
6661 	}
6662 
6663 	set_master_stream(context->streams, context->stream_count);
6664 
6665 	for (i = 0; i < context->stream_count ; i++) {
6666 		stream = context->streams[i];
6667 
6668 		if (!stream)
6669 			continue;
6670 
6671 		set_multisync_trigger_params(stream);
6672 	}
6673 }
6674 
6675 /**
6676  * DOC: FreeSync Video
6677  *
6678  * When a userspace application wants to play a video, the content follows a
6679  * standard format definition that usually specifies the FPS for that format.
6680  * The below list illustrates some video format and the expected FPS,
6681  * respectively:
6682  *
6683  * - TV/NTSC (23.976 FPS)
6684  * - Cinema (24 FPS)
6685  * - TV/PAL (25 FPS)
6686  * - TV/NTSC (29.97 FPS)
6687  * - TV/NTSC (30 FPS)
6688  * - Cinema HFR (48 FPS)
6689  * - TV/PAL (50 FPS)
6690  * - Commonly used (60 FPS)
6691  * - Multiples of 24 (48,72,96 FPS)
6692  *
6693  * The list of standards video format is not huge and can be added to the
6694  * connector modeset list beforehand. With that, userspace can leverage
6695  * FreeSync to extends the front porch in order to attain the target refresh
6696  * rate. Such a switch will happen seamlessly, without screen blanking or
6697  * reprogramming of the output in any other way. If the userspace requests a
6698  * modesetting change compatible with FreeSync modes that only differ in the
6699  * refresh rate, DC will skip the full update and avoid blink during the
6700  * transition. For example, the video player can change the modesetting from
6701  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
6702  * causing any display blink. This same concept can be applied to a mode
6703  * setting change.
6704  */
6705 static struct drm_display_mode *
6706 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
6707 		bool use_probed_modes)
6708 {
6709 	struct drm_display_mode *m, *m_pref = NULL;
6710 	u16 current_refresh, highest_refresh;
6711 	struct list_head *list_head = use_probed_modes ?
6712 		&aconnector->base.probed_modes :
6713 		&aconnector->base.modes;
6714 
6715 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
6716 		return NULL;
6717 
6718 	if (aconnector->freesync_vid_base.clock != 0)
6719 		return &aconnector->freesync_vid_base;
6720 
6721 	/* Find the preferred mode */
6722 	list_for_each_entry(m, list_head, head) {
6723 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
6724 			m_pref = m;
6725 			break;
6726 		}
6727 	}
6728 
6729 	if (!m_pref) {
6730 		/* Probably an EDID with no preferred mode. Fallback to first entry */
6731 		m_pref = list_first_entry_or_null(
6732 				&aconnector->base.modes, struct drm_display_mode, head);
6733 		if (!m_pref) {
6734 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
6735 			return NULL;
6736 		}
6737 	}
6738 
6739 	highest_refresh = drm_mode_vrefresh(m_pref);
6740 
6741 	/*
6742 	 * Find the mode with highest refresh rate with same resolution.
6743 	 * For some monitors, preferred mode is not the mode with highest
6744 	 * supported refresh rate.
6745 	 */
6746 	list_for_each_entry(m, list_head, head) {
6747 		current_refresh  = drm_mode_vrefresh(m);
6748 
6749 		if (m->hdisplay == m_pref->hdisplay &&
6750 		    m->vdisplay == m_pref->vdisplay &&
6751 		    highest_refresh < current_refresh) {
6752 			highest_refresh = current_refresh;
6753 			m_pref = m;
6754 		}
6755 	}
6756 
6757 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
6758 	return m_pref;
6759 }
6760 
6761 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
6762 		struct amdgpu_dm_connector *aconnector)
6763 {
6764 	struct drm_display_mode *high_mode;
6765 	int timing_diff;
6766 
6767 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
6768 	if (!high_mode || !mode)
6769 		return false;
6770 
6771 	timing_diff = high_mode->vtotal - mode->vtotal;
6772 
6773 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
6774 	    high_mode->hdisplay != mode->hdisplay ||
6775 	    high_mode->vdisplay != mode->vdisplay ||
6776 	    high_mode->hsync_start != mode->hsync_start ||
6777 	    high_mode->hsync_end != mode->hsync_end ||
6778 	    high_mode->htotal != mode->htotal ||
6779 	    high_mode->hskew != mode->hskew ||
6780 	    high_mode->vscan != mode->vscan ||
6781 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
6782 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
6783 		return false;
6784 	else
6785 		return true;
6786 }
6787 
6788 #if defined(CONFIG_DRM_AMD_DC_FP)
6789 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
6790 			    struct dc_sink *sink, struct dc_stream_state *stream,
6791 			    struct dsc_dec_dpcd_caps *dsc_caps)
6792 {
6793 	stream->timing.flags.DSC = 0;
6794 	dsc_caps->is_dsc_supported = false;
6795 
6796 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
6797 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
6798 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
6799 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
6800 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
6801 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
6802 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
6803 				dsc_caps);
6804 	}
6805 }
6806 
6807 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
6808 				    struct dc_sink *sink, struct dc_stream_state *stream,
6809 				    struct dsc_dec_dpcd_caps *dsc_caps,
6810 				    uint32_t max_dsc_target_bpp_limit_override)
6811 {
6812 	const struct dc_link_settings *verified_link_cap = NULL;
6813 	u32 link_bw_in_kbps;
6814 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
6815 	struct dc *dc = sink->ctx->dc;
6816 	struct dc_dsc_bw_range bw_range = {0};
6817 	struct dc_dsc_config dsc_cfg = {0};
6818 	struct dc_dsc_config_options dsc_options = {0};
6819 
6820 	dc_dsc_get_default_config_option(dc, &dsc_options);
6821 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
6822 
6823 	verified_link_cap = dc_link_get_link_cap(stream->link);
6824 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
6825 	edp_min_bpp_x16 = 8 * 16;
6826 	edp_max_bpp_x16 = 8 * 16;
6827 
6828 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
6829 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
6830 
6831 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
6832 		edp_min_bpp_x16 = edp_max_bpp_x16;
6833 
6834 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
6835 				dc->debug.dsc_min_slice_height_override,
6836 				edp_min_bpp_x16, edp_max_bpp_x16,
6837 				dsc_caps,
6838 				&stream->timing,
6839 				dc_link_get_highest_encoding_format(aconnector->dc_link),
6840 				&bw_range)) {
6841 
6842 		if (bw_range.max_kbps < link_bw_in_kbps) {
6843 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
6844 					dsc_caps,
6845 					&dsc_options,
6846 					0,
6847 					&stream->timing,
6848 					dc_link_get_highest_encoding_format(aconnector->dc_link),
6849 					&dsc_cfg)) {
6850 				stream->timing.dsc_cfg = dsc_cfg;
6851 				stream->timing.flags.DSC = 1;
6852 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
6853 			}
6854 			return;
6855 		}
6856 	}
6857 
6858 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
6859 				dsc_caps,
6860 				&dsc_options,
6861 				link_bw_in_kbps,
6862 				&stream->timing,
6863 				dc_link_get_highest_encoding_format(aconnector->dc_link),
6864 				&dsc_cfg)) {
6865 		stream->timing.dsc_cfg = dsc_cfg;
6866 		stream->timing.flags.DSC = 1;
6867 	}
6868 }
6869 
6870 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
6871 					struct dc_sink *sink, struct dc_stream_state *stream,
6872 					struct dsc_dec_dpcd_caps *dsc_caps)
6873 {
6874 	struct drm_connector *drm_connector = &aconnector->base;
6875 	u32 link_bandwidth_kbps;
6876 	struct dc *dc = sink->ctx->dc;
6877 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
6878 	u32 dsc_max_supported_bw_in_kbps;
6879 	u32 max_dsc_target_bpp_limit_override =
6880 		drm_connector->display_info.max_dsc_bpp;
6881 	struct dc_dsc_config_options dsc_options = {0};
6882 
6883 	dc_dsc_get_default_config_option(dc, &dsc_options);
6884 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
6885 
6886 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
6887 							dc_link_get_link_cap(aconnector->dc_link));
6888 
6889 	/* Set DSC policy according to dsc_clock_en */
6890 	dc_dsc_policy_set_enable_dsc_when_not_needed(
6891 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
6892 
6893 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
6894 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
6895 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
6896 
6897 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
6898 
6899 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6900 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
6901 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
6902 						dsc_caps,
6903 						&dsc_options,
6904 						link_bandwidth_kbps,
6905 						&stream->timing,
6906 						dc_link_get_highest_encoding_format(aconnector->dc_link),
6907 						&stream->timing.dsc_cfg)) {
6908 				stream->timing.flags.DSC = 1;
6909 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
6910 							__func__, drm_connector->name);
6911 			}
6912 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
6913 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
6914 					dc_link_get_highest_encoding_format(aconnector->dc_link));
6915 			max_supported_bw_in_kbps = link_bandwidth_kbps;
6916 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
6917 
6918 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
6919 					max_supported_bw_in_kbps > 0 &&
6920 					dsc_max_supported_bw_in_kbps > 0)
6921 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
6922 						dsc_caps,
6923 						&dsc_options,
6924 						dsc_max_supported_bw_in_kbps,
6925 						&stream->timing,
6926 						dc_link_get_highest_encoding_format(aconnector->dc_link),
6927 						&stream->timing.dsc_cfg)) {
6928 					stream->timing.flags.DSC = 1;
6929 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
6930 									 __func__, drm_connector->name);
6931 				}
6932 		}
6933 	}
6934 
6935 	/* Overwrite the stream flag if DSC is enabled through debugfs */
6936 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
6937 		stream->timing.flags.DSC = 1;
6938 
6939 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
6940 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
6941 
6942 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
6943 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
6944 
6945 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
6946 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
6947 }
6948 #endif
6949 
6950 static struct dc_stream_state *
6951 create_stream_for_sink(struct drm_connector *connector,
6952 		       const struct drm_display_mode *drm_mode,
6953 		       const struct dm_connector_state *dm_state,
6954 		       const struct dc_stream_state *old_stream,
6955 		       int requested_bpc)
6956 {
6957 	struct drm_device *dev = connector->dev;
6958 	struct amdgpu_dm_connector *aconnector = NULL;
6959 	struct drm_display_mode *preferred_mode = NULL;
6960 	const struct drm_connector_state *con_state = &dm_state->base;
6961 	struct dc_stream_state *stream = NULL;
6962 	struct drm_display_mode mode;
6963 	struct drm_display_mode saved_mode;
6964 	struct drm_display_mode *freesync_mode = NULL;
6965 	bool native_mode_found = false;
6966 	bool recalculate_timing = false;
6967 	bool scale = dm_state->scaling != RMX_OFF;
6968 	int mode_refresh;
6969 	int preferred_refresh = 0;
6970 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
6971 #if defined(CONFIG_DRM_AMD_DC_FP)
6972 	struct dsc_dec_dpcd_caps dsc_caps;
6973 #endif
6974 	struct dc_link *link = NULL;
6975 	struct dc_sink *sink = NULL;
6976 
6977 	drm_mode_init(&mode, drm_mode);
6978 	memset(&saved_mode, 0, sizeof(saved_mode));
6979 
6980 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
6981 		aconnector = NULL;
6982 		aconnector = to_amdgpu_dm_connector(connector);
6983 		link = aconnector->dc_link;
6984 	} else {
6985 		struct drm_writeback_connector *wbcon = NULL;
6986 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
6987 
6988 		wbcon = drm_connector_to_writeback(connector);
6989 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
6990 		link = dm_wbcon->link;
6991 	}
6992 
6993 	if (!aconnector || !aconnector->dc_sink) {
6994 		sink = create_fake_sink(dev, link);
6995 		if (!sink)
6996 			return stream;
6997 
6998 	} else {
6999 		sink = aconnector->dc_sink;
7000 		dc_sink_retain(sink);
7001 	}
7002 
7003 	stream = dc_create_stream_for_sink(sink);
7004 
7005 	if (stream == NULL) {
7006 		drm_err(dev, "Failed to create stream for sink!\n");
7007 		goto finish;
7008 	}
7009 
7010 	/* We leave this NULL for writeback connectors */
7011 	stream->dm_stream_context = aconnector;
7012 
7013 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7014 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7015 
7016 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7017 		/* Search for preferred mode */
7018 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7019 			native_mode_found = true;
7020 			break;
7021 		}
7022 	}
7023 	if (!native_mode_found)
7024 		preferred_mode = list_first_entry_or_null(
7025 				&connector->modes,
7026 				struct drm_display_mode,
7027 				head);
7028 
7029 	mode_refresh = drm_mode_vrefresh(&mode);
7030 
7031 	if (preferred_mode == NULL) {
7032 		/*
7033 		 * This may not be an error, the use case is when we have no
7034 		 * usermode calls to reset and set mode upon hotplug. In this
7035 		 * case, we call set mode ourselves to restore the previous mode
7036 		 * and the modelist may not be filled in time.
7037 		 */
7038 		drm_dbg_driver(dev, "No preferred mode found\n");
7039 	} else if (aconnector) {
7040 		recalculate_timing = amdgpu_freesync_vid_mode &&
7041 				 is_freesync_video_mode(&mode, aconnector);
7042 		if (recalculate_timing) {
7043 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7044 			drm_mode_copy(&saved_mode, &mode);
7045 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7046 			drm_mode_copy(&mode, freesync_mode);
7047 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7048 		} else {
7049 			decide_crtc_timing_for_drm_display_mode(
7050 					&mode, preferred_mode, scale);
7051 
7052 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7053 		}
7054 	}
7055 
7056 	if (recalculate_timing)
7057 		drm_mode_set_crtcinfo(&saved_mode, 0);
7058 
7059 	/*
7060 	 * If scaling is enabled and refresh rate didn't change
7061 	 * we copy the vic and polarities of the old timings
7062 	 */
7063 	if (!scale || mode_refresh != preferred_refresh)
7064 		fill_stream_properties_from_drm_display_mode(
7065 			stream, &mode, connector, con_state, NULL,
7066 			requested_bpc);
7067 	else
7068 		fill_stream_properties_from_drm_display_mode(
7069 			stream, &mode, connector, con_state, old_stream,
7070 			requested_bpc);
7071 
7072 	/* The rest isn't needed for writeback connectors */
7073 	if (!aconnector)
7074 		goto finish;
7075 
7076 	if (aconnector->timing_changed) {
7077 		drm_dbg(aconnector->base.dev,
7078 			"overriding timing for automated test, bpc %d, changing to %d\n",
7079 			stream->timing.display_color_depth,
7080 			aconnector->timing_requested->display_color_depth);
7081 		stream->timing = *aconnector->timing_requested;
7082 	}
7083 
7084 #if defined(CONFIG_DRM_AMD_DC_FP)
7085 	/* SST DSC determination policy */
7086 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7087 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7088 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7089 #endif
7090 
7091 	update_stream_scaling_settings(&mode, dm_state, stream);
7092 
7093 	fill_audio_info(
7094 		&stream->audio_info,
7095 		connector,
7096 		sink);
7097 
7098 	update_stream_signal(stream, sink);
7099 
7100 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7101 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7102 
7103 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7104 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7105 	    stream->signal == SIGNAL_TYPE_EDP) {
7106 		const struct dc_edid_caps *edid_caps;
7107 		unsigned int disable_colorimetry = 0;
7108 
7109 		if (aconnector->dc_sink) {
7110 			edid_caps = &aconnector->dc_sink->edid_caps;
7111 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7112 		}
7113 
7114 		//
7115 		// should decide stream support vsc sdp colorimetry capability
7116 		// before building vsc info packet
7117 		//
7118 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7119 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7120 						      !disable_colorimetry;
7121 
7122 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7123 			tf = TRANSFER_FUNC_GAMMA_22;
7124 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7125 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7126 
7127 	}
7128 finish:
7129 	dc_sink_release(sink);
7130 
7131 	return stream;
7132 }
7133 
7134 static enum drm_connector_status
7135 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7136 {
7137 	bool connected;
7138 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7139 
7140 	/*
7141 	 * Notes:
7142 	 * 1. This interface is NOT called in context of HPD irq.
7143 	 * 2. This interface *is called* in context of user-mode ioctl. Which
7144 	 * makes it a bad place for *any* MST-related activity.
7145 	 */
7146 
7147 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
7148 	    !aconnector->fake_enable)
7149 		connected = (aconnector->dc_sink != NULL);
7150 	else
7151 		connected = (aconnector->base.force == DRM_FORCE_ON ||
7152 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
7153 
7154 	update_subconnector_property(aconnector);
7155 
7156 	return (connected ? connector_status_connected :
7157 			connector_status_disconnected);
7158 }
7159 
7160 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7161 					    struct drm_connector_state *connector_state,
7162 					    struct drm_property *property,
7163 					    uint64_t val)
7164 {
7165 	struct drm_device *dev = connector->dev;
7166 	struct amdgpu_device *adev = drm_to_adev(dev);
7167 	struct dm_connector_state *dm_old_state =
7168 		to_dm_connector_state(connector->state);
7169 	struct dm_connector_state *dm_new_state =
7170 		to_dm_connector_state(connector_state);
7171 
7172 	int ret = -EINVAL;
7173 
7174 	if (property == dev->mode_config.scaling_mode_property) {
7175 		enum amdgpu_rmx_type rmx_type;
7176 
7177 		switch (val) {
7178 		case DRM_MODE_SCALE_CENTER:
7179 			rmx_type = RMX_CENTER;
7180 			break;
7181 		case DRM_MODE_SCALE_ASPECT:
7182 			rmx_type = RMX_ASPECT;
7183 			break;
7184 		case DRM_MODE_SCALE_FULLSCREEN:
7185 			rmx_type = RMX_FULL;
7186 			break;
7187 		case DRM_MODE_SCALE_NONE:
7188 		default:
7189 			rmx_type = RMX_OFF;
7190 			break;
7191 		}
7192 
7193 		if (dm_old_state->scaling == rmx_type)
7194 			return 0;
7195 
7196 		dm_new_state->scaling = rmx_type;
7197 		ret = 0;
7198 	} else if (property == adev->mode_info.underscan_hborder_property) {
7199 		dm_new_state->underscan_hborder = val;
7200 		ret = 0;
7201 	} else if (property == adev->mode_info.underscan_vborder_property) {
7202 		dm_new_state->underscan_vborder = val;
7203 		ret = 0;
7204 	} else if (property == adev->mode_info.underscan_property) {
7205 		dm_new_state->underscan_enable = val;
7206 		ret = 0;
7207 	}
7208 
7209 	return ret;
7210 }
7211 
7212 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7213 					    const struct drm_connector_state *state,
7214 					    struct drm_property *property,
7215 					    uint64_t *val)
7216 {
7217 	struct drm_device *dev = connector->dev;
7218 	struct amdgpu_device *adev = drm_to_adev(dev);
7219 	struct dm_connector_state *dm_state =
7220 		to_dm_connector_state(state);
7221 	int ret = -EINVAL;
7222 
7223 	if (property == dev->mode_config.scaling_mode_property) {
7224 		switch (dm_state->scaling) {
7225 		case RMX_CENTER:
7226 			*val = DRM_MODE_SCALE_CENTER;
7227 			break;
7228 		case RMX_ASPECT:
7229 			*val = DRM_MODE_SCALE_ASPECT;
7230 			break;
7231 		case RMX_FULL:
7232 			*val = DRM_MODE_SCALE_FULLSCREEN;
7233 			break;
7234 		case RMX_OFF:
7235 		default:
7236 			*val = DRM_MODE_SCALE_NONE;
7237 			break;
7238 		}
7239 		ret = 0;
7240 	} else if (property == adev->mode_info.underscan_hborder_property) {
7241 		*val = dm_state->underscan_hborder;
7242 		ret = 0;
7243 	} else if (property == adev->mode_info.underscan_vborder_property) {
7244 		*val = dm_state->underscan_vborder;
7245 		ret = 0;
7246 	} else if (property == adev->mode_info.underscan_property) {
7247 		*val = dm_state->underscan_enable;
7248 		ret = 0;
7249 	}
7250 
7251 	return ret;
7252 }
7253 
7254 /**
7255  * DOC: panel power savings
7256  *
7257  * The display manager allows you to set your desired **panel power savings**
7258  * level (between 0-4, with 0 representing off), e.g. using the following::
7259  *
7260  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7261  *
7262  * Modifying this value can have implications on color accuracy, so tread
7263  * carefully.
7264  */
7265 
7266 static ssize_t panel_power_savings_show(struct device *device,
7267 					struct device_attribute *attr,
7268 					char *buf)
7269 {
7270 	struct drm_connector *connector = dev_get_drvdata(device);
7271 	struct drm_device *dev = connector->dev;
7272 	u8 val;
7273 
7274 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7275 	val = to_dm_connector_state(connector->state)->abm_level ==
7276 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7277 		to_dm_connector_state(connector->state)->abm_level;
7278 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7279 
7280 	return sysfs_emit(buf, "%u\n", val);
7281 }
7282 
7283 static ssize_t panel_power_savings_store(struct device *device,
7284 					 struct device_attribute *attr,
7285 					 const char *buf, size_t count)
7286 {
7287 	struct drm_connector *connector = dev_get_drvdata(device);
7288 	struct drm_device *dev = connector->dev;
7289 	long val;
7290 	int ret;
7291 
7292 	ret = kstrtol(buf, 0, &val);
7293 
7294 	if (ret)
7295 		return ret;
7296 
7297 	if (val < 0 || val > 4)
7298 		return -EINVAL;
7299 
7300 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7301 	to_dm_connector_state(connector->state)->abm_level = val ?:
7302 		ABM_LEVEL_IMMEDIATE_DISABLE;
7303 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7304 
7305 	drm_kms_helper_hotplug_event(dev);
7306 
7307 	return count;
7308 }
7309 
7310 static DEVICE_ATTR_RW(panel_power_savings);
7311 
7312 static struct attribute *amdgpu_attrs[] = {
7313 	&dev_attr_panel_power_savings.attr,
7314 	NULL
7315 };
7316 
7317 static const struct attribute_group amdgpu_group = {
7318 	.name = "amdgpu",
7319 	.attrs = amdgpu_attrs
7320 };
7321 
7322 static bool
7323 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7324 {
7325 	if (amdgpu_dm_abm_level >= 0)
7326 		return false;
7327 
7328 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7329 		return false;
7330 
7331 	/* check for OLED panels */
7332 	if (amdgpu_dm_connector->bl_idx >= 0) {
7333 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7334 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7335 		struct amdgpu_dm_backlight_caps *caps;
7336 
7337 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7338 		if (caps->aux_support)
7339 			return false;
7340 	}
7341 
7342 	return true;
7343 }
7344 
7345 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7346 {
7347 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7348 
7349 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7350 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7351 
7352 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7353 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7354 }
7355 
7356 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7357 {
7358 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7359 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7360 	struct amdgpu_display_manager *dm = &adev->dm;
7361 
7362 	/*
7363 	 * Call only if mst_mgr was initialized before since it's not done
7364 	 * for all connector types.
7365 	 */
7366 	if (aconnector->mst_mgr.dev)
7367 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7368 
7369 	if (aconnector->bl_idx != -1) {
7370 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7371 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7372 	}
7373 
7374 	if (aconnector->dc_em_sink)
7375 		dc_sink_release(aconnector->dc_em_sink);
7376 	aconnector->dc_em_sink = NULL;
7377 	if (aconnector->dc_sink)
7378 		dc_sink_release(aconnector->dc_sink);
7379 	aconnector->dc_sink = NULL;
7380 
7381 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7382 	drm_connector_unregister(connector);
7383 	drm_connector_cleanup(connector);
7384 	if (aconnector->i2c) {
7385 		i2c_del_adapter(&aconnector->i2c->base);
7386 		kfree(aconnector->i2c);
7387 	}
7388 	kfree(aconnector->dm_dp_aux.aux.name);
7389 
7390 	kfree(connector);
7391 }
7392 
7393 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7394 {
7395 	struct dm_connector_state *state =
7396 		to_dm_connector_state(connector->state);
7397 
7398 	if (connector->state)
7399 		__drm_atomic_helper_connector_destroy_state(connector->state);
7400 
7401 	kfree(state);
7402 
7403 	state = kzalloc(sizeof(*state), GFP_KERNEL);
7404 
7405 	if (state) {
7406 		state->scaling = RMX_OFF;
7407 		state->underscan_enable = false;
7408 		state->underscan_hborder = 0;
7409 		state->underscan_vborder = 0;
7410 		state->base.max_requested_bpc = 8;
7411 		state->vcpi_slots = 0;
7412 		state->pbn = 0;
7413 
7414 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
7415 			if (amdgpu_dm_abm_level <= 0)
7416 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7417 			else
7418 				state->abm_level = amdgpu_dm_abm_level;
7419 		}
7420 
7421 		__drm_atomic_helper_connector_reset(connector, &state->base);
7422 	}
7423 }
7424 
7425 struct drm_connector_state *
7426 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
7427 {
7428 	struct dm_connector_state *state =
7429 		to_dm_connector_state(connector->state);
7430 
7431 	struct dm_connector_state *new_state =
7432 			kmemdup(state, sizeof(*state), GFP_KERNEL);
7433 
7434 	if (!new_state)
7435 		return NULL;
7436 
7437 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
7438 
7439 	new_state->freesync_capable = state->freesync_capable;
7440 	new_state->abm_level = state->abm_level;
7441 	new_state->scaling = state->scaling;
7442 	new_state->underscan_enable = state->underscan_enable;
7443 	new_state->underscan_hborder = state->underscan_hborder;
7444 	new_state->underscan_vborder = state->underscan_vborder;
7445 	new_state->vcpi_slots = state->vcpi_slots;
7446 	new_state->pbn = state->pbn;
7447 	return &new_state->base;
7448 }
7449 
7450 static int
7451 amdgpu_dm_connector_late_register(struct drm_connector *connector)
7452 {
7453 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7454 		to_amdgpu_dm_connector(connector);
7455 	int r;
7456 
7457 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
7458 		r = sysfs_create_group(&connector->kdev->kobj,
7459 				       &amdgpu_group);
7460 		if (r)
7461 			return r;
7462 	}
7463 
7464 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
7465 
7466 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
7467 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
7468 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
7469 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
7470 		if (r)
7471 			return r;
7472 	}
7473 
7474 #if defined(CONFIG_DEBUG_FS)
7475 	connector_debugfs_init(amdgpu_dm_connector);
7476 #endif
7477 
7478 	return 0;
7479 }
7480 
7481 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
7482 {
7483 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7484 	struct dc_link *dc_link = aconnector->dc_link;
7485 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
7486 	const struct drm_edid *drm_edid;
7487 	struct i2c_adapter *ddc;
7488 	struct drm_device *dev = connector->dev;
7489 
7490 	if (dc_link && dc_link->aux_mode)
7491 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7492 	else
7493 		ddc = &aconnector->i2c->base;
7494 
7495 	drm_edid = drm_edid_read_ddc(connector, ddc);
7496 	drm_edid_connector_update(connector, drm_edid);
7497 	if (!drm_edid) {
7498 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
7499 		return;
7500 	}
7501 
7502 	aconnector->drm_edid = drm_edid;
7503 	/* Update emulated (virtual) sink's EDID */
7504 	if (dc_em_sink && dc_link) {
7505 		// FIXME: Get rid of drm_edid_raw()
7506 		const struct edid *edid = drm_edid_raw(drm_edid);
7507 
7508 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
7509 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
7510 			(edid->extensions + 1) * EDID_LENGTH);
7511 		dm_helpers_parse_edid_caps(
7512 			dc_link,
7513 			&dc_em_sink->dc_edid,
7514 			&dc_em_sink->edid_caps);
7515 	}
7516 }
7517 
7518 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
7519 	.reset = amdgpu_dm_connector_funcs_reset,
7520 	.detect = amdgpu_dm_connector_detect,
7521 	.fill_modes = drm_helper_probe_single_connector_modes,
7522 	.destroy = amdgpu_dm_connector_destroy,
7523 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
7524 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
7525 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
7526 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
7527 	.late_register = amdgpu_dm_connector_late_register,
7528 	.early_unregister = amdgpu_dm_connector_unregister,
7529 	.force = amdgpu_dm_connector_funcs_force
7530 };
7531 
7532 static int get_modes(struct drm_connector *connector)
7533 {
7534 	return amdgpu_dm_connector_get_modes(connector);
7535 }
7536 
7537 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
7538 {
7539 	struct drm_connector *connector = &aconnector->base;
7540 	struct dc_link *dc_link = aconnector->dc_link;
7541 	struct dc_sink_init_data init_params = {
7542 			.link = aconnector->dc_link,
7543 			.sink_signal = SIGNAL_TYPE_VIRTUAL
7544 	};
7545 	const struct drm_edid *drm_edid;
7546 	const struct edid *edid;
7547 	struct i2c_adapter *ddc;
7548 
7549 	if (dc_link && dc_link->aux_mode)
7550 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7551 	else
7552 		ddc = &aconnector->i2c->base;
7553 
7554 	drm_edid = drm_edid_read_ddc(connector, ddc);
7555 	drm_edid_connector_update(connector, drm_edid);
7556 	if (!drm_edid) {
7557 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
7558 		return;
7559 	}
7560 
7561 	if (connector->display_info.is_hdmi)
7562 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
7563 
7564 	aconnector->drm_edid = drm_edid;
7565 
7566 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
7567 	aconnector->dc_em_sink = dc_link_add_remote_sink(
7568 		aconnector->dc_link,
7569 		(uint8_t *)edid,
7570 		(edid->extensions + 1) * EDID_LENGTH,
7571 		&init_params);
7572 
7573 	if (aconnector->base.force == DRM_FORCE_ON) {
7574 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
7575 		aconnector->dc_link->local_sink :
7576 		aconnector->dc_em_sink;
7577 		if (aconnector->dc_sink)
7578 			dc_sink_retain(aconnector->dc_sink);
7579 	}
7580 }
7581 
7582 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
7583 {
7584 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
7585 
7586 	/*
7587 	 * In case of headless boot with force on for DP managed connector
7588 	 * Those settings have to be != 0 to get initial modeset
7589 	 */
7590 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7591 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
7592 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
7593 	}
7594 
7595 	create_eml_sink(aconnector);
7596 }
7597 
7598 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
7599 						struct dc_stream_state *stream)
7600 {
7601 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
7602 	struct dc_plane_state *dc_plane_state = NULL;
7603 	struct dc_state *dc_state = NULL;
7604 
7605 	if (!stream)
7606 		goto cleanup;
7607 
7608 	dc_plane_state = dc_create_plane_state(dc);
7609 	if (!dc_plane_state)
7610 		goto cleanup;
7611 
7612 	dc_state = dc_state_create(dc, NULL);
7613 	if (!dc_state)
7614 		goto cleanup;
7615 
7616 	/* populate stream to plane */
7617 	dc_plane_state->src_rect.height  = stream->src.height;
7618 	dc_plane_state->src_rect.width   = stream->src.width;
7619 	dc_plane_state->dst_rect.height  = stream->src.height;
7620 	dc_plane_state->dst_rect.width   = stream->src.width;
7621 	dc_plane_state->clip_rect.height = stream->src.height;
7622 	dc_plane_state->clip_rect.width  = stream->src.width;
7623 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
7624 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
7625 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
7626 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
7627 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
7628 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
7629 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
7630 	dc_plane_state->rotation = ROTATION_ANGLE_0;
7631 	dc_plane_state->is_tiling_rotated = false;
7632 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
7633 
7634 	dc_result = dc_validate_stream(dc, stream);
7635 	if (dc_result == DC_OK)
7636 		dc_result = dc_validate_plane(dc, dc_plane_state);
7637 
7638 	if (dc_result == DC_OK)
7639 		dc_result = dc_state_add_stream(dc, dc_state, stream);
7640 
7641 	if (dc_result == DC_OK && !dc_state_add_plane(
7642 						dc,
7643 						stream,
7644 						dc_plane_state,
7645 						dc_state))
7646 		dc_result = DC_FAIL_ATTACH_SURFACES;
7647 
7648 	if (dc_result == DC_OK)
7649 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
7650 
7651 cleanup:
7652 	if (dc_state)
7653 		dc_state_release(dc_state);
7654 
7655 	if (dc_plane_state)
7656 		dc_plane_state_release(dc_plane_state);
7657 
7658 	return dc_result;
7659 }
7660 
7661 struct dc_stream_state *
7662 create_validate_stream_for_sink(struct drm_connector *connector,
7663 				const struct drm_display_mode *drm_mode,
7664 				const struct dm_connector_state *dm_state,
7665 				const struct dc_stream_state *old_stream)
7666 {
7667 	struct amdgpu_dm_connector *aconnector = NULL;
7668 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7669 	struct dc_stream_state *stream;
7670 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
7671 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
7672 	enum dc_status dc_result = DC_OK;
7673 	uint8_t bpc_limit = 6;
7674 
7675 	if (!dm_state)
7676 		return NULL;
7677 
7678 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
7679 		aconnector = to_amdgpu_dm_connector(connector);
7680 
7681 	if (aconnector &&
7682 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7683 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
7684 		bpc_limit = 8;
7685 
7686 	do {
7687 		stream = create_stream_for_sink(connector, drm_mode,
7688 						dm_state, old_stream,
7689 						requested_bpc);
7690 		if (stream == NULL) {
7691 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
7692 			break;
7693 		}
7694 
7695 		dc_result = dc_validate_stream(adev->dm.dc, stream);
7696 
7697 		if (!aconnector) /* writeback connector */
7698 			return stream;
7699 
7700 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
7701 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
7702 
7703 		if (dc_result == DC_OK)
7704 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
7705 
7706 		if (dc_result != DC_OK) {
7707 			DRM_DEBUG_KMS("Pruned mode %d x %d (clk %d) %s %s -- %s\n",
7708 				      drm_mode->hdisplay,
7709 				      drm_mode->vdisplay,
7710 				      drm_mode->clock,
7711 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
7712 				      dc_color_depth_to_str(stream->timing.display_color_depth),
7713 				      dc_status_to_str(dc_result));
7714 
7715 			dc_stream_release(stream);
7716 			stream = NULL;
7717 			requested_bpc -= 2; /* lower bpc to retry validation */
7718 		}
7719 
7720 	} while (stream == NULL && requested_bpc >= bpc_limit);
7721 
7722 	if ((dc_result == DC_FAIL_ENC_VALIDATE ||
7723 	     dc_result == DC_EXCEED_DONGLE_CAP) &&
7724 	     !aconnector->force_yuv420_output) {
7725 		DRM_DEBUG_KMS("%s:%d Retry forcing yuv420 encoding\n",
7726 				     __func__, __LINE__);
7727 
7728 		aconnector->force_yuv420_output = true;
7729 		stream = create_validate_stream_for_sink(connector, drm_mode,
7730 						dm_state, old_stream);
7731 		aconnector->force_yuv420_output = false;
7732 	}
7733 
7734 	return stream;
7735 }
7736 
7737 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
7738 				   const struct drm_display_mode *mode)
7739 {
7740 	int result = MODE_ERROR;
7741 	struct dc_sink *dc_sink;
7742 	struct drm_display_mode *test_mode;
7743 	/* TODO: Unhardcode stream count */
7744 	struct dc_stream_state *stream;
7745 	/* we always have an amdgpu_dm_connector here since we got
7746 	 * here via the amdgpu_dm_connector_helper_funcs
7747 	 */
7748 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7749 
7750 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
7751 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
7752 		return result;
7753 
7754 	/*
7755 	 * Only run this the first time mode_valid is called to initilialize
7756 	 * EDID mgmt
7757 	 */
7758 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
7759 		!aconnector->dc_em_sink)
7760 		handle_edid_mgmt(aconnector);
7761 
7762 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
7763 
7764 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
7765 				aconnector->base.force != DRM_FORCE_ON) {
7766 		drm_err(connector->dev, "dc_sink is NULL!\n");
7767 		goto fail;
7768 	}
7769 
7770 	test_mode = drm_mode_duplicate(connector->dev, mode);
7771 	if (!test_mode)
7772 		goto fail;
7773 
7774 	drm_mode_set_crtcinfo(test_mode, 0);
7775 
7776 	stream = create_validate_stream_for_sink(connector, test_mode,
7777 						 to_dm_connector_state(connector->state),
7778 						 NULL);
7779 	drm_mode_destroy(connector->dev, test_mode);
7780 	if (stream) {
7781 		dc_stream_release(stream);
7782 		result = MODE_OK;
7783 	}
7784 
7785 fail:
7786 	/* TODO: error handling*/
7787 	return result;
7788 }
7789 
7790 static int fill_hdr_info_packet(const struct drm_connector_state *state,
7791 				struct dc_info_packet *out)
7792 {
7793 	struct hdmi_drm_infoframe frame;
7794 	unsigned char buf[30]; /* 26 + 4 */
7795 	ssize_t len;
7796 	int ret, i;
7797 
7798 	memset(out, 0, sizeof(*out));
7799 
7800 	if (!state->hdr_output_metadata)
7801 		return 0;
7802 
7803 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
7804 	if (ret)
7805 		return ret;
7806 
7807 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
7808 	if (len < 0)
7809 		return (int)len;
7810 
7811 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
7812 	if (len != 30)
7813 		return -EINVAL;
7814 
7815 	/* Prepare the infopacket for DC. */
7816 	switch (state->connector->connector_type) {
7817 	case DRM_MODE_CONNECTOR_HDMIA:
7818 		out->hb0 = 0x87; /* type */
7819 		out->hb1 = 0x01; /* version */
7820 		out->hb2 = 0x1A; /* length */
7821 		out->sb[0] = buf[3]; /* checksum */
7822 		i = 1;
7823 		break;
7824 
7825 	case DRM_MODE_CONNECTOR_DisplayPort:
7826 	case DRM_MODE_CONNECTOR_eDP:
7827 		out->hb0 = 0x00; /* sdp id, zero */
7828 		out->hb1 = 0x87; /* type */
7829 		out->hb2 = 0x1D; /* payload len - 1 */
7830 		out->hb3 = (0x13 << 2); /* sdp version */
7831 		out->sb[0] = 0x01; /* version */
7832 		out->sb[1] = 0x1A; /* length */
7833 		i = 2;
7834 		break;
7835 
7836 	default:
7837 		return -EINVAL;
7838 	}
7839 
7840 	memcpy(&out->sb[i], &buf[4], 26);
7841 	out->valid = true;
7842 
7843 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
7844 		       sizeof(out->sb), false);
7845 
7846 	return 0;
7847 }
7848 
7849 static int
7850 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
7851 				 struct drm_atomic_state *state)
7852 {
7853 	struct drm_connector_state *new_con_state =
7854 		drm_atomic_get_new_connector_state(state, conn);
7855 	struct drm_connector_state *old_con_state =
7856 		drm_atomic_get_old_connector_state(state, conn);
7857 	struct drm_crtc *crtc = new_con_state->crtc;
7858 	struct drm_crtc_state *new_crtc_state;
7859 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
7860 	int ret;
7861 
7862 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
7863 		return -EINVAL;
7864 
7865 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
7866 
7867 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
7868 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
7869 		if (ret < 0)
7870 			return ret;
7871 	}
7872 
7873 	if (!crtc)
7874 		return 0;
7875 
7876 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
7877 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7878 		if (IS_ERR(new_crtc_state))
7879 			return PTR_ERR(new_crtc_state);
7880 
7881 		new_crtc_state->mode_changed = true;
7882 	}
7883 
7884 	if (new_con_state->colorspace != old_con_state->colorspace) {
7885 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7886 		if (IS_ERR(new_crtc_state))
7887 			return PTR_ERR(new_crtc_state);
7888 
7889 		new_crtc_state->mode_changed = true;
7890 	}
7891 
7892 	if (new_con_state->content_type != old_con_state->content_type) {
7893 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7894 		if (IS_ERR(new_crtc_state))
7895 			return PTR_ERR(new_crtc_state);
7896 
7897 		new_crtc_state->mode_changed = true;
7898 	}
7899 
7900 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
7901 		struct dc_info_packet hdr_infopacket;
7902 
7903 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
7904 		if (ret)
7905 			return ret;
7906 
7907 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
7908 		if (IS_ERR(new_crtc_state))
7909 			return PTR_ERR(new_crtc_state);
7910 
7911 		/*
7912 		 * DC considers the stream backends changed if the
7913 		 * static metadata changes. Forcing the modeset also
7914 		 * gives a simple way for userspace to switch from
7915 		 * 8bpc to 10bpc when setting the metadata to enter
7916 		 * or exit HDR.
7917 		 *
7918 		 * Changing the static metadata after it's been
7919 		 * set is permissible, however. So only force a
7920 		 * modeset if we're entering or exiting HDR.
7921 		 */
7922 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
7923 			!old_con_state->hdr_output_metadata ||
7924 			!new_con_state->hdr_output_metadata;
7925 	}
7926 
7927 	return 0;
7928 }
7929 
7930 static const struct drm_connector_helper_funcs
7931 amdgpu_dm_connector_helper_funcs = {
7932 	/*
7933 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
7934 	 * modes will be filtered by drm_mode_validate_size(), and those modes
7935 	 * are missing after user start lightdm. So we need to renew modes list.
7936 	 * in get_modes call back, not just return the modes count
7937 	 */
7938 	.get_modes = get_modes,
7939 	.mode_valid = amdgpu_dm_connector_mode_valid,
7940 	.atomic_check = amdgpu_dm_connector_atomic_check,
7941 };
7942 
7943 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
7944 {
7945 
7946 }
7947 
7948 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
7949 {
7950 	switch (display_color_depth) {
7951 	case COLOR_DEPTH_666:
7952 		return 6;
7953 	case COLOR_DEPTH_888:
7954 		return 8;
7955 	case COLOR_DEPTH_101010:
7956 		return 10;
7957 	case COLOR_DEPTH_121212:
7958 		return 12;
7959 	case COLOR_DEPTH_141414:
7960 		return 14;
7961 	case COLOR_DEPTH_161616:
7962 		return 16;
7963 	default:
7964 		break;
7965 	}
7966 	return 0;
7967 }
7968 
7969 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
7970 					  struct drm_crtc_state *crtc_state,
7971 					  struct drm_connector_state *conn_state)
7972 {
7973 	struct drm_atomic_state *state = crtc_state->state;
7974 	struct drm_connector *connector = conn_state->connector;
7975 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7976 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
7977 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
7978 	struct drm_dp_mst_topology_mgr *mst_mgr;
7979 	struct drm_dp_mst_port *mst_port;
7980 	struct drm_dp_mst_topology_state *mst_state;
7981 	enum dc_color_depth color_depth;
7982 	int clock, bpp = 0;
7983 	bool is_y420 = false;
7984 
7985 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
7986 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
7987 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
7988 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
7989 		enum drm_mode_status result;
7990 
7991 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
7992 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
7993 			drm_dbg_driver(encoder->dev,
7994 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
7995 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
7996 				       drm_mode_vrefresh(adjusted_mode));
7997 			dm_new_connector_state->scaling = RMX_FULL;
7998 		}
7999 		return 0;
8000 	}
8001 
8002 	if (!aconnector->mst_output_port)
8003 		return 0;
8004 
8005 	mst_port = aconnector->mst_output_port;
8006 	mst_mgr = &aconnector->mst_root->mst_mgr;
8007 
8008 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8009 		return 0;
8010 
8011 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8012 	if (IS_ERR(mst_state))
8013 		return PTR_ERR(mst_state);
8014 
8015 	mst_state->pbn_div.full = dfixed_const(dm_mst_get_pbn_divider(aconnector->mst_root->dc_link));
8016 
8017 	if (!state->duplicated) {
8018 		int max_bpc = conn_state->max_requested_bpc;
8019 
8020 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8021 			  aconnector->force_yuv420_output;
8022 		color_depth = convert_color_depth_from_display_info(connector,
8023 								    is_y420,
8024 								    max_bpc);
8025 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8026 		clock = adjusted_mode->clock;
8027 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8028 	}
8029 
8030 	dm_new_connector_state->vcpi_slots =
8031 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8032 					      dm_new_connector_state->pbn);
8033 	if (dm_new_connector_state->vcpi_slots < 0) {
8034 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8035 		return dm_new_connector_state->vcpi_slots;
8036 	}
8037 	return 0;
8038 }
8039 
8040 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8041 	.disable = dm_encoder_helper_disable,
8042 	.atomic_check = dm_encoder_helper_atomic_check
8043 };
8044 
8045 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8046 					    struct dc_state *dc_state,
8047 					    struct dsc_mst_fairness_vars *vars)
8048 {
8049 	struct dc_stream_state *stream = NULL;
8050 	struct drm_connector *connector;
8051 	struct drm_connector_state *new_con_state;
8052 	struct amdgpu_dm_connector *aconnector;
8053 	struct dm_connector_state *dm_conn_state;
8054 	int i, j, ret;
8055 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8056 
8057 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8058 
8059 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8060 			continue;
8061 
8062 		aconnector = to_amdgpu_dm_connector(connector);
8063 
8064 		if (!aconnector->mst_output_port)
8065 			continue;
8066 
8067 		if (!new_con_state || !new_con_state->crtc)
8068 			continue;
8069 
8070 		dm_conn_state = to_dm_connector_state(new_con_state);
8071 
8072 		for (j = 0; j < dc_state->stream_count; j++) {
8073 			stream = dc_state->streams[j];
8074 			if (!stream)
8075 				continue;
8076 
8077 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8078 				break;
8079 
8080 			stream = NULL;
8081 		}
8082 
8083 		if (!stream)
8084 			continue;
8085 
8086 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8087 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8088 		for (j = 0; j < dc_state->stream_count; j++) {
8089 			if (vars[j].aconnector == aconnector) {
8090 				pbn = vars[j].pbn;
8091 				break;
8092 			}
8093 		}
8094 
8095 		if (j == dc_state->stream_count || pbn_div == 0)
8096 			continue;
8097 
8098 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8099 
8100 		if (stream->timing.flags.DSC != 1) {
8101 			dm_conn_state->pbn = pbn;
8102 			dm_conn_state->vcpi_slots = slot_num;
8103 
8104 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8105 							   dm_conn_state->pbn, false);
8106 			if (ret < 0)
8107 				return ret;
8108 
8109 			continue;
8110 		}
8111 
8112 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8113 		if (vcpi < 0)
8114 			return vcpi;
8115 
8116 		dm_conn_state->pbn = pbn;
8117 		dm_conn_state->vcpi_slots = vcpi;
8118 	}
8119 	return 0;
8120 }
8121 
8122 static int to_drm_connector_type(enum signal_type st)
8123 {
8124 	switch (st) {
8125 	case SIGNAL_TYPE_HDMI_TYPE_A:
8126 		return DRM_MODE_CONNECTOR_HDMIA;
8127 	case SIGNAL_TYPE_EDP:
8128 		return DRM_MODE_CONNECTOR_eDP;
8129 	case SIGNAL_TYPE_LVDS:
8130 		return DRM_MODE_CONNECTOR_LVDS;
8131 	case SIGNAL_TYPE_RGB:
8132 		return DRM_MODE_CONNECTOR_VGA;
8133 	case SIGNAL_TYPE_DISPLAY_PORT:
8134 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8135 		return DRM_MODE_CONNECTOR_DisplayPort;
8136 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8137 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8138 		return DRM_MODE_CONNECTOR_DVID;
8139 	case SIGNAL_TYPE_VIRTUAL:
8140 		return DRM_MODE_CONNECTOR_VIRTUAL;
8141 
8142 	default:
8143 		return DRM_MODE_CONNECTOR_Unknown;
8144 	}
8145 }
8146 
8147 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8148 {
8149 	struct drm_encoder *encoder;
8150 
8151 	/* There is only one encoder per connector */
8152 	drm_connector_for_each_possible_encoder(connector, encoder)
8153 		return encoder;
8154 
8155 	return NULL;
8156 }
8157 
8158 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8159 {
8160 	struct drm_encoder *encoder;
8161 	struct amdgpu_encoder *amdgpu_encoder;
8162 
8163 	encoder = amdgpu_dm_connector_to_encoder(connector);
8164 
8165 	if (encoder == NULL)
8166 		return;
8167 
8168 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8169 
8170 	amdgpu_encoder->native_mode.clock = 0;
8171 
8172 	if (!list_empty(&connector->probed_modes)) {
8173 		struct drm_display_mode *preferred_mode = NULL;
8174 
8175 		list_for_each_entry(preferred_mode,
8176 				    &connector->probed_modes,
8177 				    head) {
8178 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8179 				amdgpu_encoder->native_mode = *preferred_mode;
8180 
8181 			break;
8182 		}
8183 
8184 	}
8185 }
8186 
8187 static struct drm_display_mode *
8188 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8189 			     char *name,
8190 			     int hdisplay, int vdisplay)
8191 {
8192 	struct drm_device *dev = encoder->dev;
8193 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8194 	struct drm_display_mode *mode = NULL;
8195 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8196 
8197 	mode = drm_mode_duplicate(dev, native_mode);
8198 
8199 	if (mode == NULL)
8200 		return NULL;
8201 
8202 	mode->hdisplay = hdisplay;
8203 	mode->vdisplay = vdisplay;
8204 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8205 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8206 
8207 	return mode;
8208 
8209 }
8210 
8211 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8212 						 struct drm_connector *connector)
8213 {
8214 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8215 	struct drm_display_mode *mode = NULL;
8216 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8217 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8218 				to_amdgpu_dm_connector(connector);
8219 	int i;
8220 	int n;
8221 	struct mode_size {
8222 		char name[DRM_DISPLAY_MODE_LEN];
8223 		int w;
8224 		int h;
8225 	} common_modes[] = {
8226 		{  "640x480",  640,  480},
8227 		{  "800x600",  800,  600},
8228 		{ "1024x768", 1024,  768},
8229 		{ "1280x720", 1280,  720},
8230 		{ "1280x800", 1280,  800},
8231 		{"1280x1024", 1280, 1024},
8232 		{ "1440x900", 1440,  900},
8233 		{"1680x1050", 1680, 1050},
8234 		{"1600x1200", 1600, 1200},
8235 		{"1920x1080", 1920, 1080},
8236 		{"1920x1200", 1920, 1200}
8237 	};
8238 
8239 	n = ARRAY_SIZE(common_modes);
8240 
8241 	for (i = 0; i < n; i++) {
8242 		struct drm_display_mode *curmode = NULL;
8243 		bool mode_existed = false;
8244 
8245 		if (common_modes[i].w > native_mode->hdisplay ||
8246 		    common_modes[i].h > native_mode->vdisplay ||
8247 		   (common_modes[i].w == native_mode->hdisplay &&
8248 		    common_modes[i].h == native_mode->vdisplay))
8249 			continue;
8250 
8251 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8252 			if (common_modes[i].w == curmode->hdisplay &&
8253 			    common_modes[i].h == curmode->vdisplay) {
8254 				mode_existed = true;
8255 				break;
8256 			}
8257 		}
8258 
8259 		if (mode_existed)
8260 			continue;
8261 
8262 		mode = amdgpu_dm_create_common_mode(encoder,
8263 				common_modes[i].name, common_modes[i].w,
8264 				common_modes[i].h);
8265 		if (!mode)
8266 			continue;
8267 
8268 		drm_mode_probed_add(connector, mode);
8269 		amdgpu_dm_connector->num_modes++;
8270 	}
8271 }
8272 
8273 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8274 {
8275 	struct drm_encoder *encoder;
8276 	struct amdgpu_encoder *amdgpu_encoder;
8277 	const struct drm_display_mode *native_mode;
8278 
8279 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8280 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8281 		return;
8282 
8283 	mutex_lock(&connector->dev->mode_config.mutex);
8284 	amdgpu_dm_connector_get_modes(connector);
8285 	mutex_unlock(&connector->dev->mode_config.mutex);
8286 
8287 	encoder = amdgpu_dm_connector_to_encoder(connector);
8288 	if (!encoder)
8289 		return;
8290 
8291 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8292 
8293 	native_mode = &amdgpu_encoder->native_mode;
8294 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8295 		return;
8296 
8297 	drm_connector_set_panel_orientation_with_quirk(connector,
8298 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8299 						       native_mode->hdisplay,
8300 						       native_mode->vdisplay);
8301 }
8302 
8303 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8304 					      const struct drm_edid *drm_edid)
8305 {
8306 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8307 			to_amdgpu_dm_connector(connector);
8308 
8309 	if (drm_edid) {
8310 		/* empty probed_modes */
8311 		INIT_LIST_HEAD(&connector->probed_modes);
8312 		amdgpu_dm_connector->num_modes =
8313 				drm_edid_connector_add_modes(connector);
8314 
8315 		/* sorting the probed modes before calling function
8316 		 * amdgpu_dm_get_native_mode() since EDID can have
8317 		 * more than one preferred mode. The modes that are
8318 		 * later in the probed mode list could be of higher
8319 		 * and preferred resolution. For example, 3840x2160
8320 		 * resolution in base EDID preferred timing and 4096x2160
8321 		 * preferred resolution in DID extension block later.
8322 		 */
8323 		drm_mode_sort(&connector->probed_modes);
8324 		amdgpu_dm_get_native_mode(connector);
8325 
8326 		/* Freesync capabilities are reset by calling
8327 		 * drm_edid_connector_add_modes() and need to be
8328 		 * restored here.
8329 		 */
8330 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8331 	} else {
8332 		amdgpu_dm_connector->num_modes = 0;
8333 	}
8334 }
8335 
8336 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8337 			      struct drm_display_mode *mode)
8338 {
8339 	struct drm_display_mode *m;
8340 
8341 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8342 		if (drm_mode_equal(m, mode))
8343 			return true;
8344 	}
8345 
8346 	return false;
8347 }
8348 
8349 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8350 {
8351 	const struct drm_display_mode *m;
8352 	struct drm_display_mode *new_mode;
8353 	uint i;
8354 	u32 new_modes_count = 0;
8355 
8356 	/* Standard FPS values
8357 	 *
8358 	 * 23.976       - TV/NTSC
8359 	 * 24           - Cinema
8360 	 * 25           - TV/PAL
8361 	 * 29.97        - TV/NTSC
8362 	 * 30           - TV/NTSC
8363 	 * 48           - Cinema HFR
8364 	 * 50           - TV/PAL
8365 	 * 60           - Commonly used
8366 	 * 48,72,96,120 - Multiples of 24
8367 	 */
8368 	static const u32 common_rates[] = {
8369 		23976, 24000, 25000, 29970, 30000,
8370 		48000, 50000, 60000, 72000, 96000, 120000
8371 	};
8372 
8373 	/*
8374 	 * Find mode with highest refresh rate with the same resolution
8375 	 * as the preferred mode. Some monitors report a preferred mode
8376 	 * with lower resolution than the highest refresh rate supported.
8377 	 */
8378 
8379 	m = get_highest_refresh_rate_mode(aconnector, true);
8380 	if (!m)
8381 		return 0;
8382 
8383 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8384 		u64 target_vtotal, target_vtotal_diff;
8385 		u64 num, den;
8386 
8387 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8388 			continue;
8389 
8390 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8391 		    common_rates[i] > aconnector->max_vfreq * 1000)
8392 			continue;
8393 
8394 		num = (unsigned long long)m->clock * 1000 * 1000;
8395 		den = common_rates[i] * (unsigned long long)m->htotal;
8396 		target_vtotal = div_u64(num, den);
8397 		target_vtotal_diff = target_vtotal - m->vtotal;
8398 
8399 		/* Check for illegal modes */
8400 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8401 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8402 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8403 			continue;
8404 
8405 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8406 		if (!new_mode)
8407 			goto out;
8408 
8409 		new_mode->vtotal += (u16)target_vtotal_diff;
8410 		new_mode->vsync_start += (u16)target_vtotal_diff;
8411 		new_mode->vsync_end += (u16)target_vtotal_diff;
8412 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8413 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8414 
8415 		if (!is_duplicate_mode(aconnector, new_mode)) {
8416 			drm_mode_probed_add(&aconnector->base, new_mode);
8417 			new_modes_count += 1;
8418 		} else
8419 			drm_mode_destroy(aconnector->base.dev, new_mode);
8420 	}
8421  out:
8422 	return new_modes_count;
8423 }
8424 
8425 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8426 						   const struct drm_edid *drm_edid)
8427 {
8428 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8429 		to_amdgpu_dm_connector(connector);
8430 
8431 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8432 		return;
8433 
8434 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8435 		amdgpu_dm_connector->num_modes +=
8436 			add_fs_modes(amdgpu_dm_connector);
8437 }
8438 
8439 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8440 {
8441 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8442 			to_amdgpu_dm_connector(connector);
8443 	struct drm_encoder *encoder;
8444 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8445 	struct dc_link_settings *verified_link_cap =
8446 			&amdgpu_dm_connector->dc_link->verified_link_cap;
8447 	const struct dc *dc = amdgpu_dm_connector->dc_link->dc;
8448 
8449 	encoder = amdgpu_dm_connector_to_encoder(connector);
8450 
8451 	if (!drm_edid) {
8452 		amdgpu_dm_connector->num_modes =
8453 				drm_add_modes_noedid(connector, 640, 480);
8454 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8455 			amdgpu_dm_connector->num_modes +=
8456 				drm_add_modes_noedid(connector, 1920, 1080);
8457 	} else {
8458 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8459 		if (encoder)
8460 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8461 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8462 	}
8463 	amdgpu_dm_fbc_init(connector);
8464 
8465 	return amdgpu_dm_connector->num_modes;
8466 }
8467 
8468 static const u32 supported_colorspaces =
8469 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8470 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8471 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8472 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8473 
8474 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8475 				     struct amdgpu_dm_connector *aconnector,
8476 				     int connector_type,
8477 				     struct dc_link *link,
8478 				     int link_index)
8479 {
8480 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8481 
8482 	/*
8483 	 * Some of the properties below require access to state, like bpc.
8484 	 * Allocate some default initial connector state with our reset helper.
8485 	 */
8486 	if (aconnector->base.funcs->reset)
8487 		aconnector->base.funcs->reset(&aconnector->base);
8488 
8489 	aconnector->connector_id = link_index;
8490 	aconnector->bl_idx = -1;
8491 	aconnector->dc_link = link;
8492 	aconnector->base.interlace_allowed = false;
8493 	aconnector->base.doublescan_allowed = false;
8494 	aconnector->base.stereo_allowed = false;
8495 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8496 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8497 	aconnector->audio_inst = -1;
8498 	aconnector->pack_sdp_v1_3 = false;
8499 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8500 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8501 	mutex_init(&aconnector->hpd_lock);
8502 	mutex_init(&aconnector->handle_mst_msg_ready);
8503 
8504 	/*
8505 	 * configure support HPD hot plug connector_>polled default value is 0
8506 	 * which means HPD hot plug not supported
8507 	 */
8508 	switch (connector_type) {
8509 	case DRM_MODE_CONNECTOR_HDMIA:
8510 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8511 		aconnector->base.ycbcr_420_allowed =
8512 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
8513 		break;
8514 	case DRM_MODE_CONNECTOR_DisplayPort:
8515 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8516 		link->link_enc = link_enc_cfg_get_link_enc(link);
8517 		ASSERT(link->link_enc);
8518 		if (link->link_enc)
8519 			aconnector->base.ycbcr_420_allowed =
8520 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
8521 		break;
8522 	case DRM_MODE_CONNECTOR_DVID:
8523 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8524 		break;
8525 	default:
8526 		break;
8527 	}
8528 
8529 	drm_object_attach_property(&aconnector->base.base,
8530 				dm->ddev->mode_config.scaling_mode_property,
8531 				DRM_MODE_SCALE_NONE);
8532 
8533 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
8534 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
8535 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
8536 
8537 	drm_object_attach_property(&aconnector->base.base,
8538 				adev->mode_info.underscan_property,
8539 				UNDERSCAN_OFF);
8540 	drm_object_attach_property(&aconnector->base.base,
8541 				adev->mode_info.underscan_hborder_property,
8542 				0);
8543 	drm_object_attach_property(&aconnector->base.base,
8544 				adev->mode_info.underscan_vborder_property,
8545 				0);
8546 
8547 	if (!aconnector->mst_root)
8548 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
8549 
8550 	aconnector->base.state->max_bpc = 16;
8551 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
8552 
8553 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8554 		/* Content Type is currently only implemented for HDMI. */
8555 		drm_connector_attach_content_type_property(&aconnector->base);
8556 	}
8557 
8558 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
8559 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
8560 			drm_connector_attach_colorspace_property(&aconnector->base);
8561 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
8562 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
8563 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
8564 			drm_connector_attach_colorspace_property(&aconnector->base);
8565 	}
8566 
8567 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
8568 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
8569 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
8570 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
8571 
8572 		if (!aconnector->mst_root)
8573 			drm_connector_attach_vrr_capable_property(&aconnector->base);
8574 
8575 		if (adev->dm.hdcp_workqueue)
8576 			drm_connector_attach_content_protection_property(&aconnector->base, true);
8577 	}
8578 
8579 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
8580 		struct drm_privacy_screen *privacy_screen;
8581 
8582 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
8583 		if (!IS_ERR(privacy_screen)) {
8584 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
8585 								     privacy_screen);
8586 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
8587 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
8588 		}
8589 	}
8590 }
8591 
8592 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
8593 			      struct i2c_msg *msgs, int num)
8594 {
8595 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
8596 	struct ddc_service *ddc_service = i2c->ddc_service;
8597 	struct i2c_command cmd;
8598 	int i;
8599 	int result = -EIO;
8600 
8601 	if (!ddc_service->ddc_pin)
8602 		return result;
8603 
8604 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
8605 
8606 	if (!cmd.payloads)
8607 		return result;
8608 
8609 	cmd.number_of_payloads = num;
8610 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
8611 	cmd.speed = 100;
8612 
8613 	for (i = 0; i < num; i++) {
8614 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
8615 		cmd.payloads[i].address = msgs[i].addr;
8616 		cmd.payloads[i].length = msgs[i].len;
8617 		cmd.payloads[i].data = msgs[i].buf;
8618 	}
8619 
8620 	if (i2c->oem) {
8621 		if (dc_submit_i2c_oem(
8622 			    ddc_service->ctx->dc,
8623 			    &cmd))
8624 			result = num;
8625 	} else {
8626 		if (dc_submit_i2c(
8627 			    ddc_service->ctx->dc,
8628 			    ddc_service->link->link_index,
8629 			    &cmd))
8630 			result = num;
8631 	}
8632 
8633 	kfree(cmd.payloads);
8634 	return result;
8635 }
8636 
8637 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
8638 {
8639 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
8640 }
8641 
8642 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
8643 	.master_xfer = amdgpu_dm_i2c_xfer,
8644 	.functionality = amdgpu_dm_i2c_func,
8645 };
8646 
8647 static struct amdgpu_i2c_adapter *
8648 create_i2c(struct ddc_service *ddc_service, bool oem)
8649 {
8650 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
8651 	struct amdgpu_i2c_adapter *i2c;
8652 
8653 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
8654 	if (!i2c)
8655 		return NULL;
8656 	i2c->base.owner = THIS_MODULE;
8657 	i2c->base.dev.parent = &adev->pdev->dev;
8658 	i2c->base.algo = &amdgpu_dm_i2c_algo;
8659 	if (oem)
8660 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
8661 	else
8662 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
8663 			 ddc_service->link->link_index);
8664 	i2c_set_adapdata(&i2c->base, i2c);
8665 	i2c->ddc_service = ddc_service;
8666 	i2c->oem = oem;
8667 
8668 	return i2c;
8669 }
8670 
8671 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
8672 {
8673 	struct cec_connector_info conn_info;
8674 	struct drm_device *ddev = aconnector->base.dev;
8675 	struct device *hdmi_dev = ddev->dev;
8676 
8677 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
8678 		drm_info(ddev, "HDMI-CEC feature masked\n");
8679 		return -EINVAL;
8680 	}
8681 
8682 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
8683 	aconnector->notifier =
8684 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
8685 	if (!aconnector->notifier) {
8686 		drm_err(ddev, "Failed to create cec notifier\n");
8687 		return -ENOMEM;
8688 	}
8689 
8690 	return 0;
8691 }
8692 
8693 /*
8694  * Note: this function assumes that dc_link_detect() was called for the
8695  * dc_link which will be represented by this aconnector.
8696  */
8697 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
8698 				    struct amdgpu_dm_connector *aconnector,
8699 				    u32 link_index,
8700 				    struct amdgpu_encoder *aencoder)
8701 {
8702 	int res = 0;
8703 	int connector_type;
8704 	struct dc *dc = dm->dc;
8705 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
8706 	struct amdgpu_i2c_adapter *i2c;
8707 
8708 	/* Not needed for writeback connector */
8709 	link->priv = aconnector;
8710 
8711 
8712 	i2c = create_i2c(link->ddc, false);
8713 	if (!i2c) {
8714 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
8715 		return -ENOMEM;
8716 	}
8717 
8718 	aconnector->i2c = i2c;
8719 	res = i2c_add_adapter(&i2c->base);
8720 
8721 	if (res) {
8722 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
8723 		goto out_free;
8724 	}
8725 
8726 	connector_type = to_drm_connector_type(link->connector_signal);
8727 
8728 	res = drm_connector_init_with_ddc(
8729 			dm->ddev,
8730 			&aconnector->base,
8731 			&amdgpu_dm_connector_funcs,
8732 			connector_type,
8733 			&i2c->base);
8734 
8735 	if (res) {
8736 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
8737 		aconnector->connector_id = -1;
8738 		goto out_free;
8739 	}
8740 
8741 	drm_connector_helper_add(
8742 			&aconnector->base,
8743 			&amdgpu_dm_connector_helper_funcs);
8744 
8745 	amdgpu_dm_connector_init_helper(
8746 		dm,
8747 		aconnector,
8748 		connector_type,
8749 		link,
8750 		link_index);
8751 
8752 	drm_connector_attach_encoder(
8753 		&aconnector->base, &aencoder->base);
8754 
8755 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
8756 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
8757 		amdgpu_dm_initialize_hdmi_connector(aconnector);
8758 
8759 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
8760 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
8761 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
8762 
8763 out_free:
8764 	if (res) {
8765 		kfree(i2c);
8766 		aconnector->i2c = NULL;
8767 	}
8768 	return res;
8769 }
8770 
8771 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
8772 {
8773 	switch (adev->mode_info.num_crtc) {
8774 	case 1:
8775 		return 0x1;
8776 	case 2:
8777 		return 0x3;
8778 	case 3:
8779 		return 0x7;
8780 	case 4:
8781 		return 0xf;
8782 	case 5:
8783 		return 0x1f;
8784 	case 6:
8785 	default:
8786 		return 0x3f;
8787 	}
8788 }
8789 
8790 static int amdgpu_dm_encoder_init(struct drm_device *dev,
8791 				  struct amdgpu_encoder *aencoder,
8792 				  uint32_t link_index)
8793 {
8794 	struct amdgpu_device *adev = drm_to_adev(dev);
8795 
8796 	int res = drm_encoder_init(dev,
8797 				   &aencoder->base,
8798 				   &amdgpu_dm_encoder_funcs,
8799 				   DRM_MODE_ENCODER_TMDS,
8800 				   NULL);
8801 
8802 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
8803 
8804 	if (!res)
8805 		aencoder->encoder_id = link_index;
8806 	else
8807 		aencoder->encoder_id = -1;
8808 
8809 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
8810 
8811 	return res;
8812 }
8813 
8814 static void manage_dm_interrupts(struct amdgpu_device *adev,
8815 				 struct amdgpu_crtc *acrtc,
8816 				 struct dm_crtc_state *acrtc_state)
8817 {
8818 	struct drm_vblank_crtc_config config = {0};
8819 	struct dc_crtc_timing *timing;
8820 	int offdelay;
8821 
8822 	if (acrtc_state) {
8823 		timing = &acrtc_state->stream->timing;
8824 
8825 		/*
8826 		 * Depending on when the HW latching event of double-buffered
8827 		 * registers happen relative to the PSR SDP deadline, and how
8828 		 * bad the Panel clock has drifted since the last ALPM off
8829 		 * event, there can be up to 3 frames of delay between sending
8830 		 * the PSR exit cmd to DMUB fw, and when the panel starts
8831 		 * displaying live frames.
8832 		 *
8833 		 * We can set:
8834 		 *
8835 		 * 20/100 * offdelay_ms = 3_frames_ms
8836 		 * => offdelay_ms = 5 * 3_frames_ms
8837 		 *
8838 		 * This ensures that `3_frames_ms` will only be experienced as a
8839 		 * 20% delay on top how long the display has been static, and
8840 		 * thus make the delay less perceivable.
8841 		 */
8842 		if (acrtc_state->stream->link->psr_settings.psr_version <
8843 		    DC_PSR_VERSION_UNSUPPORTED) {
8844 			offdelay = DIV64_U64_ROUND_UP((u64)5 * 3 * 10 *
8845 						      timing->v_total *
8846 						      timing->h_total,
8847 						      timing->pix_clk_100hz);
8848 			config.offdelay_ms = offdelay ?: 30;
8849 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
8850 			   IP_VERSION(3, 5, 0) ||
8851 			   !(adev->flags & AMD_IS_APU)) {
8852 			/*
8853 			 * Older HW and DGPU have issues with instant off;
8854 			 * use a 2 frame offdelay.
8855 			 */
8856 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
8857 						      timing->v_total *
8858 						      timing->h_total,
8859 						      timing->pix_clk_100hz);
8860 
8861 			config.offdelay_ms = offdelay ?: 30;
8862 		} else {
8863 			/* offdelay_ms = 0 will never disable vblank */
8864 			config.offdelay_ms = 1;
8865 			config.disable_immediate = true;
8866 		}
8867 
8868 		drm_crtc_vblank_on_config(&acrtc->base,
8869 					  &config);
8870 	} else {
8871 		drm_crtc_vblank_off(&acrtc->base);
8872 	}
8873 }
8874 
8875 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
8876 				      struct amdgpu_crtc *acrtc)
8877 {
8878 	int irq_type =
8879 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
8880 
8881 	/**
8882 	 * This reads the current state for the IRQ and force reapplies
8883 	 * the setting to hardware.
8884 	 */
8885 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
8886 }
8887 
8888 static bool
8889 is_scaling_state_different(const struct dm_connector_state *dm_state,
8890 			   const struct dm_connector_state *old_dm_state)
8891 {
8892 	if (dm_state->scaling != old_dm_state->scaling)
8893 		return true;
8894 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
8895 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
8896 			return true;
8897 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
8898 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
8899 			return true;
8900 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
8901 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
8902 		return true;
8903 	return false;
8904 }
8905 
8906 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
8907 					    struct drm_crtc_state *old_crtc_state,
8908 					    struct drm_connector_state *new_conn_state,
8909 					    struct drm_connector_state *old_conn_state,
8910 					    const struct drm_connector *connector,
8911 					    struct hdcp_workqueue *hdcp_w)
8912 {
8913 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8914 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
8915 
8916 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8917 		connector->index, connector->status, connector->dpms);
8918 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8919 		old_conn_state->content_protection, new_conn_state->content_protection);
8920 
8921 	if (old_crtc_state)
8922 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8923 		old_crtc_state->enable,
8924 		old_crtc_state->active,
8925 		old_crtc_state->mode_changed,
8926 		old_crtc_state->active_changed,
8927 		old_crtc_state->connectors_changed);
8928 
8929 	if (new_crtc_state)
8930 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8931 		new_crtc_state->enable,
8932 		new_crtc_state->active,
8933 		new_crtc_state->mode_changed,
8934 		new_crtc_state->active_changed,
8935 		new_crtc_state->connectors_changed);
8936 
8937 	/* hdcp content type change */
8938 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
8939 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
8940 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8941 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
8942 		return true;
8943 	}
8944 
8945 	/* CP is being re enabled, ignore this */
8946 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
8947 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
8948 		if (new_crtc_state && new_crtc_state->mode_changed) {
8949 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8950 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
8951 			return true;
8952 		}
8953 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
8954 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
8955 		return false;
8956 	}
8957 
8958 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
8959 	 *
8960 	 * Handles:	UNDESIRED -> ENABLED
8961 	 */
8962 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
8963 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
8964 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8965 
8966 	/* Stream removed and re-enabled
8967 	 *
8968 	 * Can sometimes overlap with the HPD case,
8969 	 * thus set update_hdcp to false to avoid
8970 	 * setting HDCP multiple times.
8971 	 *
8972 	 * Handles:	DESIRED -> DESIRED (Special case)
8973 	 */
8974 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
8975 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
8976 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
8977 		dm_con_state->update_hdcp = false;
8978 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
8979 			__func__);
8980 		return true;
8981 	}
8982 
8983 	/* Hot-plug, headless s3, dpms
8984 	 *
8985 	 * Only start HDCP if the display is connected/enabled.
8986 	 * update_hdcp flag will be set to false until the next
8987 	 * HPD comes in.
8988 	 *
8989 	 * Handles:	DESIRED -> DESIRED (Special case)
8990 	 */
8991 	if (dm_con_state->update_hdcp &&
8992 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
8993 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
8994 		dm_con_state->update_hdcp = false;
8995 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
8996 			__func__);
8997 		return true;
8998 	}
8999 
9000 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9001 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9002 			if (new_crtc_state && new_crtc_state->mode_changed) {
9003 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9004 					__func__);
9005 				return true;
9006 			}
9007 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9008 				__func__);
9009 			return false;
9010 		}
9011 
9012 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9013 		return false;
9014 	}
9015 
9016 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9017 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9018 			__func__);
9019 		return true;
9020 	}
9021 
9022 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9023 	return false;
9024 }
9025 
9026 static void remove_stream(struct amdgpu_device *adev,
9027 			  struct amdgpu_crtc *acrtc,
9028 			  struct dc_stream_state *stream)
9029 {
9030 	/* this is the update mode case */
9031 
9032 	acrtc->otg_inst = -1;
9033 	acrtc->enabled = false;
9034 }
9035 
9036 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9037 {
9038 
9039 	assert_spin_locked(&acrtc->base.dev->event_lock);
9040 	WARN_ON(acrtc->event);
9041 
9042 	acrtc->event = acrtc->base.state->event;
9043 
9044 	/* Set the flip status */
9045 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9046 
9047 	/* Mark this event as consumed */
9048 	acrtc->base.state->event = NULL;
9049 
9050 	drm_dbg_state(acrtc->base.dev,
9051 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9052 		      acrtc->crtc_id);
9053 }
9054 
9055 static void update_freesync_state_on_stream(
9056 	struct amdgpu_display_manager *dm,
9057 	struct dm_crtc_state *new_crtc_state,
9058 	struct dc_stream_state *new_stream,
9059 	struct dc_plane_state *surface,
9060 	u32 flip_timestamp_in_us)
9061 {
9062 	struct mod_vrr_params vrr_params;
9063 	struct dc_info_packet vrr_infopacket = {0};
9064 	struct amdgpu_device *adev = dm->adev;
9065 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9066 	unsigned long flags;
9067 	bool pack_sdp_v1_3 = false;
9068 	struct amdgpu_dm_connector *aconn;
9069 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9070 
9071 	if (!new_stream)
9072 		return;
9073 
9074 	/*
9075 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9076 	 * For now it's sufficient to just guard against these conditions.
9077 	 */
9078 
9079 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9080 		return;
9081 
9082 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9083 	vrr_params = acrtc->dm_irq_params.vrr_params;
9084 
9085 	if (surface) {
9086 		mod_freesync_handle_preflip(
9087 			dm->freesync_module,
9088 			surface,
9089 			new_stream,
9090 			flip_timestamp_in_us,
9091 			&vrr_params);
9092 
9093 		if (adev->family < AMDGPU_FAMILY_AI &&
9094 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9095 			mod_freesync_handle_v_update(dm->freesync_module,
9096 						     new_stream, &vrr_params);
9097 
9098 			/* Need to call this before the frame ends. */
9099 			dc_stream_adjust_vmin_vmax(dm->dc,
9100 						   new_crtc_state->stream,
9101 						   &vrr_params.adjust);
9102 		}
9103 	}
9104 
9105 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9106 
9107 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9108 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9109 
9110 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9111 			packet_type = PACKET_TYPE_FS_V1;
9112 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9113 			packet_type = PACKET_TYPE_FS_V2;
9114 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9115 			packet_type = PACKET_TYPE_FS_V3;
9116 
9117 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9118 					&new_stream->adaptive_sync_infopacket);
9119 	}
9120 
9121 	mod_freesync_build_vrr_infopacket(
9122 		dm->freesync_module,
9123 		new_stream,
9124 		&vrr_params,
9125 		packet_type,
9126 		TRANSFER_FUNC_UNKNOWN,
9127 		&vrr_infopacket,
9128 		pack_sdp_v1_3);
9129 
9130 	new_crtc_state->freesync_vrr_info_changed |=
9131 		(memcmp(&new_crtc_state->vrr_infopacket,
9132 			&vrr_infopacket,
9133 			sizeof(vrr_infopacket)) != 0);
9134 
9135 	acrtc->dm_irq_params.vrr_params = vrr_params;
9136 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9137 
9138 	new_stream->vrr_infopacket = vrr_infopacket;
9139 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9140 
9141 	if (new_crtc_state->freesync_vrr_info_changed)
9142 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
9143 			      new_crtc_state->base.crtc->base.id,
9144 			      (int)new_crtc_state->base.vrr_enabled,
9145 			      (int)vrr_params.state);
9146 
9147 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9148 }
9149 
9150 static void update_stream_irq_parameters(
9151 	struct amdgpu_display_manager *dm,
9152 	struct dm_crtc_state *new_crtc_state)
9153 {
9154 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9155 	struct mod_vrr_params vrr_params;
9156 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9157 	struct amdgpu_device *adev = dm->adev;
9158 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9159 	unsigned long flags;
9160 
9161 	if (!new_stream)
9162 		return;
9163 
9164 	/*
9165 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9166 	 * For now it's sufficient to just guard against these conditions.
9167 	 */
9168 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9169 		return;
9170 
9171 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9172 	vrr_params = acrtc->dm_irq_params.vrr_params;
9173 
9174 	if (new_crtc_state->vrr_supported &&
9175 	    config.min_refresh_in_uhz &&
9176 	    config.max_refresh_in_uhz) {
9177 		/*
9178 		 * if freesync compatible mode was set, config.state will be set
9179 		 * in atomic check
9180 		 */
9181 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9182 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9183 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9184 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9185 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9186 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9187 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9188 		} else {
9189 			config.state = new_crtc_state->base.vrr_enabled ?
9190 						     VRR_STATE_ACTIVE_VARIABLE :
9191 						     VRR_STATE_INACTIVE;
9192 		}
9193 	} else {
9194 		config.state = VRR_STATE_UNSUPPORTED;
9195 	}
9196 
9197 	mod_freesync_build_vrr_params(dm->freesync_module,
9198 				      new_stream,
9199 				      &config, &vrr_params);
9200 
9201 	new_crtc_state->freesync_config = config;
9202 	/* Copy state for access from DM IRQ handler */
9203 	acrtc->dm_irq_params.freesync_config = config;
9204 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9205 	acrtc->dm_irq_params.vrr_params = vrr_params;
9206 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9207 }
9208 
9209 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9210 					    struct dm_crtc_state *new_state)
9211 {
9212 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9213 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9214 
9215 	if (!old_vrr_active && new_vrr_active) {
9216 		/* Transition VRR inactive -> active:
9217 		 * While VRR is active, we must not disable vblank irq, as a
9218 		 * reenable after disable would compute bogus vblank/pflip
9219 		 * timestamps if it likely happened inside display front-porch.
9220 		 *
9221 		 * We also need vupdate irq for the actual core vblank handling
9222 		 * at end of vblank.
9223 		 */
9224 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9225 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9226 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9227 				 __func__, new_state->base.crtc->base.id);
9228 	} else if (old_vrr_active && !new_vrr_active) {
9229 		/* Transition VRR active -> inactive:
9230 		 * Allow vblank irq disable again for fixed refresh rate.
9231 		 */
9232 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9233 		drm_crtc_vblank_put(new_state->base.crtc);
9234 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9235 				 __func__, new_state->base.crtc->base.id);
9236 	}
9237 }
9238 
9239 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9240 {
9241 	struct drm_plane *plane;
9242 	struct drm_plane_state *old_plane_state;
9243 	int i;
9244 
9245 	/*
9246 	 * TODO: Make this per-stream so we don't issue redundant updates for
9247 	 * commits with multiple streams.
9248 	 */
9249 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9250 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9251 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9252 }
9253 
9254 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9255 {
9256 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9257 
9258 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9259 }
9260 
9261 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9262 				    struct drm_plane_state *old_plane_state,
9263 				    struct dc_stream_update *update)
9264 {
9265 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9266 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9267 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9268 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9269 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9270 	uint64_t address = afb ? afb->address : 0;
9271 	struct dc_cursor_position position = {0};
9272 	struct dc_cursor_attributes attributes;
9273 	int ret;
9274 
9275 	if (!plane->state->fb && !old_plane_state->fb)
9276 		return;
9277 
9278 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9279 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9280 		       plane->state->crtc_h);
9281 
9282 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9283 	if (ret)
9284 		return;
9285 
9286 	if (!position.enable) {
9287 		/* turn off cursor */
9288 		if (crtc_state && crtc_state->stream) {
9289 			dc_stream_set_cursor_position(crtc_state->stream,
9290 						      &position);
9291 			update->cursor_position = &crtc_state->stream->cursor_position;
9292 		}
9293 		return;
9294 	}
9295 
9296 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9297 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9298 
9299 	memset(&attributes, 0, sizeof(attributes));
9300 	attributes.address.high_part = upper_32_bits(address);
9301 	attributes.address.low_part  = lower_32_bits(address);
9302 	attributes.width             = plane->state->crtc_w;
9303 	attributes.height            = plane->state->crtc_h;
9304 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9305 	attributes.rotation_angle    = 0;
9306 	attributes.attribute_flags.value = 0;
9307 
9308 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9309 	 * legacy gamma setup.
9310 	 */
9311 	if (crtc_state->cm_is_degamma_srgb &&
9312 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9313 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9314 
9315 	if (afb)
9316 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9317 
9318 	if (crtc_state->stream) {
9319 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9320 						     &attributes))
9321 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9322 
9323 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9324 
9325 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9326 						   &position))
9327 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9328 
9329 		update->cursor_position = &crtc_state->stream->cursor_position;
9330 	}
9331 }
9332 
9333 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9334 					  const struct dm_crtc_state *acrtc_state,
9335 					  const u64 current_ts)
9336 {
9337 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9338 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9339 	struct amdgpu_dm_connector *aconn =
9340 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9341 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9342 
9343 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9344 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9345 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9346 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9347 			     !psr->psr_feature_enabled)
9348 			if (!aconn->disallow_edp_enter_psr)
9349 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9350 	}
9351 
9352 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9353 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9354 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9355 		if (aconn->sr_skip_count > 0)
9356 			aconn->sr_skip_count--;
9357 
9358 		/* Allow SR when skip count is 0. */
9359 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9360 
9361 		/*
9362 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9363 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9364 		 * can be enabled immediately once OS demonstrates an
9365 		 * adequate number of fast atomic commits to notify KMD
9366 		 * of update events. See `vblank_control_worker()`.
9367 		 */
9368 		if (!vrr_active &&
9369 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9370 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9371 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9372 #endif
9373 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9374 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9375 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9376 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9377 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9378 				amdgpu_dm_psr_enable(acrtc_state->stream);
9379 		}
9380 	} else {
9381 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9382 	}
9383 }
9384 
9385 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9386 				    struct drm_device *dev,
9387 				    struct amdgpu_display_manager *dm,
9388 				    struct drm_crtc *pcrtc,
9389 				    bool wait_for_vblank)
9390 {
9391 	u32 i;
9392 	u64 timestamp_ns = ktime_get_ns();
9393 	struct drm_plane *plane;
9394 	struct drm_plane_state *old_plane_state, *new_plane_state;
9395 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9396 	struct drm_crtc_state *new_pcrtc_state =
9397 			drm_atomic_get_new_crtc_state(state, pcrtc);
9398 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9399 	struct dm_crtc_state *dm_old_crtc_state =
9400 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9401 	int planes_count = 0, vpos, hpos;
9402 	unsigned long flags;
9403 	u32 target_vblank, last_flip_vblank;
9404 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9405 	bool cursor_update = false;
9406 	bool pflip_present = false;
9407 	bool dirty_rects_changed = false;
9408 	bool updated_planes_and_streams = false;
9409 	struct {
9410 		struct dc_surface_update surface_updates[MAX_SURFACES];
9411 		struct dc_plane_info plane_infos[MAX_SURFACES];
9412 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9413 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9414 		struct dc_stream_update stream_update;
9415 	} *bundle;
9416 
9417 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
9418 
9419 	if (!bundle) {
9420 		drm_err(dev, "Failed to allocate update bundle\n");
9421 		goto cleanup;
9422 	}
9423 
9424 	/*
9425 	 * Disable the cursor first if we're disabling all the planes.
9426 	 * It'll remain on the screen after the planes are re-enabled
9427 	 * if we don't.
9428 	 *
9429 	 * If the cursor is transitioning from native to overlay mode, the
9430 	 * native cursor needs to be disabled first.
9431 	 */
9432 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9433 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9434 		struct dc_cursor_position cursor_position = {0};
9435 
9436 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9437 						   &cursor_position))
9438 			drm_err(dev, "DC failed to disable native cursor\n");
9439 
9440 		bundle->stream_update.cursor_position =
9441 				&acrtc_state->stream->cursor_position;
9442 	}
9443 
9444 	if (acrtc_state->active_planes == 0 &&
9445 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9446 		amdgpu_dm_commit_cursors(state);
9447 
9448 	/* update planes when needed */
9449 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9450 		struct drm_crtc *crtc = new_plane_state->crtc;
9451 		struct drm_crtc_state *new_crtc_state;
9452 		struct drm_framebuffer *fb = new_plane_state->fb;
9453 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9454 		bool plane_needs_flip;
9455 		struct dc_plane_state *dc_plane;
9456 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9457 
9458 		/* Cursor plane is handled after stream updates */
9459 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9460 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9461 			if ((fb && crtc == pcrtc) ||
9462 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9463 				cursor_update = true;
9464 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
9465 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
9466 			}
9467 
9468 			continue;
9469 		}
9470 
9471 		if (!fb || !crtc || pcrtc != crtc)
9472 			continue;
9473 
9474 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
9475 		if (!new_crtc_state->active)
9476 			continue;
9477 
9478 		dc_plane = dm_new_plane_state->dc_state;
9479 		if (!dc_plane)
9480 			continue;
9481 
9482 		bundle->surface_updates[planes_count].surface = dc_plane;
9483 		if (new_pcrtc_state->color_mgmt_changed) {
9484 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
9485 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
9486 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
9487 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
9488 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
9489 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
9490 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
9491 		}
9492 
9493 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
9494 				     &bundle->scaling_infos[planes_count]);
9495 
9496 		bundle->surface_updates[planes_count].scaling_info =
9497 			&bundle->scaling_infos[planes_count];
9498 
9499 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
9500 
9501 		pflip_present = pflip_present || plane_needs_flip;
9502 
9503 		if (!plane_needs_flip) {
9504 			planes_count += 1;
9505 			continue;
9506 		}
9507 
9508 		fill_dc_plane_info_and_addr(
9509 			dm->adev, new_plane_state,
9510 			afb->tiling_flags,
9511 			&bundle->plane_infos[planes_count],
9512 			&bundle->flip_addrs[planes_count].address,
9513 			afb->tmz_surface);
9514 
9515 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
9516 				 new_plane_state->plane->index,
9517 				 bundle->plane_infos[planes_count].dcc.enable);
9518 
9519 		bundle->surface_updates[planes_count].plane_info =
9520 			&bundle->plane_infos[planes_count];
9521 
9522 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
9523 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
9524 			fill_dc_dirty_rects(plane, old_plane_state,
9525 					    new_plane_state, new_crtc_state,
9526 					    &bundle->flip_addrs[planes_count],
9527 					    acrtc_state->stream->link->psr_settings.psr_version ==
9528 					    DC_PSR_VERSION_SU_1,
9529 					    &dirty_rects_changed);
9530 
9531 			/*
9532 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
9533 			 * and enabled it again after dirty regions are stable to avoid video glitch.
9534 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
9535 			 * during the PSR-SU was disabled.
9536 			 */
9537 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
9538 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
9539 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9540 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9541 #endif
9542 			    dirty_rects_changed) {
9543 				mutex_lock(&dm->dc_lock);
9544 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
9545 				timestamp_ns;
9546 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
9547 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
9548 				mutex_unlock(&dm->dc_lock);
9549 			}
9550 		}
9551 
9552 		/*
9553 		 * Only allow immediate flips for fast updates that don't
9554 		 * change memory domain, FB pitch, DCC state, rotation or
9555 		 * mirroring.
9556 		 *
9557 		 * dm_crtc_helper_atomic_check() only accepts async flips with
9558 		 * fast updates.
9559 		 */
9560 		if (crtc->state->async_flip &&
9561 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
9562 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
9563 			drm_warn_once(state->dev,
9564 				      "[PLANE:%d:%s] async flip with non-fast update\n",
9565 				      plane->base.id, plane->name);
9566 
9567 		bundle->flip_addrs[planes_count].flip_immediate =
9568 			crtc->state->async_flip &&
9569 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
9570 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
9571 
9572 		timestamp_ns = ktime_get_ns();
9573 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
9574 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
9575 		bundle->surface_updates[planes_count].surface = dc_plane;
9576 
9577 		if (!bundle->surface_updates[planes_count].surface) {
9578 			drm_err(dev, "No surface for CRTC: id=%d\n",
9579 					acrtc_attach->crtc_id);
9580 			continue;
9581 		}
9582 
9583 		if (plane == pcrtc->primary)
9584 			update_freesync_state_on_stream(
9585 				dm,
9586 				acrtc_state,
9587 				acrtc_state->stream,
9588 				dc_plane,
9589 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
9590 
9591 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
9592 				 __func__,
9593 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
9594 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
9595 
9596 		planes_count += 1;
9597 
9598 	}
9599 
9600 	if (pflip_present) {
9601 		if (!vrr_active) {
9602 			/* Use old throttling in non-vrr fixed refresh rate mode
9603 			 * to keep flip scheduling based on target vblank counts
9604 			 * working in a backwards compatible way, e.g., for
9605 			 * clients using the GLX_OML_sync_control extension or
9606 			 * DRI3/Present extension with defined target_msc.
9607 			 */
9608 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
9609 		} else {
9610 			/* For variable refresh rate mode only:
9611 			 * Get vblank of last completed flip to avoid > 1 vrr
9612 			 * flips per video frame by use of throttling, but allow
9613 			 * flip programming anywhere in the possibly large
9614 			 * variable vrr vblank interval for fine-grained flip
9615 			 * timing control and more opportunity to avoid stutter
9616 			 * on late submission of flips.
9617 			 */
9618 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9619 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
9620 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9621 		}
9622 
9623 		target_vblank = last_flip_vblank + wait_for_vblank;
9624 
9625 		/*
9626 		 * Wait until we're out of the vertical blank period before the one
9627 		 * targeted by the flip
9628 		 */
9629 		while ((acrtc_attach->enabled &&
9630 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
9631 							    0, &vpos, &hpos, NULL,
9632 							    NULL, &pcrtc->hwmode)
9633 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
9634 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
9635 			(int)(target_vblank -
9636 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
9637 			usleep_range(1000, 1100);
9638 		}
9639 
9640 		/**
9641 		 * Prepare the flip event for the pageflip interrupt to handle.
9642 		 *
9643 		 * This only works in the case where we've already turned on the
9644 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
9645 		 * from 0 -> n planes we have to skip a hardware generated event
9646 		 * and rely on sending it from software.
9647 		 */
9648 		if (acrtc_attach->base.state->event &&
9649 		    acrtc_state->active_planes > 0) {
9650 			drm_crtc_vblank_get(pcrtc);
9651 
9652 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9653 
9654 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
9655 			prepare_flip_isr(acrtc_attach);
9656 
9657 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9658 		}
9659 
9660 		if (acrtc_state->stream) {
9661 			if (acrtc_state->freesync_vrr_info_changed)
9662 				bundle->stream_update.vrr_infopacket =
9663 					&acrtc_state->stream->vrr_infopacket;
9664 		}
9665 	} else if (cursor_update && acrtc_state->active_planes > 0) {
9666 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9667 		if (acrtc_attach->base.state->event) {
9668 			drm_crtc_vblank_get(pcrtc);
9669 			acrtc_attach->event = acrtc_attach->base.state->event;
9670 			acrtc_attach->base.state->event = NULL;
9671 		}
9672 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9673 	}
9674 
9675 	/* Update the planes if changed or disable if we don't have any. */
9676 	if ((planes_count || acrtc_state->active_planes == 0) &&
9677 		acrtc_state->stream) {
9678 		/*
9679 		 * If PSR or idle optimizations are enabled then flush out
9680 		 * any pending work before hardware programming.
9681 		 */
9682 		if (dm->vblank_control_workqueue)
9683 			flush_workqueue(dm->vblank_control_workqueue);
9684 
9685 		bundle->stream_update.stream = acrtc_state->stream;
9686 		if (new_pcrtc_state->mode_changed) {
9687 			bundle->stream_update.src = acrtc_state->stream->src;
9688 			bundle->stream_update.dst = acrtc_state->stream->dst;
9689 		}
9690 
9691 		if (new_pcrtc_state->color_mgmt_changed) {
9692 			/*
9693 			 * TODO: This isn't fully correct since we've actually
9694 			 * already modified the stream in place.
9695 			 */
9696 			bundle->stream_update.gamut_remap =
9697 				&acrtc_state->stream->gamut_remap_matrix;
9698 			bundle->stream_update.output_csc_transform =
9699 				&acrtc_state->stream->csc_color_matrix;
9700 			bundle->stream_update.out_transfer_func =
9701 				&acrtc_state->stream->out_transfer_func;
9702 			bundle->stream_update.lut3d_func =
9703 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
9704 			bundle->stream_update.func_shaper =
9705 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
9706 		}
9707 
9708 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
9709 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
9710 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
9711 
9712 		mutex_lock(&dm->dc_lock);
9713 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
9714 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
9715 				amdgpu_dm_replay_disable(acrtc_state->stream);
9716 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
9717 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
9718 		}
9719 		mutex_unlock(&dm->dc_lock);
9720 
9721 		/*
9722 		 * If FreeSync state on the stream has changed then we need to
9723 		 * re-adjust the min/max bounds now that DC doesn't handle this
9724 		 * as part of commit.
9725 		 */
9726 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
9727 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
9728 			dc_stream_adjust_vmin_vmax(
9729 				dm->dc, acrtc_state->stream,
9730 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
9731 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
9732 		}
9733 		mutex_lock(&dm->dc_lock);
9734 		update_planes_and_stream_adapter(dm->dc,
9735 					 acrtc_state->update_type,
9736 					 planes_count,
9737 					 acrtc_state->stream,
9738 					 &bundle->stream_update,
9739 					 bundle->surface_updates);
9740 		updated_planes_and_streams = true;
9741 
9742 		/**
9743 		 * Enable or disable the interrupts on the backend.
9744 		 *
9745 		 * Most pipes are put into power gating when unused.
9746 		 *
9747 		 * When power gating is enabled on a pipe we lose the
9748 		 * interrupt enablement state when power gating is disabled.
9749 		 *
9750 		 * So we need to update the IRQ control state in hardware
9751 		 * whenever the pipe turns on (since it could be previously
9752 		 * power gated) or off (since some pipes can't be power gated
9753 		 * on some ASICs).
9754 		 */
9755 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
9756 			dm_update_pflip_irq_state(drm_to_adev(dev),
9757 						  acrtc_attach);
9758 
9759 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
9760 		mutex_unlock(&dm->dc_lock);
9761 	}
9762 
9763 	/*
9764 	 * Update cursor state *after* programming all the planes.
9765 	 * This avoids redundant programming in the case where we're going
9766 	 * to be disabling a single plane - those pipes are being disabled.
9767 	 */
9768 	if (acrtc_state->active_planes &&
9769 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
9770 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9771 		amdgpu_dm_commit_cursors(state);
9772 
9773 cleanup:
9774 	kfree(bundle);
9775 }
9776 
9777 static void amdgpu_dm_commit_audio(struct drm_device *dev,
9778 				   struct drm_atomic_state *state)
9779 {
9780 	struct amdgpu_device *adev = drm_to_adev(dev);
9781 	struct amdgpu_dm_connector *aconnector;
9782 	struct drm_connector *connector;
9783 	struct drm_connector_state *old_con_state, *new_con_state;
9784 	struct drm_crtc_state *new_crtc_state;
9785 	struct dm_crtc_state *new_dm_crtc_state;
9786 	const struct dc_stream_status *status;
9787 	int i, inst;
9788 
9789 	/* Notify device removals. */
9790 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9791 		if (old_con_state->crtc != new_con_state->crtc) {
9792 			/* CRTC changes require notification. */
9793 			goto notify;
9794 		}
9795 
9796 		if (!new_con_state->crtc)
9797 			continue;
9798 
9799 		new_crtc_state = drm_atomic_get_new_crtc_state(
9800 			state, new_con_state->crtc);
9801 
9802 		if (!new_crtc_state)
9803 			continue;
9804 
9805 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9806 			continue;
9807 
9808 notify:
9809 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
9810 			continue;
9811 
9812 		aconnector = to_amdgpu_dm_connector(connector);
9813 
9814 		mutex_lock(&adev->dm.audio_lock);
9815 		inst = aconnector->audio_inst;
9816 		aconnector->audio_inst = -1;
9817 		mutex_unlock(&adev->dm.audio_lock);
9818 
9819 		amdgpu_dm_audio_eld_notify(adev, inst);
9820 	}
9821 
9822 	/* Notify audio device additions. */
9823 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
9824 		if (!new_con_state->crtc)
9825 			continue;
9826 
9827 		new_crtc_state = drm_atomic_get_new_crtc_state(
9828 			state, new_con_state->crtc);
9829 
9830 		if (!new_crtc_state)
9831 			continue;
9832 
9833 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9834 			continue;
9835 
9836 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
9837 		if (!new_dm_crtc_state->stream)
9838 			continue;
9839 
9840 		status = dc_stream_get_status(new_dm_crtc_state->stream);
9841 		if (!status)
9842 			continue;
9843 
9844 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
9845 			continue;
9846 
9847 		aconnector = to_amdgpu_dm_connector(connector);
9848 
9849 		mutex_lock(&adev->dm.audio_lock);
9850 		inst = status->audio_inst;
9851 		aconnector->audio_inst = inst;
9852 		mutex_unlock(&adev->dm.audio_lock);
9853 
9854 		amdgpu_dm_audio_eld_notify(adev, inst);
9855 	}
9856 }
9857 
9858 /*
9859  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
9860  * @crtc_state: the DRM CRTC state
9861  * @stream_state: the DC stream state.
9862  *
9863  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
9864  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
9865  */
9866 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
9867 						struct dc_stream_state *stream_state)
9868 {
9869 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
9870 }
9871 
9872 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
9873 			      struct dm_crtc_state *crtc_state)
9874 {
9875 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
9876 }
9877 
9878 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
9879 					struct dc_state *dc_state)
9880 {
9881 	struct drm_device *dev = state->dev;
9882 	struct amdgpu_device *adev = drm_to_adev(dev);
9883 	struct amdgpu_display_manager *dm = &adev->dm;
9884 	struct drm_crtc *crtc;
9885 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9886 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9887 	struct drm_connector_state *old_con_state;
9888 	struct drm_connector *connector;
9889 	bool mode_set_reset_required = false;
9890 	u32 i;
9891 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
9892 	bool set_backlight_level = false;
9893 
9894 	/* Disable writeback */
9895 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
9896 		struct dm_connector_state *dm_old_con_state;
9897 		struct amdgpu_crtc *acrtc;
9898 
9899 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
9900 			continue;
9901 
9902 		old_crtc_state = NULL;
9903 
9904 		dm_old_con_state = to_dm_connector_state(old_con_state);
9905 		if (!dm_old_con_state->base.crtc)
9906 			continue;
9907 
9908 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
9909 		if (acrtc)
9910 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
9911 
9912 		if (!acrtc || !acrtc->wb_enabled)
9913 			continue;
9914 
9915 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9916 
9917 		dm_clear_writeback(dm, dm_old_crtc_state);
9918 		acrtc->wb_enabled = false;
9919 	}
9920 
9921 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
9922 				      new_crtc_state, i) {
9923 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
9924 
9925 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9926 
9927 		if (old_crtc_state->active &&
9928 		    (!new_crtc_state->active ||
9929 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
9930 			manage_dm_interrupts(adev, acrtc, NULL);
9931 			dc_stream_release(dm_old_crtc_state->stream);
9932 		}
9933 	}
9934 
9935 	drm_atomic_helper_calc_timestamping_constants(state);
9936 
9937 	/* update changed items */
9938 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9939 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
9940 
9941 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9942 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9943 
9944 		drm_dbg_state(state->dev,
9945 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
9946 			acrtc->crtc_id,
9947 			new_crtc_state->enable,
9948 			new_crtc_state->active,
9949 			new_crtc_state->planes_changed,
9950 			new_crtc_state->mode_changed,
9951 			new_crtc_state->active_changed,
9952 			new_crtc_state->connectors_changed);
9953 
9954 		/* Disable cursor if disabling crtc */
9955 		if (old_crtc_state->active && !new_crtc_state->active) {
9956 			struct dc_cursor_position position;
9957 
9958 			memset(&position, 0, sizeof(position));
9959 			mutex_lock(&dm->dc_lock);
9960 			dc_exit_ips_for_hw_access(dm->dc);
9961 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
9962 			mutex_unlock(&dm->dc_lock);
9963 		}
9964 
9965 		/* Copy all transient state flags into dc state */
9966 		if (dm_new_crtc_state->stream) {
9967 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
9968 							    dm_new_crtc_state->stream);
9969 		}
9970 
9971 		/* handles headless hotplug case, updating new_state and
9972 		 * aconnector as needed
9973 		 */
9974 
9975 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
9976 
9977 			drm_dbg_atomic(dev,
9978 				       "Atomic commit: SET crtc id %d: [%p]\n",
9979 				       acrtc->crtc_id, acrtc);
9980 
9981 			if (!dm_new_crtc_state->stream) {
9982 				/*
9983 				 * this could happen because of issues with
9984 				 * userspace notifications delivery.
9985 				 * In this case userspace tries to set mode on
9986 				 * display which is disconnected in fact.
9987 				 * dc_sink is NULL in this case on aconnector.
9988 				 * We expect reset mode will come soon.
9989 				 *
9990 				 * This can also happen when unplug is done
9991 				 * during resume sequence ended
9992 				 *
9993 				 * In this case, we want to pretend we still
9994 				 * have a sink to keep the pipe running so that
9995 				 * hw state is consistent with the sw state
9996 				 */
9997 				drm_dbg_atomic(dev,
9998 					       "Failed to create new stream for crtc %d\n",
9999 						acrtc->base.base.id);
10000 				continue;
10001 			}
10002 
10003 			if (dm_old_crtc_state->stream)
10004 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10005 
10006 			pm_runtime_get_noresume(dev->dev);
10007 
10008 			acrtc->enabled = true;
10009 			acrtc->hw_mode = new_crtc_state->mode;
10010 			crtc->hwmode = new_crtc_state->mode;
10011 			mode_set_reset_required = true;
10012 			set_backlight_level = true;
10013 		} else if (modereset_required(new_crtc_state)) {
10014 			drm_dbg_atomic(dev,
10015 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10016 				       acrtc->crtc_id, acrtc);
10017 			/* i.e. reset mode */
10018 			if (dm_old_crtc_state->stream)
10019 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10020 
10021 			mode_set_reset_required = true;
10022 		}
10023 	} /* for_each_crtc_in_state() */
10024 
10025 	/* if there mode set or reset, disable eDP PSR, Replay */
10026 	if (mode_set_reset_required) {
10027 		if (dm->vblank_control_workqueue)
10028 			flush_workqueue(dm->vblank_control_workqueue);
10029 
10030 		amdgpu_dm_replay_disable_all(dm);
10031 		amdgpu_dm_psr_disable_all(dm);
10032 	}
10033 
10034 	dm_enable_per_frame_crtc_master_sync(dc_state);
10035 	mutex_lock(&dm->dc_lock);
10036 	dc_exit_ips_for_hw_access(dm->dc);
10037 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10038 
10039 	/* Allow idle optimization when vblank count is 0 for display off */
10040 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10041 		dc_allow_idle_optimizations(dm->dc, true);
10042 	mutex_unlock(&dm->dc_lock);
10043 
10044 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10045 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10046 
10047 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10048 
10049 		if (dm_new_crtc_state->stream != NULL) {
10050 			const struct dc_stream_status *status =
10051 					dc_stream_get_status(dm_new_crtc_state->stream);
10052 
10053 			if (!status)
10054 				status = dc_state_get_stream_status(dc_state,
10055 									 dm_new_crtc_state->stream);
10056 			if (!status)
10057 				drm_err(dev,
10058 					"got no status for stream %p on acrtc%p\n",
10059 					dm_new_crtc_state->stream, acrtc);
10060 			else
10061 				acrtc->otg_inst = status->primary_otg_inst;
10062 		}
10063 	}
10064 
10065 	/* During boot up and resume the DC layer will reset the panel brightness
10066 	 * to fix a flicker issue.
10067 	 * It will cause the dm->actual_brightness is not the current panel brightness
10068 	 * level. (the dm->brightness is the correct panel level)
10069 	 * So we set the backlight level with dm->brightness value after set mode
10070 	 */
10071 	if (set_backlight_level) {
10072 		for (i = 0; i < dm->num_of_edps; i++) {
10073 			if (dm->backlight_dev[i])
10074 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10075 		}
10076 	}
10077 }
10078 
10079 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10080 			      struct dm_crtc_state *crtc_state,
10081 			      struct drm_connector *connector,
10082 			      struct drm_connector_state *new_con_state)
10083 {
10084 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10085 	struct amdgpu_device *adev = dm->adev;
10086 	struct amdgpu_crtc *acrtc;
10087 	struct dc_writeback_info *wb_info;
10088 	struct pipe_ctx *pipe = NULL;
10089 	struct amdgpu_framebuffer *afb;
10090 	int i = 0;
10091 
10092 	wb_info = kzalloc(sizeof(*wb_info), GFP_KERNEL);
10093 	if (!wb_info) {
10094 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10095 		return;
10096 	}
10097 
10098 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10099 	if (!acrtc) {
10100 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10101 		kfree(wb_info);
10102 		return;
10103 	}
10104 
10105 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10106 	if (!afb) {
10107 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10108 		kfree(wb_info);
10109 		return;
10110 	}
10111 
10112 	for (i = 0; i < MAX_PIPES; i++) {
10113 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10114 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10115 			break;
10116 		}
10117 	}
10118 
10119 	/* fill in wb_info */
10120 	wb_info->wb_enabled = true;
10121 
10122 	wb_info->dwb_pipe_inst = 0;
10123 	wb_info->dwb_params.dwbscl_black_color = 0;
10124 	wb_info->dwb_params.hdr_mult = 0x1F000;
10125 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10126 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10127 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10128 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10129 
10130 	/* width & height from crtc */
10131 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10132 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10133 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10134 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10135 
10136 	wb_info->dwb_params.cnv_params.crop_en = false;
10137 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10138 
10139 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10140 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10141 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10142 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10143 
10144 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10145 
10146 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10147 
10148 	wb_info->dwb_params.scaler_taps.h_taps = 4;
10149 	wb_info->dwb_params.scaler_taps.v_taps = 4;
10150 	wb_info->dwb_params.scaler_taps.h_taps_c = 2;
10151 	wb_info->dwb_params.scaler_taps.v_taps_c = 2;
10152 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10153 
10154 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10155 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10156 
10157 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10158 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10159 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10160 	}
10161 
10162 	wb_info->mcif_buf_params.p_vmid = 1;
10163 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10164 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10165 		wb_info->mcif_warmup_params.region_size =
10166 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10167 	}
10168 	wb_info->mcif_warmup_params.p_vmid = 1;
10169 	wb_info->writeback_source_plane = pipe->plane_state;
10170 
10171 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10172 
10173 	acrtc->wb_pending = true;
10174 	acrtc->wb_conn = wb_conn;
10175 	drm_writeback_queue_job(wb_conn, new_con_state);
10176 }
10177 
10178 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10179 {
10180 	struct drm_connector_state *old_con_state, *new_con_state;
10181 	struct drm_device *dev = state->dev;
10182 	struct drm_connector *connector;
10183 	struct amdgpu_device *adev = drm_to_adev(dev);
10184 	int i;
10185 
10186 	if (!adev->dm.hdcp_workqueue)
10187 		return;
10188 
10189 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10190 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10191 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10192 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10193 		struct dm_crtc_state *dm_new_crtc_state;
10194 		struct amdgpu_dm_connector *aconnector;
10195 
10196 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10197 			continue;
10198 
10199 		aconnector = to_amdgpu_dm_connector(connector);
10200 
10201 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10202 
10203 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10204 			connector->index, connector->status, connector->dpms);
10205 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10206 			old_con_state->content_protection, new_con_state->content_protection);
10207 
10208 		if (aconnector->dc_sink) {
10209 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10210 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10211 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10212 				aconnector->dc_sink->edid_caps.display_name);
10213 			}
10214 		}
10215 
10216 		new_crtc_state = NULL;
10217 		old_crtc_state = NULL;
10218 
10219 		if (acrtc) {
10220 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10221 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10222 		}
10223 
10224 		if (old_crtc_state)
10225 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10226 			old_crtc_state->enable,
10227 			old_crtc_state->active,
10228 			old_crtc_state->mode_changed,
10229 			old_crtc_state->active_changed,
10230 			old_crtc_state->connectors_changed);
10231 
10232 		if (new_crtc_state)
10233 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10234 			new_crtc_state->enable,
10235 			new_crtc_state->active,
10236 			new_crtc_state->mode_changed,
10237 			new_crtc_state->active_changed,
10238 			new_crtc_state->connectors_changed);
10239 
10240 
10241 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10242 
10243 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10244 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10245 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10246 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10247 			dm_new_con_state->update_hdcp = true;
10248 			continue;
10249 		}
10250 
10251 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10252 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10253 			/* when display is unplugged from mst hub, connctor will
10254 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10255 			 * hdcp perperties, like type, undesired, desired, enabled,
10256 			 * will be lost. So, save hdcp properties into hdcp_work within
10257 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10258 			 * plugged back with same display index, its hdcp properties
10259 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10260 			 */
10261 
10262 			bool enable_encryption = false;
10263 
10264 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10265 				enable_encryption = true;
10266 
10267 			if (aconnector->dc_link && aconnector->dc_sink &&
10268 				aconnector->dc_link->type == dc_connection_mst_branch) {
10269 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10270 				struct hdcp_workqueue *hdcp_w =
10271 					&hdcp_work[aconnector->dc_link->link_index];
10272 
10273 				hdcp_w->hdcp_content_type[connector->index] =
10274 					new_con_state->hdcp_content_type;
10275 				hdcp_w->content_protection[connector->index] =
10276 					new_con_state->content_protection;
10277 			}
10278 
10279 			if (new_crtc_state && new_crtc_state->mode_changed &&
10280 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10281 				enable_encryption = true;
10282 
10283 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10284 
10285 			if (aconnector->dc_link)
10286 				hdcp_update_display(
10287 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10288 					new_con_state->hdcp_content_type, enable_encryption);
10289 		}
10290 	}
10291 }
10292 
10293 /**
10294  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10295  * @state: The atomic state to commit
10296  *
10297  * This will tell DC to commit the constructed DC state from atomic_check,
10298  * programming the hardware. Any failures here implies a hardware failure, since
10299  * atomic check should have filtered anything non-kosher.
10300  */
10301 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10302 {
10303 	struct drm_device *dev = state->dev;
10304 	struct amdgpu_device *adev = drm_to_adev(dev);
10305 	struct amdgpu_display_manager *dm = &adev->dm;
10306 	struct dm_atomic_state *dm_state;
10307 	struct dc_state *dc_state = NULL;
10308 	u32 i, j;
10309 	struct drm_crtc *crtc;
10310 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10311 	unsigned long flags;
10312 	bool wait_for_vblank = true;
10313 	struct drm_connector *connector;
10314 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10315 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10316 	int crtc_disable_count = 0;
10317 
10318 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10319 
10320 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10321 	drm_dp_mst_atomic_wait_for_dependencies(state);
10322 
10323 	dm_state = dm_atomic_get_new_state(state);
10324 	if (dm_state && dm_state->context) {
10325 		dc_state = dm_state->context;
10326 		amdgpu_dm_commit_streams(state, dc_state);
10327 	}
10328 
10329 	amdgpu_dm_update_hdcp(state);
10330 
10331 	/* Handle connector state changes */
10332 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10333 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10334 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10335 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10336 		struct dc_surface_update *dummy_updates;
10337 		struct dc_stream_update stream_update;
10338 		struct dc_info_packet hdr_packet;
10339 		struct dc_stream_status *status = NULL;
10340 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10341 
10342 		memset(&stream_update, 0, sizeof(stream_update));
10343 
10344 		if (acrtc) {
10345 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10346 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10347 		}
10348 
10349 		/* Skip any modesets/resets */
10350 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10351 			continue;
10352 
10353 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10354 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10355 
10356 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10357 							     dm_old_con_state);
10358 
10359 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10360 			(dm_old_crtc_state->stream->output_color_space !=
10361 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10362 			output_color_space_changed = true;
10363 
10364 		abm_changed = dm_new_crtc_state->abm_level !=
10365 			      dm_old_crtc_state->abm_level;
10366 
10367 		hdr_changed =
10368 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10369 
10370 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10371 			continue;
10372 
10373 		stream_update.stream = dm_new_crtc_state->stream;
10374 		if (scaling_changed) {
10375 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
10376 					dm_new_con_state, dm_new_crtc_state->stream);
10377 
10378 			stream_update.src = dm_new_crtc_state->stream->src;
10379 			stream_update.dst = dm_new_crtc_state->stream->dst;
10380 		}
10381 
10382 		if (output_color_space_changed) {
10383 			dm_new_crtc_state->stream->output_color_space
10384 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
10385 
10386 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
10387 		}
10388 
10389 		if (abm_changed) {
10390 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10391 
10392 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10393 		}
10394 
10395 		if (hdr_changed) {
10396 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10397 			stream_update.hdr_static_metadata = &hdr_packet;
10398 		}
10399 
10400 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10401 
10402 		if (WARN_ON(!status))
10403 			continue;
10404 
10405 		WARN_ON(!status->plane_count);
10406 
10407 		/*
10408 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10409 		 * Here we create an empty update on each plane.
10410 		 * To fix this, DC should permit updating only stream properties.
10411 		 */
10412 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_ATOMIC);
10413 		if (!dummy_updates) {
10414 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
10415 			continue;
10416 		}
10417 		for (j = 0; j < status->plane_count; j++)
10418 			dummy_updates[j].surface = status->plane_states[0];
10419 
10420 		sort(dummy_updates, status->plane_count,
10421 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10422 
10423 		mutex_lock(&dm->dc_lock);
10424 		dc_exit_ips_for_hw_access(dm->dc);
10425 		dc_update_planes_and_stream(dm->dc,
10426 					    dummy_updates,
10427 					    status->plane_count,
10428 					    dm_new_crtc_state->stream,
10429 					    &stream_update);
10430 		mutex_unlock(&dm->dc_lock);
10431 		kfree(dummy_updates);
10432 
10433 		drm_connector_update_privacy_screen(new_con_state);
10434 	}
10435 
10436 	/**
10437 	 * Enable interrupts for CRTCs that are newly enabled or went through
10438 	 * a modeset. It was intentionally deferred until after the front end
10439 	 * state was modified to wait until the OTG was on and so the IRQ
10440 	 * handlers didn't access stale or invalid state.
10441 	 */
10442 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10443 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10444 #ifdef CONFIG_DEBUG_FS
10445 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
10446 #endif
10447 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
10448 		if (old_crtc_state->active && !new_crtc_state->active)
10449 			crtc_disable_count++;
10450 
10451 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10452 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10453 
10454 		/* For freesync config update on crtc state and params for irq */
10455 		update_stream_irq_parameters(dm, dm_new_crtc_state);
10456 
10457 #ifdef CONFIG_DEBUG_FS
10458 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10459 		cur_crc_src = acrtc->dm_irq_params.crc_src;
10460 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10461 #endif
10462 
10463 		if (new_crtc_state->active &&
10464 		    (!old_crtc_state->active ||
10465 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10466 			dc_stream_retain(dm_new_crtc_state->stream);
10467 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
10468 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
10469 		}
10470 		/* Handle vrr on->off / off->on transitions */
10471 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
10472 
10473 #ifdef CONFIG_DEBUG_FS
10474 		if (new_crtc_state->active &&
10475 		    (!old_crtc_state->active ||
10476 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10477 			/**
10478 			 * Frontend may have changed so reapply the CRC capture
10479 			 * settings for the stream.
10480 			 */
10481 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
10482 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
10483 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
10484 					uint8_t cnt;
10485 
10486 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10487 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
10488 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
10489 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
10490 
10491 							/**
10492 							 * It takes 2 frames for HW to stably generate CRC when
10493 							 * resuming from suspend, so we set skip_frame_cnt 2.
10494 							 */
10495 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
10496 						}
10497 					}
10498 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10499 				}
10500 #endif
10501 				if (amdgpu_dm_crtc_configure_crc_source(
10502 					crtc, dm_new_crtc_state, cur_crc_src))
10503 					drm_dbg_atomic(dev, "Failed to configure crc source");
10504 			}
10505 		}
10506 #endif
10507 	}
10508 
10509 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
10510 		if (new_crtc_state->async_flip)
10511 			wait_for_vblank = false;
10512 
10513 	/* update planes when needed per crtc*/
10514 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
10515 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10516 
10517 		if (dm_new_crtc_state->stream)
10518 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
10519 	}
10520 
10521 	/* Enable writeback */
10522 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10523 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10524 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10525 
10526 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10527 			continue;
10528 
10529 		if (!new_con_state->writeback_job)
10530 			continue;
10531 
10532 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10533 
10534 		if (!new_crtc_state)
10535 			continue;
10536 
10537 		if (acrtc->wb_enabled)
10538 			continue;
10539 
10540 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10541 
10542 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
10543 		acrtc->wb_enabled = true;
10544 	}
10545 
10546 	/* Update audio instances for each connector. */
10547 	amdgpu_dm_commit_audio(dev, state);
10548 
10549 	/* restore the backlight level */
10550 	for (i = 0; i < dm->num_of_edps; i++) {
10551 		if (dm->backlight_dev[i] &&
10552 		    (dm->actual_brightness[i] != dm->brightness[i]))
10553 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10554 	}
10555 
10556 	/*
10557 	 * send vblank event on all events not handled in flip and
10558 	 * mark consumed event for drm_atomic_helper_commit_hw_done
10559 	 */
10560 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10561 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10562 
10563 		if (new_crtc_state->event)
10564 			drm_send_event_locked(dev, &new_crtc_state->event->base);
10565 
10566 		new_crtc_state->event = NULL;
10567 	}
10568 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10569 
10570 	/* Signal HW programming completion */
10571 	drm_atomic_helper_commit_hw_done(state);
10572 
10573 	if (wait_for_vblank)
10574 		drm_atomic_helper_wait_for_flip_done(dev, state);
10575 
10576 	drm_atomic_helper_cleanup_planes(dev, state);
10577 
10578 	/* Don't free the memory if we are hitting this as part of suspend.
10579 	 * This way we don't free any memory during suspend; see
10580 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
10581 	 * non-suspend modeset or when the driver is torn down.
10582 	 */
10583 	if (!adev->in_suspend) {
10584 		/* return the stolen vga memory back to VRAM */
10585 		if (!adev->mman.keep_stolen_vga_memory)
10586 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
10587 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
10588 	}
10589 
10590 	/*
10591 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
10592 	 * so we can put the GPU into runtime suspend if we're not driving any
10593 	 * displays anymore
10594 	 */
10595 	for (i = 0; i < crtc_disable_count; i++)
10596 		pm_runtime_put_autosuspend(dev->dev);
10597 	pm_runtime_mark_last_busy(dev->dev);
10598 
10599 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
10600 }
10601 
10602 static int dm_force_atomic_commit(struct drm_connector *connector)
10603 {
10604 	int ret = 0;
10605 	struct drm_device *ddev = connector->dev;
10606 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
10607 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
10608 	struct drm_plane *plane = disconnected_acrtc->base.primary;
10609 	struct drm_connector_state *conn_state;
10610 	struct drm_crtc_state *crtc_state;
10611 	struct drm_plane_state *plane_state;
10612 
10613 	if (!state)
10614 		return -ENOMEM;
10615 
10616 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
10617 
10618 	/* Construct an atomic state to restore previous display setting */
10619 
10620 	/*
10621 	 * Attach connectors to drm_atomic_state
10622 	 */
10623 	conn_state = drm_atomic_get_connector_state(state, connector);
10624 
10625 	/* Check for error in getting connector state */
10626 	if (IS_ERR(conn_state)) {
10627 		ret = PTR_ERR(conn_state);
10628 		goto out;
10629 	}
10630 
10631 	/* Attach crtc to drm_atomic_state*/
10632 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
10633 
10634 	/* Check for error in getting crtc state */
10635 	if (IS_ERR(crtc_state)) {
10636 		ret = PTR_ERR(crtc_state);
10637 		goto out;
10638 	}
10639 
10640 	/* force a restore */
10641 	crtc_state->mode_changed = true;
10642 
10643 	/* Attach plane to drm_atomic_state */
10644 	plane_state = drm_atomic_get_plane_state(state, plane);
10645 
10646 	/* Check for error in getting plane state */
10647 	if (IS_ERR(plane_state)) {
10648 		ret = PTR_ERR(plane_state);
10649 		goto out;
10650 	}
10651 
10652 	/* Call commit internally with the state we just constructed */
10653 	ret = drm_atomic_commit(state);
10654 
10655 out:
10656 	drm_atomic_state_put(state);
10657 	if (ret)
10658 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
10659 
10660 	return ret;
10661 }
10662 
10663 /*
10664  * This function handles all cases when set mode does not come upon hotplug.
10665  * This includes when a display is unplugged then plugged back into the
10666  * same port and when running without usermode desktop manager supprot
10667  */
10668 void dm_restore_drm_connector_state(struct drm_device *dev,
10669 				    struct drm_connector *connector)
10670 {
10671 	struct amdgpu_dm_connector *aconnector;
10672 	struct amdgpu_crtc *disconnected_acrtc;
10673 	struct dm_crtc_state *acrtc_state;
10674 
10675 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10676 		return;
10677 
10678 	aconnector = to_amdgpu_dm_connector(connector);
10679 
10680 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
10681 		return;
10682 
10683 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
10684 	if (!disconnected_acrtc)
10685 		return;
10686 
10687 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
10688 	if (!acrtc_state->stream)
10689 		return;
10690 
10691 	/*
10692 	 * If the previous sink is not released and different from the current,
10693 	 * we deduce we are in a state where we can not rely on usermode call
10694 	 * to turn on the display, so we do it here
10695 	 */
10696 	if (acrtc_state->stream->sink != aconnector->dc_sink)
10697 		dm_force_atomic_commit(&aconnector->base);
10698 }
10699 
10700 /*
10701  * Grabs all modesetting locks to serialize against any blocking commits,
10702  * Waits for completion of all non blocking commits.
10703  */
10704 static int do_aquire_global_lock(struct drm_device *dev,
10705 				 struct drm_atomic_state *state)
10706 {
10707 	struct drm_crtc *crtc;
10708 	struct drm_crtc_commit *commit;
10709 	long ret;
10710 
10711 	/*
10712 	 * Adding all modeset locks to aquire_ctx will
10713 	 * ensure that when the framework release it the
10714 	 * extra locks we are locking here will get released to
10715 	 */
10716 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
10717 	if (ret)
10718 		return ret;
10719 
10720 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
10721 		spin_lock(&crtc->commit_lock);
10722 		commit = list_first_entry_or_null(&crtc->commit_list,
10723 				struct drm_crtc_commit, commit_entry);
10724 		if (commit)
10725 			drm_crtc_commit_get(commit);
10726 		spin_unlock(&crtc->commit_lock);
10727 
10728 		if (!commit)
10729 			continue;
10730 
10731 		/*
10732 		 * Make sure all pending HW programming completed and
10733 		 * page flips done
10734 		 */
10735 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
10736 
10737 		if (ret > 0)
10738 			ret = wait_for_completion_interruptible_timeout(
10739 					&commit->flip_done, 10*HZ);
10740 
10741 		if (ret == 0)
10742 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
10743 				  crtc->base.id, crtc->name);
10744 
10745 		drm_crtc_commit_put(commit);
10746 	}
10747 
10748 	return ret < 0 ? ret : 0;
10749 }
10750 
10751 static void get_freesync_config_for_crtc(
10752 	struct dm_crtc_state *new_crtc_state,
10753 	struct dm_connector_state *new_con_state)
10754 {
10755 	struct mod_freesync_config config = {0};
10756 	struct amdgpu_dm_connector *aconnector;
10757 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
10758 	int vrefresh = drm_mode_vrefresh(mode);
10759 	bool fs_vid_mode = false;
10760 
10761 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10762 		return;
10763 
10764 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
10765 
10766 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
10767 					vrefresh >= aconnector->min_vfreq &&
10768 					vrefresh <= aconnector->max_vfreq;
10769 
10770 	if (new_crtc_state->vrr_supported) {
10771 		new_crtc_state->stream->ignore_msa_timing_param = true;
10772 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
10773 
10774 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
10775 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
10776 		config.vsif_supported = true;
10777 		config.btr = true;
10778 
10779 		if (fs_vid_mode) {
10780 			config.state = VRR_STATE_ACTIVE_FIXED;
10781 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
10782 			goto out;
10783 		} else if (new_crtc_state->base.vrr_enabled) {
10784 			config.state = VRR_STATE_ACTIVE_VARIABLE;
10785 		} else {
10786 			config.state = VRR_STATE_INACTIVE;
10787 		}
10788 	}
10789 out:
10790 	new_crtc_state->freesync_config = config;
10791 }
10792 
10793 static void reset_freesync_config_for_crtc(
10794 	struct dm_crtc_state *new_crtc_state)
10795 {
10796 	new_crtc_state->vrr_supported = false;
10797 
10798 	memset(&new_crtc_state->vrr_infopacket, 0,
10799 	       sizeof(new_crtc_state->vrr_infopacket));
10800 }
10801 
10802 static bool
10803 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
10804 				 struct drm_crtc_state *new_crtc_state)
10805 {
10806 	const struct drm_display_mode *old_mode, *new_mode;
10807 
10808 	if (!old_crtc_state || !new_crtc_state)
10809 		return false;
10810 
10811 	old_mode = &old_crtc_state->mode;
10812 	new_mode = &new_crtc_state->mode;
10813 
10814 	if (old_mode->clock       == new_mode->clock &&
10815 	    old_mode->hdisplay    == new_mode->hdisplay &&
10816 	    old_mode->vdisplay    == new_mode->vdisplay &&
10817 	    old_mode->htotal      == new_mode->htotal &&
10818 	    old_mode->vtotal      != new_mode->vtotal &&
10819 	    old_mode->hsync_start == new_mode->hsync_start &&
10820 	    old_mode->vsync_start != new_mode->vsync_start &&
10821 	    old_mode->hsync_end   == new_mode->hsync_end &&
10822 	    old_mode->vsync_end   != new_mode->vsync_end &&
10823 	    old_mode->hskew       == new_mode->hskew &&
10824 	    old_mode->vscan       == new_mode->vscan &&
10825 	    (old_mode->vsync_end - old_mode->vsync_start) ==
10826 	    (new_mode->vsync_end - new_mode->vsync_start))
10827 		return true;
10828 
10829 	return false;
10830 }
10831 
10832 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
10833 {
10834 	u64 num, den, res;
10835 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
10836 
10837 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
10838 
10839 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
10840 	den = (unsigned long long)new_crtc_state->mode.htotal *
10841 	      (unsigned long long)new_crtc_state->mode.vtotal;
10842 
10843 	res = div_u64(num, den);
10844 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
10845 }
10846 
10847 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
10848 			 struct drm_atomic_state *state,
10849 			 struct drm_crtc *crtc,
10850 			 struct drm_crtc_state *old_crtc_state,
10851 			 struct drm_crtc_state *new_crtc_state,
10852 			 bool enable,
10853 			 bool *lock_and_validation_needed)
10854 {
10855 	struct dm_atomic_state *dm_state = NULL;
10856 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10857 	struct dc_stream_state *new_stream;
10858 	struct amdgpu_device *adev = dm->adev;
10859 	int ret = 0;
10860 
10861 	/*
10862 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
10863 	 * update changed items
10864 	 */
10865 	struct amdgpu_crtc *acrtc = NULL;
10866 	struct drm_connector *connector = NULL;
10867 	struct amdgpu_dm_connector *aconnector = NULL;
10868 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
10869 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
10870 
10871 	new_stream = NULL;
10872 
10873 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10874 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10875 	acrtc = to_amdgpu_crtc(crtc);
10876 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
10877 	if (connector)
10878 		aconnector = to_amdgpu_dm_connector(connector);
10879 
10880 	/* TODO This hack should go away */
10881 	if (connector && enable) {
10882 		/* Make sure fake sink is created in plug-in scenario */
10883 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
10884 									connector);
10885 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
10886 									connector);
10887 
10888 		if (WARN_ON(!drm_new_conn_state)) {
10889 			ret = -EINVAL;
10890 			goto fail;
10891 		}
10892 
10893 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
10894 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
10895 
10896 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10897 			goto skip_modeset;
10898 
10899 		new_stream = create_validate_stream_for_sink(connector,
10900 							     &new_crtc_state->mode,
10901 							     dm_new_conn_state,
10902 							     dm_old_crtc_state->stream);
10903 
10904 		/*
10905 		 * we can have no stream on ACTION_SET if a display
10906 		 * was disconnected during S3, in this case it is not an
10907 		 * error, the OS will be updated after detection, and
10908 		 * will do the right thing on next atomic commit
10909 		 */
10910 
10911 		if (!new_stream) {
10912 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
10913 					__func__, acrtc->base.base.id);
10914 			ret = -ENOMEM;
10915 			goto fail;
10916 		}
10917 
10918 		/*
10919 		 * TODO: Check VSDB bits to decide whether this should
10920 		 * be enabled or not.
10921 		 */
10922 		new_stream->triggered_crtc_reset.enabled =
10923 			dm->force_timing_sync;
10924 
10925 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
10926 
10927 		ret = fill_hdr_info_packet(drm_new_conn_state,
10928 					   &new_stream->hdr_static_metadata);
10929 		if (ret)
10930 			goto fail;
10931 
10932 		/*
10933 		 * If we already removed the old stream from the context
10934 		 * (and set the new stream to NULL) then we can't reuse
10935 		 * the old stream even if the stream and scaling are unchanged.
10936 		 * We'll hit the BUG_ON and black screen.
10937 		 *
10938 		 * TODO: Refactor this function to allow this check to work
10939 		 * in all conditions.
10940 		 */
10941 		if (amdgpu_freesync_vid_mode &&
10942 		    dm_new_crtc_state->stream &&
10943 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
10944 			goto skip_modeset;
10945 
10946 		if (dm_new_crtc_state->stream &&
10947 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10948 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
10949 			new_crtc_state->mode_changed = false;
10950 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
10951 					 new_crtc_state->mode_changed);
10952 		}
10953 	}
10954 
10955 	/* mode_changed flag may get updated above, need to check again */
10956 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10957 		goto skip_modeset;
10958 
10959 	drm_dbg_state(state->dev,
10960 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10961 		acrtc->crtc_id,
10962 		new_crtc_state->enable,
10963 		new_crtc_state->active,
10964 		new_crtc_state->planes_changed,
10965 		new_crtc_state->mode_changed,
10966 		new_crtc_state->active_changed,
10967 		new_crtc_state->connectors_changed);
10968 
10969 	/* Remove stream for any changed/disabled CRTC */
10970 	if (!enable) {
10971 
10972 		if (!dm_old_crtc_state->stream)
10973 			goto skip_modeset;
10974 
10975 		/* Unset freesync video if it was active before */
10976 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
10977 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
10978 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
10979 		}
10980 
10981 		/* Now check if we should set freesync video mode */
10982 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
10983 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
10984 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
10985 		    is_timing_unchanged_for_freesync(new_crtc_state,
10986 						     old_crtc_state)) {
10987 			new_crtc_state->mode_changed = false;
10988 			drm_dbg_driver(adev_to_drm(adev),
10989 				"Mode change not required for front porch change, setting mode_changed to %d",
10990 				new_crtc_state->mode_changed);
10991 
10992 			set_freesync_fixed_config(dm_new_crtc_state);
10993 
10994 			goto skip_modeset;
10995 		} else if (amdgpu_freesync_vid_mode && aconnector &&
10996 			   is_freesync_video_mode(&new_crtc_state->mode,
10997 						  aconnector)) {
10998 			struct drm_display_mode *high_mode;
10999 
11000 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11001 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11002 				set_freesync_fixed_config(dm_new_crtc_state);
11003 		}
11004 
11005 		ret = dm_atomic_get_state(state, &dm_state);
11006 		if (ret)
11007 			goto fail;
11008 
11009 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11010 				crtc->base.id);
11011 
11012 		/* i.e. reset mode */
11013 		if (dc_state_remove_stream(
11014 				dm->dc,
11015 				dm_state->context,
11016 				dm_old_crtc_state->stream) != DC_OK) {
11017 			ret = -EINVAL;
11018 			goto fail;
11019 		}
11020 
11021 		dc_stream_release(dm_old_crtc_state->stream);
11022 		dm_new_crtc_state->stream = NULL;
11023 
11024 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11025 
11026 		*lock_and_validation_needed = true;
11027 
11028 	} else {/* Add stream for any updated/enabled CRTC */
11029 		/*
11030 		 * Quick fix to prevent NULL pointer on new_stream when
11031 		 * added MST connectors not found in existing crtc_state in the chained mode
11032 		 * TODO: need to dig out the root cause of that
11033 		 */
11034 		if (!connector)
11035 			goto skip_modeset;
11036 
11037 		if (modereset_required(new_crtc_state))
11038 			goto skip_modeset;
11039 
11040 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11041 				     dm_old_crtc_state->stream)) {
11042 
11043 			WARN_ON(dm_new_crtc_state->stream);
11044 
11045 			ret = dm_atomic_get_state(state, &dm_state);
11046 			if (ret)
11047 				goto fail;
11048 
11049 			dm_new_crtc_state->stream = new_stream;
11050 
11051 			dc_stream_retain(new_stream);
11052 
11053 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
11054 					 crtc->base.id);
11055 
11056 			if (dc_state_add_stream(
11057 					dm->dc,
11058 					dm_state->context,
11059 					dm_new_crtc_state->stream) != DC_OK) {
11060 				ret = -EINVAL;
11061 				goto fail;
11062 			}
11063 
11064 			*lock_and_validation_needed = true;
11065 		}
11066 	}
11067 
11068 skip_modeset:
11069 	/* Release extra reference */
11070 	if (new_stream)
11071 		dc_stream_release(new_stream);
11072 
11073 	/*
11074 	 * We want to do dc stream updates that do not require a
11075 	 * full modeset below.
11076 	 */
11077 	if (!(enable && connector && new_crtc_state->active))
11078 		return 0;
11079 	/*
11080 	 * Given above conditions, the dc state cannot be NULL because:
11081 	 * 1. We're in the process of enabling CRTCs (just been added
11082 	 *    to the dc context, or already is on the context)
11083 	 * 2. Has a valid connector attached, and
11084 	 * 3. Is currently active and enabled.
11085 	 * => The dc stream state currently exists.
11086 	 */
11087 	BUG_ON(dm_new_crtc_state->stream == NULL);
11088 
11089 	/* Scaling or underscan settings */
11090 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11091 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11092 		update_stream_scaling_settings(
11093 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11094 
11095 	/* ABM settings */
11096 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11097 
11098 	/*
11099 	 * Color management settings. We also update color properties
11100 	 * when a modeset is needed, to ensure it gets reprogrammed.
11101 	 */
11102 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11103 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11104 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11105 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11106 		if (ret)
11107 			goto fail;
11108 	}
11109 
11110 	/* Update Freesync settings. */
11111 	get_freesync_config_for_crtc(dm_new_crtc_state,
11112 				     dm_new_conn_state);
11113 
11114 	return ret;
11115 
11116 fail:
11117 	if (new_stream)
11118 		dc_stream_release(new_stream);
11119 	return ret;
11120 }
11121 
11122 static bool should_reset_plane(struct drm_atomic_state *state,
11123 			       struct drm_plane *plane,
11124 			       struct drm_plane_state *old_plane_state,
11125 			       struct drm_plane_state *new_plane_state)
11126 {
11127 	struct drm_plane *other;
11128 	struct drm_plane_state *old_other_state, *new_other_state;
11129 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11130 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11131 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11132 	int i;
11133 
11134 	/*
11135 	 * TODO: Remove this hack for all asics once it proves that the
11136 	 * fast updates works fine on DCN3.2+.
11137 	 */
11138 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11139 	    state->allow_modeset)
11140 		return true;
11141 
11142 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11143 		return true;
11144 
11145 	/* Exit early if we know that we're adding or removing the plane. */
11146 	if (old_plane_state->crtc != new_plane_state->crtc)
11147 		return true;
11148 
11149 	/* old crtc == new_crtc == NULL, plane not in context. */
11150 	if (!new_plane_state->crtc)
11151 		return false;
11152 
11153 	new_crtc_state =
11154 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11155 	old_crtc_state =
11156 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11157 
11158 	if (!new_crtc_state)
11159 		return true;
11160 
11161 	/*
11162 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11163 	 * released from the state
11164 	 */
11165 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11166 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11167 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11168 	    old_dm_crtc_state != NULL &&
11169 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11170 		return true;
11171 	}
11172 
11173 	/* CRTC Degamma changes currently require us to recreate planes. */
11174 	if (new_crtc_state->color_mgmt_changed)
11175 		return true;
11176 
11177 	/*
11178 	 * On zpos change, planes need to be reordered by removing and re-adding
11179 	 * them one by one to the dc state, in order of descending zpos.
11180 	 *
11181 	 * TODO: We can likely skip bandwidth validation if the only thing that
11182 	 * changed about the plane was it'z z-ordering.
11183 	 */
11184 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11185 		return true;
11186 
11187 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11188 		return true;
11189 
11190 	/*
11191 	 * If there are any new primary or overlay planes being added or
11192 	 * removed then the z-order can potentially change. To ensure
11193 	 * correct z-order and pipe acquisition the current DC architecture
11194 	 * requires us to remove and recreate all existing planes.
11195 	 *
11196 	 * TODO: Come up with a more elegant solution for this.
11197 	 */
11198 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11199 		struct amdgpu_framebuffer *old_afb, *new_afb;
11200 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11201 
11202 		dm_new_other_state = to_dm_plane_state(new_other_state);
11203 		dm_old_other_state = to_dm_plane_state(old_other_state);
11204 
11205 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11206 			continue;
11207 
11208 		if (old_other_state->crtc != new_plane_state->crtc &&
11209 		    new_other_state->crtc != new_plane_state->crtc)
11210 			continue;
11211 
11212 		if (old_other_state->crtc != new_other_state->crtc)
11213 			return true;
11214 
11215 		/* Src/dst size and scaling updates. */
11216 		if (old_other_state->src_w != new_other_state->src_w ||
11217 		    old_other_state->src_h != new_other_state->src_h ||
11218 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11219 		    old_other_state->crtc_h != new_other_state->crtc_h)
11220 			return true;
11221 
11222 		/* Rotation / mirroring updates. */
11223 		if (old_other_state->rotation != new_other_state->rotation)
11224 			return true;
11225 
11226 		/* Blending updates. */
11227 		if (old_other_state->pixel_blend_mode !=
11228 		    new_other_state->pixel_blend_mode)
11229 			return true;
11230 
11231 		/* Alpha updates. */
11232 		if (old_other_state->alpha != new_other_state->alpha)
11233 			return true;
11234 
11235 		/* Colorspace changes. */
11236 		if (old_other_state->color_range != new_other_state->color_range ||
11237 		    old_other_state->color_encoding != new_other_state->color_encoding)
11238 			return true;
11239 
11240 		/* HDR/Transfer Function changes. */
11241 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11242 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11243 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11244 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11245 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11246 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11247 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11248 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11249 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11250 			return true;
11251 
11252 		/* Framebuffer checks fall at the end. */
11253 		if (!old_other_state->fb || !new_other_state->fb)
11254 			continue;
11255 
11256 		/* Pixel format changes can require bandwidth updates. */
11257 		if (old_other_state->fb->format != new_other_state->fb->format)
11258 			return true;
11259 
11260 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11261 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11262 
11263 		/* Tiling and DCC changes also require bandwidth updates. */
11264 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11265 		    old_afb->base.modifier != new_afb->base.modifier)
11266 			return true;
11267 	}
11268 
11269 	return false;
11270 }
11271 
11272 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11273 			      struct drm_plane_state *new_plane_state,
11274 			      struct drm_framebuffer *fb)
11275 {
11276 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11277 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11278 	unsigned int pitch;
11279 	bool linear;
11280 
11281 	if (fb->width > new_acrtc->max_cursor_width ||
11282 	    fb->height > new_acrtc->max_cursor_height) {
11283 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
11284 				 new_plane_state->fb->width,
11285 				 new_plane_state->fb->height);
11286 		return -EINVAL;
11287 	}
11288 	if (new_plane_state->src_w != fb->width << 16 ||
11289 	    new_plane_state->src_h != fb->height << 16) {
11290 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
11291 		return -EINVAL;
11292 	}
11293 
11294 	/* Pitch in pixels */
11295 	pitch = fb->pitches[0] / fb->format->cpp[0];
11296 
11297 	if (fb->width != pitch) {
11298 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
11299 				 fb->width, pitch);
11300 		return -EINVAL;
11301 	}
11302 
11303 	switch (pitch) {
11304 	case 64:
11305 	case 128:
11306 	case 256:
11307 		/* FB pitch is supported by cursor plane */
11308 		break;
11309 	default:
11310 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
11311 		return -EINVAL;
11312 	}
11313 
11314 	/* Core DRM takes care of checking FB modifiers, so we only need to
11315 	 * check tiling flags when the FB doesn't have a modifier.
11316 	 */
11317 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11318 		if (adev->family >= AMDGPU_FAMILY_GC_12_0_0) {
11319 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11320 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11321 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11322 		} else {
11323 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11324 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11325 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11326 		}
11327 		if (!linear) {
11328 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
11329 			return -EINVAL;
11330 		}
11331 	}
11332 
11333 	return 0;
11334 }
11335 
11336 /*
11337  * Helper function for checking the cursor in native mode
11338  */
11339 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11340 					struct drm_plane *plane,
11341 					struct drm_plane_state *new_plane_state,
11342 					bool enable)
11343 {
11344 
11345 	struct amdgpu_crtc *new_acrtc;
11346 	int ret;
11347 
11348 	if (!enable || !new_plane_crtc ||
11349 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11350 		return 0;
11351 
11352 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11353 
11354 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11355 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
11356 		return -EINVAL;
11357 	}
11358 
11359 	if (new_plane_state->fb) {
11360 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11361 						new_plane_state->fb);
11362 		if (ret)
11363 			return ret;
11364 	}
11365 
11366 	return 0;
11367 }
11368 
11369 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11370 					   struct drm_crtc *old_plane_crtc,
11371 					   struct drm_crtc *new_plane_crtc,
11372 					   bool enable)
11373 {
11374 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11375 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11376 
11377 	if (!enable) {
11378 		if (old_plane_crtc == NULL)
11379 			return true;
11380 
11381 		old_crtc_state = drm_atomic_get_old_crtc_state(
11382 			state, old_plane_crtc);
11383 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11384 
11385 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11386 	} else {
11387 		if (new_plane_crtc == NULL)
11388 			return true;
11389 
11390 		new_crtc_state = drm_atomic_get_new_crtc_state(
11391 			state, new_plane_crtc);
11392 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11393 
11394 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11395 	}
11396 }
11397 
11398 static int dm_update_plane_state(struct dc *dc,
11399 				 struct drm_atomic_state *state,
11400 				 struct drm_plane *plane,
11401 				 struct drm_plane_state *old_plane_state,
11402 				 struct drm_plane_state *new_plane_state,
11403 				 bool enable,
11404 				 bool *lock_and_validation_needed,
11405 				 bool *is_top_most_overlay)
11406 {
11407 
11408 	struct dm_atomic_state *dm_state = NULL;
11409 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11410 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11411 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11412 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11413 	bool needs_reset, update_native_cursor;
11414 	int ret = 0;
11415 
11416 
11417 	new_plane_crtc = new_plane_state->crtc;
11418 	old_plane_crtc = old_plane_state->crtc;
11419 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11420 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11421 
11422 	update_native_cursor = dm_should_update_native_cursor(state,
11423 							      old_plane_crtc,
11424 							      new_plane_crtc,
11425 							      enable);
11426 
11427 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11428 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11429 						    new_plane_state, enable);
11430 		if (ret)
11431 			return ret;
11432 
11433 		return 0;
11434 	}
11435 
11436 	needs_reset = should_reset_plane(state, plane, old_plane_state,
11437 					 new_plane_state);
11438 
11439 	/* Remove any changed/removed planes */
11440 	if (!enable) {
11441 		if (!needs_reset)
11442 			return 0;
11443 
11444 		if (!old_plane_crtc)
11445 			return 0;
11446 
11447 		old_crtc_state = drm_atomic_get_old_crtc_state(
11448 				state, old_plane_crtc);
11449 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11450 
11451 		if (!dm_old_crtc_state->stream)
11452 			return 0;
11453 
11454 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
11455 				plane->base.id, old_plane_crtc->base.id);
11456 
11457 		ret = dm_atomic_get_state(state, &dm_state);
11458 		if (ret)
11459 			return ret;
11460 
11461 		if (!dc_state_remove_plane(
11462 				dc,
11463 				dm_old_crtc_state->stream,
11464 				dm_old_plane_state->dc_state,
11465 				dm_state->context)) {
11466 
11467 			return -EINVAL;
11468 		}
11469 
11470 		if (dm_old_plane_state->dc_state)
11471 			dc_plane_state_release(dm_old_plane_state->dc_state);
11472 
11473 		dm_new_plane_state->dc_state = NULL;
11474 
11475 		*lock_and_validation_needed = true;
11476 
11477 	} else { /* Add new planes */
11478 		struct dc_plane_state *dc_new_plane_state;
11479 
11480 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
11481 			return 0;
11482 
11483 		if (!new_plane_crtc)
11484 			return 0;
11485 
11486 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
11487 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11488 
11489 		if (!dm_new_crtc_state->stream)
11490 			return 0;
11491 
11492 		if (!needs_reset)
11493 			return 0;
11494 
11495 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
11496 		if (ret)
11497 			goto out;
11498 
11499 		WARN_ON(dm_new_plane_state->dc_state);
11500 
11501 		dc_new_plane_state = dc_create_plane_state(dc);
11502 		if (!dc_new_plane_state) {
11503 			ret = -ENOMEM;
11504 			goto out;
11505 		}
11506 
11507 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
11508 				 plane->base.id, new_plane_crtc->base.id);
11509 
11510 		ret = fill_dc_plane_attributes(
11511 			drm_to_adev(new_plane_crtc->dev),
11512 			dc_new_plane_state,
11513 			new_plane_state,
11514 			new_crtc_state);
11515 		if (ret) {
11516 			dc_plane_state_release(dc_new_plane_state);
11517 			goto out;
11518 		}
11519 
11520 		ret = dm_atomic_get_state(state, &dm_state);
11521 		if (ret) {
11522 			dc_plane_state_release(dc_new_plane_state);
11523 			goto out;
11524 		}
11525 
11526 		/*
11527 		 * Any atomic check errors that occur after this will
11528 		 * not need a release. The plane state will be attached
11529 		 * to the stream, and therefore part of the atomic
11530 		 * state. It'll be released when the atomic state is
11531 		 * cleaned.
11532 		 */
11533 		if (!dc_state_add_plane(
11534 				dc,
11535 				dm_new_crtc_state->stream,
11536 				dc_new_plane_state,
11537 				dm_state->context)) {
11538 
11539 			dc_plane_state_release(dc_new_plane_state);
11540 			ret = -EINVAL;
11541 			goto out;
11542 		}
11543 
11544 		dm_new_plane_state->dc_state = dc_new_plane_state;
11545 
11546 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
11547 
11548 		/* Tell DC to do a full surface update every time there
11549 		 * is a plane change. Inefficient, but works for now.
11550 		 */
11551 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
11552 
11553 		*lock_and_validation_needed = true;
11554 	}
11555 
11556 out:
11557 	/* If enabling cursor overlay failed, attempt fallback to native mode */
11558 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
11559 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11560 						    new_plane_state, enable);
11561 		if (ret)
11562 			return ret;
11563 
11564 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
11565 	}
11566 
11567 	return ret;
11568 }
11569 
11570 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
11571 				       int *src_w, int *src_h)
11572 {
11573 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
11574 	case DRM_MODE_ROTATE_90:
11575 	case DRM_MODE_ROTATE_270:
11576 		*src_w = plane_state->src_h >> 16;
11577 		*src_h = plane_state->src_w >> 16;
11578 		break;
11579 	case DRM_MODE_ROTATE_0:
11580 	case DRM_MODE_ROTATE_180:
11581 	default:
11582 		*src_w = plane_state->src_w >> 16;
11583 		*src_h = plane_state->src_h >> 16;
11584 		break;
11585 	}
11586 }
11587 
11588 static void
11589 dm_get_plane_scale(struct drm_plane_state *plane_state,
11590 		   int *out_plane_scale_w, int *out_plane_scale_h)
11591 {
11592 	int plane_src_w, plane_src_h;
11593 
11594 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
11595 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
11596 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
11597 }
11598 
11599 /*
11600  * The normalized_zpos value cannot be used by this iterator directly. It's only
11601  * calculated for enabled planes, potentially causing normalized_zpos collisions
11602  * between enabled/disabled planes in the atomic state. We need a unique value
11603  * so that the iterator will not generate the same object twice, or loop
11604  * indefinitely.
11605  */
11606 static inline struct __drm_planes_state *__get_next_zpos(
11607 	struct drm_atomic_state *state,
11608 	struct __drm_planes_state *prev)
11609 {
11610 	unsigned int highest_zpos = 0, prev_zpos = 256;
11611 	uint32_t highest_id = 0, prev_id = UINT_MAX;
11612 	struct drm_plane_state *new_plane_state;
11613 	struct drm_plane *plane;
11614 	int i, highest_i = -1;
11615 
11616 	if (prev != NULL) {
11617 		prev_zpos = prev->new_state->zpos;
11618 		prev_id = prev->ptr->base.id;
11619 	}
11620 
11621 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
11622 		/* Skip planes with higher zpos than the previously returned */
11623 		if (new_plane_state->zpos > prev_zpos ||
11624 		    (new_plane_state->zpos == prev_zpos &&
11625 		     plane->base.id >= prev_id))
11626 			continue;
11627 
11628 		/* Save the index of the plane with highest zpos */
11629 		if (new_plane_state->zpos > highest_zpos ||
11630 		    (new_plane_state->zpos == highest_zpos &&
11631 		     plane->base.id > highest_id)) {
11632 			highest_zpos = new_plane_state->zpos;
11633 			highest_id = plane->base.id;
11634 			highest_i = i;
11635 		}
11636 	}
11637 
11638 	if (highest_i < 0)
11639 		return NULL;
11640 
11641 	return &state->planes[highest_i];
11642 }
11643 
11644 /*
11645  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
11646  * by descending zpos, as read from the new plane state. This is the same
11647  * ordering as defined by drm_atomic_normalize_zpos().
11648  */
11649 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
11650 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
11651 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
11652 		for_each_if(((plane) = __i->ptr,				\
11653 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
11654 			     (old_plane_state) = __i->old_state,		\
11655 			     (new_plane_state) = __i->new_state, 1))
11656 
11657 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
11658 {
11659 	struct drm_connector *connector;
11660 	struct drm_connector_state *conn_state, *old_conn_state;
11661 	struct amdgpu_dm_connector *aconnector = NULL;
11662 	int i;
11663 
11664 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
11665 		if (!conn_state->crtc)
11666 			conn_state = old_conn_state;
11667 
11668 		if (conn_state->crtc != crtc)
11669 			continue;
11670 
11671 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11672 			continue;
11673 
11674 		aconnector = to_amdgpu_dm_connector(connector);
11675 		if (!aconnector->mst_output_port || !aconnector->mst_root)
11676 			aconnector = NULL;
11677 		else
11678 			break;
11679 	}
11680 
11681 	if (!aconnector)
11682 		return 0;
11683 
11684 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
11685 }
11686 
11687 /**
11688  * DOC: Cursor Modes - Native vs Overlay
11689  *
11690  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
11691  * plane. It does not require a dedicated hw plane to enable, but it is
11692  * subjected to the same z-order and scaling as the hw plane. It also has format
11693  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
11694  * hw plane.
11695  *
11696  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
11697  * own scaling and z-pos. It also has no blending restrictions. It lends to a
11698  * cursor behavior more akin to a DRM client's expectations. However, it does
11699  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
11700  * available.
11701  */
11702 
11703 /**
11704  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
11705  * @adev: amdgpu device
11706  * @state: DRM atomic state
11707  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
11708  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
11709  *
11710  * Get whether the cursor should be enabled in native mode, or overlay mode, on
11711  * the dm_crtc_state.
11712  *
11713  * The cursor should be enabled in overlay mode if there exists an underlying
11714  * plane - on which the cursor may be blended - that is either YUV formatted, or
11715  * scaled differently from the cursor.
11716  *
11717  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
11718  * calling this function.
11719  *
11720  * Return: 0 on success, or an error code if getting the cursor plane state
11721  * failed.
11722  */
11723 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
11724 				   struct drm_atomic_state *state,
11725 				   struct dm_crtc_state *dm_crtc_state,
11726 				   enum amdgpu_dm_cursor_mode *cursor_mode)
11727 {
11728 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
11729 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
11730 	struct drm_plane *plane;
11731 	bool consider_mode_change = false;
11732 	bool entire_crtc_covered = false;
11733 	bool cursor_changed = false;
11734 	int underlying_scale_w, underlying_scale_h;
11735 	int cursor_scale_w, cursor_scale_h;
11736 	int i;
11737 
11738 	/* Overlay cursor not supported on HW before DCN
11739 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
11740 	 * as previous DCN generations, so enable native mode on DCN401 in addition to DCE
11741 	 */
11742 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0 ||
11743 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
11744 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11745 		return 0;
11746 	}
11747 
11748 	/* Init cursor_mode to be the same as current */
11749 	*cursor_mode = dm_crtc_state->cursor_mode;
11750 
11751 	/*
11752 	 * Cursor mode can change if a plane's format changes, scale changes, is
11753 	 * enabled/disabled, or z-order changes.
11754 	 */
11755 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
11756 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
11757 
11758 		/* Only care about planes on this CRTC */
11759 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
11760 			continue;
11761 
11762 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
11763 			cursor_changed = true;
11764 
11765 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
11766 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
11767 		    old_plane_state->fb->format != plane_state->fb->format) {
11768 			consider_mode_change = true;
11769 			break;
11770 		}
11771 
11772 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
11773 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
11774 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
11775 			consider_mode_change = true;
11776 			break;
11777 		}
11778 	}
11779 
11780 	if (!consider_mode_change && !crtc_state->zpos_changed)
11781 		return 0;
11782 
11783 	/*
11784 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
11785 	 * no need to set cursor mode. This avoids needlessly locking the cursor
11786 	 * state.
11787 	 */
11788 	if (!cursor_changed &&
11789 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
11790 		return 0;
11791 	}
11792 
11793 	cursor_state = drm_atomic_get_plane_state(state,
11794 						  crtc_state->crtc->cursor);
11795 	if (IS_ERR(cursor_state))
11796 		return PTR_ERR(cursor_state);
11797 
11798 	/* Cursor is disabled */
11799 	if (!cursor_state->fb)
11800 		return 0;
11801 
11802 	/* For all planes in descending z-order (all of which are below cursor
11803 	 * as per zpos definitions), check their scaling and format
11804 	 */
11805 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
11806 
11807 		/* Only care about non-cursor planes on this CRTC */
11808 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
11809 		    plane->type == DRM_PLANE_TYPE_CURSOR)
11810 			continue;
11811 
11812 		/* Underlying plane is YUV format - use overlay cursor */
11813 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
11814 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11815 			return 0;
11816 		}
11817 
11818 		dm_get_plane_scale(plane_state,
11819 				   &underlying_scale_w, &underlying_scale_h);
11820 		dm_get_plane_scale(cursor_state,
11821 				   &cursor_scale_w, &cursor_scale_h);
11822 
11823 		/* Underlying plane has different scale - use overlay cursor */
11824 		if (cursor_scale_w != underlying_scale_w &&
11825 		    cursor_scale_h != underlying_scale_h) {
11826 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11827 			return 0;
11828 		}
11829 
11830 		/* If this plane covers the whole CRTC, no need to check planes underneath */
11831 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
11832 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
11833 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
11834 			entire_crtc_covered = true;
11835 			break;
11836 		}
11837 	}
11838 
11839 	/* If planes do not cover the entire CRTC, use overlay mode to enable
11840 	 * cursor over holes
11841 	 */
11842 	if (entire_crtc_covered)
11843 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
11844 	else
11845 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
11846 
11847 	return 0;
11848 }
11849 
11850 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
11851 					    struct drm_atomic_state *state,
11852 					    struct drm_crtc_state *crtc_state)
11853 {
11854 	struct drm_plane *plane;
11855 	struct drm_plane_state *new_plane_state, *old_plane_state;
11856 
11857 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
11858 		new_plane_state = drm_atomic_get_plane_state(state, plane);
11859 		old_plane_state = drm_atomic_get_plane_state(state, plane);
11860 
11861 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
11862 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
11863 			return false;
11864 		}
11865 
11866 		if (old_plane_state->fb && new_plane_state->fb &&
11867 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
11868 			return true;
11869 	}
11870 
11871 	return false;
11872 }
11873 
11874 /**
11875  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
11876  *
11877  * @dev: The DRM device
11878  * @state: The atomic state to commit
11879  *
11880  * Validate that the given atomic state is programmable by DC into hardware.
11881  * This involves constructing a &struct dc_state reflecting the new hardware
11882  * state we wish to commit, then querying DC to see if it is programmable. It's
11883  * important not to modify the existing DC state. Otherwise, atomic_check
11884  * may unexpectedly commit hardware changes.
11885  *
11886  * When validating the DC state, it's important that the right locks are
11887  * acquired. For full updates case which removes/adds/updates streams on one
11888  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
11889  * that any such full update commit will wait for completion of any outstanding
11890  * flip using DRMs synchronization events.
11891  *
11892  * Note that DM adds the affected connectors for all CRTCs in state, when that
11893  * might not seem necessary. This is because DC stream creation requires the
11894  * DC sink, which is tied to the DRM connector state. Cleaning this up should
11895  * be possible but non-trivial - a possible TODO item.
11896  *
11897  * Return: -Error code if validation failed.
11898  */
11899 static int amdgpu_dm_atomic_check(struct drm_device *dev,
11900 				  struct drm_atomic_state *state)
11901 {
11902 	struct amdgpu_device *adev = drm_to_adev(dev);
11903 	struct dm_atomic_state *dm_state = NULL;
11904 	struct dc *dc = adev->dm.dc;
11905 	struct drm_connector *connector;
11906 	struct drm_connector_state *old_con_state, *new_con_state;
11907 	struct drm_crtc *crtc;
11908 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11909 	struct drm_plane *plane;
11910 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
11911 	enum dc_status status;
11912 	int ret, i;
11913 	bool lock_and_validation_needed = false;
11914 	bool is_top_most_overlay = true;
11915 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11916 	struct drm_dp_mst_topology_mgr *mgr;
11917 	struct drm_dp_mst_topology_state *mst_state;
11918 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
11919 
11920 	trace_amdgpu_dm_atomic_check_begin(state);
11921 
11922 	ret = drm_atomic_helper_check_modeset(dev, state);
11923 	if (ret) {
11924 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
11925 		goto fail;
11926 	}
11927 
11928 	/* Check connector changes */
11929 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11930 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11931 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11932 
11933 		/* Skip connectors that are disabled or part of modeset already. */
11934 		if (!new_con_state->crtc)
11935 			continue;
11936 
11937 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
11938 		if (IS_ERR(new_crtc_state)) {
11939 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
11940 			ret = PTR_ERR(new_crtc_state);
11941 			goto fail;
11942 		}
11943 
11944 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
11945 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
11946 			new_crtc_state->connectors_changed = true;
11947 	}
11948 
11949 	if (dc_resource_is_dsc_encoding_supported(dc)) {
11950 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11951 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11952 				ret = add_affected_mst_dsc_crtcs(state, crtc);
11953 				if (ret) {
11954 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
11955 					goto fail;
11956 				}
11957 			}
11958 		}
11959 	}
11960 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11961 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11962 
11963 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
11964 		    !new_crtc_state->color_mgmt_changed &&
11965 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
11966 			dm_old_crtc_state->dsc_force_changed == false)
11967 			continue;
11968 
11969 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
11970 		if (ret) {
11971 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
11972 			goto fail;
11973 		}
11974 
11975 		if (!new_crtc_state->enable)
11976 			continue;
11977 
11978 		ret = drm_atomic_add_affected_connectors(state, crtc);
11979 		if (ret) {
11980 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
11981 			goto fail;
11982 		}
11983 
11984 		ret = drm_atomic_add_affected_planes(state, crtc);
11985 		if (ret) {
11986 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
11987 			goto fail;
11988 		}
11989 
11990 		if (dm_old_crtc_state->dsc_force_changed)
11991 			new_crtc_state->mode_changed = true;
11992 	}
11993 
11994 	/*
11995 	 * Add all primary and overlay planes on the CRTC to the state
11996 	 * whenever a plane is enabled to maintain correct z-ordering
11997 	 * and to enable fast surface updates.
11998 	 */
11999 	drm_for_each_crtc(crtc, dev) {
12000 		bool modified = false;
12001 
12002 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12003 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12004 				continue;
12005 
12006 			if (new_plane_state->crtc == crtc ||
12007 			    old_plane_state->crtc == crtc) {
12008 				modified = true;
12009 				break;
12010 			}
12011 		}
12012 
12013 		if (!modified)
12014 			continue;
12015 
12016 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12017 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12018 				continue;
12019 
12020 			new_plane_state =
12021 				drm_atomic_get_plane_state(state, plane);
12022 
12023 			if (IS_ERR(new_plane_state)) {
12024 				ret = PTR_ERR(new_plane_state);
12025 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12026 				goto fail;
12027 			}
12028 		}
12029 	}
12030 
12031 	/*
12032 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12033 	 * hw plane on which to enable the hw cursor (see
12034 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12035 	 * atomic state, so call drm helper to normalize zpos.
12036 	 */
12037 	ret = drm_atomic_normalize_zpos(dev, state);
12038 	if (ret) {
12039 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12040 		goto fail;
12041 	}
12042 
12043 	/*
12044 	 * Determine whether cursors on each CRTC should be enabled in native or
12045 	 * overlay mode.
12046 	 */
12047 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12048 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12049 
12050 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12051 					      &dm_new_crtc_state->cursor_mode);
12052 		if (ret) {
12053 			drm_dbg(dev, "Failed to determine cursor mode\n");
12054 			goto fail;
12055 		}
12056 
12057 		/*
12058 		 * If overlay cursor is needed, DC cannot go through the
12059 		 * native cursor update path. All enabled planes on the CRTC
12060 		 * need to be added for DC to not disable a plane by mistake
12061 		 */
12062 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12063 			ret = drm_atomic_add_affected_planes(state, crtc);
12064 			if (ret)
12065 				goto fail;
12066 		}
12067 	}
12068 
12069 	/* Remove exiting planes if they are modified */
12070 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12071 
12072 		ret = dm_update_plane_state(dc, state, plane,
12073 					    old_plane_state,
12074 					    new_plane_state,
12075 					    false,
12076 					    &lock_and_validation_needed,
12077 					    &is_top_most_overlay);
12078 		if (ret) {
12079 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12080 			goto fail;
12081 		}
12082 	}
12083 
12084 	/* Disable all crtcs which require disable */
12085 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12086 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12087 					   old_crtc_state,
12088 					   new_crtc_state,
12089 					   false,
12090 					   &lock_and_validation_needed);
12091 		if (ret) {
12092 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12093 			goto fail;
12094 		}
12095 	}
12096 
12097 	/* Enable all crtcs which require enable */
12098 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12099 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12100 					   old_crtc_state,
12101 					   new_crtc_state,
12102 					   true,
12103 					   &lock_and_validation_needed);
12104 		if (ret) {
12105 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12106 			goto fail;
12107 		}
12108 	}
12109 
12110 	/* Add new/modified planes */
12111 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12112 		ret = dm_update_plane_state(dc, state, plane,
12113 					    old_plane_state,
12114 					    new_plane_state,
12115 					    true,
12116 					    &lock_and_validation_needed,
12117 					    &is_top_most_overlay);
12118 		if (ret) {
12119 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12120 			goto fail;
12121 		}
12122 	}
12123 
12124 #if defined(CONFIG_DRM_AMD_DC_FP)
12125 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12126 		ret = pre_validate_dsc(state, &dm_state, vars);
12127 		if (ret != 0)
12128 			goto fail;
12129 	}
12130 #endif
12131 
12132 	/* Run this here since we want to validate the streams we created */
12133 	ret = drm_atomic_helper_check_planes(dev, state);
12134 	if (ret) {
12135 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12136 		goto fail;
12137 	}
12138 
12139 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12140 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12141 		if (dm_new_crtc_state->mpo_requested)
12142 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12143 	}
12144 
12145 	/* Check cursor restrictions */
12146 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12147 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12148 		int is_rotated, is_scaled;
12149 
12150 		/* Overlay cusor not subject to native cursor restrictions */
12151 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12152 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12153 			continue;
12154 
12155 		/* Check if rotation or scaling is enabled on DCN401 */
12156 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12157 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12158 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12159 
12160 			is_rotated = new_cursor_state &&
12161 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12162 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12163 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12164 
12165 			if (is_rotated || is_scaled) {
12166 				drm_dbg_driver(
12167 					crtc->dev,
12168 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12169 					crtc->base.id, crtc->name);
12170 				ret = -EINVAL;
12171 				goto fail;
12172 			}
12173 		}
12174 
12175 		/* If HW can only do native cursor, check restrictions again */
12176 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12177 					      &required_cursor_mode);
12178 		if (ret) {
12179 			drm_dbg_driver(crtc->dev,
12180 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12181 				       crtc->base.id, crtc->name);
12182 			goto fail;
12183 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12184 			drm_dbg_driver(crtc->dev,
12185 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12186 				       crtc->base.id, crtc->name);
12187 			ret = -EINVAL;
12188 			goto fail;
12189 		}
12190 	}
12191 
12192 	if (state->legacy_cursor_update) {
12193 		/*
12194 		 * This is a fast cursor update coming from the plane update
12195 		 * helper, check if it can be done asynchronously for better
12196 		 * performance.
12197 		 */
12198 		state->async_update =
12199 			!drm_atomic_helper_async_check(dev, state);
12200 
12201 		/*
12202 		 * Skip the remaining global validation if this is an async
12203 		 * update. Cursor updates can be done without affecting
12204 		 * state or bandwidth calcs and this avoids the performance
12205 		 * penalty of locking the private state object and
12206 		 * allocating a new dc_state.
12207 		 */
12208 		if (state->async_update)
12209 			return 0;
12210 	}
12211 
12212 	/* Check scaling and underscan changes*/
12213 	/* TODO Removed scaling changes validation due to inability to commit
12214 	 * new stream into context w\o causing full reset. Need to
12215 	 * decide how to handle.
12216 	 */
12217 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12218 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12219 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12220 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12221 
12222 		/* Skip any modesets/resets */
12223 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12224 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12225 			continue;
12226 
12227 		/* Skip any thing not scale or underscan changes */
12228 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12229 			continue;
12230 
12231 		lock_and_validation_needed = true;
12232 	}
12233 
12234 	/* set the slot info for each mst_state based on the link encoding format */
12235 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12236 		struct amdgpu_dm_connector *aconnector;
12237 		struct drm_connector *connector;
12238 		struct drm_connector_list_iter iter;
12239 		u8 link_coding_cap;
12240 
12241 		drm_connector_list_iter_begin(dev, &iter);
12242 		drm_for_each_connector_iter(connector, &iter) {
12243 			if (connector->index == mst_state->mgr->conn_base_id) {
12244 				aconnector = to_amdgpu_dm_connector(connector);
12245 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12246 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12247 
12248 				break;
12249 			}
12250 		}
12251 		drm_connector_list_iter_end(&iter);
12252 	}
12253 
12254 	/**
12255 	 * Streams and planes are reset when there are changes that affect
12256 	 * bandwidth. Anything that affects bandwidth needs to go through
12257 	 * DC global validation to ensure that the configuration can be applied
12258 	 * to hardware.
12259 	 *
12260 	 * We have to currently stall out here in atomic_check for outstanding
12261 	 * commits to finish in this case because our IRQ handlers reference
12262 	 * DRM state directly - we can end up disabling interrupts too early
12263 	 * if we don't.
12264 	 *
12265 	 * TODO: Remove this stall and drop DM state private objects.
12266 	 */
12267 	if (lock_and_validation_needed) {
12268 		ret = dm_atomic_get_state(state, &dm_state);
12269 		if (ret) {
12270 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12271 			goto fail;
12272 		}
12273 
12274 		ret = do_aquire_global_lock(dev, state);
12275 		if (ret) {
12276 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12277 			goto fail;
12278 		}
12279 
12280 #if defined(CONFIG_DRM_AMD_DC_FP)
12281 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12282 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12283 			if (ret) {
12284 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12285 				ret = -EINVAL;
12286 				goto fail;
12287 			}
12288 		}
12289 #endif
12290 
12291 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12292 		if (ret) {
12293 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12294 			goto fail;
12295 		}
12296 
12297 		/*
12298 		 * Perform validation of MST topology in the state:
12299 		 * We need to perform MST atomic check before calling
12300 		 * dc_validate_global_state(), or there is a chance
12301 		 * to get stuck in an infinite loop and hang eventually.
12302 		 */
12303 		ret = drm_dp_mst_atomic_check(state);
12304 		if (ret) {
12305 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12306 			goto fail;
12307 		}
12308 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12309 		if (status != DC_OK) {
12310 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12311 				       dc_status_to_str(status), status);
12312 			ret = -EINVAL;
12313 			goto fail;
12314 		}
12315 	} else {
12316 		/*
12317 		 * The commit is a fast update. Fast updates shouldn't change
12318 		 * the DC context, affect global validation, and can have their
12319 		 * commit work done in parallel with other commits not touching
12320 		 * the same resource. If we have a new DC context as part of
12321 		 * the DM atomic state from validation we need to free it and
12322 		 * retain the existing one instead.
12323 		 *
12324 		 * Furthermore, since the DM atomic state only contains the DC
12325 		 * context and can safely be annulled, we can free the state
12326 		 * and clear the associated private object now to free
12327 		 * some memory and avoid a possible use-after-free later.
12328 		 */
12329 
12330 		for (i = 0; i < state->num_private_objs; i++) {
12331 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12332 
12333 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12334 				int j = state->num_private_objs-1;
12335 
12336 				dm_atomic_destroy_state(obj,
12337 						state->private_objs[i].state);
12338 
12339 				/* If i is not at the end of the array then the
12340 				 * last element needs to be moved to where i was
12341 				 * before the array can safely be truncated.
12342 				 */
12343 				if (i != j)
12344 					state->private_objs[i] =
12345 						state->private_objs[j];
12346 
12347 				state->private_objs[j].ptr = NULL;
12348 				state->private_objs[j].state = NULL;
12349 				state->private_objs[j].old_state = NULL;
12350 				state->private_objs[j].new_state = NULL;
12351 
12352 				state->num_private_objs = j;
12353 				break;
12354 			}
12355 		}
12356 	}
12357 
12358 	/* Store the overall update type for use later in atomic check. */
12359 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12360 		struct dm_crtc_state *dm_new_crtc_state =
12361 			to_dm_crtc_state(new_crtc_state);
12362 
12363 		/*
12364 		 * Only allow async flips for fast updates that don't change
12365 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12366 		 */
12367 		if (new_crtc_state->async_flip &&
12368 		    (lock_and_validation_needed ||
12369 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12370 			drm_dbg_atomic(crtc->dev,
12371 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12372 				       crtc->base.id, crtc->name);
12373 			ret = -EINVAL;
12374 			goto fail;
12375 		}
12376 
12377 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12378 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12379 	}
12380 
12381 	/* Must be success */
12382 	WARN_ON(ret);
12383 
12384 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12385 
12386 	return ret;
12387 
12388 fail:
12389 	if (ret == -EDEADLK)
12390 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12391 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12392 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12393 	else
12394 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12395 
12396 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12397 
12398 	return ret;
12399 }
12400 
12401 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12402 		unsigned int offset,
12403 		unsigned int total_length,
12404 		u8 *data,
12405 		unsigned int length,
12406 		struct amdgpu_hdmi_vsdb_info *vsdb)
12407 {
12408 	bool res;
12409 	union dmub_rb_cmd cmd;
12410 	struct dmub_cmd_send_edid_cea *input;
12411 	struct dmub_cmd_edid_cea_output *output;
12412 
12413 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12414 		return false;
12415 
12416 	memset(&cmd, 0, sizeof(cmd));
12417 
12418 	input = &cmd.edid_cea.data.input;
12419 
12420 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12421 	cmd.edid_cea.header.sub_type = 0;
12422 	cmd.edid_cea.header.payload_bytes =
12423 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12424 	input->offset = offset;
12425 	input->length = length;
12426 	input->cea_total_length = total_length;
12427 	memcpy(input->payload, data, length);
12428 
12429 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12430 	if (!res) {
12431 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
12432 		return false;
12433 	}
12434 
12435 	output = &cmd.edid_cea.data.output;
12436 
12437 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
12438 		if (!output->ack.success) {
12439 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
12440 					output->ack.offset);
12441 		}
12442 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
12443 		if (!output->amd_vsdb.vsdb_found)
12444 			return false;
12445 
12446 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
12447 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
12448 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
12449 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
12450 	} else {
12451 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
12452 		return false;
12453 	}
12454 
12455 	return true;
12456 }
12457 
12458 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
12459 		u8 *edid_ext, int len,
12460 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12461 {
12462 	int i;
12463 
12464 	/* send extension block to DMCU for parsing */
12465 	for (i = 0; i < len; i += 8) {
12466 		bool res;
12467 		int offset;
12468 
12469 		/* send 8 bytes a time */
12470 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
12471 			return false;
12472 
12473 		if (i+8 == len) {
12474 			/* EDID block sent completed, expect result */
12475 			int version, min_rate, max_rate;
12476 
12477 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
12478 			if (res) {
12479 				/* amd vsdb found */
12480 				vsdb_info->freesync_supported = 1;
12481 				vsdb_info->amd_vsdb_version = version;
12482 				vsdb_info->min_refresh_rate_hz = min_rate;
12483 				vsdb_info->max_refresh_rate_hz = max_rate;
12484 				return true;
12485 			}
12486 			/* not amd vsdb */
12487 			return false;
12488 		}
12489 
12490 		/* check for ack*/
12491 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
12492 		if (!res)
12493 			return false;
12494 	}
12495 
12496 	return false;
12497 }
12498 
12499 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
12500 		u8 *edid_ext, int len,
12501 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12502 {
12503 	int i;
12504 
12505 	/* send extension block to DMCU for parsing */
12506 	for (i = 0; i < len; i += 8) {
12507 		/* send 8 bytes a time */
12508 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
12509 			return false;
12510 	}
12511 
12512 	return vsdb_info->freesync_supported;
12513 }
12514 
12515 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
12516 		u8 *edid_ext, int len,
12517 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
12518 {
12519 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
12520 	bool ret;
12521 
12522 	mutex_lock(&adev->dm.dc_lock);
12523 	if (adev->dm.dmub_srv)
12524 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
12525 	else
12526 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
12527 	mutex_unlock(&adev->dm.dc_lock);
12528 	return ret;
12529 }
12530 
12531 static void parse_edid_displayid_vrr(struct drm_connector *connector,
12532 				     const struct edid *edid)
12533 {
12534 	u8 *edid_ext = NULL;
12535 	int i;
12536 	int j = 0;
12537 	u16 min_vfreq;
12538 	u16 max_vfreq;
12539 
12540 	if (edid == NULL || edid->extensions == 0)
12541 		return;
12542 
12543 	/* Find DisplayID extension */
12544 	for (i = 0; i < edid->extensions; i++) {
12545 		edid_ext = (void *)(edid + (i + 1));
12546 		if (edid_ext[0] == DISPLAYID_EXT)
12547 			break;
12548 	}
12549 
12550 	if (edid_ext == NULL)
12551 		return;
12552 
12553 	while (j < EDID_LENGTH) {
12554 		/* Get dynamic video timing range from DisplayID if available */
12555 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
12556 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
12557 			min_vfreq = edid_ext[j+9];
12558 			if (edid_ext[j+1] & 7)
12559 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
12560 			else
12561 				max_vfreq = edid_ext[j+10];
12562 
12563 			if (max_vfreq && min_vfreq) {
12564 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
12565 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
12566 
12567 				return;
12568 			}
12569 		}
12570 		j++;
12571 	}
12572 }
12573 
12574 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12575 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
12576 {
12577 	u8 *edid_ext = NULL;
12578 	int i;
12579 	int j = 0;
12580 
12581 	if (edid == NULL || edid->extensions == 0)
12582 		return -ENODEV;
12583 
12584 	/* Find DisplayID extension */
12585 	for (i = 0; i < edid->extensions; i++) {
12586 		edid_ext = (void *)(edid + (i + 1));
12587 		if (edid_ext[0] == DISPLAYID_EXT)
12588 			break;
12589 	}
12590 
12591 	while (j < EDID_LENGTH - sizeof(struct amd_vsdb_block)) {
12592 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
12593 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
12594 
12595 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
12596 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
12597 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
12598 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
12599 			DRM_DEBUG_KMS("Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
12600 
12601 			return true;
12602 		}
12603 		j++;
12604 	}
12605 
12606 	return false;
12607 }
12608 
12609 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
12610 			       const struct edid *edid,
12611 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
12612 {
12613 	u8 *edid_ext = NULL;
12614 	int i;
12615 	bool valid_vsdb_found = false;
12616 
12617 	/*----- drm_find_cea_extension() -----*/
12618 	/* No EDID or EDID extensions */
12619 	if (edid == NULL || edid->extensions == 0)
12620 		return -ENODEV;
12621 
12622 	/* Find CEA extension */
12623 	for (i = 0; i < edid->extensions; i++) {
12624 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
12625 		if (edid_ext[0] == CEA_EXT)
12626 			break;
12627 	}
12628 
12629 	if (i == edid->extensions)
12630 		return -ENODEV;
12631 
12632 	/*----- cea_db_offsets() -----*/
12633 	if (edid_ext[0] != CEA_EXT)
12634 		return -ENODEV;
12635 
12636 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
12637 
12638 	return valid_vsdb_found ? i : -ENODEV;
12639 }
12640 
12641 /**
12642  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
12643  *
12644  * @connector: Connector to query.
12645  * @drm_edid: DRM EDID from monitor
12646  *
12647  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
12648  * track of some of the display information in the internal data struct used by
12649  * amdgpu_dm. This function checks which type of connector we need to set the
12650  * FreeSync parameters.
12651  */
12652 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
12653 				    const struct drm_edid *drm_edid)
12654 {
12655 	int i = 0;
12656 	struct amdgpu_dm_connector *amdgpu_dm_connector =
12657 			to_amdgpu_dm_connector(connector);
12658 	struct dm_connector_state *dm_con_state = NULL;
12659 	struct dc_sink *sink;
12660 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
12661 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
12662 	const struct edid *edid;
12663 	bool freesync_capable = false;
12664 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
12665 
12666 	if (!connector->state) {
12667 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
12668 		goto update;
12669 	}
12670 
12671 	sink = amdgpu_dm_connector->dc_sink ?
12672 		amdgpu_dm_connector->dc_sink :
12673 		amdgpu_dm_connector->dc_em_sink;
12674 
12675 	drm_edid_connector_update(connector, drm_edid);
12676 
12677 	if (!drm_edid || !sink) {
12678 		dm_con_state = to_dm_connector_state(connector->state);
12679 
12680 		amdgpu_dm_connector->min_vfreq = 0;
12681 		amdgpu_dm_connector->max_vfreq = 0;
12682 		freesync_capable = false;
12683 
12684 		goto update;
12685 	}
12686 
12687 	dm_con_state = to_dm_connector_state(connector->state);
12688 
12689 	if (!adev->dm.freesync_module)
12690 		goto update;
12691 
12692 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
12693 
12694 	/* Some eDP panels only have the refresh rate range info in DisplayID */
12695 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
12696 	     connector->display_info.monitor_range.max_vfreq == 0))
12697 		parse_edid_displayid_vrr(connector, edid);
12698 
12699 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
12700 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
12701 		if (amdgpu_dm_connector->dc_link &&
12702 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
12703 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
12704 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
12705 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12706 				freesync_capable = true;
12707 		}
12708 
12709 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12710 
12711 		if (vsdb_info.replay_mode) {
12712 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
12713 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
12714 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
12715 		}
12716 
12717 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
12718 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12719 		if (i >= 0 && vsdb_info.freesync_supported) {
12720 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12721 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12722 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12723 				freesync_capable = true;
12724 
12725 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12726 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12727 		}
12728 	}
12729 
12730 	if (amdgpu_dm_connector->dc_link)
12731 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
12732 
12733 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
12734 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
12735 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
12736 
12737 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
12738 			amdgpu_dm_connector->as_type = as_type;
12739 			amdgpu_dm_connector->vsdb_info = vsdb_info;
12740 
12741 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
12742 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
12743 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
12744 				freesync_capable = true;
12745 
12746 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
12747 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
12748 		}
12749 	}
12750 
12751 update:
12752 	if (dm_con_state)
12753 		dm_con_state->freesync_capable = freesync_capable;
12754 
12755 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
12756 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
12757 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
12758 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
12759 	}
12760 
12761 	if (connector->vrr_capable_property)
12762 		drm_connector_set_vrr_capable_property(connector,
12763 						       freesync_capable);
12764 }
12765 
12766 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
12767 {
12768 	struct amdgpu_device *adev = drm_to_adev(dev);
12769 	struct dc *dc = adev->dm.dc;
12770 	int i;
12771 
12772 	mutex_lock(&adev->dm.dc_lock);
12773 	if (dc->current_state) {
12774 		for (i = 0; i < dc->current_state->stream_count; ++i)
12775 			dc->current_state->streams[i]
12776 				->triggered_crtc_reset.enabled =
12777 				adev->dm.force_timing_sync;
12778 
12779 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
12780 		dc_trigger_sync(dc, dc->current_state);
12781 	}
12782 	mutex_unlock(&adev->dm.dc_lock);
12783 }
12784 
12785 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
12786 {
12787 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
12788 		dc_exit_ips_for_hw_access(dc);
12789 }
12790 
12791 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
12792 		       u32 value, const char *func_name)
12793 {
12794 #ifdef DM_CHECK_ADDR_0
12795 	if (address == 0) {
12796 		drm_err(adev_to_drm(ctx->driver_context),
12797 			"invalid register write. address = 0");
12798 		return;
12799 	}
12800 #endif
12801 
12802 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12803 	cgs_write_register(ctx->cgs_device, address, value);
12804 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
12805 }
12806 
12807 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
12808 			  const char *func_name)
12809 {
12810 	u32 value;
12811 #ifdef DM_CHECK_ADDR_0
12812 	if (address == 0) {
12813 		drm_err(adev_to_drm(ctx->driver_context),
12814 			"invalid register read; address = 0\n");
12815 		return 0;
12816 	}
12817 #endif
12818 
12819 	if (ctx->dmub_srv &&
12820 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
12821 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
12822 		ASSERT(false);
12823 		return 0;
12824 	}
12825 
12826 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
12827 
12828 	value = cgs_read_register(ctx->cgs_device, address);
12829 
12830 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
12831 
12832 	return value;
12833 }
12834 
12835 int amdgpu_dm_process_dmub_aux_transfer_sync(
12836 		struct dc_context *ctx,
12837 		unsigned int link_index,
12838 		struct aux_payload *payload,
12839 		enum aux_return_code_type *operation_result)
12840 {
12841 	struct amdgpu_device *adev = ctx->driver_context;
12842 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
12843 	int ret = -1;
12844 
12845 	mutex_lock(&adev->dm.dpia_aux_lock);
12846 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
12847 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
12848 		goto out;
12849 	}
12850 
12851 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12852 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
12853 		*operation_result = AUX_RET_ERROR_TIMEOUT;
12854 		goto out;
12855 	}
12856 
12857 	if (p_notify->result != AUX_RET_SUCCESS) {
12858 		/*
12859 		 * Transient states before tunneling is enabled could
12860 		 * lead to this error. We can ignore this for now.
12861 		 */
12862 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
12863 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
12864 					payload->address, payload->length,
12865 					p_notify->result);
12866 		}
12867 		*operation_result = p_notify->result;
12868 		goto out;
12869 	}
12870 
12871 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
12872 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
12873 		/* The reply is stored in the top nibble of the command. */
12874 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
12875 
12876 	/*write req may receive a byte indicating partially written number as well*/
12877 	if (p_notify->aux_reply.length)
12878 		memcpy(payload->data, p_notify->aux_reply.data,
12879 				p_notify->aux_reply.length);
12880 
12881 	/* success */
12882 	ret = p_notify->aux_reply.length;
12883 	*operation_result = p_notify->result;
12884 out:
12885 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
12886 	mutex_unlock(&adev->dm.dpia_aux_lock);
12887 	return ret;
12888 }
12889 
12890 static void abort_fused_io(
12891 		struct dc_context *ctx,
12892 		const struct dmub_cmd_fused_request *request
12893 )
12894 {
12895 	union dmub_rb_cmd command = { 0 };
12896 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
12897 
12898 	io->header.type = DMUB_CMD__FUSED_IO;
12899 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
12900 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
12901 	io->request = *request;
12902 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
12903 }
12904 
12905 static bool execute_fused_io(
12906 		struct amdgpu_device *dev,
12907 		struct dc_context *ctx,
12908 		union dmub_rb_cmd *commands,
12909 		uint8_t count,
12910 		uint32_t timeout_us
12911 )
12912 {
12913 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
12914 
12915 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
12916 		return false;
12917 
12918 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
12919 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
12920 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
12921 			&& first->header.ret_status
12922 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
12923 
12924 	if (!result)
12925 		return false;
12926 
12927 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
12928 		reinit_completion(&sync->replied);
12929 
12930 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
12931 
12932 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
12933 
12934 		if (reply->identifier == first->request.identifier) {
12935 			first->request = *reply;
12936 			return true;
12937 		}
12938 	}
12939 
12940 	reinit_completion(&sync->replied);
12941 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
12942 	abort_fused_io(ctx, &first->request);
12943 	return false;
12944 }
12945 
12946 bool amdgpu_dm_execute_fused_io(
12947 		struct amdgpu_device *dev,
12948 		struct dc_link *link,
12949 		union dmub_rb_cmd *commands,
12950 		uint8_t count,
12951 		uint32_t timeout_us)
12952 {
12953 	struct amdgpu_display_manager *dm = &dev->dm;
12954 
12955 	mutex_lock(&dm->dpia_aux_lock);
12956 
12957 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
12958 
12959 	mutex_unlock(&dm->dpia_aux_lock);
12960 	return result;
12961 }
12962 
12963 int amdgpu_dm_process_dmub_set_config_sync(
12964 		struct dc_context *ctx,
12965 		unsigned int link_index,
12966 		struct set_config_cmd_payload *payload,
12967 		enum set_config_status *operation_result)
12968 {
12969 	struct amdgpu_device *adev = ctx->driver_context;
12970 	bool is_cmd_complete;
12971 	int ret;
12972 
12973 	mutex_lock(&adev->dm.dpia_aux_lock);
12974 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
12975 			link_index, payload, adev->dm.dmub_notify);
12976 
12977 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
12978 		ret = 0;
12979 		*operation_result = adev->dm.dmub_notify->sc_status;
12980 	} else {
12981 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
12982 		ret = -1;
12983 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
12984 	}
12985 
12986 	if (!is_cmd_complete)
12987 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
12988 	mutex_unlock(&adev->dm.dpia_aux_lock);
12989 	return ret;
12990 }
12991 
12992 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
12993 {
12994 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
12995 }
12996 
12997 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)
12998 {
12999 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13000 }
13001 
13002 void dm_acpi_process_phy_transition_interlock(
13003 	const struct dc_context *ctx,
13004 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13005 {
13006 	// Not yet implemented
13007 }
13008