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