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