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