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