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