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