xref: /openbmc/linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 9b93eb475aa9e7ad856780886cb3c435b6176b76)
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 "dc/inc/core_types.h"
32 #include "dal_asic_id.h"
33 
34 #include "vid.h"
35 #include "amdgpu.h"
36 #include "amdgpu_display.h"
37 #include "amdgpu_ucode.h"
38 #include "atom.h"
39 #include "amdgpu_dm.h"
40 #include "amdgpu_pm.h"
41 
42 #include "amd_shared.h"
43 #include "amdgpu_dm_irq.h"
44 #include "dm_helpers.h"
45 #include "amdgpu_dm_mst_types.h"
46 #if defined(CONFIG_DEBUG_FS)
47 #include "amdgpu_dm_debugfs.h"
48 #endif
49 
50 #include "ivsrcid/ivsrcid_vislands30.h"
51 
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/version.h>
55 #include <linux/types.h>
56 #include <linux/pm_runtime.h>
57 #include <linux/firmware.h>
58 
59 #include <drm/drmP.h>
60 #include <drm/drm_atomic.h>
61 #include <drm/drm_atomic_uapi.h>
62 #include <drm/drm_atomic_helper.h>
63 #include <drm/drm_dp_mst_helper.h>
64 #include <drm/drm_fb_helper.h>
65 #include <drm/drm_edid.h>
66 
67 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
68 #include "ivsrcid/irqsrcs_dcn_1_0.h"
69 
70 #include "dcn/dcn_1_0_offset.h"
71 #include "dcn/dcn_1_0_sh_mask.h"
72 #include "soc15_hw_ip.h"
73 #include "vega10_ip_offset.h"
74 
75 #include "soc15_common.h"
76 #endif
77 
78 #include "modules/inc/mod_freesync.h"
79 #include "modules/power/power_helpers.h"
80 #include "modules/inc/mod_info_packet.h"
81 
82 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
83 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
84 
85 /**
86  * DOC: overview
87  *
88  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
89  * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
90  * requests into DC requests, and DC responses into DRM responses.
91  *
92  * The root control structure is &struct amdgpu_display_manager.
93  */
94 
95 /* basic init/fini API */
96 static int amdgpu_dm_init(struct amdgpu_device *adev);
97 static void amdgpu_dm_fini(struct amdgpu_device *adev);
98 
99 /*
100  * initializes drm_device display related structures, based on the information
101  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
102  * drm_encoder, drm_mode_config
103  *
104  * Returns 0 on success
105  */
106 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
107 /* removes and deallocates the drm structures, created by the above function */
108 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
109 
110 static void
111 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
112 
113 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
114 				struct drm_plane *plane,
115 				unsigned long possible_crtcs,
116 				const struct dc_plane_cap *plane_cap);
117 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
118 			       struct drm_plane *plane,
119 			       uint32_t link_index);
120 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
121 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
122 				    uint32_t link_index,
123 				    struct amdgpu_encoder *amdgpu_encoder);
124 static int amdgpu_dm_encoder_init(struct drm_device *dev,
125 				  struct amdgpu_encoder *aencoder,
126 				  uint32_t link_index);
127 
128 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
129 
130 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
131 				   struct drm_atomic_state *state,
132 				   bool nonblock);
133 
134 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
135 
136 static int amdgpu_dm_atomic_check(struct drm_device *dev,
137 				  struct drm_atomic_state *state);
138 
139 static void handle_cursor_update(struct drm_plane *plane,
140 				 struct drm_plane_state *old_plane_state);
141 
142 /*
143  * dm_vblank_get_counter
144  *
145  * @brief
146  * Get counter for number of vertical blanks
147  *
148  * @param
149  * struct amdgpu_device *adev - [in] desired amdgpu device
150  * int disp_idx - [in] which CRTC to get the counter from
151  *
152  * @return
153  * Counter for vertical blanks
154  */
155 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
156 {
157 	if (crtc >= adev->mode_info.num_crtc)
158 		return 0;
159 	else {
160 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
161 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
162 				acrtc->base.state);
163 
164 
165 		if (acrtc_state->stream == NULL) {
166 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
167 				  crtc);
168 			return 0;
169 		}
170 
171 		return dc_stream_get_vblank_counter(acrtc_state->stream);
172 	}
173 }
174 
175 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
176 				  u32 *vbl, u32 *position)
177 {
178 	uint32_t v_blank_start, v_blank_end, h_position, v_position;
179 
180 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
181 		return -EINVAL;
182 	else {
183 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
184 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
185 						acrtc->base.state);
186 
187 		if (acrtc_state->stream ==  NULL) {
188 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
189 				  crtc);
190 			return 0;
191 		}
192 
193 		/*
194 		 * TODO rework base driver to use values directly.
195 		 * for now parse it back into reg-format
196 		 */
197 		dc_stream_get_scanoutpos(acrtc_state->stream,
198 					 &v_blank_start,
199 					 &v_blank_end,
200 					 &h_position,
201 					 &v_position);
202 
203 		*position = v_position | (h_position << 16);
204 		*vbl = v_blank_start | (v_blank_end << 16);
205 	}
206 
207 	return 0;
208 }
209 
210 static bool dm_is_idle(void *handle)
211 {
212 	/* XXX todo */
213 	return true;
214 }
215 
216 static int dm_wait_for_idle(void *handle)
217 {
218 	/* XXX todo */
219 	return 0;
220 }
221 
222 static bool dm_check_soft_reset(void *handle)
223 {
224 	return false;
225 }
226 
227 static int dm_soft_reset(void *handle)
228 {
229 	/* XXX todo */
230 	return 0;
231 }
232 
233 static struct amdgpu_crtc *
234 get_crtc_by_otg_inst(struct amdgpu_device *adev,
235 		     int otg_inst)
236 {
237 	struct drm_device *dev = adev->ddev;
238 	struct drm_crtc *crtc;
239 	struct amdgpu_crtc *amdgpu_crtc;
240 
241 	if (otg_inst == -1) {
242 		WARN_ON(1);
243 		return adev->mode_info.crtcs[0];
244 	}
245 
246 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
247 		amdgpu_crtc = to_amdgpu_crtc(crtc);
248 
249 		if (amdgpu_crtc->otg_inst == otg_inst)
250 			return amdgpu_crtc;
251 	}
252 
253 	return NULL;
254 }
255 
256 static inline bool amdgpu_dm_vrr_active(struct dm_crtc_state *dm_state)
257 {
258 	return dm_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE ||
259 	       dm_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
260 }
261 
262 static void dm_pflip_high_irq(void *interrupt_params)
263 {
264 	struct amdgpu_crtc *amdgpu_crtc;
265 	struct common_irq_params *irq_params = interrupt_params;
266 	struct amdgpu_device *adev = irq_params->adev;
267 	unsigned long flags;
268 	struct drm_pending_vblank_event *e;
269 	struct dm_crtc_state *acrtc_state;
270 	uint32_t vpos, hpos, v_blank_start, v_blank_end;
271 	bool vrr_active;
272 
273 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
274 
275 	/* IRQ could occur when in initial stage */
276 	/* TODO work and BO cleanup */
277 	if (amdgpu_crtc == NULL) {
278 		DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
279 		return;
280 	}
281 
282 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
283 
284 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
285 		DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
286 						 amdgpu_crtc->pflip_status,
287 						 AMDGPU_FLIP_SUBMITTED,
288 						 amdgpu_crtc->crtc_id,
289 						 amdgpu_crtc);
290 		spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
291 		return;
292 	}
293 
294 	/* page flip completed. */
295 	e = amdgpu_crtc->event;
296 	amdgpu_crtc->event = NULL;
297 
298 	if (!e)
299 		WARN_ON(1);
300 
301 	acrtc_state = to_dm_crtc_state(amdgpu_crtc->base.state);
302 	vrr_active = amdgpu_dm_vrr_active(acrtc_state);
303 
304 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
305 	if (!vrr_active ||
306 	    !dc_stream_get_scanoutpos(acrtc_state->stream, &v_blank_start,
307 				      &v_blank_end, &hpos, &vpos) ||
308 	    (vpos < v_blank_start)) {
309 		/* Update to correct count and vblank timestamp if racing with
310 		 * vblank irq. This also updates to the correct vblank timestamp
311 		 * even in VRR mode, as scanout is past the front-porch atm.
312 		 */
313 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
314 
315 		/* Wake up userspace by sending the pageflip event with proper
316 		 * count and timestamp of vblank of flip completion.
317 		 */
318 		if (e) {
319 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
320 
321 			/* Event sent, so done with vblank for this flip */
322 			drm_crtc_vblank_put(&amdgpu_crtc->base);
323 		}
324 	} else if (e) {
325 		/* VRR active and inside front-porch: vblank count and
326 		 * timestamp for pageflip event will only be up to date after
327 		 * drm_crtc_handle_vblank() has been executed from late vblank
328 		 * irq handler after start of back-porch (vline 0). We queue the
329 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
330 		 * updated timestamp and count, once it runs after us.
331 		 *
332 		 * We need to open-code this instead of using the helper
333 		 * drm_crtc_arm_vblank_event(), as that helper would
334 		 * call drm_crtc_accurate_vblank_count(), which we must
335 		 * not call in VRR mode while we are in front-porch!
336 		 */
337 
338 		/* sequence will be replaced by real count during send-out. */
339 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
340 		e->pipe = amdgpu_crtc->crtc_id;
341 
342 		list_add_tail(&e->base.link, &adev->ddev->vblank_event_list);
343 		e = NULL;
344 	}
345 
346 	/* Keep track of vblank of this flip for flip throttling. We use the
347 	 * cooked hw counter, as that one incremented at start of this vblank
348 	 * of pageflip completion, so last_flip_vblank is the forbidden count
349 	 * for queueing new pageflips if vsync + VRR is enabled.
350 	 */
351 	amdgpu_crtc->last_flip_vblank = amdgpu_get_vblank_counter_kms(adev->ddev,
352 							amdgpu_crtc->crtc_id);
353 
354 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
355 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
356 
357 	DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
358 			 amdgpu_crtc->crtc_id, amdgpu_crtc,
359 			 vrr_active, (int) !e);
360 }
361 
362 static void dm_vupdate_high_irq(void *interrupt_params)
363 {
364 	struct common_irq_params *irq_params = interrupt_params;
365 	struct amdgpu_device *adev = irq_params->adev;
366 	struct amdgpu_crtc *acrtc;
367 	struct dm_crtc_state *acrtc_state;
368 	unsigned long flags;
369 
370 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
371 
372 	if (acrtc) {
373 		acrtc_state = to_dm_crtc_state(acrtc->base.state);
374 
375 		DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
376 				 amdgpu_dm_vrr_active(acrtc_state));
377 
378 		/* Core vblank handling is done here after end of front-porch in
379 		 * vrr mode, as vblank timestamping will give valid results
380 		 * while now done after front-porch. This will also deliver
381 		 * page-flip completion events that have been queued to us
382 		 * if a pageflip happened inside front-porch.
383 		 */
384 		if (amdgpu_dm_vrr_active(acrtc_state)) {
385 			drm_crtc_handle_vblank(&acrtc->base);
386 
387 			/* BTR processing for pre-DCE12 ASICs */
388 			if (acrtc_state->stream &&
389 			    adev->family < AMDGPU_FAMILY_AI) {
390 				spin_lock_irqsave(&adev->ddev->event_lock, flags);
391 				mod_freesync_handle_v_update(
392 				    adev->dm.freesync_module,
393 				    acrtc_state->stream,
394 				    &acrtc_state->vrr_params);
395 
396 				dc_stream_adjust_vmin_vmax(
397 				    adev->dm.dc,
398 				    acrtc_state->stream,
399 				    &acrtc_state->vrr_params.adjust);
400 				spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
401 			}
402 		}
403 	}
404 }
405 
406 static void dm_crtc_high_irq(void *interrupt_params)
407 {
408 	struct common_irq_params *irq_params = interrupt_params;
409 	struct amdgpu_device *adev = irq_params->adev;
410 	struct amdgpu_crtc *acrtc;
411 	struct dm_crtc_state *acrtc_state;
412 	unsigned long flags;
413 
414 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
415 
416 	if (acrtc) {
417 		acrtc_state = to_dm_crtc_state(acrtc->base.state);
418 
419 		DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
420 				 amdgpu_dm_vrr_active(acrtc_state));
421 
422 		/* Core vblank handling at start of front-porch is only possible
423 		 * in non-vrr mode, as only there vblank timestamping will give
424 		 * valid results while done in front-porch. Otherwise defer it
425 		 * to dm_vupdate_high_irq after end of front-porch.
426 		 */
427 		if (!amdgpu_dm_vrr_active(acrtc_state))
428 			drm_crtc_handle_vblank(&acrtc->base);
429 
430 		/* Following stuff must happen at start of vblank, for crc
431 		 * computation and below-the-range btr support in vrr mode.
432 		 */
433 		amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
434 
435 		if (acrtc_state->stream && adev->family >= AMDGPU_FAMILY_AI &&
436 		    acrtc_state->vrr_params.supported &&
437 		    acrtc_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE) {
438 			spin_lock_irqsave(&adev->ddev->event_lock, flags);
439 			mod_freesync_handle_v_update(
440 				adev->dm.freesync_module,
441 				acrtc_state->stream,
442 				&acrtc_state->vrr_params);
443 
444 			dc_stream_adjust_vmin_vmax(
445 				adev->dm.dc,
446 				acrtc_state->stream,
447 				&acrtc_state->vrr_params.adjust);
448 			spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
449 		}
450 	}
451 }
452 
453 static int dm_set_clockgating_state(void *handle,
454 		  enum amd_clockgating_state state)
455 {
456 	return 0;
457 }
458 
459 static int dm_set_powergating_state(void *handle,
460 		  enum amd_powergating_state state)
461 {
462 	return 0;
463 }
464 
465 /* Prototypes of private functions */
466 static int dm_early_init(void* handle);
467 
468 /* Allocate memory for FBC compressed data  */
469 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
470 {
471 	struct drm_device *dev = connector->dev;
472 	struct amdgpu_device *adev = dev->dev_private;
473 	struct dm_comressor_info *compressor = &adev->dm.compressor;
474 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
475 	struct drm_display_mode *mode;
476 	unsigned long max_size = 0;
477 
478 	if (adev->dm.dc->fbc_compressor == NULL)
479 		return;
480 
481 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
482 		return;
483 
484 	if (compressor->bo_ptr)
485 		return;
486 
487 
488 	list_for_each_entry(mode, &connector->modes, head) {
489 		if (max_size < mode->htotal * mode->vtotal)
490 			max_size = mode->htotal * mode->vtotal;
491 	}
492 
493 	if (max_size) {
494 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
495 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
496 			    &compressor->gpu_addr, &compressor->cpu_addr);
497 
498 		if (r)
499 			DRM_ERROR("DM: Failed to initialize FBC\n");
500 		else {
501 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
502 			DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
503 		}
504 
505 	}
506 
507 }
508 
509 static int amdgpu_dm_init(struct amdgpu_device *adev)
510 {
511 	struct dc_init_data init_data;
512 	adev->dm.ddev = adev->ddev;
513 	adev->dm.adev = adev;
514 
515 	/* Zero all the fields */
516 	memset(&init_data, 0, sizeof(init_data));
517 
518 	mutex_init(&adev->dm.dc_lock);
519 
520 	if(amdgpu_dm_irq_init(adev)) {
521 		DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
522 		goto error;
523 	}
524 
525 	init_data.asic_id.chip_family = adev->family;
526 
527 	init_data.asic_id.pci_revision_id = adev->rev_id;
528 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
529 
530 	init_data.asic_id.vram_width = adev->gmc.vram_width;
531 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
532 	init_data.asic_id.atombios_base_address =
533 		adev->mode_info.atom_context->bios;
534 
535 	init_data.driver = adev;
536 
537 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
538 
539 	if (!adev->dm.cgs_device) {
540 		DRM_ERROR("amdgpu: failed to create cgs device.\n");
541 		goto error;
542 	}
543 
544 	init_data.cgs_device = adev->dm.cgs_device;
545 
546 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
547 
548 	/*
549 	 * TODO debug why this doesn't work on Raven
550 	 */
551 	if (adev->flags & AMD_IS_APU &&
552 	    adev->asic_type >= CHIP_CARRIZO &&
553 	    adev->asic_type < CHIP_RAVEN)
554 		init_data.flags.gpu_vm_support = true;
555 
556 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
557 		init_data.flags.fbc_support = true;
558 
559 	init_data.flags.power_down_display_on_boot = true;
560 
561 	/* Display Core create. */
562 	adev->dm.dc = dc_create(&init_data);
563 
564 	if (adev->dm.dc) {
565 		DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
566 	} else {
567 		DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
568 		goto error;
569 	}
570 
571 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
572 	if (!adev->dm.freesync_module) {
573 		DRM_ERROR(
574 		"amdgpu: failed to initialize freesync_module.\n");
575 	} else
576 		DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
577 				adev->dm.freesync_module);
578 
579 	amdgpu_dm_init_color_mod();
580 
581 	if (amdgpu_dm_initialize_drm_device(adev)) {
582 		DRM_ERROR(
583 		"amdgpu: failed to initialize sw for display support.\n");
584 		goto error;
585 	}
586 
587 	/* Update the actual used number of crtc */
588 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
589 
590 	/* TODO: Add_display_info? */
591 
592 	/* TODO use dynamic cursor width */
593 	adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
594 	adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
595 
596 	if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
597 		DRM_ERROR(
598 		"amdgpu: failed to initialize sw for display support.\n");
599 		goto error;
600 	}
601 
602 #if defined(CONFIG_DEBUG_FS)
603 	if (dtn_debugfs_init(adev))
604 		DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
605 #endif
606 
607 	DRM_DEBUG_DRIVER("KMS initialized.\n");
608 
609 	return 0;
610 error:
611 	amdgpu_dm_fini(adev);
612 
613 	return -EINVAL;
614 }
615 
616 static void amdgpu_dm_fini(struct amdgpu_device *adev)
617 {
618 	amdgpu_dm_destroy_drm_device(&adev->dm);
619 
620 	/* DC Destroy TODO: Replace destroy DAL */
621 	if (adev->dm.dc)
622 		dc_destroy(&adev->dm.dc);
623 	/*
624 	 * TODO: pageflip, vlank interrupt
625 	 *
626 	 * amdgpu_dm_irq_fini(adev);
627 	 */
628 
629 	if (adev->dm.cgs_device) {
630 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
631 		adev->dm.cgs_device = NULL;
632 	}
633 	if (adev->dm.freesync_module) {
634 		mod_freesync_destroy(adev->dm.freesync_module);
635 		adev->dm.freesync_module = NULL;
636 	}
637 
638 	mutex_destroy(&adev->dm.dc_lock);
639 
640 	return;
641 }
642 
643 static int load_dmcu_fw(struct amdgpu_device *adev)
644 {
645 	const char *fw_name_dmcu = NULL;
646 	int r;
647 	const struct dmcu_firmware_header_v1_0 *hdr;
648 
649 	switch(adev->asic_type) {
650 	case CHIP_BONAIRE:
651 	case CHIP_HAWAII:
652 	case CHIP_KAVERI:
653 	case CHIP_KABINI:
654 	case CHIP_MULLINS:
655 	case CHIP_TONGA:
656 	case CHIP_FIJI:
657 	case CHIP_CARRIZO:
658 	case CHIP_STONEY:
659 	case CHIP_POLARIS11:
660 	case CHIP_POLARIS10:
661 	case CHIP_POLARIS12:
662 	case CHIP_VEGAM:
663 	case CHIP_VEGA10:
664 	case CHIP_VEGA12:
665 	case CHIP_VEGA20:
666 		return 0;
667 	case CHIP_RAVEN:
668 #if defined(CONFIG_DRM_AMD_DC_DCN1_01)
669 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
670 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
671 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
672 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
673 		else
674 #endif
675 			return 0;
676 		break;
677 	default:
678 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
679 		return -EINVAL;
680 	}
681 
682 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
683 		DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
684 		return 0;
685 	}
686 
687 	r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
688 	if (r == -ENOENT) {
689 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
690 		DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
691 		adev->dm.fw_dmcu = NULL;
692 		return 0;
693 	}
694 	if (r) {
695 		dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
696 			fw_name_dmcu);
697 		return r;
698 	}
699 
700 	r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
701 	if (r) {
702 		dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
703 			fw_name_dmcu);
704 		release_firmware(adev->dm.fw_dmcu);
705 		adev->dm.fw_dmcu = NULL;
706 		return r;
707 	}
708 
709 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
710 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
711 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
712 	adev->firmware.fw_size +=
713 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
714 
715 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
716 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
717 	adev->firmware.fw_size +=
718 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
719 
720 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
721 
722 	DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
723 
724 	return 0;
725 }
726 
727 static int dm_sw_init(void *handle)
728 {
729 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
730 
731 	return load_dmcu_fw(adev);
732 }
733 
734 static int dm_sw_fini(void *handle)
735 {
736 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
737 
738 	if(adev->dm.fw_dmcu) {
739 		release_firmware(adev->dm.fw_dmcu);
740 		adev->dm.fw_dmcu = NULL;
741 	}
742 
743 	return 0;
744 }
745 
746 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
747 {
748 	struct amdgpu_dm_connector *aconnector;
749 	struct drm_connector *connector;
750 	int ret = 0;
751 
752 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
753 
754 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
755 		aconnector = to_amdgpu_dm_connector(connector);
756 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
757 		    aconnector->mst_mgr.aux) {
758 			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
759 					aconnector, aconnector->base.base.id);
760 
761 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
762 			if (ret < 0) {
763 				DRM_ERROR("DM_MST: Failed to start MST\n");
764 				((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
765 				return ret;
766 				}
767 			}
768 	}
769 
770 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
771 	return ret;
772 }
773 
774 static int dm_late_init(void *handle)
775 {
776 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
777 
778 	struct dmcu_iram_parameters params;
779 	unsigned int linear_lut[16];
780 	int i;
781 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
782 	bool ret;
783 
784 	for (i = 0; i < 16; i++)
785 		linear_lut[i] = 0xFFFF * i / 15;
786 
787 	params.set = 0;
788 	params.backlight_ramping_start = 0xCCCC;
789 	params.backlight_ramping_reduction = 0xCCCCCCCC;
790 	params.backlight_lut_array_size = 16;
791 	params.backlight_lut_array = linear_lut;
792 
793 	ret = dmcu_load_iram(dmcu, params);
794 
795 	if (!ret)
796 		return -EINVAL;
797 
798 	return detect_mst_link_for_all_connectors(adev->ddev);
799 }
800 
801 static void s3_handle_mst(struct drm_device *dev, bool suspend)
802 {
803 	struct amdgpu_dm_connector *aconnector;
804 	struct drm_connector *connector;
805 	struct drm_dp_mst_topology_mgr *mgr;
806 	int ret;
807 	bool need_hotplug = false;
808 
809 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
810 
811 	list_for_each_entry(connector, &dev->mode_config.connector_list,
812 			    head) {
813 		aconnector = to_amdgpu_dm_connector(connector);
814 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
815 		    aconnector->mst_port)
816 			continue;
817 
818 		mgr = &aconnector->mst_mgr;
819 
820 		if (suspend) {
821 			drm_dp_mst_topology_mgr_suspend(mgr);
822 		} else {
823 			ret = drm_dp_mst_topology_mgr_resume(mgr);
824 			if (ret < 0) {
825 				drm_dp_mst_topology_mgr_set_mst(mgr, false);
826 				need_hotplug = true;
827 			}
828 		}
829 	}
830 
831 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
832 
833 	if (need_hotplug)
834 		drm_kms_helper_hotplug_event(dev);
835 }
836 
837 /**
838  * dm_hw_init() - Initialize DC device
839  * @handle: The base driver device containing the amdpgu_dm device.
840  *
841  * Initialize the &struct amdgpu_display_manager device. This involves calling
842  * the initializers of each DM component, then populating the struct with them.
843  *
844  * Although the function implies hardware initialization, both hardware and
845  * software are initialized here. Splitting them out to their relevant init
846  * hooks is a future TODO item.
847  *
848  * Some notable things that are initialized here:
849  *
850  * - Display Core, both software and hardware
851  * - DC modules that we need (freesync and color management)
852  * - DRM software states
853  * - Interrupt sources and handlers
854  * - Vblank support
855  * - Debug FS entries, if enabled
856  */
857 static int dm_hw_init(void *handle)
858 {
859 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
860 	/* Create DAL display manager */
861 	amdgpu_dm_init(adev);
862 	amdgpu_dm_hpd_init(adev);
863 
864 	return 0;
865 }
866 
867 /**
868  * dm_hw_fini() - Teardown DC device
869  * @handle: The base driver device containing the amdpgu_dm device.
870  *
871  * Teardown components within &struct amdgpu_display_manager that require
872  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
873  * were loaded. Also flush IRQ workqueues and disable them.
874  */
875 static int dm_hw_fini(void *handle)
876 {
877 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
878 
879 	amdgpu_dm_hpd_fini(adev);
880 
881 	amdgpu_dm_irq_fini(adev);
882 	amdgpu_dm_fini(adev);
883 	return 0;
884 }
885 
886 static int dm_suspend(void *handle)
887 {
888 	struct amdgpu_device *adev = handle;
889 	struct amdgpu_display_manager *dm = &adev->dm;
890 	int ret = 0;
891 
892 	WARN_ON(adev->dm.cached_state);
893 	adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
894 
895 	s3_handle_mst(adev->ddev, true);
896 
897 	amdgpu_dm_irq_suspend(adev);
898 
899 
900 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
901 
902 	return ret;
903 }
904 
905 static struct amdgpu_dm_connector *
906 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
907 					     struct drm_crtc *crtc)
908 {
909 	uint32_t i;
910 	struct drm_connector_state *new_con_state;
911 	struct drm_connector *connector;
912 	struct drm_crtc *crtc_from_state;
913 
914 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
915 		crtc_from_state = new_con_state->crtc;
916 
917 		if (crtc_from_state == crtc)
918 			return to_amdgpu_dm_connector(connector);
919 	}
920 
921 	return NULL;
922 }
923 
924 static void emulated_link_detect(struct dc_link *link)
925 {
926 	struct dc_sink_init_data sink_init_data = { 0 };
927 	struct display_sink_capability sink_caps = { 0 };
928 	enum dc_edid_status edid_status;
929 	struct dc_context *dc_ctx = link->ctx;
930 	struct dc_sink *sink = NULL;
931 	struct dc_sink *prev_sink = NULL;
932 
933 	link->type = dc_connection_none;
934 	prev_sink = link->local_sink;
935 
936 	if (prev_sink != NULL)
937 		dc_sink_retain(prev_sink);
938 
939 	switch (link->connector_signal) {
940 	case SIGNAL_TYPE_HDMI_TYPE_A: {
941 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
942 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
943 		break;
944 	}
945 
946 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
947 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
948 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
949 		break;
950 	}
951 
952 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
953 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
954 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
955 		break;
956 	}
957 
958 	case SIGNAL_TYPE_LVDS: {
959 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
960 		sink_caps.signal = SIGNAL_TYPE_LVDS;
961 		break;
962 	}
963 
964 	case SIGNAL_TYPE_EDP: {
965 		sink_caps.transaction_type =
966 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
967 		sink_caps.signal = SIGNAL_TYPE_EDP;
968 		break;
969 	}
970 
971 	case SIGNAL_TYPE_DISPLAY_PORT: {
972 		sink_caps.transaction_type =
973 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
974 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
975 		break;
976 	}
977 
978 	default:
979 		DC_ERROR("Invalid connector type! signal:%d\n",
980 			link->connector_signal);
981 		return;
982 	}
983 
984 	sink_init_data.link = link;
985 	sink_init_data.sink_signal = sink_caps.signal;
986 
987 	sink = dc_sink_create(&sink_init_data);
988 	if (!sink) {
989 		DC_ERROR("Failed to create sink!\n");
990 		return;
991 	}
992 
993 	/* dc_sink_create returns a new reference */
994 	link->local_sink = sink;
995 
996 	edid_status = dm_helpers_read_local_edid(
997 			link->ctx,
998 			link,
999 			sink);
1000 
1001 	if (edid_status != EDID_OK)
1002 		DC_ERROR("Failed to read EDID");
1003 
1004 }
1005 
1006 static int dm_resume(void *handle)
1007 {
1008 	struct amdgpu_device *adev = handle;
1009 	struct drm_device *ddev = adev->ddev;
1010 	struct amdgpu_display_manager *dm = &adev->dm;
1011 	struct amdgpu_dm_connector *aconnector;
1012 	struct drm_connector *connector;
1013 	struct drm_crtc *crtc;
1014 	struct drm_crtc_state *new_crtc_state;
1015 	struct dm_crtc_state *dm_new_crtc_state;
1016 	struct drm_plane *plane;
1017 	struct drm_plane_state *new_plane_state;
1018 	struct dm_plane_state *dm_new_plane_state;
1019 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1020 	enum dc_connection_type new_connection_type = dc_connection_none;
1021 	int i;
1022 
1023 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
1024 	dc_release_state(dm_state->context);
1025 	dm_state->context = dc_create_state(dm->dc);
1026 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1027 	dc_resource_state_construct(dm->dc, dm_state->context);
1028 
1029 	/* power on hardware */
1030 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1031 
1032 	/* program HPD filter */
1033 	dc_resume(dm->dc);
1034 
1035 	/* On resume we need to  rewrite the MSTM control bits to enamble MST*/
1036 	s3_handle_mst(ddev, false);
1037 
1038 	/*
1039 	 * early enable HPD Rx IRQ, should be done before set mode as short
1040 	 * pulse interrupts are used for MST
1041 	 */
1042 	amdgpu_dm_irq_resume_early(adev);
1043 
1044 	/* Do detection*/
1045 	list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
1046 		aconnector = to_amdgpu_dm_connector(connector);
1047 
1048 		/*
1049 		 * this is the case when traversing through already created
1050 		 * MST connectors, should be skipped
1051 		 */
1052 		if (aconnector->mst_port)
1053 			continue;
1054 
1055 		mutex_lock(&aconnector->hpd_lock);
1056 		if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1057 			DRM_ERROR("KMS: Failed to detect connector\n");
1058 
1059 		if (aconnector->base.force && new_connection_type == dc_connection_none)
1060 			emulated_link_detect(aconnector->dc_link);
1061 		else
1062 			dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
1063 
1064 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
1065 			aconnector->fake_enable = false;
1066 
1067 		if (aconnector->dc_sink)
1068 			dc_sink_release(aconnector->dc_sink);
1069 		aconnector->dc_sink = NULL;
1070 		amdgpu_dm_update_connector_after_detect(aconnector);
1071 		mutex_unlock(&aconnector->hpd_lock);
1072 	}
1073 
1074 	/* Force mode set in atomic commit */
1075 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
1076 		new_crtc_state->active_changed = true;
1077 
1078 	/*
1079 	 * atomic_check is expected to create the dc states. We need to release
1080 	 * them here, since they were duplicated as part of the suspend
1081 	 * procedure.
1082 	 */
1083 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1084 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1085 		if (dm_new_crtc_state->stream) {
1086 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1087 			dc_stream_release(dm_new_crtc_state->stream);
1088 			dm_new_crtc_state->stream = NULL;
1089 		}
1090 	}
1091 
1092 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1093 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
1094 		if (dm_new_plane_state->dc_state) {
1095 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1096 			dc_plane_state_release(dm_new_plane_state->dc_state);
1097 			dm_new_plane_state->dc_state = NULL;
1098 		}
1099 	}
1100 
1101 	drm_atomic_helper_resume(ddev, dm->cached_state);
1102 
1103 	dm->cached_state = NULL;
1104 
1105 	amdgpu_dm_irq_resume_late(adev);
1106 
1107 	return 0;
1108 }
1109 
1110 /**
1111  * DOC: DM Lifecycle
1112  *
1113  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
1114  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
1115  * the base driver's device list to be initialized and torn down accordingly.
1116  *
1117  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
1118  */
1119 
1120 static const struct amd_ip_funcs amdgpu_dm_funcs = {
1121 	.name = "dm",
1122 	.early_init = dm_early_init,
1123 	.late_init = dm_late_init,
1124 	.sw_init = dm_sw_init,
1125 	.sw_fini = dm_sw_fini,
1126 	.hw_init = dm_hw_init,
1127 	.hw_fini = dm_hw_fini,
1128 	.suspend = dm_suspend,
1129 	.resume = dm_resume,
1130 	.is_idle = dm_is_idle,
1131 	.wait_for_idle = dm_wait_for_idle,
1132 	.check_soft_reset = dm_check_soft_reset,
1133 	.soft_reset = dm_soft_reset,
1134 	.set_clockgating_state = dm_set_clockgating_state,
1135 	.set_powergating_state = dm_set_powergating_state,
1136 };
1137 
1138 const struct amdgpu_ip_block_version dm_ip_block =
1139 {
1140 	.type = AMD_IP_BLOCK_TYPE_DCE,
1141 	.major = 1,
1142 	.minor = 0,
1143 	.rev = 0,
1144 	.funcs = &amdgpu_dm_funcs,
1145 };
1146 
1147 
1148 /**
1149  * DOC: atomic
1150  *
1151  * *WIP*
1152  */
1153 
1154 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1155 	.fb_create = amdgpu_display_user_framebuffer_create,
1156 	.output_poll_changed = drm_fb_helper_output_poll_changed,
1157 	.atomic_check = amdgpu_dm_atomic_check,
1158 	.atomic_commit = amdgpu_dm_atomic_commit,
1159 };
1160 
1161 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1162 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1163 };
1164 
1165 static void
1166 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1167 {
1168 	struct drm_connector *connector = &aconnector->base;
1169 	struct drm_device *dev = connector->dev;
1170 	struct dc_sink *sink;
1171 
1172 	/* MST handled by drm_mst framework */
1173 	if (aconnector->mst_mgr.mst_state == true)
1174 		return;
1175 
1176 
1177 	sink = aconnector->dc_link->local_sink;
1178 	if (sink)
1179 		dc_sink_retain(sink);
1180 
1181 	/*
1182 	 * Edid mgmt connector gets first update only in mode_valid hook and then
1183 	 * the connector sink is set to either fake or physical sink depends on link status.
1184 	 * Skip if already done during boot.
1185 	 */
1186 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1187 			&& aconnector->dc_em_sink) {
1188 
1189 		/*
1190 		 * For S3 resume with headless use eml_sink to fake stream
1191 		 * because on resume connector->sink is set to NULL
1192 		 */
1193 		mutex_lock(&dev->mode_config.mutex);
1194 
1195 		if (sink) {
1196 			if (aconnector->dc_sink) {
1197 				amdgpu_dm_update_freesync_caps(connector, NULL);
1198 				/*
1199 				 * retain and release below are used to
1200 				 * bump up refcount for sink because the link doesn't point
1201 				 * to it anymore after disconnect, so on next crtc to connector
1202 				 * reshuffle by UMD we will get into unwanted dc_sink release
1203 				 */
1204 				dc_sink_release(aconnector->dc_sink);
1205 			}
1206 			aconnector->dc_sink = sink;
1207 			dc_sink_retain(aconnector->dc_sink);
1208 			amdgpu_dm_update_freesync_caps(connector,
1209 					aconnector->edid);
1210 		} else {
1211 			amdgpu_dm_update_freesync_caps(connector, NULL);
1212 			if (!aconnector->dc_sink) {
1213 				aconnector->dc_sink = aconnector->dc_em_sink;
1214 				dc_sink_retain(aconnector->dc_sink);
1215 			}
1216 		}
1217 
1218 		mutex_unlock(&dev->mode_config.mutex);
1219 
1220 		if (sink)
1221 			dc_sink_release(sink);
1222 		return;
1223 	}
1224 
1225 	/*
1226 	 * TODO: temporary guard to look for proper fix
1227 	 * if this sink is MST sink, we should not do anything
1228 	 */
1229 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
1230 		dc_sink_release(sink);
1231 		return;
1232 	}
1233 
1234 	if (aconnector->dc_sink == sink) {
1235 		/*
1236 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
1237 		 * Do nothing!!
1238 		 */
1239 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1240 				aconnector->connector_id);
1241 		if (sink)
1242 			dc_sink_release(sink);
1243 		return;
1244 	}
1245 
1246 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1247 		aconnector->connector_id, aconnector->dc_sink, sink);
1248 
1249 	mutex_lock(&dev->mode_config.mutex);
1250 
1251 	/*
1252 	 * 1. Update status of the drm connector
1253 	 * 2. Send an event and let userspace tell us what to do
1254 	 */
1255 	if (sink) {
1256 		/*
1257 		 * TODO: check if we still need the S3 mode update workaround.
1258 		 * If yes, put it here.
1259 		 */
1260 		if (aconnector->dc_sink)
1261 			amdgpu_dm_update_freesync_caps(connector, NULL);
1262 
1263 		aconnector->dc_sink = sink;
1264 		dc_sink_retain(aconnector->dc_sink);
1265 		if (sink->dc_edid.length == 0) {
1266 			aconnector->edid = NULL;
1267 			drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1268 		} else {
1269 			aconnector->edid =
1270 				(struct edid *) sink->dc_edid.raw_edid;
1271 
1272 
1273 			drm_connector_update_edid_property(connector,
1274 					aconnector->edid);
1275 			drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1276 					    aconnector->edid);
1277 		}
1278 		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1279 
1280 	} else {
1281 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1282 		amdgpu_dm_update_freesync_caps(connector, NULL);
1283 		drm_connector_update_edid_property(connector, NULL);
1284 		aconnector->num_modes = 0;
1285 		dc_sink_release(aconnector->dc_sink);
1286 		aconnector->dc_sink = NULL;
1287 		aconnector->edid = NULL;
1288 	}
1289 
1290 	mutex_unlock(&dev->mode_config.mutex);
1291 
1292 	if (sink)
1293 		dc_sink_release(sink);
1294 }
1295 
1296 static void handle_hpd_irq(void *param)
1297 {
1298 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1299 	struct drm_connector *connector = &aconnector->base;
1300 	struct drm_device *dev = connector->dev;
1301 	enum dc_connection_type new_connection_type = dc_connection_none;
1302 
1303 	/*
1304 	 * In case of failure or MST no need to update connector status or notify the OS
1305 	 * since (for MST case) MST does this in its own context.
1306 	 */
1307 	mutex_lock(&aconnector->hpd_lock);
1308 
1309 	if (aconnector->fake_enable)
1310 		aconnector->fake_enable = false;
1311 
1312 	if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1313 		DRM_ERROR("KMS: Failed to detect connector\n");
1314 
1315 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
1316 		emulated_link_detect(aconnector->dc_link);
1317 
1318 
1319 		drm_modeset_lock_all(dev);
1320 		dm_restore_drm_connector_state(dev, connector);
1321 		drm_modeset_unlock_all(dev);
1322 
1323 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1324 			drm_kms_helper_hotplug_event(dev);
1325 
1326 	} else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1327 		amdgpu_dm_update_connector_after_detect(aconnector);
1328 
1329 
1330 		drm_modeset_lock_all(dev);
1331 		dm_restore_drm_connector_state(dev, connector);
1332 		drm_modeset_unlock_all(dev);
1333 
1334 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1335 			drm_kms_helper_hotplug_event(dev);
1336 	}
1337 	mutex_unlock(&aconnector->hpd_lock);
1338 
1339 }
1340 
1341 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1342 {
1343 	uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1344 	uint8_t dret;
1345 	bool new_irq_handled = false;
1346 	int dpcd_addr;
1347 	int dpcd_bytes_to_read;
1348 
1349 	const int max_process_count = 30;
1350 	int process_count = 0;
1351 
1352 	const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1353 
1354 	if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1355 		dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1356 		/* DPCD 0x200 - 0x201 for downstream IRQ */
1357 		dpcd_addr = DP_SINK_COUNT;
1358 	} else {
1359 		dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1360 		/* DPCD 0x2002 - 0x2005 for downstream IRQ */
1361 		dpcd_addr = DP_SINK_COUNT_ESI;
1362 	}
1363 
1364 	dret = drm_dp_dpcd_read(
1365 		&aconnector->dm_dp_aux.aux,
1366 		dpcd_addr,
1367 		esi,
1368 		dpcd_bytes_to_read);
1369 
1370 	while (dret == dpcd_bytes_to_read &&
1371 		process_count < max_process_count) {
1372 		uint8_t retry;
1373 		dret = 0;
1374 
1375 		process_count++;
1376 
1377 		DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1378 		/* handle HPD short pulse irq */
1379 		if (aconnector->mst_mgr.mst_state)
1380 			drm_dp_mst_hpd_irq(
1381 				&aconnector->mst_mgr,
1382 				esi,
1383 				&new_irq_handled);
1384 
1385 		if (new_irq_handled) {
1386 			/* ACK at DPCD to notify down stream */
1387 			const int ack_dpcd_bytes_to_write =
1388 				dpcd_bytes_to_read - 1;
1389 
1390 			for (retry = 0; retry < 3; retry++) {
1391 				uint8_t wret;
1392 
1393 				wret = drm_dp_dpcd_write(
1394 					&aconnector->dm_dp_aux.aux,
1395 					dpcd_addr + 1,
1396 					&esi[1],
1397 					ack_dpcd_bytes_to_write);
1398 				if (wret == ack_dpcd_bytes_to_write)
1399 					break;
1400 			}
1401 
1402 			/* check if there is new irq to be handled */
1403 			dret = drm_dp_dpcd_read(
1404 				&aconnector->dm_dp_aux.aux,
1405 				dpcd_addr,
1406 				esi,
1407 				dpcd_bytes_to_read);
1408 
1409 			new_irq_handled = false;
1410 		} else {
1411 			break;
1412 		}
1413 	}
1414 
1415 	if (process_count == max_process_count)
1416 		DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1417 }
1418 
1419 static void handle_hpd_rx_irq(void *param)
1420 {
1421 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1422 	struct drm_connector *connector = &aconnector->base;
1423 	struct drm_device *dev = connector->dev;
1424 	struct dc_link *dc_link = aconnector->dc_link;
1425 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1426 	enum dc_connection_type new_connection_type = dc_connection_none;
1427 
1428 	/*
1429 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1430 	 * conflict, after implement i2c helper, this mutex should be
1431 	 * retired.
1432 	 */
1433 	if (dc_link->type != dc_connection_mst_branch)
1434 		mutex_lock(&aconnector->hpd_lock);
1435 
1436 	if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1437 			!is_mst_root_connector) {
1438 		/* Downstream Port status changed. */
1439 		if (!dc_link_detect_sink(dc_link, &new_connection_type))
1440 			DRM_ERROR("KMS: Failed to detect connector\n");
1441 
1442 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
1443 			emulated_link_detect(dc_link);
1444 
1445 			if (aconnector->fake_enable)
1446 				aconnector->fake_enable = false;
1447 
1448 			amdgpu_dm_update_connector_after_detect(aconnector);
1449 
1450 
1451 			drm_modeset_lock_all(dev);
1452 			dm_restore_drm_connector_state(dev, connector);
1453 			drm_modeset_unlock_all(dev);
1454 
1455 			drm_kms_helper_hotplug_event(dev);
1456 		} else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1457 
1458 			if (aconnector->fake_enable)
1459 				aconnector->fake_enable = false;
1460 
1461 			amdgpu_dm_update_connector_after_detect(aconnector);
1462 
1463 
1464 			drm_modeset_lock_all(dev);
1465 			dm_restore_drm_connector_state(dev, connector);
1466 			drm_modeset_unlock_all(dev);
1467 
1468 			drm_kms_helper_hotplug_event(dev);
1469 		}
1470 	}
1471 	if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1472 	    (dc_link->type == dc_connection_mst_branch))
1473 		dm_handle_hpd_rx_irq(aconnector);
1474 
1475 	if (dc_link->type != dc_connection_mst_branch) {
1476 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1477 		mutex_unlock(&aconnector->hpd_lock);
1478 	}
1479 }
1480 
1481 static void register_hpd_handlers(struct amdgpu_device *adev)
1482 {
1483 	struct drm_device *dev = adev->ddev;
1484 	struct drm_connector *connector;
1485 	struct amdgpu_dm_connector *aconnector;
1486 	const struct dc_link *dc_link;
1487 	struct dc_interrupt_params int_params = {0};
1488 
1489 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1490 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1491 
1492 	list_for_each_entry(connector,
1493 			&dev->mode_config.connector_list, head)	{
1494 
1495 		aconnector = to_amdgpu_dm_connector(connector);
1496 		dc_link = aconnector->dc_link;
1497 
1498 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1499 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1500 			int_params.irq_source = dc_link->irq_source_hpd;
1501 
1502 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1503 					handle_hpd_irq,
1504 					(void *) aconnector);
1505 		}
1506 
1507 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1508 
1509 			/* Also register for DP short pulse (hpd_rx). */
1510 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1511 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
1512 
1513 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1514 					handle_hpd_rx_irq,
1515 					(void *) aconnector);
1516 		}
1517 	}
1518 }
1519 
1520 /* Register IRQ sources and initialize IRQ callbacks */
1521 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1522 {
1523 	struct dc *dc = adev->dm.dc;
1524 	struct common_irq_params *c_irq_params;
1525 	struct dc_interrupt_params int_params = {0};
1526 	int r;
1527 	int i;
1528 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1529 
1530 	if (adev->asic_type == CHIP_VEGA10 ||
1531 	    adev->asic_type == CHIP_VEGA12 ||
1532 	    adev->asic_type == CHIP_VEGA20 ||
1533 	    adev->asic_type == CHIP_RAVEN)
1534 		client_id = SOC15_IH_CLIENTID_DCE;
1535 
1536 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1537 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1538 
1539 	/*
1540 	 * Actions of amdgpu_irq_add_id():
1541 	 * 1. Register a set() function with base driver.
1542 	 *    Base driver will call set() function to enable/disable an
1543 	 *    interrupt in DC hardware.
1544 	 * 2. Register amdgpu_dm_irq_handler().
1545 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1546 	 *    coming from DC hardware.
1547 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1548 	 *    for acknowledging and handling. */
1549 
1550 	/* Use VBLANK interrupt */
1551 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1552 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1553 		if (r) {
1554 			DRM_ERROR("Failed to add crtc irq id!\n");
1555 			return r;
1556 		}
1557 
1558 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1559 		int_params.irq_source =
1560 			dc_interrupt_to_irq_source(dc, i, 0);
1561 
1562 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1563 
1564 		c_irq_params->adev = adev;
1565 		c_irq_params->irq_src = int_params.irq_source;
1566 
1567 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1568 				dm_crtc_high_irq, c_irq_params);
1569 	}
1570 
1571 	/* Use VUPDATE interrupt */
1572 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
1573 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
1574 		if (r) {
1575 			DRM_ERROR("Failed to add vupdate irq id!\n");
1576 			return r;
1577 		}
1578 
1579 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1580 		int_params.irq_source =
1581 			dc_interrupt_to_irq_source(dc, i, 0);
1582 
1583 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1584 
1585 		c_irq_params->adev = adev;
1586 		c_irq_params->irq_src = int_params.irq_source;
1587 
1588 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1589 				dm_vupdate_high_irq, c_irq_params);
1590 	}
1591 
1592 	/* Use GRPH_PFLIP interrupt */
1593 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1594 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1595 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1596 		if (r) {
1597 			DRM_ERROR("Failed to add page flip irq id!\n");
1598 			return r;
1599 		}
1600 
1601 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1602 		int_params.irq_source =
1603 			dc_interrupt_to_irq_source(dc, i, 0);
1604 
1605 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1606 
1607 		c_irq_params->adev = adev;
1608 		c_irq_params->irq_src = int_params.irq_source;
1609 
1610 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1611 				dm_pflip_high_irq, c_irq_params);
1612 
1613 	}
1614 
1615 	/* HPD */
1616 	r = amdgpu_irq_add_id(adev, client_id,
1617 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1618 	if (r) {
1619 		DRM_ERROR("Failed to add hpd irq id!\n");
1620 		return r;
1621 	}
1622 
1623 	register_hpd_handlers(adev);
1624 
1625 	return 0;
1626 }
1627 
1628 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1629 /* Register IRQ sources and initialize IRQ callbacks */
1630 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1631 {
1632 	struct dc *dc = adev->dm.dc;
1633 	struct common_irq_params *c_irq_params;
1634 	struct dc_interrupt_params int_params = {0};
1635 	int r;
1636 	int i;
1637 
1638 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1639 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1640 
1641 	/*
1642 	 * Actions of amdgpu_irq_add_id():
1643 	 * 1. Register a set() function with base driver.
1644 	 *    Base driver will call set() function to enable/disable an
1645 	 *    interrupt in DC hardware.
1646 	 * 2. Register amdgpu_dm_irq_handler().
1647 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1648 	 *    coming from DC hardware.
1649 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1650 	 *    for acknowledging and handling.
1651 	 */
1652 
1653 	/* Use VSTARTUP interrupt */
1654 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1655 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1656 			i++) {
1657 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1658 
1659 		if (r) {
1660 			DRM_ERROR("Failed to add crtc irq id!\n");
1661 			return r;
1662 		}
1663 
1664 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1665 		int_params.irq_source =
1666 			dc_interrupt_to_irq_source(dc, i, 0);
1667 
1668 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1669 
1670 		c_irq_params->adev = adev;
1671 		c_irq_params->irq_src = int_params.irq_source;
1672 
1673 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1674 				dm_crtc_high_irq, c_irq_params);
1675 	}
1676 
1677 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
1678 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
1679 	 * to trigger at end of each vblank, regardless of state of the lock,
1680 	 * matching DCE behaviour.
1681 	 */
1682 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
1683 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
1684 	     i++) {
1685 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
1686 
1687 		if (r) {
1688 			DRM_ERROR("Failed to add vupdate irq id!\n");
1689 			return r;
1690 		}
1691 
1692 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1693 		int_params.irq_source =
1694 			dc_interrupt_to_irq_source(dc, i, 0);
1695 
1696 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1697 
1698 		c_irq_params->adev = adev;
1699 		c_irq_params->irq_src = int_params.irq_source;
1700 
1701 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1702 				dm_vupdate_high_irq, c_irq_params);
1703 	}
1704 
1705 	/* Use GRPH_PFLIP interrupt */
1706 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1707 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1708 			i++) {
1709 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1710 		if (r) {
1711 			DRM_ERROR("Failed to add page flip irq id!\n");
1712 			return r;
1713 		}
1714 
1715 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1716 		int_params.irq_source =
1717 			dc_interrupt_to_irq_source(dc, i, 0);
1718 
1719 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1720 
1721 		c_irq_params->adev = adev;
1722 		c_irq_params->irq_src = int_params.irq_source;
1723 
1724 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1725 				dm_pflip_high_irq, c_irq_params);
1726 
1727 	}
1728 
1729 	/* HPD */
1730 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1731 			&adev->hpd_irq);
1732 	if (r) {
1733 		DRM_ERROR("Failed to add hpd irq id!\n");
1734 		return r;
1735 	}
1736 
1737 	register_hpd_handlers(adev);
1738 
1739 	return 0;
1740 }
1741 #endif
1742 
1743 /*
1744  * Acquires the lock for the atomic state object and returns
1745  * the new atomic state.
1746  *
1747  * This should only be called during atomic check.
1748  */
1749 static int dm_atomic_get_state(struct drm_atomic_state *state,
1750 			       struct dm_atomic_state **dm_state)
1751 {
1752 	struct drm_device *dev = state->dev;
1753 	struct amdgpu_device *adev = dev->dev_private;
1754 	struct amdgpu_display_manager *dm = &adev->dm;
1755 	struct drm_private_state *priv_state;
1756 
1757 	if (*dm_state)
1758 		return 0;
1759 
1760 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
1761 	if (IS_ERR(priv_state))
1762 		return PTR_ERR(priv_state);
1763 
1764 	*dm_state = to_dm_atomic_state(priv_state);
1765 
1766 	return 0;
1767 }
1768 
1769 struct dm_atomic_state *
1770 dm_atomic_get_new_state(struct drm_atomic_state *state)
1771 {
1772 	struct drm_device *dev = state->dev;
1773 	struct amdgpu_device *adev = dev->dev_private;
1774 	struct amdgpu_display_manager *dm = &adev->dm;
1775 	struct drm_private_obj *obj;
1776 	struct drm_private_state *new_obj_state;
1777 	int i;
1778 
1779 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
1780 		if (obj->funcs == dm->atomic_obj.funcs)
1781 			return to_dm_atomic_state(new_obj_state);
1782 	}
1783 
1784 	return NULL;
1785 }
1786 
1787 struct dm_atomic_state *
1788 dm_atomic_get_old_state(struct drm_atomic_state *state)
1789 {
1790 	struct drm_device *dev = state->dev;
1791 	struct amdgpu_device *adev = dev->dev_private;
1792 	struct amdgpu_display_manager *dm = &adev->dm;
1793 	struct drm_private_obj *obj;
1794 	struct drm_private_state *old_obj_state;
1795 	int i;
1796 
1797 	for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
1798 		if (obj->funcs == dm->atomic_obj.funcs)
1799 			return to_dm_atomic_state(old_obj_state);
1800 	}
1801 
1802 	return NULL;
1803 }
1804 
1805 static struct drm_private_state *
1806 dm_atomic_duplicate_state(struct drm_private_obj *obj)
1807 {
1808 	struct dm_atomic_state *old_state, *new_state;
1809 
1810 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
1811 	if (!new_state)
1812 		return NULL;
1813 
1814 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
1815 
1816 	old_state = to_dm_atomic_state(obj->state);
1817 
1818 	if (old_state && old_state->context)
1819 		new_state->context = dc_copy_state(old_state->context);
1820 
1821 	if (!new_state->context) {
1822 		kfree(new_state);
1823 		return NULL;
1824 	}
1825 
1826 	return &new_state->base;
1827 }
1828 
1829 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
1830 				    struct drm_private_state *state)
1831 {
1832 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1833 
1834 	if (dm_state && dm_state->context)
1835 		dc_release_state(dm_state->context);
1836 
1837 	kfree(dm_state);
1838 }
1839 
1840 static struct drm_private_state_funcs dm_atomic_state_funcs = {
1841 	.atomic_duplicate_state = dm_atomic_duplicate_state,
1842 	.atomic_destroy_state = dm_atomic_destroy_state,
1843 };
1844 
1845 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1846 {
1847 	struct dm_atomic_state *state;
1848 	int r;
1849 
1850 	adev->mode_info.mode_config_initialized = true;
1851 
1852 	adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1853 	adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1854 
1855 	adev->ddev->mode_config.max_width = 16384;
1856 	adev->ddev->mode_config.max_height = 16384;
1857 
1858 	adev->ddev->mode_config.preferred_depth = 24;
1859 	adev->ddev->mode_config.prefer_shadow = 1;
1860 	/* indicates support for immediate flip */
1861 	adev->ddev->mode_config.async_page_flip = true;
1862 
1863 	adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1864 
1865 	state = kzalloc(sizeof(*state), GFP_KERNEL);
1866 	if (!state)
1867 		return -ENOMEM;
1868 
1869 	state->context = dc_create_state(adev->dm.dc);
1870 	if (!state->context) {
1871 		kfree(state);
1872 		return -ENOMEM;
1873 	}
1874 
1875 	dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
1876 
1877 	drm_atomic_private_obj_init(adev->ddev,
1878 				    &adev->dm.atomic_obj,
1879 				    &state->base,
1880 				    &dm_atomic_state_funcs);
1881 
1882 	r = amdgpu_display_modeset_create_props(adev);
1883 	if (r)
1884 		return r;
1885 
1886 	return 0;
1887 }
1888 
1889 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
1890 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
1891 
1892 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1893 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1894 
1895 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
1896 {
1897 #if defined(CONFIG_ACPI)
1898 	struct amdgpu_dm_backlight_caps caps;
1899 
1900 	if (dm->backlight_caps.caps_valid)
1901 		return;
1902 
1903 	amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
1904 	if (caps.caps_valid) {
1905 		dm->backlight_caps.min_input_signal = caps.min_input_signal;
1906 		dm->backlight_caps.max_input_signal = caps.max_input_signal;
1907 		dm->backlight_caps.caps_valid = true;
1908 	} else {
1909 		dm->backlight_caps.min_input_signal =
1910 				AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1911 		dm->backlight_caps.max_input_signal =
1912 				AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1913 	}
1914 #else
1915 	dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1916 	dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1917 #endif
1918 }
1919 
1920 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1921 {
1922 	struct amdgpu_display_manager *dm = bl_get_data(bd);
1923 	struct amdgpu_dm_backlight_caps caps;
1924 	uint32_t brightness = bd->props.brightness;
1925 
1926 	amdgpu_dm_update_backlight_caps(dm);
1927 	caps = dm->backlight_caps;
1928 	/*
1929 	 * The brightness input is in the range 0-255
1930 	 * It needs to be rescaled to be between the
1931 	 * requested min and max input signal
1932 	 *
1933 	 * It also needs to be scaled up by 0x101 to
1934 	 * match the DC interface which has a range of
1935 	 * 0 to 0xffff
1936 	 */
1937 	brightness =
1938 		brightness
1939 		* 0x101
1940 		* (caps.max_input_signal - caps.min_input_signal)
1941 		/ AMDGPU_MAX_BL_LEVEL
1942 		+ caps.min_input_signal * 0x101;
1943 
1944 	if (dc_link_set_backlight_level(dm->backlight_link,
1945 			brightness, 0))
1946 		return 0;
1947 	else
1948 		return 1;
1949 }
1950 
1951 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1952 {
1953 	struct amdgpu_display_manager *dm = bl_get_data(bd);
1954 	int ret = dc_link_get_backlight_level(dm->backlight_link);
1955 
1956 	if (ret == DC_ERROR_UNEXPECTED)
1957 		return bd->props.brightness;
1958 	return ret;
1959 }
1960 
1961 static const struct backlight_ops amdgpu_dm_backlight_ops = {
1962 	.get_brightness = amdgpu_dm_backlight_get_brightness,
1963 	.update_status	= amdgpu_dm_backlight_update_status,
1964 };
1965 
1966 static void
1967 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1968 {
1969 	char bl_name[16];
1970 	struct backlight_properties props = { 0 };
1971 
1972 	amdgpu_dm_update_backlight_caps(dm);
1973 
1974 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1975 	props.brightness = AMDGPU_MAX_BL_LEVEL;
1976 	props.type = BACKLIGHT_RAW;
1977 
1978 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1979 			dm->adev->ddev->primary->index);
1980 
1981 	dm->backlight_dev = backlight_device_register(bl_name,
1982 			dm->adev->ddev->dev,
1983 			dm,
1984 			&amdgpu_dm_backlight_ops,
1985 			&props);
1986 
1987 	if (IS_ERR(dm->backlight_dev))
1988 		DRM_ERROR("DM: Backlight registration failed!\n");
1989 	else
1990 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1991 }
1992 
1993 #endif
1994 
1995 static int initialize_plane(struct amdgpu_display_manager *dm,
1996 			    struct amdgpu_mode_info *mode_info, int plane_id,
1997 			    enum drm_plane_type plane_type,
1998 			    const struct dc_plane_cap *plane_cap)
1999 {
2000 	struct drm_plane *plane;
2001 	unsigned long possible_crtcs;
2002 	int ret = 0;
2003 
2004 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
2005 	if (!plane) {
2006 		DRM_ERROR("KMS: Failed to allocate plane\n");
2007 		return -ENOMEM;
2008 	}
2009 	plane->type = plane_type;
2010 
2011 	/*
2012 	 * HACK: IGT tests expect that the primary plane for a CRTC
2013 	 * can only have one possible CRTC. Only expose support for
2014 	 * any CRTC if they're not going to be used as a primary plane
2015 	 * for a CRTC - like overlay or underlay planes.
2016 	 */
2017 	possible_crtcs = 1 << plane_id;
2018 	if (plane_id >= dm->dc->caps.max_streams)
2019 		possible_crtcs = 0xff;
2020 
2021 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2022 
2023 	if (ret) {
2024 		DRM_ERROR("KMS: Failed to initialize plane\n");
2025 		kfree(plane);
2026 		return ret;
2027 	}
2028 
2029 	if (mode_info)
2030 		mode_info->planes[plane_id] = plane;
2031 
2032 	return ret;
2033 }
2034 
2035 
2036 static void register_backlight_device(struct amdgpu_display_manager *dm,
2037 				      struct dc_link *link)
2038 {
2039 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2040 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2041 
2042 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2043 	    link->type != dc_connection_none) {
2044 		/*
2045 		 * Event if registration failed, we should continue with
2046 		 * DM initialization because not having a backlight control
2047 		 * is better then a black screen.
2048 		 */
2049 		amdgpu_dm_register_backlight_device(dm);
2050 
2051 		if (dm->backlight_dev)
2052 			dm->backlight_link = link;
2053 	}
2054 #endif
2055 }
2056 
2057 
2058 /*
2059  * In this architecture, the association
2060  * connector -> encoder -> crtc
2061  * id not really requried. The crtc and connector will hold the
2062  * display_index as an abstraction to use with DAL component
2063  *
2064  * Returns 0 on success
2065  */
2066 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2067 {
2068 	struct amdgpu_display_manager *dm = &adev->dm;
2069 	int32_t i;
2070 	struct amdgpu_dm_connector *aconnector = NULL;
2071 	struct amdgpu_encoder *aencoder = NULL;
2072 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
2073 	uint32_t link_cnt;
2074 	int32_t primary_planes;
2075 	enum dc_connection_type new_connection_type = dc_connection_none;
2076 	const struct dc_plane_cap *plane;
2077 
2078 	link_cnt = dm->dc->caps.max_links;
2079 	if (amdgpu_dm_mode_config_init(dm->adev)) {
2080 		DRM_ERROR("DM: Failed to initialize mode config\n");
2081 		return -EINVAL;
2082 	}
2083 
2084 	/* There is one primary plane per CRTC */
2085 	primary_planes = dm->dc->caps.max_streams;
2086 	ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
2087 
2088 	/*
2089 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
2090 	 * Order is reversed to match iteration order in atomic check.
2091 	 */
2092 	for (i = (primary_planes - 1); i >= 0; i--) {
2093 		plane = &dm->dc->caps.planes[i];
2094 
2095 		if (initialize_plane(dm, mode_info, i,
2096 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
2097 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
2098 			goto fail;
2099 		}
2100 	}
2101 
2102 	/*
2103 	 * Initialize overlay planes, index starting after primary planes.
2104 	 * These planes have a higher DRM index than the primary planes since
2105 	 * they should be considered as having a higher z-order.
2106 	 * Order is reversed to match iteration order in atomic check.
2107 	 *
2108 	 * Only support DCN for now, and only expose one so we don't encourage
2109 	 * userspace to use up all the pipes.
2110 	 */
2111 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2112 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2113 
2114 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2115 			continue;
2116 
2117 		if (!plane->blends_with_above || !plane->blends_with_below)
2118 			continue;
2119 
2120 		if (!plane->pixel_format_support.argb8888)
2121 			continue;
2122 
2123 		if (initialize_plane(dm, NULL, primary_planes + i,
2124 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
2125 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
2126 			goto fail;
2127 		}
2128 
2129 		/* Only create one overlay plane. */
2130 		break;
2131 	}
2132 
2133 	for (i = 0; i < dm->dc->caps.max_streams; i++)
2134 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2135 			DRM_ERROR("KMS: Failed to initialize crtc\n");
2136 			goto fail;
2137 		}
2138 
2139 	dm->display_indexes_num = dm->dc->caps.max_streams;
2140 
2141 	/* loops over all connectors on the board */
2142 	for (i = 0; i < link_cnt; i++) {
2143 		struct dc_link *link = NULL;
2144 
2145 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
2146 			DRM_ERROR(
2147 				"KMS: Cannot support more than %d display indexes\n",
2148 					AMDGPU_DM_MAX_DISPLAY_INDEX);
2149 			continue;
2150 		}
2151 
2152 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
2153 		if (!aconnector)
2154 			goto fail;
2155 
2156 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
2157 		if (!aencoder)
2158 			goto fail;
2159 
2160 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2161 			DRM_ERROR("KMS: Failed to initialize encoder\n");
2162 			goto fail;
2163 		}
2164 
2165 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2166 			DRM_ERROR("KMS: Failed to initialize connector\n");
2167 			goto fail;
2168 		}
2169 
2170 		link = dc_get_link_at_index(dm->dc, i);
2171 
2172 		if (!dc_link_detect_sink(link, &new_connection_type))
2173 			DRM_ERROR("KMS: Failed to detect connector\n");
2174 
2175 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2176 			emulated_link_detect(link);
2177 			amdgpu_dm_update_connector_after_detect(aconnector);
2178 
2179 		} else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
2180 			amdgpu_dm_update_connector_after_detect(aconnector);
2181 			register_backlight_device(dm, link);
2182 		}
2183 
2184 
2185 	}
2186 
2187 	/* Software is initialized. Now we can register interrupt handlers. */
2188 	switch (adev->asic_type) {
2189 	case CHIP_BONAIRE:
2190 	case CHIP_HAWAII:
2191 	case CHIP_KAVERI:
2192 	case CHIP_KABINI:
2193 	case CHIP_MULLINS:
2194 	case CHIP_TONGA:
2195 	case CHIP_FIJI:
2196 	case CHIP_CARRIZO:
2197 	case CHIP_STONEY:
2198 	case CHIP_POLARIS11:
2199 	case CHIP_POLARIS10:
2200 	case CHIP_POLARIS12:
2201 	case CHIP_VEGAM:
2202 	case CHIP_VEGA10:
2203 	case CHIP_VEGA12:
2204 	case CHIP_VEGA20:
2205 		if (dce110_register_irq_handlers(dm->adev)) {
2206 			DRM_ERROR("DM: Failed to initialize IRQ\n");
2207 			goto fail;
2208 		}
2209 		break;
2210 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2211 	case CHIP_RAVEN:
2212 		if (dcn10_register_irq_handlers(dm->adev)) {
2213 			DRM_ERROR("DM: Failed to initialize IRQ\n");
2214 			goto fail;
2215 		}
2216 		break;
2217 #endif
2218 	default:
2219 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2220 		goto fail;
2221 	}
2222 
2223 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2224 		dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2225 
2226 	return 0;
2227 fail:
2228 	kfree(aencoder);
2229 	kfree(aconnector);
2230 
2231 	return -EINVAL;
2232 }
2233 
2234 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2235 {
2236 	drm_mode_config_cleanup(dm->ddev);
2237 	drm_atomic_private_obj_fini(&dm->atomic_obj);
2238 	return;
2239 }
2240 
2241 /******************************************************************************
2242  * amdgpu_display_funcs functions
2243  *****************************************************************************/
2244 
2245 /*
2246  * dm_bandwidth_update - program display watermarks
2247  *
2248  * @adev: amdgpu_device pointer
2249  *
2250  * Calculate and program the display watermarks and line buffer allocation.
2251  */
2252 static void dm_bandwidth_update(struct amdgpu_device *adev)
2253 {
2254 	/* TODO: implement later */
2255 }
2256 
2257 static const struct amdgpu_display_funcs dm_display_funcs = {
2258 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2259 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2260 	.backlight_set_level = NULL, /* never called for DC */
2261 	.backlight_get_level = NULL, /* never called for DC */
2262 	.hpd_sense = NULL,/* called unconditionally */
2263 	.hpd_set_polarity = NULL, /* called unconditionally */
2264 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2265 	.page_flip_get_scanoutpos =
2266 		dm_crtc_get_scanoutpos,/* called unconditionally */
2267 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2268 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
2269 };
2270 
2271 #if defined(CONFIG_DEBUG_KERNEL_DC)
2272 
2273 static ssize_t s3_debug_store(struct device *device,
2274 			      struct device_attribute *attr,
2275 			      const char *buf,
2276 			      size_t count)
2277 {
2278 	int ret;
2279 	int s3_state;
2280 	struct pci_dev *pdev = to_pci_dev(device);
2281 	struct drm_device *drm_dev = pci_get_drvdata(pdev);
2282 	struct amdgpu_device *adev = drm_dev->dev_private;
2283 
2284 	ret = kstrtoint(buf, 0, &s3_state);
2285 
2286 	if (ret == 0) {
2287 		if (s3_state) {
2288 			dm_resume(adev);
2289 			drm_kms_helper_hotplug_event(adev->ddev);
2290 		} else
2291 			dm_suspend(adev);
2292 	}
2293 
2294 	return ret == 0 ? count : 0;
2295 }
2296 
2297 DEVICE_ATTR_WO(s3_debug);
2298 
2299 #endif
2300 
2301 static int dm_early_init(void *handle)
2302 {
2303 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2304 
2305 	switch (adev->asic_type) {
2306 	case CHIP_BONAIRE:
2307 	case CHIP_HAWAII:
2308 		adev->mode_info.num_crtc = 6;
2309 		adev->mode_info.num_hpd = 6;
2310 		adev->mode_info.num_dig = 6;
2311 		break;
2312 	case CHIP_KAVERI:
2313 		adev->mode_info.num_crtc = 4;
2314 		adev->mode_info.num_hpd = 6;
2315 		adev->mode_info.num_dig = 7;
2316 		break;
2317 	case CHIP_KABINI:
2318 	case CHIP_MULLINS:
2319 		adev->mode_info.num_crtc = 2;
2320 		adev->mode_info.num_hpd = 6;
2321 		adev->mode_info.num_dig = 6;
2322 		break;
2323 	case CHIP_FIJI:
2324 	case CHIP_TONGA:
2325 		adev->mode_info.num_crtc = 6;
2326 		adev->mode_info.num_hpd = 6;
2327 		adev->mode_info.num_dig = 7;
2328 		break;
2329 	case CHIP_CARRIZO:
2330 		adev->mode_info.num_crtc = 3;
2331 		adev->mode_info.num_hpd = 6;
2332 		adev->mode_info.num_dig = 9;
2333 		break;
2334 	case CHIP_STONEY:
2335 		adev->mode_info.num_crtc = 2;
2336 		adev->mode_info.num_hpd = 6;
2337 		adev->mode_info.num_dig = 9;
2338 		break;
2339 	case CHIP_POLARIS11:
2340 	case CHIP_POLARIS12:
2341 		adev->mode_info.num_crtc = 5;
2342 		adev->mode_info.num_hpd = 5;
2343 		adev->mode_info.num_dig = 5;
2344 		break;
2345 	case CHIP_POLARIS10:
2346 	case CHIP_VEGAM:
2347 		adev->mode_info.num_crtc = 6;
2348 		adev->mode_info.num_hpd = 6;
2349 		adev->mode_info.num_dig = 6;
2350 		break;
2351 	case CHIP_VEGA10:
2352 	case CHIP_VEGA12:
2353 	case CHIP_VEGA20:
2354 		adev->mode_info.num_crtc = 6;
2355 		adev->mode_info.num_hpd = 6;
2356 		adev->mode_info.num_dig = 6;
2357 		break;
2358 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2359 	case CHIP_RAVEN:
2360 		adev->mode_info.num_crtc = 4;
2361 		adev->mode_info.num_hpd = 4;
2362 		adev->mode_info.num_dig = 4;
2363 		break;
2364 #endif
2365 	default:
2366 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2367 		return -EINVAL;
2368 	}
2369 
2370 	amdgpu_dm_set_irq_funcs(adev);
2371 
2372 	if (adev->mode_info.funcs == NULL)
2373 		adev->mode_info.funcs = &dm_display_funcs;
2374 
2375 	/*
2376 	 * Note: Do NOT change adev->audio_endpt_rreg and
2377 	 * adev->audio_endpt_wreg because they are initialised in
2378 	 * amdgpu_device_init()
2379 	 */
2380 #if defined(CONFIG_DEBUG_KERNEL_DC)
2381 	device_create_file(
2382 		adev->ddev->dev,
2383 		&dev_attr_s3_debug);
2384 #endif
2385 
2386 	return 0;
2387 }
2388 
2389 static bool modeset_required(struct drm_crtc_state *crtc_state,
2390 			     struct dc_stream_state *new_stream,
2391 			     struct dc_stream_state *old_stream)
2392 {
2393 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
2394 		return false;
2395 
2396 	if (!crtc_state->enable)
2397 		return false;
2398 
2399 	return crtc_state->active;
2400 }
2401 
2402 static bool modereset_required(struct drm_crtc_state *crtc_state)
2403 {
2404 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
2405 		return false;
2406 
2407 	return !crtc_state->enable || !crtc_state->active;
2408 }
2409 
2410 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2411 {
2412 	drm_encoder_cleanup(encoder);
2413 	kfree(encoder);
2414 }
2415 
2416 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2417 	.destroy = amdgpu_dm_encoder_destroy,
2418 };
2419 
2420 
2421 static int fill_dc_scaling_info(const struct drm_plane_state *state,
2422 				struct dc_scaling_info *scaling_info)
2423 {
2424 	int scale_w, scale_h;
2425 
2426 	memset(scaling_info, 0, sizeof(*scaling_info));
2427 
2428 	/* Source is fixed 16.16 but we ignore mantissa for now... */
2429 	scaling_info->src_rect.x = state->src_x >> 16;
2430 	scaling_info->src_rect.y = state->src_y >> 16;
2431 
2432 	scaling_info->src_rect.width = state->src_w >> 16;
2433 	if (scaling_info->src_rect.width == 0)
2434 		return -EINVAL;
2435 
2436 	scaling_info->src_rect.height = state->src_h >> 16;
2437 	if (scaling_info->src_rect.height == 0)
2438 		return -EINVAL;
2439 
2440 	scaling_info->dst_rect.x = state->crtc_x;
2441 	scaling_info->dst_rect.y = state->crtc_y;
2442 
2443 	if (state->crtc_w == 0)
2444 		return -EINVAL;
2445 
2446 	scaling_info->dst_rect.width = state->crtc_w;
2447 
2448 	if (state->crtc_h == 0)
2449 		return -EINVAL;
2450 
2451 	scaling_info->dst_rect.height = state->crtc_h;
2452 
2453 	/* DRM doesn't specify clipping on destination output. */
2454 	scaling_info->clip_rect = scaling_info->dst_rect;
2455 
2456 	/* TODO: Validate scaling per-format with DC plane caps */
2457 	scale_w = scaling_info->dst_rect.width * 1000 /
2458 		  scaling_info->src_rect.width;
2459 
2460 	if (scale_w < 250 || scale_w > 16000)
2461 		return -EINVAL;
2462 
2463 	scale_h = scaling_info->dst_rect.height * 1000 /
2464 		  scaling_info->src_rect.height;
2465 
2466 	if (scale_h < 250 || scale_h > 16000)
2467 		return -EINVAL;
2468 
2469 	/*
2470 	 * The "scaling_quality" can be ignored for now, quality = 0 has DC
2471 	 * assume reasonable defaults based on the format.
2472 	 */
2473 
2474 	return 0;
2475 }
2476 
2477 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2478 		       uint64_t *tiling_flags)
2479 {
2480 	struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2481 	int r = amdgpu_bo_reserve(rbo, false);
2482 
2483 	if (unlikely(r)) {
2484 		/* Don't show error message when returning -ERESTARTSYS */
2485 		if (r != -ERESTARTSYS)
2486 			DRM_ERROR("Unable to reserve buffer: %d\n", r);
2487 		return r;
2488 	}
2489 
2490 	if (tiling_flags)
2491 		amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2492 
2493 	amdgpu_bo_unreserve(rbo);
2494 
2495 	return r;
2496 }
2497 
2498 static inline uint64_t get_dcc_address(uint64_t address, uint64_t tiling_flags)
2499 {
2500 	uint32_t offset = AMDGPU_TILING_GET(tiling_flags, DCC_OFFSET_256B);
2501 
2502 	return offset ? (address + offset * 256) : 0;
2503 }
2504 
2505 static int
2506 fill_plane_dcc_attributes(struct amdgpu_device *adev,
2507 			  const struct amdgpu_framebuffer *afb,
2508 			  const enum surface_pixel_format format,
2509 			  const enum dc_rotation_angle rotation,
2510 			  const union plane_size *plane_size,
2511 			  const union dc_tiling_info *tiling_info,
2512 			  const uint64_t info,
2513 			  struct dc_plane_dcc_param *dcc,
2514 			  struct dc_plane_address *address)
2515 {
2516 	struct dc *dc = adev->dm.dc;
2517 	struct dc_dcc_surface_param input;
2518 	struct dc_surface_dcc_cap output;
2519 	uint32_t offset = AMDGPU_TILING_GET(info, DCC_OFFSET_256B);
2520 	uint32_t i64b = AMDGPU_TILING_GET(info, DCC_INDEPENDENT_64B) != 0;
2521 	uint64_t dcc_address;
2522 
2523 	memset(&input, 0, sizeof(input));
2524 	memset(&output, 0, sizeof(output));
2525 
2526 	if (!offset)
2527 		return 0;
2528 
2529 	if (format >= SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2530 		return 0;
2531 
2532 	if (!dc->cap_funcs.get_dcc_compression_cap)
2533 		return -EINVAL;
2534 
2535 	input.format = format;
2536 	input.surface_size.width = plane_size->grph.surface_size.width;
2537 	input.surface_size.height = plane_size->grph.surface_size.height;
2538 	input.swizzle_mode = tiling_info->gfx9.swizzle;
2539 
2540 	if (rotation == ROTATION_ANGLE_0 || rotation == ROTATION_ANGLE_180)
2541 		input.scan = SCAN_DIRECTION_HORIZONTAL;
2542 	else if (rotation == ROTATION_ANGLE_90 || rotation == ROTATION_ANGLE_270)
2543 		input.scan = SCAN_DIRECTION_VERTICAL;
2544 
2545 	if (!dc->cap_funcs.get_dcc_compression_cap(dc, &input, &output))
2546 		return -EINVAL;
2547 
2548 	if (!output.capable)
2549 		return -EINVAL;
2550 
2551 	if (i64b == 0 && output.grph.rgb.independent_64b_blks != 0)
2552 		return -EINVAL;
2553 
2554 	dcc->enable = 1;
2555 	dcc->grph.meta_pitch =
2556 		AMDGPU_TILING_GET(info, DCC_PITCH_MAX) + 1;
2557 	dcc->grph.independent_64b_blks = i64b;
2558 
2559 	dcc_address = get_dcc_address(afb->address, info);
2560 	address->grph.meta_addr.low_part = lower_32_bits(dcc_address);
2561 	address->grph.meta_addr.high_part = upper_32_bits(dcc_address);
2562 
2563 	return 0;
2564 }
2565 
2566 static int
2567 fill_plane_buffer_attributes(struct amdgpu_device *adev,
2568 			     const struct amdgpu_framebuffer *afb,
2569 			     const enum surface_pixel_format format,
2570 			     const enum dc_rotation_angle rotation,
2571 			     const uint64_t tiling_flags,
2572 			     union dc_tiling_info *tiling_info,
2573 			     union plane_size *plane_size,
2574 			     struct dc_plane_dcc_param *dcc,
2575 			     struct dc_plane_address *address)
2576 {
2577 	const struct drm_framebuffer *fb = &afb->base;
2578 	int ret;
2579 
2580 	memset(tiling_info, 0, sizeof(*tiling_info));
2581 	memset(plane_size, 0, sizeof(*plane_size));
2582 	memset(dcc, 0, sizeof(*dcc));
2583 	memset(address, 0, sizeof(*address));
2584 
2585 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2586 		plane_size->grph.surface_size.x = 0;
2587 		plane_size->grph.surface_size.y = 0;
2588 		plane_size->grph.surface_size.width = fb->width;
2589 		plane_size->grph.surface_size.height = fb->height;
2590 		plane_size->grph.surface_pitch =
2591 			fb->pitches[0] / fb->format->cpp[0];
2592 
2593 		address->type = PLN_ADDR_TYPE_GRAPHICS;
2594 		address->grph.addr.low_part = lower_32_bits(afb->address);
2595 		address->grph.addr.high_part = upper_32_bits(afb->address);
2596 	} else if (format < SURFACE_PIXEL_FORMAT_INVALID) {
2597 		uint64_t chroma_addr = afb->address + fb->offsets[1];
2598 
2599 		plane_size->video.luma_size.x = 0;
2600 		plane_size->video.luma_size.y = 0;
2601 		plane_size->video.luma_size.width = fb->width;
2602 		plane_size->video.luma_size.height = fb->height;
2603 		plane_size->video.luma_pitch =
2604 			fb->pitches[0] / fb->format->cpp[0];
2605 
2606 		plane_size->video.chroma_size.x = 0;
2607 		plane_size->video.chroma_size.y = 0;
2608 		/* TODO: set these based on surface format */
2609 		plane_size->video.chroma_size.width = fb->width / 2;
2610 		plane_size->video.chroma_size.height = fb->height / 2;
2611 
2612 		plane_size->video.chroma_pitch =
2613 			fb->pitches[1] / fb->format->cpp[1];
2614 
2615 		address->type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2616 		address->video_progressive.luma_addr.low_part =
2617 			lower_32_bits(afb->address);
2618 		address->video_progressive.luma_addr.high_part =
2619 			upper_32_bits(afb->address);
2620 		address->video_progressive.chroma_addr.low_part =
2621 			lower_32_bits(chroma_addr);
2622 		address->video_progressive.chroma_addr.high_part =
2623 			upper_32_bits(chroma_addr);
2624 	}
2625 
2626 	/* Fill GFX8 params */
2627 	if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2628 		unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2629 
2630 		bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2631 		bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2632 		mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2633 		tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2634 		num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2635 
2636 		/* XXX fix me for VI */
2637 		tiling_info->gfx8.num_banks = num_banks;
2638 		tiling_info->gfx8.array_mode =
2639 				DC_ARRAY_2D_TILED_THIN1;
2640 		tiling_info->gfx8.tile_split = tile_split;
2641 		tiling_info->gfx8.bank_width = bankw;
2642 		tiling_info->gfx8.bank_height = bankh;
2643 		tiling_info->gfx8.tile_aspect = mtaspect;
2644 		tiling_info->gfx8.tile_mode =
2645 				DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2646 	} else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2647 			== DC_ARRAY_1D_TILED_THIN1) {
2648 		tiling_info->gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2649 	}
2650 
2651 	tiling_info->gfx8.pipe_config =
2652 			AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2653 
2654 	if (adev->asic_type == CHIP_VEGA10 ||
2655 	    adev->asic_type == CHIP_VEGA12 ||
2656 	    adev->asic_type == CHIP_VEGA20 ||
2657 	    adev->asic_type == CHIP_RAVEN) {
2658 		/* Fill GFX9 params */
2659 		tiling_info->gfx9.num_pipes =
2660 			adev->gfx.config.gb_addr_config_fields.num_pipes;
2661 		tiling_info->gfx9.num_banks =
2662 			adev->gfx.config.gb_addr_config_fields.num_banks;
2663 		tiling_info->gfx9.pipe_interleave =
2664 			adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2665 		tiling_info->gfx9.num_shader_engines =
2666 			adev->gfx.config.gb_addr_config_fields.num_se;
2667 		tiling_info->gfx9.max_compressed_frags =
2668 			adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2669 		tiling_info->gfx9.num_rb_per_se =
2670 			adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2671 		tiling_info->gfx9.swizzle =
2672 			AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2673 		tiling_info->gfx9.shaderEnable = 1;
2674 
2675 		ret = fill_plane_dcc_attributes(adev, afb, format, rotation,
2676 						plane_size, tiling_info,
2677 						tiling_flags, dcc, address);
2678 		if (ret)
2679 			return ret;
2680 	}
2681 
2682 	return 0;
2683 }
2684 
2685 static void
2686 fill_blending_from_plane_state(const struct drm_plane_state *plane_state,
2687 			       bool *per_pixel_alpha, bool *global_alpha,
2688 			       int *global_alpha_value)
2689 {
2690 	*per_pixel_alpha = false;
2691 	*global_alpha = false;
2692 	*global_alpha_value = 0xff;
2693 
2694 	if (plane_state->plane->type != DRM_PLANE_TYPE_OVERLAY)
2695 		return;
2696 
2697 	if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) {
2698 		static const uint32_t alpha_formats[] = {
2699 			DRM_FORMAT_ARGB8888,
2700 			DRM_FORMAT_RGBA8888,
2701 			DRM_FORMAT_ABGR8888,
2702 		};
2703 		uint32_t format = plane_state->fb->format->format;
2704 		unsigned int i;
2705 
2706 		for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
2707 			if (format == alpha_formats[i]) {
2708 				*per_pixel_alpha = true;
2709 				break;
2710 			}
2711 		}
2712 	}
2713 
2714 	if (plane_state->alpha < 0xffff) {
2715 		*global_alpha = true;
2716 		*global_alpha_value = plane_state->alpha >> 8;
2717 	}
2718 }
2719 
2720 static int
2721 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
2722 			    const enum surface_pixel_format format,
2723 			    enum dc_color_space *color_space)
2724 {
2725 	bool full_range;
2726 
2727 	*color_space = COLOR_SPACE_SRGB;
2728 
2729 	/* DRM color properties only affect non-RGB formats. */
2730 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2731 		return 0;
2732 
2733 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2734 
2735 	switch (plane_state->color_encoding) {
2736 	case DRM_COLOR_YCBCR_BT601:
2737 		if (full_range)
2738 			*color_space = COLOR_SPACE_YCBCR601;
2739 		else
2740 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
2741 		break;
2742 
2743 	case DRM_COLOR_YCBCR_BT709:
2744 		if (full_range)
2745 			*color_space = COLOR_SPACE_YCBCR709;
2746 		else
2747 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
2748 		break;
2749 
2750 	case DRM_COLOR_YCBCR_BT2020:
2751 		if (full_range)
2752 			*color_space = COLOR_SPACE_2020_YCBCR;
2753 		else
2754 			return -EINVAL;
2755 		break;
2756 
2757 	default:
2758 		return -EINVAL;
2759 	}
2760 
2761 	return 0;
2762 }
2763 
2764 static int
2765 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2766 			    const struct drm_plane_state *plane_state,
2767 			    const uint64_t tiling_flags,
2768 			    struct dc_plane_info *plane_info,
2769 			    struct dc_plane_address *address)
2770 {
2771 	const struct drm_framebuffer *fb = plane_state->fb;
2772 	const struct amdgpu_framebuffer *afb =
2773 		to_amdgpu_framebuffer(plane_state->fb);
2774 	struct drm_format_name_buf format_name;
2775 	int ret;
2776 
2777 	memset(plane_info, 0, sizeof(*plane_info));
2778 
2779 	switch (fb->format->format) {
2780 	case DRM_FORMAT_C8:
2781 		plane_info->format =
2782 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2783 		break;
2784 	case DRM_FORMAT_RGB565:
2785 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2786 		break;
2787 	case DRM_FORMAT_XRGB8888:
2788 	case DRM_FORMAT_ARGB8888:
2789 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2790 		break;
2791 	case DRM_FORMAT_XRGB2101010:
2792 	case DRM_FORMAT_ARGB2101010:
2793 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2794 		break;
2795 	case DRM_FORMAT_XBGR2101010:
2796 	case DRM_FORMAT_ABGR2101010:
2797 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2798 		break;
2799 	case DRM_FORMAT_XBGR8888:
2800 	case DRM_FORMAT_ABGR8888:
2801 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2802 		break;
2803 	case DRM_FORMAT_NV21:
2804 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2805 		break;
2806 	case DRM_FORMAT_NV12:
2807 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2808 		break;
2809 	default:
2810 		DRM_ERROR(
2811 			"Unsupported screen format %s\n",
2812 			drm_get_format_name(fb->format->format, &format_name));
2813 		return -EINVAL;
2814 	}
2815 
2816 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
2817 	case DRM_MODE_ROTATE_0:
2818 		plane_info->rotation = ROTATION_ANGLE_0;
2819 		break;
2820 	case DRM_MODE_ROTATE_90:
2821 		plane_info->rotation = ROTATION_ANGLE_90;
2822 		break;
2823 	case DRM_MODE_ROTATE_180:
2824 		plane_info->rotation = ROTATION_ANGLE_180;
2825 		break;
2826 	case DRM_MODE_ROTATE_270:
2827 		plane_info->rotation = ROTATION_ANGLE_270;
2828 		break;
2829 	default:
2830 		plane_info->rotation = ROTATION_ANGLE_0;
2831 		break;
2832 	}
2833 
2834 	plane_info->visible = true;
2835 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
2836 
2837 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
2838 					  &plane_info->color_space);
2839 	if (ret)
2840 		return ret;
2841 
2842 	ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
2843 					   plane_info->rotation, tiling_flags,
2844 					   &plane_info->tiling_info,
2845 					   &plane_info->plane_size,
2846 					   &plane_info->dcc, address);
2847 	if (ret)
2848 		return ret;
2849 
2850 	fill_blending_from_plane_state(
2851 		plane_state, &plane_info->per_pixel_alpha,
2852 		&plane_info->global_alpha, &plane_info->global_alpha_value);
2853 
2854 	return 0;
2855 }
2856 
2857 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
2858 				    struct dc_plane_state *dc_plane_state,
2859 				    struct drm_plane_state *plane_state,
2860 				    struct drm_crtc_state *crtc_state)
2861 {
2862 	const struct amdgpu_framebuffer *amdgpu_fb =
2863 		to_amdgpu_framebuffer(plane_state->fb);
2864 	struct dc_scaling_info scaling_info;
2865 	struct dc_plane_info plane_info;
2866 	uint64_t tiling_flags;
2867 	int ret;
2868 
2869 	ret = fill_dc_scaling_info(plane_state, &scaling_info);
2870 	if (ret)
2871 		return ret;
2872 
2873 	dc_plane_state->src_rect = scaling_info.src_rect;
2874 	dc_plane_state->dst_rect = scaling_info.dst_rect;
2875 	dc_plane_state->clip_rect = scaling_info.clip_rect;
2876 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
2877 
2878 	ret = get_fb_info(amdgpu_fb, &tiling_flags);
2879 	if (ret)
2880 		return ret;
2881 
2882 	ret = fill_dc_plane_info_and_addr(adev, plane_state, tiling_flags,
2883 					  &plane_info,
2884 					  &dc_plane_state->address);
2885 	if (ret)
2886 		return ret;
2887 
2888 	dc_plane_state->format = plane_info.format;
2889 	dc_plane_state->color_space = plane_info.color_space;
2890 	dc_plane_state->format = plane_info.format;
2891 	dc_plane_state->plane_size = plane_info.plane_size;
2892 	dc_plane_state->rotation = plane_info.rotation;
2893 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
2894 	dc_plane_state->stereo_format = plane_info.stereo_format;
2895 	dc_plane_state->tiling_info = plane_info.tiling_info;
2896 	dc_plane_state->visible = plane_info.visible;
2897 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
2898 	dc_plane_state->global_alpha = plane_info.global_alpha;
2899 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
2900 	dc_plane_state->dcc = plane_info.dcc;
2901 
2902 	/*
2903 	 * Always set input transfer function, since plane state is refreshed
2904 	 * every time.
2905 	 */
2906 	ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2907 	if (ret) {
2908 		dc_transfer_func_release(dc_plane_state->in_transfer_func);
2909 		dc_plane_state->in_transfer_func = NULL;
2910 	}
2911 
2912 	return ret;
2913 }
2914 
2915 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2916 					   const struct dm_connector_state *dm_state,
2917 					   struct dc_stream_state *stream)
2918 {
2919 	enum amdgpu_rmx_type rmx_type;
2920 
2921 	struct rect src = { 0 }; /* viewport in composition space*/
2922 	struct rect dst = { 0 }; /* stream addressable area */
2923 
2924 	/* no mode. nothing to be done */
2925 	if (!mode)
2926 		return;
2927 
2928 	/* Full screen scaling by default */
2929 	src.width = mode->hdisplay;
2930 	src.height = mode->vdisplay;
2931 	dst.width = stream->timing.h_addressable;
2932 	dst.height = stream->timing.v_addressable;
2933 
2934 	if (dm_state) {
2935 		rmx_type = dm_state->scaling;
2936 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2937 			if (src.width * dst.height <
2938 					src.height * dst.width) {
2939 				/* height needs less upscaling/more downscaling */
2940 				dst.width = src.width *
2941 						dst.height / src.height;
2942 			} else {
2943 				/* width needs less upscaling/more downscaling */
2944 				dst.height = src.height *
2945 						dst.width / src.width;
2946 			}
2947 		} else if (rmx_type == RMX_CENTER) {
2948 			dst = src;
2949 		}
2950 
2951 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
2952 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
2953 
2954 		if (dm_state->underscan_enable) {
2955 			dst.x += dm_state->underscan_hborder / 2;
2956 			dst.y += dm_state->underscan_vborder / 2;
2957 			dst.width -= dm_state->underscan_hborder;
2958 			dst.height -= dm_state->underscan_vborder;
2959 		}
2960 	}
2961 
2962 	stream->src = src;
2963 	stream->dst = dst;
2964 
2965 	DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2966 			dst.x, dst.y, dst.width, dst.height);
2967 
2968 }
2969 
2970 static enum dc_color_depth
2971 convert_color_depth_from_display_info(const struct drm_connector *connector,
2972 				      const struct drm_connector_state *state)
2973 {
2974 	uint32_t bpc = connector->display_info.bpc;
2975 
2976 	if (state) {
2977 		bpc = state->max_bpc;
2978 		/* Round down to the nearest even number. */
2979 		bpc = bpc - (bpc & 1);
2980 	}
2981 
2982 	switch (bpc) {
2983 	case 0:
2984 		/*
2985 		 * Temporary Work around, DRM doesn't parse color depth for
2986 		 * EDID revision before 1.4
2987 		 * TODO: Fix edid parsing
2988 		 */
2989 		return COLOR_DEPTH_888;
2990 	case 6:
2991 		return COLOR_DEPTH_666;
2992 	case 8:
2993 		return COLOR_DEPTH_888;
2994 	case 10:
2995 		return COLOR_DEPTH_101010;
2996 	case 12:
2997 		return COLOR_DEPTH_121212;
2998 	case 14:
2999 		return COLOR_DEPTH_141414;
3000 	case 16:
3001 		return COLOR_DEPTH_161616;
3002 	default:
3003 		return COLOR_DEPTH_UNDEFINED;
3004 	}
3005 }
3006 
3007 static enum dc_aspect_ratio
3008 get_aspect_ratio(const struct drm_display_mode *mode_in)
3009 {
3010 	/* 1-1 mapping, since both enums follow the HDMI spec. */
3011 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
3012 }
3013 
3014 static enum dc_color_space
3015 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
3016 {
3017 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
3018 
3019 	switch (dc_crtc_timing->pixel_encoding)	{
3020 	case PIXEL_ENCODING_YCBCR422:
3021 	case PIXEL_ENCODING_YCBCR444:
3022 	case PIXEL_ENCODING_YCBCR420:
3023 	{
3024 		/*
3025 		 * 27030khz is the separation point between HDTV and SDTV
3026 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
3027 		 * respectively
3028 		 */
3029 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
3030 			if (dc_crtc_timing->flags.Y_ONLY)
3031 				color_space =
3032 					COLOR_SPACE_YCBCR709_LIMITED;
3033 			else
3034 				color_space = COLOR_SPACE_YCBCR709;
3035 		} else {
3036 			if (dc_crtc_timing->flags.Y_ONLY)
3037 				color_space =
3038 					COLOR_SPACE_YCBCR601_LIMITED;
3039 			else
3040 				color_space = COLOR_SPACE_YCBCR601;
3041 		}
3042 
3043 	}
3044 	break;
3045 	case PIXEL_ENCODING_RGB:
3046 		color_space = COLOR_SPACE_SRGB;
3047 		break;
3048 
3049 	default:
3050 		WARN_ON(1);
3051 		break;
3052 	}
3053 
3054 	return color_space;
3055 }
3056 
3057 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
3058 {
3059 	if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3060 		return;
3061 
3062 	timing_out->display_color_depth--;
3063 }
3064 
3065 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
3066 						const struct drm_display_info *info)
3067 {
3068 	int normalized_clk;
3069 	if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3070 		return;
3071 	do {
3072 		normalized_clk = timing_out->pix_clk_100hz / 10;
3073 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
3074 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3075 			normalized_clk /= 2;
3076 		/* Adjusting pix clock following on HDMI spec based on colour depth */
3077 		switch (timing_out->display_color_depth) {
3078 		case COLOR_DEPTH_101010:
3079 			normalized_clk = (normalized_clk * 30) / 24;
3080 			break;
3081 		case COLOR_DEPTH_121212:
3082 			normalized_clk = (normalized_clk * 36) / 24;
3083 			break;
3084 		case COLOR_DEPTH_161616:
3085 			normalized_clk = (normalized_clk * 48) / 24;
3086 			break;
3087 		default:
3088 			return;
3089 		}
3090 		if (normalized_clk <= info->max_tmds_clock)
3091 			return;
3092 		reduce_mode_colour_depth(timing_out);
3093 
3094 	} while (timing_out->display_color_depth > COLOR_DEPTH_888);
3095 
3096 }
3097 
3098 static void fill_stream_properties_from_drm_display_mode(
3099 	struct dc_stream_state *stream,
3100 	const struct drm_display_mode *mode_in,
3101 	const struct drm_connector *connector,
3102 	const struct drm_connector_state *connector_state,
3103 	const struct dc_stream_state *old_stream)
3104 {
3105 	struct dc_crtc_timing *timing_out = &stream->timing;
3106 	const struct drm_display_info *info = &connector->display_info;
3107 
3108 	memset(timing_out, 0, sizeof(struct dc_crtc_timing));
3109 
3110 	timing_out->h_border_left = 0;
3111 	timing_out->h_border_right = 0;
3112 	timing_out->v_border_top = 0;
3113 	timing_out->v_border_bottom = 0;
3114 	/* TODO: un-hardcode */
3115 	if (drm_mode_is_420_only(info, mode_in)
3116 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3117 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3118 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
3119 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3120 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
3121 	else
3122 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
3123 
3124 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
3125 	timing_out->display_color_depth = convert_color_depth_from_display_info(
3126 		connector, connector_state);
3127 	timing_out->scan_type = SCANNING_TYPE_NODATA;
3128 	timing_out->hdmi_vic = 0;
3129 
3130 	if(old_stream) {
3131 		timing_out->vic = old_stream->timing.vic;
3132 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
3133 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
3134 	} else {
3135 		timing_out->vic = drm_match_cea_mode(mode_in);
3136 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
3137 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
3138 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
3139 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
3140 	}
3141 
3142 	timing_out->h_addressable = mode_in->crtc_hdisplay;
3143 	timing_out->h_total = mode_in->crtc_htotal;
3144 	timing_out->h_sync_width =
3145 		mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
3146 	timing_out->h_front_porch =
3147 		mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
3148 	timing_out->v_total = mode_in->crtc_vtotal;
3149 	timing_out->v_addressable = mode_in->crtc_vdisplay;
3150 	timing_out->v_front_porch =
3151 		mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
3152 	timing_out->v_sync_width =
3153 		mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
3154 	timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
3155 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
3156 
3157 	stream->output_color_space = get_output_color_space(timing_out);
3158 
3159 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
3160 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
3161 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3162 		adjust_colour_depth_from_display_info(timing_out, info);
3163 }
3164 
3165 static void fill_audio_info(struct audio_info *audio_info,
3166 			    const struct drm_connector *drm_connector,
3167 			    const struct dc_sink *dc_sink)
3168 {
3169 	int i = 0;
3170 	int cea_revision = 0;
3171 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
3172 
3173 	audio_info->manufacture_id = edid_caps->manufacturer_id;
3174 	audio_info->product_id = edid_caps->product_id;
3175 
3176 	cea_revision = drm_connector->display_info.cea_rev;
3177 
3178 	strscpy(audio_info->display_name,
3179 		edid_caps->display_name,
3180 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
3181 
3182 	if (cea_revision >= 3) {
3183 		audio_info->mode_count = edid_caps->audio_mode_count;
3184 
3185 		for (i = 0; i < audio_info->mode_count; ++i) {
3186 			audio_info->modes[i].format_code =
3187 					(enum audio_format_code)
3188 					(edid_caps->audio_modes[i].format_code);
3189 			audio_info->modes[i].channel_count =
3190 					edid_caps->audio_modes[i].channel_count;
3191 			audio_info->modes[i].sample_rates.all =
3192 					edid_caps->audio_modes[i].sample_rate;
3193 			audio_info->modes[i].sample_size =
3194 					edid_caps->audio_modes[i].sample_size;
3195 		}
3196 	}
3197 
3198 	audio_info->flags.all = edid_caps->speaker_flags;
3199 
3200 	/* TODO: We only check for the progressive mode, check for interlace mode too */
3201 	if (drm_connector->latency_present[0]) {
3202 		audio_info->video_latency = drm_connector->video_latency[0];
3203 		audio_info->audio_latency = drm_connector->audio_latency[0];
3204 	}
3205 
3206 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
3207 
3208 }
3209 
3210 static void
3211 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
3212 				      struct drm_display_mode *dst_mode)
3213 {
3214 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
3215 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
3216 	dst_mode->crtc_clock = src_mode->crtc_clock;
3217 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
3218 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
3219 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
3220 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
3221 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
3222 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
3223 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
3224 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
3225 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
3226 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
3227 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
3228 }
3229 
3230 static void
3231 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
3232 					const struct drm_display_mode *native_mode,
3233 					bool scale_enabled)
3234 {
3235 	if (scale_enabled) {
3236 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3237 	} else if (native_mode->clock == drm_mode->clock &&
3238 			native_mode->htotal == drm_mode->htotal &&
3239 			native_mode->vtotal == drm_mode->vtotal) {
3240 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3241 	} else {
3242 		/* no scaling nor amdgpu inserted, no need to patch */
3243 	}
3244 }
3245 
3246 static struct dc_sink *
3247 create_fake_sink(struct amdgpu_dm_connector *aconnector)
3248 {
3249 	struct dc_sink_init_data sink_init_data = { 0 };
3250 	struct dc_sink *sink = NULL;
3251 	sink_init_data.link = aconnector->dc_link;
3252 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
3253 
3254 	sink = dc_sink_create(&sink_init_data);
3255 	if (!sink) {
3256 		DRM_ERROR("Failed to create sink!\n");
3257 		return NULL;
3258 	}
3259 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
3260 
3261 	return sink;
3262 }
3263 
3264 static void set_multisync_trigger_params(
3265 		struct dc_stream_state *stream)
3266 {
3267 	if (stream->triggered_crtc_reset.enabled) {
3268 		stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
3269 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
3270 	}
3271 }
3272 
3273 static void set_master_stream(struct dc_stream_state *stream_set[],
3274 			      int stream_count)
3275 {
3276 	int j, highest_rfr = 0, master_stream = 0;
3277 
3278 	for (j = 0;  j < stream_count; j++) {
3279 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
3280 			int refresh_rate = 0;
3281 
3282 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
3283 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
3284 			if (refresh_rate > highest_rfr) {
3285 				highest_rfr = refresh_rate;
3286 				master_stream = j;
3287 			}
3288 		}
3289 	}
3290 	for (j = 0;  j < stream_count; j++) {
3291 		if (stream_set[j])
3292 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
3293 	}
3294 }
3295 
3296 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
3297 {
3298 	int i = 0;
3299 
3300 	if (context->stream_count < 2)
3301 		return;
3302 	for (i = 0; i < context->stream_count ; i++) {
3303 		if (!context->streams[i])
3304 			continue;
3305 		/*
3306 		 * TODO: add a function to read AMD VSDB bits and set
3307 		 * crtc_sync_master.multi_sync_enabled flag
3308 		 * For now it's set to false
3309 		 */
3310 		set_multisync_trigger_params(context->streams[i]);
3311 	}
3312 	set_master_stream(context->streams, context->stream_count);
3313 }
3314 
3315 static struct dc_stream_state *
3316 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
3317 		       const struct drm_display_mode *drm_mode,
3318 		       const struct dm_connector_state *dm_state,
3319 		       const struct dc_stream_state *old_stream)
3320 {
3321 	struct drm_display_mode *preferred_mode = NULL;
3322 	struct drm_connector *drm_connector;
3323 	const struct drm_connector_state *con_state =
3324 		dm_state ? &dm_state->base : NULL;
3325 	struct dc_stream_state *stream = NULL;
3326 	struct drm_display_mode mode = *drm_mode;
3327 	bool native_mode_found = false;
3328 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
3329 	int mode_refresh;
3330 	int preferred_refresh = 0;
3331 
3332 	struct dc_sink *sink = NULL;
3333 	if (aconnector == NULL) {
3334 		DRM_ERROR("aconnector is NULL!\n");
3335 		return stream;
3336 	}
3337 
3338 	drm_connector = &aconnector->base;
3339 
3340 	if (!aconnector->dc_sink) {
3341 		sink = create_fake_sink(aconnector);
3342 		if (!sink)
3343 			return stream;
3344 	} else {
3345 		sink = aconnector->dc_sink;
3346 		dc_sink_retain(sink);
3347 	}
3348 
3349 	stream = dc_create_stream_for_sink(sink);
3350 
3351 	if (stream == NULL) {
3352 		DRM_ERROR("Failed to create stream for sink!\n");
3353 		goto finish;
3354 	}
3355 
3356 	stream->dm_stream_context = aconnector;
3357 
3358 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
3359 		/* Search for preferred mode */
3360 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
3361 			native_mode_found = true;
3362 			break;
3363 		}
3364 	}
3365 	if (!native_mode_found)
3366 		preferred_mode = list_first_entry_or_null(
3367 				&aconnector->base.modes,
3368 				struct drm_display_mode,
3369 				head);
3370 
3371 	mode_refresh = drm_mode_vrefresh(&mode);
3372 
3373 	if (preferred_mode == NULL) {
3374 		/*
3375 		 * This may not be an error, the use case is when we have no
3376 		 * usermode calls to reset and set mode upon hotplug. In this
3377 		 * case, we call set mode ourselves to restore the previous mode
3378 		 * and the modelist may not be filled in in time.
3379 		 */
3380 		DRM_DEBUG_DRIVER("No preferred mode found\n");
3381 	} else {
3382 		decide_crtc_timing_for_drm_display_mode(
3383 				&mode, preferred_mode,
3384 				dm_state ? (dm_state->scaling != RMX_OFF) : false);
3385 		preferred_refresh = drm_mode_vrefresh(preferred_mode);
3386 	}
3387 
3388 	if (!dm_state)
3389 		drm_mode_set_crtcinfo(&mode, 0);
3390 
3391 	/*
3392 	* If scaling is enabled and refresh rate didn't change
3393 	* we copy the vic and polarities of the old timings
3394 	*/
3395 	if (!scale || mode_refresh != preferred_refresh)
3396 		fill_stream_properties_from_drm_display_mode(stream,
3397 			&mode, &aconnector->base, con_state, NULL);
3398 	else
3399 		fill_stream_properties_from_drm_display_mode(stream,
3400 			&mode, &aconnector->base, con_state, old_stream);
3401 
3402 	update_stream_scaling_settings(&mode, dm_state, stream);
3403 
3404 	fill_audio_info(
3405 		&stream->audio_info,
3406 		drm_connector,
3407 		sink);
3408 
3409 	update_stream_signal(stream, sink);
3410 
3411 finish:
3412 	dc_sink_release(sink);
3413 
3414 	return stream;
3415 }
3416 
3417 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
3418 {
3419 	drm_crtc_cleanup(crtc);
3420 	kfree(crtc);
3421 }
3422 
3423 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
3424 				  struct drm_crtc_state *state)
3425 {
3426 	struct dm_crtc_state *cur = to_dm_crtc_state(state);
3427 
3428 	/* TODO Destroy dc_stream objects are stream object is flattened */
3429 	if (cur->stream)
3430 		dc_stream_release(cur->stream);
3431 
3432 
3433 	__drm_atomic_helper_crtc_destroy_state(state);
3434 
3435 
3436 	kfree(state);
3437 }
3438 
3439 static void dm_crtc_reset_state(struct drm_crtc *crtc)
3440 {
3441 	struct dm_crtc_state *state;
3442 
3443 	if (crtc->state)
3444 		dm_crtc_destroy_state(crtc, crtc->state);
3445 
3446 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3447 	if (WARN_ON(!state))
3448 		return;
3449 
3450 	crtc->state = &state->base;
3451 	crtc->state->crtc = crtc;
3452 
3453 }
3454 
3455 static struct drm_crtc_state *
3456 dm_crtc_duplicate_state(struct drm_crtc *crtc)
3457 {
3458 	struct dm_crtc_state *state, *cur;
3459 
3460 	cur = to_dm_crtc_state(crtc->state);
3461 
3462 	if (WARN_ON(!crtc->state))
3463 		return NULL;
3464 
3465 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3466 	if (!state)
3467 		return NULL;
3468 
3469 	__drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
3470 
3471 	if (cur->stream) {
3472 		state->stream = cur->stream;
3473 		dc_stream_retain(state->stream);
3474 	}
3475 
3476 	state->active_planes = cur->active_planes;
3477 	state->interrupts_enabled = cur->interrupts_enabled;
3478 	state->vrr_params = cur->vrr_params;
3479 	state->vrr_infopacket = cur->vrr_infopacket;
3480 	state->abm_level = cur->abm_level;
3481 	state->vrr_supported = cur->vrr_supported;
3482 	state->freesync_config = cur->freesync_config;
3483 	state->crc_enabled = cur->crc_enabled;
3484 
3485 	/* TODO Duplicate dc_stream after objects are stream object is flattened */
3486 
3487 	return &state->base;
3488 }
3489 
3490 static inline int dm_set_vupdate_irq(struct drm_crtc *crtc, bool enable)
3491 {
3492 	enum dc_irq_source irq_source;
3493 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3494 	struct amdgpu_device *adev = crtc->dev->dev_private;
3495 	int rc;
3496 
3497 	irq_source = IRQ_TYPE_VUPDATE + acrtc->otg_inst;
3498 
3499 	rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3500 
3501 	DRM_DEBUG_DRIVER("crtc %d - vupdate irq %sabling: r=%d\n",
3502 			 acrtc->crtc_id, enable ? "en" : "dis", rc);
3503 	return rc;
3504 }
3505 
3506 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
3507 {
3508 	enum dc_irq_source irq_source;
3509 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3510 	struct amdgpu_device *adev = crtc->dev->dev_private;
3511 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3512 	int rc = 0;
3513 
3514 	if (enable) {
3515 		/* vblank irq on -> Only need vupdate irq in vrr mode */
3516 		if (amdgpu_dm_vrr_active(acrtc_state))
3517 			rc = dm_set_vupdate_irq(crtc, true);
3518 	} else {
3519 		/* vblank irq off -> vupdate irq off */
3520 		rc = dm_set_vupdate_irq(crtc, false);
3521 	}
3522 
3523 	if (rc)
3524 		return rc;
3525 
3526 	irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3527 	return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3528 }
3529 
3530 static int dm_enable_vblank(struct drm_crtc *crtc)
3531 {
3532 	return dm_set_vblank(crtc, true);
3533 }
3534 
3535 static void dm_disable_vblank(struct drm_crtc *crtc)
3536 {
3537 	dm_set_vblank(crtc, false);
3538 }
3539 
3540 /* Implemented only the options currently availible for the driver */
3541 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
3542 	.reset = dm_crtc_reset_state,
3543 	.destroy = amdgpu_dm_crtc_destroy,
3544 	.gamma_set = drm_atomic_helper_legacy_gamma_set,
3545 	.set_config = drm_atomic_helper_set_config,
3546 	.page_flip = drm_atomic_helper_page_flip,
3547 	.atomic_duplicate_state = dm_crtc_duplicate_state,
3548 	.atomic_destroy_state = dm_crtc_destroy_state,
3549 	.set_crc_source = amdgpu_dm_crtc_set_crc_source,
3550 	.verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
3551 	.enable_vblank = dm_enable_vblank,
3552 	.disable_vblank = dm_disable_vblank,
3553 };
3554 
3555 static enum drm_connector_status
3556 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
3557 {
3558 	bool connected;
3559 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3560 
3561 	/*
3562 	 * Notes:
3563 	 * 1. This interface is NOT called in context of HPD irq.
3564 	 * 2. This interface *is called* in context of user-mode ioctl. Which
3565 	 * makes it a bad place for *any* MST-related activity.
3566 	 */
3567 
3568 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
3569 	    !aconnector->fake_enable)
3570 		connected = (aconnector->dc_sink != NULL);
3571 	else
3572 		connected = (aconnector->base.force == DRM_FORCE_ON);
3573 
3574 	return (connected ? connector_status_connected :
3575 			connector_status_disconnected);
3576 }
3577 
3578 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
3579 					    struct drm_connector_state *connector_state,
3580 					    struct drm_property *property,
3581 					    uint64_t val)
3582 {
3583 	struct drm_device *dev = connector->dev;
3584 	struct amdgpu_device *adev = dev->dev_private;
3585 	struct dm_connector_state *dm_old_state =
3586 		to_dm_connector_state(connector->state);
3587 	struct dm_connector_state *dm_new_state =
3588 		to_dm_connector_state(connector_state);
3589 
3590 	int ret = -EINVAL;
3591 
3592 	if (property == dev->mode_config.scaling_mode_property) {
3593 		enum amdgpu_rmx_type rmx_type;
3594 
3595 		switch (val) {
3596 		case DRM_MODE_SCALE_CENTER:
3597 			rmx_type = RMX_CENTER;
3598 			break;
3599 		case DRM_MODE_SCALE_ASPECT:
3600 			rmx_type = RMX_ASPECT;
3601 			break;
3602 		case DRM_MODE_SCALE_FULLSCREEN:
3603 			rmx_type = RMX_FULL;
3604 			break;
3605 		case DRM_MODE_SCALE_NONE:
3606 		default:
3607 			rmx_type = RMX_OFF;
3608 			break;
3609 		}
3610 
3611 		if (dm_old_state->scaling == rmx_type)
3612 			return 0;
3613 
3614 		dm_new_state->scaling = rmx_type;
3615 		ret = 0;
3616 	} else if (property == adev->mode_info.underscan_hborder_property) {
3617 		dm_new_state->underscan_hborder = val;
3618 		ret = 0;
3619 	} else if (property == adev->mode_info.underscan_vborder_property) {
3620 		dm_new_state->underscan_vborder = val;
3621 		ret = 0;
3622 	} else if (property == adev->mode_info.underscan_property) {
3623 		dm_new_state->underscan_enable = val;
3624 		ret = 0;
3625 	} else if (property == adev->mode_info.abm_level_property) {
3626 		dm_new_state->abm_level = val;
3627 		ret = 0;
3628 	}
3629 
3630 	return ret;
3631 }
3632 
3633 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3634 					    const struct drm_connector_state *state,
3635 					    struct drm_property *property,
3636 					    uint64_t *val)
3637 {
3638 	struct drm_device *dev = connector->dev;
3639 	struct amdgpu_device *adev = dev->dev_private;
3640 	struct dm_connector_state *dm_state =
3641 		to_dm_connector_state(state);
3642 	int ret = -EINVAL;
3643 
3644 	if (property == dev->mode_config.scaling_mode_property) {
3645 		switch (dm_state->scaling) {
3646 		case RMX_CENTER:
3647 			*val = DRM_MODE_SCALE_CENTER;
3648 			break;
3649 		case RMX_ASPECT:
3650 			*val = DRM_MODE_SCALE_ASPECT;
3651 			break;
3652 		case RMX_FULL:
3653 			*val = DRM_MODE_SCALE_FULLSCREEN;
3654 			break;
3655 		case RMX_OFF:
3656 		default:
3657 			*val = DRM_MODE_SCALE_NONE;
3658 			break;
3659 		}
3660 		ret = 0;
3661 	} else if (property == adev->mode_info.underscan_hborder_property) {
3662 		*val = dm_state->underscan_hborder;
3663 		ret = 0;
3664 	} else if (property == adev->mode_info.underscan_vborder_property) {
3665 		*val = dm_state->underscan_vborder;
3666 		ret = 0;
3667 	} else if (property == adev->mode_info.underscan_property) {
3668 		*val = dm_state->underscan_enable;
3669 		ret = 0;
3670 	} else if (property == adev->mode_info.abm_level_property) {
3671 		*val = dm_state->abm_level;
3672 		ret = 0;
3673 	}
3674 
3675 	return ret;
3676 }
3677 
3678 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
3679 {
3680 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3681 	const struct dc_link *link = aconnector->dc_link;
3682 	struct amdgpu_device *adev = connector->dev->dev_private;
3683 	struct amdgpu_display_manager *dm = &adev->dm;
3684 
3685 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3686 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3687 
3688 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
3689 	    link->type != dc_connection_none &&
3690 	    dm->backlight_dev) {
3691 		backlight_device_unregister(dm->backlight_dev);
3692 		dm->backlight_dev = NULL;
3693 	}
3694 #endif
3695 
3696 	if (aconnector->dc_em_sink)
3697 		dc_sink_release(aconnector->dc_em_sink);
3698 	aconnector->dc_em_sink = NULL;
3699 	if (aconnector->dc_sink)
3700 		dc_sink_release(aconnector->dc_sink);
3701 	aconnector->dc_sink = NULL;
3702 
3703 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
3704 	drm_connector_unregister(connector);
3705 	drm_connector_cleanup(connector);
3706 	kfree(connector);
3707 }
3708 
3709 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
3710 {
3711 	struct dm_connector_state *state =
3712 		to_dm_connector_state(connector->state);
3713 
3714 	if (connector->state)
3715 		__drm_atomic_helper_connector_destroy_state(connector->state);
3716 
3717 	kfree(state);
3718 
3719 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3720 
3721 	if (state) {
3722 		state->scaling = RMX_OFF;
3723 		state->underscan_enable = false;
3724 		state->underscan_hborder = 0;
3725 		state->underscan_vborder = 0;
3726 
3727 		__drm_atomic_helper_connector_reset(connector, &state->base);
3728 	}
3729 }
3730 
3731 struct drm_connector_state *
3732 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
3733 {
3734 	struct dm_connector_state *state =
3735 		to_dm_connector_state(connector->state);
3736 
3737 	struct dm_connector_state *new_state =
3738 			kmemdup(state, sizeof(*state), GFP_KERNEL);
3739 
3740 	if (!new_state)
3741 		return NULL;
3742 
3743 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
3744 
3745 	new_state->freesync_capable = state->freesync_capable;
3746 	new_state->abm_level = state->abm_level;
3747 	new_state->scaling = state->scaling;
3748 	new_state->underscan_enable = state->underscan_enable;
3749 	new_state->underscan_hborder = state->underscan_hborder;
3750 	new_state->underscan_vborder = state->underscan_vborder;
3751 
3752 	return &new_state->base;
3753 }
3754 
3755 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
3756 	.reset = amdgpu_dm_connector_funcs_reset,
3757 	.detect = amdgpu_dm_connector_detect,
3758 	.fill_modes = drm_helper_probe_single_connector_modes,
3759 	.destroy = amdgpu_dm_connector_destroy,
3760 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
3761 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
3762 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
3763 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property
3764 };
3765 
3766 static int get_modes(struct drm_connector *connector)
3767 {
3768 	return amdgpu_dm_connector_get_modes(connector);
3769 }
3770 
3771 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
3772 {
3773 	struct dc_sink_init_data init_params = {
3774 			.link = aconnector->dc_link,
3775 			.sink_signal = SIGNAL_TYPE_VIRTUAL
3776 	};
3777 	struct edid *edid;
3778 
3779 	if (!aconnector->base.edid_blob_ptr) {
3780 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
3781 				aconnector->base.name);
3782 
3783 		aconnector->base.force = DRM_FORCE_OFF;
3784 		aconnector->base.override_edid = false;
3785 		return;
3786 	}
3787 
3788 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
3789 
3790 	aconnector->edid = edid;
3791 
3792 	aconnector->dc_em_sink = dc_link_add_remote_sink(
3793 		aconnector->dc_link,
3794 		(uint8_t *)edid,
3795 		(edid->extensions + 1) * EDID_LENGTH,
3796 		&init_params);
3797 
3798 	if (aconnector->base.force == DRM_FORCE_ON) {
3799 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
3800 		aconnector->dc_link->local_sink :
3801 		aconnector->dc_em_sink;
3802 		dc_sink_retain(aconnector->dc_sink);
3803 	}
3804 }
3805 
3806 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
3807 {
3808 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
3809 
3810 	/*
3811 	 * In case of headless boot with force on for DP managed connector
3812 	 * Those settings have to be != 0 to get initial modeset
3813 	 */
3814 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
3815 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
3816 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
3817 	}
3818 
3819 
3820 	aconnector->base.override_edid = true;
3821 	create_eml_sink(aconnector);
3822 }
3823 
3824 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
3825 				   struct drm_display_mode *mode)
3826 {
3827 	int result = MODE_ERROR;
3828 	struct dc_sink *dc_sink;
3829 	struct amdgpu_device *adev = connector->dev->dev_private;
3830 	/* TODO: Unhardcode stream count */
3831 	struct dc_stream_state *stream;
3832 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3833 	enum dc_status dc_result = DC_OK;
3834 
3835 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
3836 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
3837 		return result;
3838 
3839 	/*
3840 	 * Only run this the first time mode_valid is called to initilialize
3841 	 * EDID mgmt
3842 	 */
3843 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
3844 		!aconnector->dc_em_sink)
3845 		handle_edid_mgmt(aconnector);
3846 
3847 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
3848 
3849 	if (dc_sink == NULL) {
3850 		DRM_ERROR("dc_sink is NULL!\n");
3851 		goto fail;
3852 	}
3853 
3854 	stream = create_stream_for_sink(aconnector, mode, NULL, NULL);
3855 	if (stream == NULL) {
3856 		DRM_ERROR("Failed to create stream for sink!\n");
3857 		goto fail;
3858 	}
3859 
3860 	dc_result = dc_validate_stream(adev->dm.dc, stream);
3861 
3862 	if (dc_result == DC_OK)
3863 		result = MODE_OK;
3864 	else
3865 		DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
3866 			      mode->vdisplay,
3867 			      mode->hdisplay,
3868 			      mode->clock,
3869 			      dc_result);
3870 
3871 	dc_stream_release(stream);
3872 
3873 fail:
3874 	/* TODO: error handling*/
3875 	return result;
3876 }
3877 
3878 static const struct drm_connector_helper_funcs
3879 amdgpu_dm_connector_helper_funcs = {
3880 	/*
3881 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
3882 	 * modes will be filtered by drm_mode_validate_size(), and those modes
3883 	 * are missing after user start lightdm. So we need to renew modes list.
3884 	 * in get_modes call back, not just return the modes count
3885 	 */
3886 	.get_modes = get_modes,
3887 	.mode_valid = amdgpu_dm_connector_mode_valid,
3888 };
3889 
3890 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
3891 {
3892 }
3893 
3894 static bool does_crtc_have_active_cursor(struct drm_crtc_state *new_crtc_state)
3895 {
3896 	struct drm_device *dev = new_crtc_state->crtc->dev;
3897 	struct drm_plane *plane;
3898 
3899 	drm_for_each_plane_mask(plane, dev, new_crtc_state->plane_mask) {
3900 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
3901 			return true;
3902 	}
3903 
3904 	return false;
3905 }
3906 
3907 static int count_crtc_active_planes(struct drm_crtc_state *new_crtc_state)
3908 {
3909 	struct drm_atomic_state *state = new_crtc_state->state;
3910 	struct drm_plane *plane;
3911 	int num_active = 0;
3912 
3913 	drm_for_each_plane_mask(plane, state->dev, new_crtc_state->plane_mask) {
3914 		struct drm_plane_state *new_plane_state;
3915 
3916 		/* Cursor planes are "fake". */
3917 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
3918 			continue;
3919 
3920 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
3921 
3922 		if (!new_plane_state) {
3923 			/*
3924 			 * The plane is enable on the CRTC and hasn't changed
3925 			 * state. This means that it previously passed
3926 			 * validation and is therefore enabled.
3927 			 */
3928 			num_active += 1;
3929 			continue;
3930 		}
3931 
3932 		/* We need a framebuffer to be considered enabled. */
3933 		num_active += (new_plane_state->fb != NULL);
3934 	}
3935 
3936 	return num_active;
3937 }
3938 
3939 /*
3940  * Sets whether interrupts should be enabled on a specific CRTC.
3941  * We require that the stream be enabled and that there exist active
3942  * DC planes on the stream.
3943  */
3944 static void
3945 dm_update_crtc_interrupt_state(struct drm_crtc *crtc,
3946 			       struct drm_crtc_state *new_crtc_state)
3947 {
3948 	struct dm_crtc_state *dm_new_crtc_state =
3949 		to_dm_crtc_state(new_crtc_state);
3950 
3951 	dm_new_crtc_state->active_planes = 0;
3952 	dm_new_crtc_state->interrupts_enabled = false;
3953 
3954 	if (!dm_new_crtc_state->stream)
3955 		return;
3956 
3957 	dm_new_crtc_state->active_planes =
3958 		count_crtc_active_planes(new_crtc_state);
3959 
3960 	dm_new_crtc_state->interrupts_enabled =
3961 		dm_new_crtc_state->active_planes > 0;
3962 }
3963 
3964 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
3965 				       struct drm_crtc_state *state)
3966 {
3967 	struct amdgpu_device *adev = crtc->dev->dev_private;
3968 	struct dc *dc = adev->dm.dc;
3969 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
3970 	int ret = -EINVAL;
3971 
3972 	/*
3973 	 * Update interrupt state for the CRTC. This needs to happen whenever
3974 	 * the CRTC has changed or whenever any of its planes have changed.
3975 	 * Atomic check satisfies both of these requirements since the CRTC
3976 	 * is added to the state by DRM during drm_atomic_helper_check_planes.
3977 	 */
3978 	dm_update_crtc_interrupt_state(crtc, state);
3979 
3980 	if (unlikely(!dm_crtc_state->stream &&
3981 		     modeset_required(state, NULL, dm_crtc_state->stream))) {
3982 		WARN_ON(1);
3983 		return ret;
3984 	}
3985 
3986 	/* In some use cases, like reset, no stream is attached */
3987 	if (!dm_crtc_state->stream)
3988 		return 0;
3989 
3990 	/*
3991 	 * We want at least one hardware plane enabled to use
3992 	 * the stream with a cursor enabled.
3993 	 */
3994 	if (state->enable && state->active &&
3995 	    does_crtc_have_active_cursor(state) &&
3996 	    dm_crtc_state->active_planes == 0)
3997 		return -EINVAL;
3998 
3999 	if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
4000 		return 0;
4001 
4002 	return ret;
4003 }
4004 
4005 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
4006 				      const struct drm_display_mode *mode,
4007 				      struct drm_display_mode *adjusted_mode)
4008 {
4009 	return true;
4010 }
4011 
4012 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
4013 	.disable = dm_crtc_helper_disable,
4014 	.atomic_check = dm_crtc_helper_atomic_check,
4015 	.mode_fixup = dm_crtc_helper_mode_fixup
4016 };
4017 
4018 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
4019 {
4020 
4021 }
4022 
4023 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
4024 					  struct drm_crtc_state *crtc_state,
4025 					  struct drm_connector_state *conn_state)
4026 {
4027 	return 0;
4028 }
4029 
4030 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
4031 	.disable = dm_encoder_helper_disable,
4032 	.atomic_check = dm_encoder_helper_atomic_check
4033 };
4034 
4035 static void dm_drm_plane_reset(struct drm_plane *plane)
4036 {
4037 	struct dm_plane_state *amdgpu_state = NULL;
4038 
4039 	if (plane->state)
4040 		plane->funcs->atomic_destroy_state(plane, plane->state);
4041 
4042 	amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
4043 	WARN_ON(amdgpu_state == NULL);
4044 
4045 	if (amdgpu_state)
4046 		__drm_atomic_helper_plane_reset(plane, &amdgpu_state->base);
4047 }
4048 
4049 static struct drm_plane_state *
4050 dm_drm_plane_duplicate_state(struct drm_plane *plane)
4051 {
4052 	struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
4053 
4054 	old_dm_plane_state = to_dm_plane_state(plane->state);
4055 	dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
4056 	if (!dm_plane_state)
4057 		return NULL;
4058 
4059 	__drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
4060 
4061 	if (old_dm_plane_state->dc_state) {
4062 		dm_plane_state->dc_state = old_dm_plane_state->dc_state;
4063 		dc_plane_state_retain(dm_plane_state->dc_state);
4064 	}
4065 
4066 	return &dm_plane_state->base;
4067 }
4068 
4069 void dm_drm_plane_destroy_state(struct drm_plane *plane,
4070 				struct drm_plane_state *state)
4071 {
4072 	struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
4073 
4074 	if (dm_plane_state->dc_state)
4075 		dc_plane_state_release(dm_plane_state->dc_state);
4076 
4077 	drm_atomic_helper_plane_destroy_state(plane, state);
4078 }
4079 
4080 static const struct drm_plane_funcs dm_plane_funcs = {
4081 	.update_plane	= drm_atomic_helper_update_plane,
4082 	.disable_plane	= drm_atomic_helper_disable_plane,
4083 	.destroy	= drm_primary_helper_destroy,
4084 	.reset = dm_drm_plane_reset,
4085 	.atomic_duplicate_state = dm_drm_plane_duplicate_state,
4086 	.atomic_destroy_state = dm_drm_plane_destroy_state,
4087 };
4088 
4089 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
4090 				      struct drm_plane_state *new_state)
4091 {
4092 	struct amdgpu_framebuffer *afb;
4093 	struct drm_gem_object *obj;
4094 	struct amdgpu_device *adev;
4095 	struct amdgpu_bo *rbo;
4096 	struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
4097 	uint64_t tiling_flags;
4098 	uint32_t domain;
4099 	int r;
4100 
4101 	dm_plane_state_old = to_dm_plane_state(plane->state);
4102 	dm_plane_state_new = to_dm_plane_state(new_state);
4103 
4104 	if (!new_state->fb) {
4105 		DRM_DEBUG_DRIVER("No FB bound\n");
4106 		return 0;
4107 	}
4108 
4109 	afb = to_amdgpu_framebuffer(new_state->fb);
4110 	obj = new_state->fb->obj[0];
4111 	rbo = gem_to_amdgpu_bo(obj);
4112 	adev = amdgpu_ttm_adev(rbo->tbo.bdev);
4113 	r = amdgpu_bo_reserve(rbo, false);
4114 	if (unlikely(r != 0))
4115 		return r;
4116 
4117 	if (plane->type != DRM_PLANE_TYPE_CURSOR)
4118 		domain = amdgpu_display_supported_domains(adev);
4119 	else
4120 		domain = AMDGPU_GEM_DOMAIN_VRAM;
4121 
4122 	r = amdgpu_bo_pin(rbo, domain);
4123 	if (unlikely(r != 0)) {
4124 		if (r != -ERESTARTSYS)
4125 			DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
4126 		amdgpu_bo_unreserve(rbo);
4127 		return r;
4128 	}
4129 
4130 	r = amdgpu_ttm_alloc_gart(&rbo->tbo);
4131 	if (unlikely(r != 0)) {
4132 		amdgpu_bo_unpin(rbo);
4133 		amdgpu_bo_unreserve(rbo);
4134 		DRM_ERROR("%p bind failed\n", rbo);
4135 		return r;
4136 	}
4137 
4138 	amdgpu_bo_get_tiling_flags(rbo, &tiling_flags);
4139 
4140 	amdgpu_bo_unreserve(rbo);
4141 
4142 	afb->address = amdgpu_bo_gpu_offset(rbo);
4143 
4144 	amdgpu_bo_ref(rbo);
4145 
4146 	if (dm_plane_state_new->dc_state &&
4147 			dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
4148 		struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
4149 
4150 		fill_plane_buffer_attributes(
4151 			adev, afb, plane_state->format, plane_state->rotation,
4152 			tiling_flags, &plane_state->tiling_info,
4153 			&plane_state->plane_size, &plane_state->dcc,
4154 			&plane_state->address);
4155 	}
4156 
4157 	return 0;
4158 }
4159 
4160 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
4161 				       struct drm_plane_state *old_state)
4162 {
4163 	struct amdgpu_bo *rbo;
4164 	int r;
4165 
4166 	if (!old_state->fb)
4167 		return;
4168 
4169 	rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
4170 	r = amdgpu_bo_reserve(rbo, false);
4171 	if (unlikely(r)) {
4172 		DRM_ERROR("failed to reserve rbo before unpin\n");
4173 		return;
4174 	}
4175 
4176 	amdgpu_bo_unpin(rbo);
4177 	amdgpu_bo_unreserve(rbo);
4178 	amdgpu_bo_unref(&rbo);
4179 }
4180 
4181 static int dm_plane_atomic_check(struct drm_plane *plane,
4182 				 struct drm_plane_state *state)
4183 {
4184 	struct amdgpu_device *adev = plane->dev->dev_private;
4185 	struct dc *dc = adev->dm.dc;
4186 	struct dm_plane_state *dm_plane_state;
4187 	struct dc_scaling_info scaling_info;
4188 	int ret;
4189 
4190 	dm_plane_state = to_dm_plane_state(state);
4191 
4192 	if (!dm_plane_state->dc_state)
4193 		return 0;
4194 
4195 	ret = fill_dc_scaling_info(state, &scaling_info);
4196 	if (ret)
4197 		return ret;
4198 
4199 	if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
4200 		return 0;
4201 
4202 	return -EINVAL;
4203 }
4204 
4205 static int dm_plane_atomic_async_check(struct drm_plane *plane,
4206 				       struct drm_plane_state *new_plane_state)
4207 {
4208 	struct drm_plane_state *old_plane_state =
4209 		drm_atomic_get_old_plane_state(new_plane_state->state, plane);
4210 
4211 	/* Only support async updates on cursor planes. */
4212 	if (plane->type != DRM_PLANE_TYPE_CURSOR)
4213 		return -EINVAL;
4214 
4215 	/*
4216 	 * DRM calls prepare_fb and cleanup_fb on new_plane_state for
4217 	 * async commits so don't allow fb changes.
4218 	 */
4219 	if (old_plane_state->fb != new_plane_state->fb)
4220 		return -EINVAL;
4221 
4222 	return 0;
4223 }
4224 
4225 static void dm_plane_atomic_async_update(struct drm_plane *plane,
4226 					 struct drm_plane_state *new_state)
4227 {
4228 	struct drm_plane_state *old_state =
4229 		drm_atomic_get_old_plane_state(new_state->state, plane);
4230 
4231 	if (plane->state->fb != new_state->fb)
4232 		drm_atomic_set_fb_for_plane(plane->state, new_state->fb);
4233 
4234 	plane->state->src_x = new_state->src_x;
4235 	plane->state->src_y = new_state->src_y;
4236 	plane->state->src_w = new_state->src_w;
4237 	plane->state->src_h = new_state->src_h;
4238 	plane->state->crtc_x = new_state->crtc_x;
4239 	plane->state->crtc_y = new_state->crtc_y;
4240 	plane->state->crtc_w = new_state->crtc_w;
4241 	plane->state->crtc_h = new_state->crtc_h;
4242 
4243 	handle_cursor_update(plane, old_state);
4244 }
4245 
4246 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
4247 	.prepare_fb = dm_plane_helper_prepare_fb,
4248 	.cleanup_fb = dm_plane_helper_cleanup_fb,
4249 	.atomic_check = dm_plane_atomic_check,
4250 	.atomic_async_check = dm_plane_atomic_async_check,
4251 	.atomic_async_update = dm_plane_atomic_async_update
4252 };
4253 
4254 /*
4255  * TODO: these are currently initialized to rgb formats only.
4256  * For future use cases we should either initialize them dynamically based on
4257  * plane capabilities, or initialize this array to all formats, so internal drm
4258  * check will succeed, and let DC implement proper check
4259  */
4260 static const uint32_t rgb_formats[] = {
4261 	DRM_FORMAT_XRGB8888,
4262 	DRM_FORMAT_ARGB8888,
4263 	DRM_FORMAT_RGBA8888,
4264 	DRM_FORMAT_XRGB2101010,
4265 	DRM_FORMAT_XBGR2101010,
4266 	DRM_FORMAT_ARGB2101010,
4267 	DRM_FORMAT_ABGR2101010,
4268 	DRM_FORMAT_XBGR8888,
4269 	DRM_FORMAT_ABGR8888,
4270 	DRM_FORMAT_RGB565,
4271 };
4272 
4273 static const uint32_t overlay_formats[] = {
4274 	DRM_FORMAT_XRGB8888,
4275 	DRM_FORMAT_ARGB8888,
4276 	DRM_FORMAT_RGBA8888,
4277 	DRM_FORMAT_XBGR8888,
4278 	DRM_FORMAT_ABGR8888,
4279 	DRM_FORMAT_RGB565
4280 };
4281 
4282 static const u32 cursor_formats[] = {
4283 	DRM_FORMAT_ARGB8888
4284 };
4285 
4286 static int get_plane_formats(const struct drm_plane *plane,
4287 			     const struct dc_plane_cap *plane_cap,
4288 			     uint32_t *formats, int max_formats)
4289 {
4290 	int i, num_formats = 0;
4291 
4292 	/*
4293 	 * TODO: Query support for each group of formats directly from
4294 	 * DC plane caps. This will require adding more formats to the
4295 	 * caps list.
4296 	 */
4297 
4298 	switch (plane->type) {
4299 	case DRM_PLANE_TYPE_PRIMARY:
4300 		for (i = 0; i < ARRAY_SIZE(rgb_formats); ++i) {
4301 			if (num_formats >= max_formats)
4302 				break;
4303 
4304 			formats[num_formats++] = rgb_formats[i];
4305 		}
4306 
4307 		if (plane_cap && plane_cap->pixel_format_support.nv12)
4308 			formats[num_formats++] = DRM_FORMAT_NV12;
4309 		break;
4310 
4311 	case DRM_PLANE_TYPE_OVERLAY:
4312 		for (i = 0; i < ARRAY_SIZE(overlay_formats); ++i) {
4313 			if (num_formats >= max_formats)
4314 				break;
4315 
4316 			formats[num_formats++] = overlay_formats[i];
4317 		}
4318 		break;
4319 
4320 	case DRM_PLANE_TYPE_CURSOR:
4321 		for (i = 0; i < ARRAY_SIZE(cursor_formats); ++i) {
4322 			if (num_formats >= max_formats)
4323 				break;
4324 
4325 			formats[num_formats++] = cursor_formats[i];
4326 		}
4327 		break;
4328 	}
4329 
4330 	return num_formats;
4331 }
4332 
4333 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
4334 				struct drm_plane *plane,
4335 				unsigned long possible_crtcs,
4336 				const struct dc_plane_cap *plane_cap)
4337 {
4338 	uint32_t formats[32];
4339 	int num_formats;
4340 	int res = -EPERM;
4341 
4342 	num_formats = get_plane_formats(plane, plane_cap, formats,
4343 					ARRAY_SIZE(formats));
4344 
4345 	res = drm_universal_plane_init(dm->adev->ddev, plane, possible_crtcs,
4346 				       &dm_plane_funcs, formats, num_formats,
4347 				       NULL, plane->type, NULL);
4348 	if (res)
4349 		return res;
4350 
4351 	if (plane->type == DRM_PLANE_TYPE_OVERLAY &&
4352 	    plane_cap && plane_cap->per_pixel_alpha) {
4353 		unsigned int blend_caps = BIT(DRM_MODE_BLEND_PIXEL_NONE) |
4354 					  BIT(DRM_MODE_BLEND_PREMULTI);
4355 
4356 		drm_plane_create_alpha_property(plane);
4357 		drm_plane_create_blend_mode_property(plane, blend_caps);
4358 	}
4359 
4360 	if (plane->type == DRM_PLANE_TYPE_PRIMARY &&
4361 	    plane_cap && plane_cap->pixel_format_support.nv12) {
4362 		/* This only affects YUV formats. */
4363 		drm_plane_create_color_properties(
4364 			plane,
4365 			BIT(DRM_COLOR_YCBCR_BT601) |
4366 			BIT(DRM_COLOR_YCBCR_BT709),
4367 			BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
4368 			BIT(DRM_COLOR_YCBCR_FULL_RANGE),
4369 			DRM_COLOR_YCBCR_BT709, DRM_COLOR_YCBCR_LIMITED_RANGE);
4370 	}
4371 
4372 	drm_plane_helper_add(plane, &dm_plane_helper_funcs);
4373 
4374 	/* Create (reset) the plane state */
4375 	if (plane->funcs->reset)
4376 		plane->funcs->reset(plane);
4377 
4378 	return 0;
4379 }
4380 
4381 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
4382 			       struct drm_plane *plane,
4383 			       uint32_t crtc_index)
4384 {
4385 	struct amdgpu_crtc *acrtc = NULL;
4386 	struct drm_plane *cursor_plane;
4387 
4388 	int res = -ENOMEM;
4389 
4390 	cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
4391 	if (!cursor_plane)
4392 		goto fail;
4393 
4394 	cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
4395 	res = amdgpu_dm_plane_init(dm, cursor_plane, 0, NULL);
4396 
4397 	acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
4398 	if (!acrtc)
4399 		goto fail;
4400 
4401 	res = drm_crtc_init_with_planes(
4402 			dm->ddev,
4403 			&acrtc->base,
4404 			plane,
4405 			cursor_plane,
4406 			&amdgpu_dm_crtc_funcs, NULL);
4407 
4408 	if (res)
4409 		goto fail;
4410 
4411 	drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
4412 
4413 	/* Create (reset) the plane state */
4414 	if (acrtc->base.funcs->reset)
4415 		acrtc->base.funcs->reset(&acrtc->base);
4416 
4417 	acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
4418 	acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
4419 
4420 	acrtc->crtc_id = crtc_index;
4421 	acrtc->base.enabled = false;
4422 	acrtc->otg_inst = -1;
4423 
4424 	dm->adev->mode_info.crtcs[crtc_index] = acrtc;
4425 	drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
4426 				   true, MAX_COLOR_LUT_ENTRIES);
4427 	drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
4428 
4429 	return 0;
4430 
4431 fail:
4432 	kfree(acrtc);
4433 	kfree(cursor_plane);
4434 	return res;
4435 }
4436 
4437 
4438 static int to_drm_connector_type(enum signal_type st)
4439 {
4440 	switch (st) {
4441 	case SIGNAL_TYPE_HDMI_TYPE_A:
4442 		return DRM_MODE_CONNECTOR_HDMIA;
4443 	case SIGNAL_TYPE_EDP:
4444 		return DRM_MODE_CONNECTOR_eDP;
4445 	case SIGNAL_TYPE_LVDS:
4446 		return DRM_MODE_CONNECTOR_LVDS;
4447 	case SIGNAL_TYPE_RGB:
4448 		return DRM_MODE_CONNECTOR_VGA;
4449 	case SIGNAL_TYPE_DISPLAY_PORT:
4450 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
4451 		return DRM_MODE_CONNECTOR_DisplayPort;
4452 	case SIGNAL_TYPE_DVI_DUAL_LINK:
4453 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
4454 		return DRM_MODE_CONNECTOR_DVID;
4455 	case SIGNAL_TYPE_VIRTUAL:
4456 		return DRM_MODE_CONNECTOR_VIRTUAL;
4457 
4458 	default:
4459 		return DRM_MODE_CONNECTOR_Unknown;
4460 	}
4461 }
4462 
4463 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
4464 {
4465 	return drm_encoder_find(connector->dev, NULL, connector->encoder_ids[0]);
4466 }
4467 
4468 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
4469 {
4470 	struct drm_encoder *encoder;
4471 	struct amdgpu_encoder *amdgpu_encoder;
4472 
4473 	encoder = amdgpu_dm_connector_to_encoder(connector);
4474 
4475 	if (encoder == NULL)
4476 		return;
4477 
4478 	amdgpu_encoder = to_amdgpu_encoder(encoder);
4479 
4480 	amdgpu_encoder->native_mode.clock = 0;
4481 
4482 	if (!list_empty(&connector->probed_modes)) {
4483 		struct drm_display_mode *preferred_mode = NULL;
4484 
4485 		list_for_each_entry(preferred_mode,
4486 				    &connector->probed_modes,
4487 				    head) {
4488 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
4489 				amdgpu_encoder->native_mode = *preferred_mode;
4490 
4491 			break;
4492 		}
4493 
4494 	}
4495 }
4496 
4497 static struct drm_display_mode *
4498 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
4499 			     char *name,
4500 			     int hdisplay, int vdisplay)
4501 {
4502 	struct drm_device *dev = encoder->dev;
4503 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4504 	struct drm_display_mode *mode = NULL;
4505 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4506 
4507 	mode = drm_mode_duplicate(dev, native_mode);
4508 
4509 	if (mode == NULL)
4510 		return NULL;
4511 
4512 	mode->hdisplay = hdisplay;
4513 	mode->vdisplay = vdisplay;
4514 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
4515 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
4516 
4517 	return mode;
4518 
4519 }
4520 
4521 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
4522 						 struct drm_connector *connector)
4523 {
4524 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4525 	struct drm_display_mode *mode = NULL;
4526 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4527 	struct amdgpu_dm_connector *amdgpu_dm_connector =
4528 				to_amdgpu_dm_connector(connector);
4529 	int i;
4530 	int n;
4531 	struct mode_size {
4532 		char name[DRM_DISPLAY_MODE_LEN];
4533 		int w;
4534 		int h;
4535 	} common_modes[] = {
4536 		{  "640x480",  640,  480},
4537 		{  "800x600",  800,  600},
4538 		{ "1024x768", 1024,  768},
4539 		{ "1280x720", 1280,  720},
4540 		{ "1280x800", 1280,  800},
4541 		{"1280x1024", 1280, 1024},
4542 		{ "1440x900", 1440,  900},
4543 		{"1680x1050", 1680, 1050},
4544 		{"1600x1200", 1600, 1200},
4545 		{"1920x1080", 1920, 1080},
4546 		{"1920x1200", 1920, 1200}
4547 	};
4548 
4549 	n = ARRAY_SIZE(common_modes);
4550 
4551 	for (i = 0; i < n; i++) {
4552 		struct drm_display_mode *curmode = NULL;
4553 		bool mode_existed = false;
4554 
4555 		if (common_modes[i].w > native_mode->hdisplay ||
4556 		    common_modes[i].h > native_mode->vdisplay ||
4557 		   (common_modes[i].w == native_mode->hdisplay &&
4558 		    common_modes[i].h == native_mode->vdisplay))
4559 			continue;
4560 
4561 		list_for_each_entry(curmode, &connector->probed_modes, head) {
4562 			if (common_modes[i].w == curmode->hdisplay &&
4563 			    common_modes[i].h == curmode->vdisplay) {
4564 				mode_existed = true;
4565 				break;
4566 			}
4567 		}
4568 
4569 		if (mode_existed)
4570 			continue;
4571 
4572 		mode = amdgpu_dm_create_common_mode(encoder,
4573 				common_modes[i].name, common_modes[i].w,
4574 				common_modes[i].h);
4575 		drm_mode_probed_add(connector, mode);
4576 		amdgpu_dm_connector->num_modes++;
4577 	}
4578 }
4579 
4580 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
4581 					      struct edid *edid)
4582 {
4583 	struct amdgpu_dm_connector *amdgpu_dm_connector =
4584 			to_amdgpu_dm_connector(connector);
4585 
4586 	if (edid) {
4587 		/* empty probed_modes */
4588 		INIT_LIST_HEAD(&connector->probed_modes);
4589 		amdgpu_dm_connector->num_modes =
4590 				drm_add_edid_modes(connector, edid);
4591 
4592 		/* sorting the probed modes before calling function
4593 		 * amdgpu_dm_get_native_mode() since EDID can have
4594 		 * more than one preferred mode. The modes that are
4595 		 * later in the probed mode list could be of higher
4596 		 * and preferred resolution. For example, 3840x2160
4597 		 * resolution in base EDID preferred timing and 4096x2160
4598 		 * preferred resolution in DID extension block later.
4599 		 */
4600 		drm_mode_sort(&connector->probed_modes);
4601 		amdgpu_dm_get_native_mode(connector);
4602 	} else {
4603 		amdgpu_dm_connector->num_modes = 0;
4604 	}
4605 }
4606 
4607 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
4608 {
4609 	struct amdgpu_dm_connector *amdgpu_dm_connector =
4610 			to_amdgpu_dm_connector(connector);
4611 	struct drm_encoder *encoder;
4612 	struct edid *edid = amdgpu_dm_connector->edid;
4613 
4614 	encoder = amdgpu_dm_connector_to_encoder(connector);
4615 
4616 	if (!edid || !drm_edid_is_valid(edid)) {
4617 		amdgpu_dm_connector->num_modes =
4618 				drm_add_modes_noedid(connector, 640, 480);
4619 	} else {
4620 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
4621 		amdgpu_dm_connector_add_common_modes(encoder, connector);
4622 	}
4623 	amdgpu_dm_fbc_init(connector);
4624 
4625 	return amdgpu_dm_connector->num_modes;
4626 }
4627 
4628 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
4629 				     struct amdgpu_dm_connector *aconnector,
4630 				     int connector_type,
4631 				     struct dc_link *link,
4632 				     int link_index)
4633 {
4634 	struct amdgpu_device *adev = dm->ddev->dev_private;
4635 
4636 	aconnector->connector_id = link_index;
4637 	aconnector->dc_link = link;
4638 	aconnector->base.interlace_allowed = false;
4639 	aconnector->base.doublescan_allowed = false;
4640 	aconnector->base.stereo_allowed = false;
4641 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
4642 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
4643 	mutex_init(&aconnector->hpd_lock);
4644 
4645 	/*
4646 	 * configure support HPD hot plug connector_>polled default value is 0
4647 	 * which means HPD hot plug not supported
4648 	 */
4649 	switch (connector_type) {
4650 	case DRM_MODE_CONNECTOR_HDMIA:
4651 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4652 		aconnector->base.ycbcr_420_allowed =
4653 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
4654 		break;
4655 	case DRM_MODE_CONNECTOR_DisplayPort:
4656 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4657 		aconnector->base.ycbcr_420_allowed =
4658 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
4659 		break;
4660 	case DRM_MODE_CONNECTOR_DVID:
4661 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4662 		break;
4663 	default:
4664 		break;
4665 	}
4666 
4667 	drm_object_attach_property(&aconnector->base.base,
4668 				dm->ddev->mode_config.scaling_mode_property,
4669 				DRM_MODE_SCALE_NONE);
4670 
4671 	drm_object_attach_property(&aconnector->base.base,
4672 				adev->mode_info.underscan_property,
4673 				UNDERSCAN_OFF);
4674 	drm_object_attach_property(&aconnector->base.base,
4675 				adev->mode_info.underscan_hborder_property,
4676 				0);
4677 	drm_object_attach_property(&aconnector->base.base,
4678 				adev->mode_info.underscan_vborder_property,
4679 				0);
4680 
4681 	drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
4682 
4683 	/* This defaults to the max in the range, but we want 8bpc. */
4684 	aconnector->base.state->max_bpc = 8;
4685 	aconnector->base.state->max_requested_bpc = 8;
4686 
4687 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
4688 	    dc_is_dmcu_initialized(adev->dm.dc)) {
4689 		drm_object_attach_property(&aconnector->base.base,
4690 				adev->mode_info.abm_level_property, 0);
4691 	}
4692 
4693 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
4694 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
4695 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
4696 		drm_connector_attach_vrr_capable_property(
4697 			&aconnector->base);
4698 	}
4699 }
4700 
4701 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
4702 			      struct i2c_msg *msgs, int num)
4703 {
4704 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
4705 	struct ddc_service *ddc_service = i2c->ddc_service;
4706 	struct i2c_command cmd;
4707 	int i;
4708 	int result = -EIO;
4709 
4710 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
4711 
4712 	if (!cmd.payloads)
4713 		return result;
4714 
4715 	cmd.number_of_payloads = num;
4716 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
4717 	cmd.speed = 100;
4718 
4719 	for (i = 0; i < num; i++) {
4720 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
4721 		cmd.payloads[i].address = msgs[i].addr;
4722 		cmd.payloads[i].length = msgs[i].len;
4723 		cmd.payloads[i].data = msgs[i].buf;
4724 	}
4725 
4726 	if (dc_submit_i2c(
4727 			ddc_service->ctx->dc,
4728 			ddc_service->ddc_pin->hw_info.ddc_channel,
4729 			&cmd))
4730 		result = num;
4731 
4732 	kfree(cmd.payloads);
4733 	return result;
4734 }
4735 
4736 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
4737 {
4738 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
4739 }
4740 
4741 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
4742 	.master_xfer = amdgpu_dm_i2c_xfer,
4743 	.functionality = amdgpu_dm_i2c_func,
4744 };
4745 
4746 static struct amdgpu_i2c_adapter *
4747 create_i2c(struct ddc_service *ddc_service,
4748 	   int link_index,
4749 	   int *res)
4750 {
4751 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
4752 	struct amdgpu_i2c_adapter *i2c;
4753 
4754 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
4755 	if (!i2c)
4756 		return NULL;
4757 	i2c->base.owner = THIS_MODULE;
4758 	i2c->base.class = I2C_CLASS_DDC;
4759 	i2c->base.dev.parent = &adev->pdev->dev;
4760 	i2c->base.algo = &amdgpu_dm_i2c_algo;
4761 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
4762 	i2c_set_adapdata(&i2c->base, i2c);
4763 	i2c->ddc_service = ddc_service;
4764 	i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
4765 
4766 	return i2c;
4767 }
4768 
4769 
4770 /*
4771  * Note: this function assumes that dc_link_detect() was called for the
4772  * dc_link which will be represented by this aconnector.
4773  */
4774 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
4775 				    struct amdgpu_dm_connector *aconnector,
4776 				    uint32_t link_index,
4777 				    struct amdgpu_encoder *aencoder)
4778 {
4779 	int res = 0;
4780 	int connector_type;
4781 	struct dc *dc = dm->dc;
4782 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
4783 	struct amdgpu_i2c_adapter *i2c;
4784 
4785 	link->priv = aconnector;
4786 
4787 	DRM_DEBUG_DRIVER("%s()\n", __func__);
4788 
4789 	i2c = create_i2c(link->ddc, link->link_index, &res);
4790 	if (!i2c) {
4791 		DRM_ERROR("Failed to create i2c adapter data\n");
4792 		return -ENOMEM;
4793 	}
4794 
4795 	aconnector->i2c = i2c;
4796 	res = i2c_add_adapter(&i2c->base);
4797 
4798 	if (res) {
4799 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
4800 		goto out_free;
4801 	}
4802 
4803 	connector_type = to_drm_connector_type(link->connector_signal);
4804 
4805 	res = drm_connector_init(
4806 			dm->ddev,
4807 			&aconnector->base,
4808 			&amdgpu_dm_connector_funcs,
4809 			connector_type);
4810 
4811 	if (res) {
4812 		DRM_ERROR("connector_init failed\n");
4813 		aconnector->connector_id = -1;
4814 		goto out_free;
4815 	}
4816 
4817 	drm_connector_helper_add(
4818 			&aconnector->base,
4819 			&amdgpu_dm_connector_helper_funcs);
4820 
4821 	if (aconnector->base.funcs->reset)
4822 		aconnector->base.funcs->reset(&aconnector->base);
4823 
4824 	amdgpu_dm_connector_init_helper(
4825 		dm,
4826 		aconnector,
4827 		connector_type,
4828 		link,
4829 		link_index);
4830 
4831 	drm_connector_attach_encoder(
4832 		&aconnector->base, &aencoder->base);
4833 
4834 	drm_connector_register(&aconnector->base);
4835 #if defined(CONFIG_DEBUG_FS)
4836 	res = connector_debugfs_init(aconnector);
4837 	if (res) {
4838 		DRM_ERROR("Failed to create debugfs for connector");
4839 		goto out_free;
4840 	}
4841 	aconnector->debugfs_dpcd_address = 0;
4842 	aconnector->debugfs_dpcd_size = 0;
4843 #endif
4844 
4845 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
4846 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
4847 		amdgpu_dm_initialize_dp_connector(dm, aconnector);
4848 
4849 out_free:
4850 	if (res) {
4851 		kfree(i2c);
4852 		aconnector->i2c = NULL;
4853 	}
4854 	return res;
4855 }
4856 
4857 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
4858 {
4859 	switch (adev->mode_info.num_crtc) {
4860 	case 1:
4861 		return 0x1;
4862 	case 2:
4863 		return 0x3;
4864 	case 3:
4865 		return 0x7;
4866 	case 4:
4867 		return 0xf;
4868 	case 5:
4869 		return 0x1f;
4870 	case 6:
4871 	default:
4872 		return 0x3f;
4873 	}
4874 }
4875 
4876 static int amdgpu_dm_encoder_init(struct drm_device *dev,
4877 				  struct amdgpu_encoder *aencoder,
4878 				  uint32_t link_index)
4879 {
4880 	struct amdgpu_device *adev = dev->dev_private;
4881 
4882 	int res = drm_encoder_init(dev,
4883 				   &aencoder->base,
4884 				   &amdgpu_dm_encoder_funcs,
4885 				   DRM_MODE_ENCODER_TMDS,
4886 				   NULL);
4887 
4888 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
4889 
4890 	if (!res)
4891 		aencoder->encoder_id = link_index;
4892 	else
4893 		aencoder->encoder_id = -1;
4894 
4895 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
4896 
4897 	return res;
4898 }
4899 
4900 static void manage_dm_interrupts(struct amdgpu_device *adev,
4901 				 struct amdgpu_crtc *acrtc,
4902 				 bool enable)
4903 {
4904 	/*
4905 	 * this is not correct translation but will work as soon as VBLANK
4906 	 * constant is the same as PFLIP
4907 	 */
4908 	int irq_type =
4909 		amdgpu_display_crtc_idx_to_irq_type(
4910 			adev,
4911 			acrtc->crtc_id);
4912 
4913 	if (enable) {
4914 		drm_crtc_vblank_on(&acrtc->base);
4915 		amdgpu_irq_get(
4916 			adev,
4917 			&adev->pageflip_irq,
4918 			irq_type);
4919 	} else {
4920 
4921 		amdgpu_irq_put(
4922 			adev,
4923 			&adev->pageflip_irq,
4924 			irq_type);
4925 		drm_crtc_vblank_off(&acrtc->base);
4926 	}
4927 }
4928 
4929 static bool
4930 is_scaling_state_different(const struct dm_connector_state *dm_state,
4931 			   const struct dm_connector_state *old_dm_state)
4932 {
4933 	if (dm_state->scaling != old_dm_state->scaling)
4934 		return true;
4935 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
4936 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
4937 			return true;
4938 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
4939 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
4940 			return true;
4941 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
4942 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
4943 		return true;
4944 	return false;
4945 }
4946 
4947 static void remove_stream(struct amdgpu_device *adev,
4948 			  struct amdgpu_crtc *acrtc,
4949 			  struct dc_stream_state *stream)
4950 {
4951 	/* this is the update mode case */
4952 
4953 	acrtc->otg_inst = -1;
4954 	acrtc->enabled = false;
4955 }
4956 
4957 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
4958 			       struct dc_cursor_position *position)
4959 {
4960 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
4961 	int x, y;
4962 	int xorigin = 0, yorigin = 0;
4963 
4964 	position->enable = false;
4965 	position->x = 0;
4966 	position->y = 0;
4967 
4968 	if (!crtc || !plane->state->fb)
4969 		return 0;
4970 
4971 	if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
4972 	    (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
4973 		DRM_ERROR("%s: bad cursor width or height %d x %d\n",
4974 			  __func__,
4975 			  plane->state->crtc_w,
4976 			  plane->state->crtc_h);
4977 		return -EINVAL;
4978 	}
4979 
4980 	x = plane->state->crtc_x;
4981 	y = plane->state->crtc_y;
4982 
4983 	if (x <= -amdgpu_crtc->max_cursor_width ||
4984 	    y <= -amdgpu_crtc->max_cursor_height)
4985 		return 0;
4986 
4987 	if (crtc->primary->state) {
4988 		/* avivo cursor are offset into the total surface */
4989 		x += crtc->primary->state->src_x >> 16;
4990 		y += crtc->primary->state->src_y >> 16;
4991 	}
4992 
4993 	if (x < 0) {
4994 		xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
4995 		x = 0;
4996 	}
4997 	if (y < 0) {
4998 		yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
4999 		y = 0;
5000 	}
5001 	position->enable = true;
5002 	position->x = x;
5003 	position->y = y;
5004 	position->x_hotspot = xorigin;
5005 	position->y_hotspot = yorigin;
5006 
5007 	return 0;
5008 }
5009 
5010 static void handle_cursor_update(struct drm_plane *plane,
5011 				 struct drm_plane_state *old_plane_state)
5012 {
5013 	struct amdgpu_device *adev = plane->dev->dev_private;
5014 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
5015 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
5016 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
5017 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5018 	uint64_t address = afb ? afb->address : 0;
5019 	struct dc_cursor_position position;
5020 	struct dc_cursor_attributes attributes;
5021 	int ret;
5022 
5023 	if (!plane->state->fb && !old_plane_state->fb)
5024 		return;
5025 
5026 	DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
5027 			 __func__,
5028 			 amdgpu_crtc->crtc_id,
5029 			 plane->state->crtc_w,
5030 			 plane->state->crtc_h);
5031 
5032 	ret = get_cursor_position(plane, crtc, &position);
5033 	if (ret)
5034 		return;
5035 
5036 	if (!position.enable) {
5037 		/* turn off cursor */
5038 		if (crtc_state && crtc_state->stream) {
5039 			mutex_lock(&adev->dm.dc_lock);
5040 			dc_stream_set_cursor_position(crtc_state->stream,
5041 						      &position);
5042 			mutex_unlock(&adev->dm.dc_lock);
5043 		}
5044 		return;
5045 	}
5046 
5047 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
5048 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
5049 
5050 	memset(&attributes, 0, sizeof(attributes));
5051 	attributes.address.high_part = upper_32_bits(address);
5052 	attributes.address.low_part  = lower_32_bits(address);
5053 	attributes.width             = plane->state->crtc_w;
5054 	attributes.height            = plane->state->crtc_h;
5055 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
5056 	attributes.rotation_angle    = 0;
5057 	attributes.attribute_flags.value = 0;
5058 
5059 	attributes.pitch = attributes.width;
5060 
5061 	if (crtc_state->stream) {
5062 		mutex_lock(&adev->dm.dc_lock);
5063 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
5064 							 &attributes))
5065 			DRM_ERROR("DC failed to set cursor attributes\n");
5066 
5067 		if (!dc_stream_set_cursor_position(crtc_state->stream,
5068 						   &position))
5069 			DRM_ERROR("DC failed to set cursor position\n");
5070 		mutex_unlock(&adev->dm.dc_lock);
5071 	}
5072 }
5073 
5074 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
5075 {
5076 
5077 	assert_spin_locked(&acrtc->base.dev->event_lock);
5078 	WARN_ON(acrtc->event);
5079 
5080 	acrtc->event = acrtc->base.state->event;
5081 
5082 	/* Set the flip status */
5083 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
5084 
5085 	/* Mark this event as consumed */
5086 	acrtc->base.state->event = NULL;
5087 
5088 	DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
5089 						 acrtc->crtc_id);
5090 }
5091 
5092 static void update_freesync_state_on_stream(
5093 	struct amdgpu_display_manager *dm,
5094 	struct dm_crtc_state *new_crtc_state,
5095 	struct dc_stream_state *new_stream,
5096 	struct dc_plane_state *surface,
5097 	u32 flip_timestamp_in_us)
5098 {
5099 	struct mod_vrr_params vrr_params;
5100 	struct dc_info_packet vrr_infopacket = {0};
5101 	struct amdgpu_device *adev = dm->adev;
5102 	unsigned long flags;
5103 
5104 	if (!new_stream)
5105 		return;
5106 
5107 	/*
5108 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
5109 	 * For now it's sufficient to just guard against these conditions.
5110 	 */
5111 
5112 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5113 		return;
5114 
5115 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
5116 	vrr_params = new_crtc_state->vrr_params;
5117 
5118 	if (surface) {
5119 		mod_freesync_handle_preflip(
5120 			dm->freesync_module,
5121 			surface,
5122 			new_stream,
5123 			flip_timestamp_in_us,
5124 			&vrr_params);
5125 
5126 		if (adev->family < AMDGPU_FAMILY_AI &&
5127 		    amdgpu_dm_vrr_active(new_crtc_state)) {
5128 			mod_freesync_handle_v_update(dm->freesync_module,
5129 						     new_stream, &vrr_params);
5130 
5131 			/* Need to call this before the frame ends. */
5132 			dc_stream_adjust_vmin_vmax(dm->dc,
5133 						   new_crtc_state->stream,
5134 						   &vrr_params.adjust);
5135 		}
5136 	}
5137 
5138 	mod_freesync_build_vrr_infopacket(
5139 		dm->freesync_module,
5140 		new_stream,
5141 		&vrr_params,
5142 		PACKET_TYPE_VRR,
5143 		TRANSFER_FUNC_UNKNOWN,
5144 		&vrr_infopacket);
5145 
5146 	new_crtc_state->freesync_timing_changed |=
5147 		(memcmp(&new_crtc_state->vrr_params.adjust,
5148 			&vrr_params.adjust,
5149 			sizeof(vrr_params.adjust)) != 0);
5150 
5151 	new_crtc_state->freesync_vrr_info_changed |=
5152 		(memcmp(&new_crtc_state->vrr_infopacket,
5153 			&vrr_infopacket,
5154 			sizeof(vrr_infopacket)) != 0);
5155 
5156 	new_crtc_state->vrr_params = vrr_params;
5157 	new_crtc_state->vrr_infopacket = vrr_infopacket;
5158 
5159 	new_stream->adjust = new_crtc_state->vrr_params.adjust;
5160 	new_stream->vrr_infopacket = vrr_infopacket;
5161 
5162 	if (new_crtc_state->freesync_vrr_info_changed)
5163 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
5164 			      new_crtc_state->base.crtc->base.id,
5165 			      (int)new_crtc_state->base.vrr_enabled,
5166 			      (int)vrr_params.state);
5167 
5168 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5169 }
5170 
5171 static void pre_update_freesync_state_on_stream(
5172 	struct amdgpu_display_manager *dm,
5173 	struct dm_crtc_state *new_crtc_state)
5174 {
5175 	struct dc_stream_state *new_stream = new_crtc_state->stream;
5176 	struct mod_vrr_params vrr_params;
5177 	struct mod_freesync_config config = new_crtc_state->freesync_config;
5178 	struct amdgpu_device *adev = dm->adev;
5179 	unsigned long flags;
5180 
5181 	if (!new_stream)
5182 		return;
5183 
5184 	/*
5185 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
5186 	 * For now it's sufficient to just guard against these conditions.
5187 	 */
5188 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5189 		return;
5190 
5191 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
5192 	vrr_params = new_crtc_state->vrr_params;
5193 
5194 	if (new_crtc_state->vrr_supported &&
5195 	    config.min_refresh_in_uhz &&
5196 	    config.max_refresh_in_uhz) {
5197 		config.state = new_crtc_state->base.vrr_enabled ?
5198 			VRR_STATE_ACTIVE_VARIABLE :
5199 			VRR_STATE_INACTIVE;
5200 	} else {
5201 		config.state = VRR_STATE_UNSUPPORTED;
5202 	}
5203 
5204 	mod_freesync_build_vrr_params(dm->freesync_module,
5205 				      new_stream,
5206 				      &config, &vrr_params);
5207 
5208 	new_crtc_state->freesync_timing_changed |=
5209 		(memcmp(&new_crtc_state->vrr_params.adjust,
5210 			&vrr_params.adjust,
5211 			sizeof(vrr_params.adjust)) != 0);
5212 
5213 	new_crtc_state->vrr_params = vrr_params;
5214 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5215 }
5216 
5217 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
5218 					    struct dm_crtc_state *new_state)
5219 {
5220 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
5221 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
5222 
5223 	if (!old_vrr_active && new_vrr_active) {
5224 		/* Transition VRR inactive -> active:
5225 		 * While VRR is active, we must not disable vblank irq, as a
5226 		 * reenable after disable would compute bogus vblank/pflip
5227 		 * timestamps if it likely happened inside display front-porch.
5228 		 *
5229 		 * We also need vupdate irq for the actual core vblank handling
5230 		 * at end of vblank.
5231 		 */
5232 		dm_set_vupdate_irq(new_state->base.crtc, true);
5233 		drm_crtc_vblank_get(new_state->base.crtc);
5234 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
5235 				 __func__, new_state->base.crtc->base.id);
5236 	} else if (old_vrr_active && !new_vrr_active) {
5237 		/* Transition VRR active -> inactive:
5238 		 * Allow vblank irq disable again for fixed refresh rate.
5239 		 */
5240 		dm_set_vupdate_irq(new_state->base.crtc, false);
5241 		drm_crtc_vblank_put(new_state->base.crtc);
5242 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
5243 				 __func__, new_state->base.crtc->base.id);
5244 	}
5245 }
5246 
5247 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
5248 {
5249 	struct drm_plane *plane;
5250 	struct drm_plane_state *old_plane_state, *new_plane_state;
5251 	int i;
5252 
5253 	/*
5254 	 * TODO: Make this per-stream so we don't issue redundant updates for
5255 	 * commits with multiple streams.
5256 	 */
5257 	for_each_oldnew_plane_in_state(state, plane, old_plane_state,
5258 				       new_plane_state, i)
5259 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
5260 			handle_cursor_update(plane, old_plane_state);
5261 }
5262 
5263 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
5264 				    struct dc_state *dc_state,
5265 				    struct drm_device *dev,
5266 				    struct amdgpu_display_manager *dm,
5267 				    struct drm_crtc *pcrtc,
5268 				    bool wait_for_vblank)
5269 {
5270 	uint32_t i;
5271 	uint64_t timestamp_ns;
5272 	struct drm_plane *plane;
5273 	struct drm_plane_state *old_plane_state, *new_plane_state;
5274 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
5275 	struct drm_crtc_state *new_pcrtc_state =
5276 			drm_atomic_get_new_crtc_state(state, pcrtc);
5277 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
5278 	struct dm_crtc_state *dm_old_crtc_state =
5279 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
5280 	int planes_count = 0, vpos, hpos;
5281 	long r;
5282 	unsigned long flags;
5283 	struct amdgpu_bo *abo;
5284 	uint64_t tiling_flags;
5285 	uint32_t target_vblank, last_flip_vblank;
5286 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
5287 	bool pflip_present = false;
5288 	struct {
5289 		struct dc_surface_update surface_updates[MAX_SURFACES];
5290 		struct dc_plane_info plane_infos[MAX_SURFACES];
5291 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
5292 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
5293 		struct dc_stream_update stream_update;
5294 	} *bundle;
5295 
5296 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
5297 
5298 	if (!bundle) {
5299 		dm_error("Failed to allocate update bundle\n");
5300 		goto cleanup;
5301 	}
5302 
5303 	/*
5304 	 * Disable the cursor first if we're disabling all the planes.
5305 	 * It'll remain on the screen after the planes are re-enabled
5306 	 * if we don't.
5307 	 */
5308 	if (acrtc_state->active_planes == 0)
5309 		amdgpu_dm_commit_cursors(state);
5310 
5311 	/* update planes when needed */
5312 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
5313 		struct drm_crtc *crtc = new_plane_state->crtc;
5314 		struct drm_crtc_state *new_crtc_state;
5315 		struct drm_framebuffer *fb = new_plane_state->fb;
5316 		bool plane_needs_flip;
5317 		struct dc_plane_state *dc_plane;
5318 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
5319 
5320 		/* Cursor plane is handled after stream updates */
5321 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
5322 			continue;
5323 
5324 		if (!fb || !crtc || pcrtc != crtc)
5325 			continue;
5326 
5327 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
5328 		if (!new_crtc_state->active)
5329 			continue;
5330 
5331 		dc_plane = dm_new_plane_state->dc_state;
5332 
5333 		bundle->surface_updates[planes_count].surface = dc_plane;
5334 		if (new_pcrtc_state->color_mgmt_changed) {
5335 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
5336 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
5337 		}
5338 
5339 		fill_dc_scaling_info(new_plane_state,
5340 				     &bundle->scaling_infos[planes_count]);
5341 
5342 		bundle->surface_updates[planes_count].scaling_info =
5343 			&bundle->scaling_infos[planes_count];
5344 
5345 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
5346 
5347 		pflip_present = pflip_present || plane_needs_flip;
5348 
5349 		if (!plane_needs_flip) {
5350 			planes_count += 1;
5351 			continue;
5352 		}
5353 
5354 		abo = gem_to_amdgpu_bo(fb->obj[0]);
5355 
5356 		/*
5357 		 * Wait for all fences on this FB. Do limited wait to avoid
5358 		 * deadlock during GPU reset when this fence will not signal
5359 		 * but we hold reservation lock for the BO.
5360 		 */
5361 		r = reservation_object_wait_timeout_rcu(abo->tbo.resv, true,
5362 							false,
5363 							msecs_to_jiffies(5000));
5364 		if (unlikely(r <= 0))
5365 			DRM_ERROR("Waiting for fences timed out or interrupted!");
5366 
5367 		/*
5368 		 * TODO This might fail and hence better not used, wait
5369 		 * explicitly on fences instead
5370 		 * and in general should be called for
5371 		 * blocking commit to as per framework helpers
5372 		 */
5373 		r = amdgpu_bo_reserve(abo, true);
5374 		if (unlikely(r != 0))
5375 			DRM_ERROR("failed to reserve buffer before flip\n");
5376 
5377 		amdgpu_bo_get_tiling_flags(abo, &tiling_flags);
5378 
5379 		amdgpu_bo_unreserve(abo);
5380 
5381 		fill_dc_plane_info_and_addr(
5382 			dm->adev, new_plane_state, tiling_flags,
5383 			&bundle->plane_infos[planes_count],
5384 			&bundle->flip_addrs[planes_count].address);
5385 
5386 		bundle->surface_updates[planes_count].plane_info =
5387 			&bundle->plane_infos[planes_count];
5388 
5389 		bundle->flip_addrs[planes_count].flip_immediate =
5390 				(crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
5391 
5392 		timestamp_ns = ktime_get_ns();
5393 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
5394 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
5395 		bundle->surface_updates[planes_count].surface = dc_plane;
5396 
5397 		if (!bundle->surface_updates[planes_count].surface) {
5398 			DRM_ERROR("No surface for CRTC: id=%d\n",
5399 					acrtc_attach->crtc_id);
5400 			continue;
5401 		}
5402 
5403 		if (plane == pcrtc->primary)
5404 			update_freesync_state_on_stream(
5405 				dm,
5406 				acrtc_state,
5407 				acrtc_state->stream,
5408 				dc_plane,
5409 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
5410 
5411 		DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x\n",
5412 				 __func__,
5413 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
5414 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
5415 
5416 		planes_count += 1;
5417 
5418 	}
5419 
5420 	if (pflip_present) {
5421 		if (!vrr_active) {
5422 			/* Use old throttling in non-vrr fixed refresh rate mode
5423 			 * to keep flip scheduling based on target vblank counts
5424 			 * working in a backwards compatible way, e.g., for
5425 			 * clients using the GLX_OML_sync_control extension or
5426 			 * DRI3/Present extension with defined target_msc.
5427 			 */
5428 			last_flip_vblank = amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id);
5429 		}
5430 		else {
5431 			/* For variable refresh rate mode only:
5432 			 * Get vblank of last completed flip to avoid > 1 vrr
5433 			 * flips per video frame by use of throttling, but allow
5434 			 * flip programming anywhere in the possibly large
5435 			 * variable vrr vblank interval for fine-grained flip
5436 			 * timing control and more opportunity to avoid stutter
5437 			 * on late submission of flips.
5438 			 */
5439 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5440 			last_flip_vblank = acrtc_attach->last_flip_vblank;
5441 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5442 		}
5443 
5444 		target_vblank = last_flip_vblank + wait_for_vblank;
5445 
5446 		/*
5447 		 * Wait until we're out of the vertical blank period before the one
5448 		 * targeted by the flip
5449 		 */
5450 		while ((acrtc_attach->enabled &&
5451 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
5452 							    0, &vpos, &hpos, NULL,
5453 							    NULL, &pcrtc->hwmode)
5454 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
5455 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
5456 			(int)(target_vblank -
5457 			  amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id)) > 0)) {
5458 			usleep_range(1000, 1100);
5459 		}
5460 
5461 		if (acrtc_attach->base.state->event) {
5462 			drm_crtc_vblank_get(pcrtc);
5463 
5464 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5465 
5466 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
5467 			prepare_flip_isr(acrtc_attach);
5468 
5469 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5470 		}
5471 
5472 		if (acrtc_state->stream) {
5473 			if (acrtc_state->freesync_vrr_info_changed)
5474 				bundle->stream_update.vrr_infopacket =
5475 					&acrtc_state->stream->vrr_infopacket;
5476 		}
5477 	}
5478 
5479 	/* Update the planes if changed or disable if we don't have any. */
5480 	if (planes_count || acrtc_state->active_planes == 0) {
5481 		if (new_pcrtc_state->mode_changed) {
5482 			bundle->stream_update.src = acrtc_state->stream->src;
5483 			bundle->stream_update.dst = acrtc_state->stream->dst;
5484 		}
5485 
5486 		if (new_pcrtc_state->color_mgmt_changed)
5487 			bundle->stream_update.out_transfer_func = acrtc_state->stream->out_transfer_func;
5488 
5489 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
5490 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
5491 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
5492 
5493 		/*
5494 		 * If FreeSync state on the stream has changed then we need to
5495 		 * re-adjust the min/max bounds now that DC doesn't handle this
5496 		 * as part of commit.
5497 		 */
5498 		if (amdgpu_dm_vrr_active(dm_old_crtc_state) !=
5499 		    amdgpu_dm_vrr_active(acrtc_state)) {
5500 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5501 			dc_stream_adjust_vmin_vmax(
5502 				dm->dc, acrtc_state->stream,
5503 				&acrtc_state->vrr_params.adjust);
5504 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5505 		}
5506 
5507 		mutex_lock(&dm->dc_lock);
5508 		dc_commit_updates_for_stream(dm->dc,
5509 						     bundle->surface_updates,
5510 						     planes_count,
5511 						     acrtc_state->stream,
5512 						     &bundle->stream_update,
5513 						     dc_state);
5514 		mutex_unlock(&dm->dc_lock);
5515 	}
5516 
5517 	/*
5518 	 * Update cursor state *after* programming all the planes.
5519 	 * This avoids redundant programming in the case where we're going
5520 	 * to be disabling a single plane - those pipes are being disabled.
5521 	 */
5522 	if (acrtc_state->active_planes)
5523 		amdgpu_dm_commit_cursors(state);
5524 
5525 cleanup:
5526 	kfree(bundle);
5527 }
5528 
5529 /*
5530  * Enable interrupts on CRTCs that are newly active, undergone
5531  * a modeset, or have active planes again.
5532  *
5533  * Done in two passes, based on the for_modeset flag:
5534  * Pass 1: For CRTCs going through modeset
5535  * Pass 2: For CRTCs going from 0 to n active planes
5536  *
5537  * Interrupts can only be enabled after the planes are programmed,
5538  * so this requires a two-pass approach since we don't want to
5539  * just defer the interrupts until after commit planes every time.
5540  */
5541 static void amdgpu_dm_enable_crtc_interrupts(struct drm_device *dev,
5542 					     struct drm_atomic_state *state,
5543 					     bool for_modeset)
5544 {
5545 	struct amdgpu_device *adev = dev->dev_private;
5546 	struct drm_crtc *crtc;
5547 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5548 	int i;
5549 
5550 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5551 				      new_crtc_state, i) {
5552 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5553 		struct dm_crtc_state *dm_new_crtc_state =
5554 			to_dm_crtc_state(new_crtc_state);
5555 		struct dm_crtc_state *dm_old_crtc_state =
5556 			to_dm_crtc_state(old_crtc_state);
5557 		bool modeset = drm_atomic_crtc_needs_modeset(new_crtc_state);
5558 		bool run_pass;
5559 
5560 		run_pass = (for_modeset && modeset) ||
5561 			   (!for_modeset && !modeset &&
5562 			    !dm_old_crtc_state->interrupts_enabled);
5563 
5564 		if (!run_pass)
5565 			continue;
5566 
5567 		if (!dm_new_crtc_state->interrupts_enabled)
5568 			continue;
5569 
5570 		manage_dm_interrupts(adev, acrtc, true);
5571 
5572 #ifdef CONFIG_DEBUG_FS
5573 		/* The stream has changed so CRC capture needs to re-enabled. */
5574 		if (dm_new_crtc_state->crc_enabled) {
5575 			dm_new_crtc_state->crc_enabled = false;
5576 			amdgpu_dm_crtc_set_crc_source(crtc, "auto");
5577 		}
5578 #endif
5579 	}
5580 }
5581 
5582 /*
5583  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
5584  * @crtc_state: the DRM CRTC state
5585  * @stream_state: the DC stream state.
5586  *
5587  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
5588  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
5589  */
5590 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
5591 						struct dc_stream_state *stream_state)
5592 {
5593 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
5594 }
5595 
5596 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
5597 				   struct drm_atomic_state *state,
5598 				   bool nonblock)
5599 {
5600 	struct drm_crtc *crtc;
5601 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5602 	struct amdgpu_device *adev = dev->dev_private;
5603 	int i;
5604 
5605 	/*
5606 	 * We evade vblank and pflip interrupts on CRTCs that are undergoing
5607 	 * a modeset, being disabled, or have no active planes.
5608 	 *
5609 	 * It's done in atomic commit rather than commit tail for now since
5610 	 * some of these interrupt handlers access the current CRTC state and
5611 	 * potentially the stream pointer itself.
5612 	 *
5613 	 * Since the atomic state is swapped within atomic commit and not within
5614 	 * commit tail this would leave to new state (that hasn't been committed yet)
5615 	 * being accesssed from within the handlers.
5616 	 *
5617 	 * TODO: Fix this so we can do this in commit tail and not have to block
5618 	 * in atomic check.
5619 	 */
5620 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5621 		struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5622 		struct dm_crtc_state *dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5623 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5624 
5625 		if (dm_old_crtc_state->interrupts_enabled &&
5626 		    (!dm_new_crtc_state->interrupts_enabled ||
5627 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5628 			/*
5629 			 * Drop the extra vblank reference added by CRC
5630 			 * capture if applicable.
5631 			 */
5632 			if (dm_new_crtc_state->crc_enabled)
5633 				drm_crtc_vblank_put(crtc);
5634 
5635 			/*
5636 			 * Only keep CRC capture enabled if there's
5637 			 * still a stream for the CRTC.
5638 			 */
5639 			if (!dm_new_crtc_state->stream)
5640 				dm_new_crtc_state->crc_enabled = false;
5641 
5642 			manage_dm_interrupts(adev, acrtc, false);
5643 		}
5644 	}
5645 	/*
5646 	 * Add check here for SoC's that support hardware cursor plane, to
5647 	 * unset legacy_cursor_update
5648 	 */
5649 
5650 	return drm_atomic_helper_commit(dev, state, nonblock);
5651 
5652 	/*TODO Handle EINTR, reenable IRQ*/
5653 }
5654 
5655 /**
5656  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
5657  * @state: The atomic state to commit
5658  *
5659  * This will tell DC to commit the constructed DC state from atomic_check,
5660  * programming the hardware. Any failures here implies a hardware failure, since
5661  * atomic check should have filtered anything non-kosher.
5662  */
5663 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
5664 {
5665 	struct drm_device *dev = state->dev;
5666 	struct amdgpu_device *adev = dev->dev_private;
5667 	struct amdgpu_display_manager *dm = &adev->dm;
5668 	struct dm_atomic_state *dm_state;
5669 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
5670 	uint32_t i, j;
5671 	struct drm_crtc *crtc;
5672 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5673 	unsigned long flags;
5674 	bool wait_for_vblank = true;
5675 	struct drm_connector *connector;
5676 	struct drm_connector_state *old_con_state, *new_con_state;
5677 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5678 	int crtc_disable_count = 0;
5679 
5680 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
5681 
5682 	dm_state = dm_atomic_get_new_state(state);
5683 	if (dm_state && dm_state->context) {
5684 		dc_state = dm_state->context;
5685 	} else {
5686 		/* No state changes, retain current state. */
5687 		dc_state_temp = dc_create_state(dm->dc);
5688 		ASSERT(dc_state_temp);
5689 		dc_state = dc_state_temp;
5690 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
5691 	}
5692 
5693 	/* update changed items */
5694 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5695 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5696 
5697 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5698 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5699 
5700 		DRM_DEBUG_DRIVER(
5701 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
5702 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
5703 			"connectors_changed:%d\n",
5704 			acrtc->crtc_id,
5705 			new_crtc_state->enable,
5706 			new_crtc_state->active,
5707 			new_crtc_state->planes_changed,
5708 			new_crtc_state->mode_changed,
5709 			new_crtc_state->active_changed,
5710 			new_crtc_state->connectors_changed);
5711 
5712 		/* Copy all transient state flags into dc state */
5713 		if (dm_new_crtc_state->stream) {
5714 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
5715 							    dm_new_crtc_state->stream);
5716 		}
5717 
5718 		/* handles headless hotplug case, updating new_state and
5719 		 * aconnector as needed
5720 		 */
5721 
5722 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
5723 
5724 			DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
5725 
5726 			if (!dm_new_crtc_state->stream) {
5727 				/*
5728 				 * this could happen because of issues with
5729 				 * userspace notifications delivery.
5730 				 * In this case userspace tries to set mode on
5731 				 * display which is disconnected in fact.
5732 				 * dc_sink is NULL in this case on aconnector.
5733 				 * We expect reset mode will come soon.
5734 				 *
5735 				 * This can also happen when unplug is done
5736 				 * during resume sequence ended
5737 				 *
5738 				 * In this case, we want to pretend we still
5739 				 * have a sink to keep the pipe running so that
5740 				 * hw state is consistent with the sw state
5741 				 */
5742 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
5743 						__func__, acrtc->base.base.id);
5744 				continue;
5745 			}
5746 
5747 			if (dm_old_crtc_state->stream)
5748 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
5749 
5750 			pm_runtime_get_noresume(dev->dev);
5751 
5752 			acrtc->enabled = true;
5753 			acrtc->hw_mode = new_crtc_state->mode;
5754 			crtc->hwmode = new_crtc_state->mode;
5755 		} else if (modereset_required(new_crtc_state)) {
5756 			DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
5757 
5758 			/* i.e. reset mode */
5759 			if (dm_old_crtc_state->stream)
5760 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
5761 		}
5762 	} /* for_each_crtc_in_state() */
5763 
5764 	if (dc_state) {
5765 		dm_enable_per_frame_crtc_master_sync(dc_state);
5766 		mutex_lock(&dm->dc_lock);
5767 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
5768 		mutex_unlock(&dm->dc_lock);
5769 	}
5770 
5771 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5772 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5773 
5774 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5775 
5776 		if (dm_new_crtc_state->stream != NULL) {
5777 			const struct dc_stream_status *status =
5778 					dc_stream_get_status(dm_new_crtc_state->stream);
5779 
5780 			if (!status)
5781 				status = dc_stream_get_status_from_state(dc_state,
5782 									 dm_new_crtc_state->stream);
5783 
5784 			if (!status)
5785 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
5786 			else
5787 				acrtc->otg_inst = status->primary_otg_inst;
5788 		}
5789 	}
5790 
5791 	/* Handle connector state changes */
5792 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5793 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5794 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5795 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5796 		struct dc_surface_update dummy_updates[MAX_SURFACES];
5797 		struct dc_stream_update stream_update;
5798 		struct dc_stream_status *status = NULL;
5799 
5800 		memset(&dummy_updates, 0, sizeof(dummy_updates));
5801 		memset(&stream_update, 0, sizeof(stream_update));
5802 
5803 		if (acrtc) {
5804 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5805 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5806 		}
5807 
5808 		/* Skip any modesets/resets */
5809 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
5810 			continue;
5811 
5812 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5813 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5814 
5815 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state) &&
5816 				(dm_new_crtc_state->abm_level == dm_old_crtc_state->abm_level))
5817 			continue;
5818 
5819 		if (is_scaling_state_different(dm_new_con_state, dm_old_con_state)) {
5820 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
5821 					dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
5822 
5823 			stream_update.src = dm_new_crtc_state->stream->src;
5824 			stream_update.dst = dm_new_crtc_state->stream->dst;
5825 		}
5826 
5827 		if (dm_new_crtc_state->abm_level != dm_old_crtc_state->abm_level) {
5828 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
5829 
5830 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
5831 		}
5832 
5833 		status = dc_stream_get_status(dm_new_crtc_state->stream);
5834 		WARN_ON(!status);
5835 		WARN_ON(!status->plane_count);
5836 
5837 		/*
5838 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
5839 		 * Here we create an empty update on each plane.
5840 		 * To fix this, DC should permit updating only stream properties.
5841 		 */
5842 		for (j = 0; j < status->plane_count; j++)
5843 			dummy_updates[j].surface = status->plane_states[0];
5844 
5845 
5846 		mutex_lock(&dm->dc_lock);
5847 		dc_commit_updates_for_stream(dm->dc,
5848 						     dummy_updates,
5849 						     status->plane_count,
5850 						     dm_new_crtc_state->stream,
5851 						     &stream_update,
5852 						     dc_state);
5853 		mutex_unlock(&dm->dc_lock);
5854 	}
5855 
5856 	/* Count number of newly disabled CRTCs for dropping PM refs later. */
5857 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5858 				      new_crtc_state, i) {
5859 		if (old_crtc_state->active && !new_crtc_state->active)
5860 			crtc_disable_count++;
5861 
5862 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5863 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5864 
5865 		/* Update freesync active state. */
5866 		pre_update_freesync_state_on_stream(dm, dm_new_crtc_state);
5867 
5868 		/* Handle vrr on->off / off->on transitions */
5869 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state,
5870 						dm_new_crtc_state);
5871 	}
5872 
5873 	/* Enable interrupts for CRTCs going through a modeset. */
5874 	amdgpu_dm_enable_crtc_interrupts(dev, state, true);
5875 
5876 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
5877 		if (new_crtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC)
5878 			wait_for_vblank = false;
5879 
5880 	/* update planes when needed per crtc*/
5881 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
5882 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5883 
5884 		if (dm_new_crtc_state->stream)
5885 			amdgpu_dm_commit_planes(state, dc_state, dev,
5886 						dm, crtc, wait_for_vblank);
5887 	}
5888 
5889 	/* Enable interrupts for CRTCs going from 0 to n active planes. */
5890 	amdgpu_dm_enable_crtc_interrupts(dev, state, false);
5891 
5892 	/*
5893 	 * send vblank event on all events not handled in flip and
5894 	 * mark consumed event for drm_atomic_helper_commit_hw_done
5895 	 */
5896 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
5897 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5898 
5899 		if (new_crtc_state->event)
5900 			drm_send_event_locked(dev, &new_crtc_state->event->base);
5901 
5902 		new_crtc_state->event = NULL;
5903 	}
5904 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5905 
5906 	/* Signal HW programming completion */
5907 	drm_atomic_helper_commit_hw_done(state);
5908 
5909 	if (wait_for_vblank)
5910 		drm_atomic_helper_wait_for_flip_done(dev, state);
5911 
5912 	drm_atomic_helper_cleanup_planes(dev, state);
5913 
5914 	/*
5915 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
5916 	 * so we can put the GPU into runtime suspend if we're not driving any
5917 	 * displays anymore
5918 	 */
5919 	for (i = 0; i < crtc_disable_count; i++)
5920 		pm_runtime_put_autosuspend(dev->dev);
5921 	pm_runtime_mark_last_busy(dev->dev);
5922 
5923 	if (dc_state_temp)
5924 		dc_release_state(dc_state_temp);
5925 }
5926 
5927 
5928 static int dm_force_atomic_commit(struct drm_connector *connector)
5929 {
5930 	int ret = 0;
5931 	struct drm_device *ddev = connector->dev;
5932 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
5933 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
5934 	struct drm_plane *plane = disconnected_acrtc->base.primary;
5935 	struct drm_connector_state *conn_state;
5936 	struct drm_crtc_state *crtc_state;
5937 	struct drm_plane_state *plane_state;
5938 
5939 	if (!state)
5940 		return -ENOMEM;
5941 
5942 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
5943 
5944 	/* Construct an atomic state to restore previous display setting */
5945 
5946 	/*
5947 	 * Attach connectors to drm_atomic_state
5948 	 */
5949 	conn_state = drm_atomic_get_connector_state(state, connector);
5950 
5951 	ret = PTR_ERR_OR_ZERO(conn_state);
5952 	if (ret)
5953 		goto err;
5954 
5955 	/* Attach crtc to drm_atomic_state*/
5956 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
5957 
5958 	ret = PTR_ERR_OR_ZERO(crtc_state);
5959 	if (ret)
5960 		goto err;
5961 
5962 	/* force a restore */
5963 	crtc_state->mode_changed = true;
5964 
5965 	/* Attach plane to drm_atomic_state */
5966 	plane_state = drm_atomic_get_plane_state(state, plane);
5967 
5968 	ret = PTR_ERR_OR_ZERO(plane_state);
5969 	if (ret)
5970 		goto err;
5971 
5972 
5973 	/* Call commit internally with the state we just constructed */
5974 	ret = drm_atomic_commit(state);
5975 	if (!ret)
5976 		return 0;
5977 
5978 err:
5979 	DRM_ERROR("Restoring old state failed with %i\n", ret);
5980 	drm_atomic_state_put(state);
5981 
5982 	return ret;
5983 }
5984 
5985 /*
5986  * This function handles all cases when set mode does not come upon hotplug.
5987  * This includes when a display is unplugged then plugged back into the
5988  * same port and when running without usermode desktop manager supprot
5989  */
5990 void dm_restore_drm_connector_state(struct drm_device *dev,
5991 				    struct drm_connector *connector)
5992 {
5993 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5994 	struct amdgpu_crtc *disconnected_acrtc;
5995 	struct dm_crtc_state *acrtc_state;
5996 
5997 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
5998 		return;
5999 
6000 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6001 	if (!disconnected_acrtc)
6002 		return;
6003 
6004 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
6005 	if (!acrtc_state->stream)
6006 		return;
6007 
6008 	/*
6009 	 * If the previous sink is not released and different from the current,
6010 	 * we deduce we are in a state where we can not rely on usermode call
6011 	 * to turn on the display, so we do it here
6012 	 */
6013 	if (acrtc_state->stream->sink != aconnector->dc_sink)
6014 		dm_force_atomic_commit(&aconnector->base);
6015 }
6016 
6017 /*
6018  * Grabs all modesetting locks to serialize against any blocking commits,
6019  * Waits for completion of all non blocking commits.
6020  */
6021 static int do_aquire_global_lock(struct drm_device *dev,
6022 				 struct drm_atomic_state *state)
6023 {
6024 	struct drm_crtc *crtc;
6025 	struct drm_crtc_commit *commit;
6026 	long ret;
6027 
6028 	/*
6029 	 * Adding all modeset locks to aquire_ctx will
6030 	 * ensure that when the framework release it the
6031 	 * extra locks we are locking here will get released to
6032 	 */
6033 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
6034 	if (ret)
6035 		return ret;
6036 
6037 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6038 		spin_lock(&crtc->commit_lock);
6039 		commit = list_first_entry_or_null(&crtc->commit_list,
6040 				struct drm_crtc_commit, commit_entry);
6041 		if (commit)
6042 			drm_crtc_commit_get(commit);
6043 		spin_unlock(&crtc->commit_lock);
6044 
6045 		if (!commit)
6046 			continue;
6047 
6048 		/*
6049 		 * Make sure all pending HW programming completed and
6050 		 * page flips done
6051 		 */
6052 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
6053 
6054 		if (ret > 0)
6055 			ret = wait_for_completion_interruptible_timeout(
6056 					&commit->flip_done, 10*HZ);
6057 
6058 		if (ret == 0)
6059 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
6060 				  "timed out\n", crtc->base.id, crtc->name);
6061 
6062 		drm_crtc_commit_put(commit);
6063 	}
6064 
6065 	return ret < 0 ? ret : 0;
6066 }
6067 
6068 static void get_freesync_config_for_crtc(
6069 	struct dm_crtc_state *new_crtc_state,
6070 	struct dm_connector_state *new_con_state)
6071 {
6072 	struct mod_freesync_config config = {0};
6073 	struct amdgpu_dm_connector *aconnector =
6074 			to_amdgpu_dm_connector(new_con_state->base.connector);
6075 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
6076 	int vrefresh = drm_mode_vrefresh(mode);
6077 
6078 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
6079 					vrefresh >= aconnector->min_vfreq &&
6080 					vrefresh <= aconnector->max_vfreq;
6081 
6082 	if (new_crtc_state->vrr_supported) {
6083 		new_crtc_state->stream->ignore_msa_timing_param = true;
6084 		config.state = new_crtc_state->base.vrr_enabled ?
6085 				VRR_STATE_ACTIVE_VARIABLE :
6086 				VRR_STATE_INACTIVE;
6087 		config.min_refresh_in_uhz =
6088 				aconnector->min_vfreq * 1000000;
6089 		config.max_refresh_in_uhz =
6090 				aconnector->max_vfreq * 1000000;
6091 		config.vsif_supported = true;
6092 		config.btr = true;
6093 	}
6094 
6095 	new_crtc_state->freesync_config = config;
6096 }
6097 
6098 static void reset_freesync_config_for_crtc(
6099 	struct dm_crtc_state *new_crtc_state)
6100 {
6101 	new_crtc_state->vrr_supported = false;
6102 
6103 	memset(&new_crtc_state->vrr_params, 0,
6104 	       sizeof(new_crtc_state->vrr_params));
6105 	memset(&new_crtc_state->vrr_infopacket, 0,
6106 	       sizeof(new_crtc_state->vrr_infopacket));
6107 }
6108 
6109 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
6110 				struct drm_atomic_state *state,
6111 				struct drm_crtc *crtc,
6112 				struct drm_crtc_state *old_crtc_state,
6113 				struct drm_crtc_state *new_crtc_state,
6114 				bool enable,
6115 				bool *lock_and_validation_needed)
6116 {
6117 	struct dm_atomic_state *dm_state = NULL;
6118 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6119 	struct dc_stream_state *new_stream;
6120 	int ret = 0;
6121 
6122 	/*
6123 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
6124 	 * update changed items
6125 	 */
6126 	struct amdgpu_crtc *acrtc = NULL;
6127 	struct amdgpu_dm_connector *aconnector = NULL;
6128 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
6129 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
6130 
6131 	new_stream = NULL;
6132 
6133 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6134 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6135 	acrtc = to_amdgpu_crtc(crtc);
6136 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
6137 
6138 	/* TODO This hack should go away */
6139 	if (aconnector && enable) {
6140 		/* Make sure fake sink is created in plug-in scenario */
6141 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
6142 							    &aconnector->base);
6143 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
6144 							    &aconnector->base);
6145 
6146 		if (IS_ERR(drm_new_conn_state)) {
6147 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
6148 			goto fail;
6149 		}
6150 
6151 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
6152 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
6153 
6154 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6155 			goto skip_modeset;
6156 
6157 		new_stream = create_stream_for_sink(aconnector,
6158 						     &new_crtc_state->mode,
6159 						    dm_new_conn_state,
6160 						    dm_old_crtc_state->stream);
6161 
6162 		/*
6163 		 * we can have no stream on ACTION_SET if a display
6164 		 * was disconnected during S3, in this case it is not an
6165 		 * error, the OS will be updated after detection, and
6166 		 * will do the right thing on next atomic commit
6167 		 */
6168 
6169 		if (!new_stream) {
6170 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6171 					__func__, acrtc->base.base.id);
6172 			ret = -ENOMEM;
6173 			goto fail;
6174 		}
6175 
6176 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6177 
6178 		if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
6179 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
6180 			new_crtc_state->mode_changed = false;
6181 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
6182 					 new_crtc_state->mode_changed);
6183 		}
6184 	}
6185 
6186 	/* mode_changed flag may get updated above, need to check again */
6187 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6188 		goto skip_modeset;
6189 
6190 	DRM_DEBUG_DRIVER(
6191 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6192 		"planes_changed:%d, mode_changed:%d,active_changed:%d,"
6193 		"connectors_changed:%d\n",
6194 		acrtc->crtc_id,
6195 		new_crtc_state->enable,
6196 		new_crtc_state->active,
6197 		new_crtc_state->planes_changed,
6198 		new_crtc_state->mode_changed,
6199 		new_crtc_state->active_changed,
6200 		new_crtc_state->connectors_changed);
6201 
6202 	/* Remove stream for any changed/disabled CRTC */
6203 	if (!enable) {
6204 
6205 		if (!dm_old_crtc_state->stream)
6206 			goto skip_modeset;
6207 
6208 		ret = dm_atomic_get_state(state, &dm_state);
6209 		if (ret)
6210 			goto fail;
6211 
6212 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
6213 				crtc->base.id);
6214 
6215 		/* i.e. reset mode */
6216 		if (dc_remove_stream_from_ctx(
6217 				dm->dc,
6218 				dm_state->context,
6219 				dm_old_crtc_state->stream) != DC_OK) {
6220 			ret = -EINVAL;
6221 			goto fail;
6222 		}
6223 
6224 		dc_stream_release(dm_old_crtc_state->stream);
6225 		dm_new_crtc_state->stream = NULL;
6226 
6227 		reset_freesync_config_for_crtc(dm_new_crtc_state);
6228 
6229 		*lock_and_validation_needed = true;
6230 
6231 	} else {/* Add stream for any updated/enabled CRTC */
6232 		/*
6233 		 * Quick fix to prevent NULL pointer on new_stream when
6234 		 * added MST connectors not found in existing crtc_state in the chained mode
6235 		 * TODO: need to dig out the root cause of that
6236 		 */
6237 		if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
6238 			goto skip_modeset;
6239 
6240 		if (modereset_required(new_crtc_state))
6241 			goto skip_modeset;
6242 
6243 		if (modeset_required(new_crtc_state, new_stream,
6244 				     dm_old_crtc_state->stream)) {
6245 
6246 			WARN_ON(dm_new_crtc_state->stream);
6247 
6248 			ret = dm_atomic_get_state(state, &dm_state);
6249 			if (ret)
6250 				goto fail;
6251 
6252 			dm_new_crtc_state->stream = new_stream;
6253 
6254 			dc_stream_retain(new_stream);
6255 
6256 			DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
6257 						crtc->base.id);
6258 
6259 			if (dc_add_stream_to_ctx(
6260 					dm->dc,
6261 					dm_state->context,
6262 					dm_new_crtc_state->stream) != DC_OK) {
6263 				ret = -EINVAL;
6264 				goto fail;
6265 			}
6266 
6267 			*lock_and_validation_needed = true;
6268 		}
6269 	}
6270 
6271 skip_modeset:
6272 	/* Release extra reference */
6273 	if (new_stream)
6274 		 dc_stream_release(new_stream);
6275 
6276 	/*
6277 	 * We want to do dc stream updates that do not require a
6278 	 * full modeset below.
6279 	 */
6280 	if (!(enable && aconnector && new_crtc_state->enable &&
6281 	      new_crtc_state->active))
6282 		return 0;
6283 	/*
6284 	 * Given above conditions, the dc state cannot be NULL because:
6285 	 * 1. We're in the process of enabling CRTCs (just been added
6286 	 *    to the dc context, or already is on the context)
6287 	 * 2. Has a valid connector attached, and
6288 	 * 3. Is currently active and enabled.
6289 	 * => The dc stream state currently exists.
6290 	 */
6291 	BUG_ON(dm_new_crtc_state->stream == NULL);
6292 
6293 	/* Scaling or underscan settings */
6294 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
6295 		update_stream_scaling_settings(
6296 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
6297 
6298 	/* ABM settings */
6299 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6300 
6301 	/*
6302 	 * Color management settings. We also update color properties
6303 	 * when a modeset is needed, to ensure it gets reprogrammed.
6304 	 */
6305 	if (dm_new_crtc_state->base.color_mgmt_changed ||
6306 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
6307 		ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
6308 		if (ret)
6309 			goto fail;
6310 		amdgpu_dm_set_ctm(dm_new_crtc_state);
6311 	}
6312 
6313 	/* Update Freesync settings. */
6314 	get_freesync_config_for_crtc(dm_new_crtc_state,
6315 				     dm_new_conn_state);
6316 
6317 	return ret;
6318 
6319 fail:
6320 	if (new_stream)
6321 		dc_stream_release(new_stream);
6322 	return ret;
6323 }
6324 
6325 static bool should_reset_plane(struct drm_atomic_state *state,
6326 			       struct drm_plane *plane,
6327 			       struct drm_plane_state *old_plane_state,
6328 			       struct drm_plane_state *new_plane_state)
6329 {
6330 	struct drm_plane *other;
6331 	struct drm_plane_state *old_other_state, *new_other_state;
6332 	struct drm_crtc_state *new_crtc_state;
6333 	int i;
6334 
6335 	/*
6336 	 * TODO: Remove this hack once the checks below are sufficient
6337 	 * enough to determine when we need to reset all the planes on
6338 	 * the stream.
6339 	 */
6340 	if (state->allow_modeset)
6341 		return true;
6342 
6343 	/* Exit early if we know that we're adding or removing the plane. */
6344 	if (old_plane_state->crtc != new_plane_state->crtc)
6345 		return true;
6346 
6347 	/* old crtc == new_crtc == NULL, plane not in context. */
6348 	if (!new_plane_state->crtc)
6349 		return false;
6350 
6351 	new_crtc_state =
6352 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
6353 
6354 	if (!new_crtc_state)
6355 		return true;
6356 
6357 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
6358 		return true;
6359 
6360 	/*
6361 	 * If there are any new primary or overlay planes being added or
6362 	 * removed then the z-order can potentially change. To ensure
6363 	 * correct z-order and pipe acquisition the current DC architecture
6364 	 * requires us to remove and recreate all existing planes.
6365 	 *
6366 	 * TODO: Come up with a more elegant solution for this.
6367 	 */
6368 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
6369 		if (other->type == DRM_PLANE_TYPE_CURSOR)
6370 			continue;
6371 
6372 		if (old_other_state->crtc != new_plane_state->crtc &&
6373 		    new_other_state->crtc != new_plane_state->crtc)
6374 			continue;
6375 
6376 		if (old_other_state->crtc != new_other_state->crtc)
6377 			return true;
6378 
6379 		/* TODO: Remove this once we can handle fast format changes. */
6380 		if (old_other_state->fb && new_other_state->fb &&
6381 		    old_other_state->fb->format != new_other_state->fb->format)
6382 			return true;
6383 	}
6384 
6385 	return false;
6386 }
6387 
6388 static int dm_update_plane_state(struct dc *dc,
6389 				 struct drm_atomic_state *state,
6390 				 struct drm_plane *plane,
6391 				 struct drm_plane_state *old_plane_state,
6392 				 struct drm_plane_state *new_plane_state,
6393 				 bool enable,
6394 				 bool *lock_and_validation_needed)
6395 {
6396 
6397 	struct dm_atomic_state *dm_state = NULL;
6398 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6399 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6400 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
6401 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
6402 	bool needs_reset;
6403 	int ret = 0;
6404 
6405 
6406 	new_plane_crtc = new_plane_state->crtc;
6407 	old_plane_crtc = old_plane_state->crtc;
6408 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
6409 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
6410 
6411 	/*TODO Implement atomic check for cursor plane */
6412 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6413 		return 0;
6414 
6415 	needs_reset = should_reset_plane(state, plane, old_plane_state,
6416 					 new_plane_state);
6417 
6418 	/* Remove any changed/removed planes */
6419 	if (!enable) {
6420 		if (!needs_reset)
6421 			return 0;
6422 
6423 		if (!old_plane_crtc)
6424 			return 0;
6425 
6426 		old_crtc_state = drm_atomic_get_old_crtc_state(
6427 				state, old_plane_crtc);
6428 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6429 
6430 		if (!dm_old_crtc_state->stream)
6431 			return 0;
6432 
6433 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
6434 				plane->base.id, old_plane_crtc->base.id);
6435 
6436 		ret = dm_atomic_get_state(state, &dm_state);
6437 		if (ret)
6438 			return ret;
6439 
6440 		if (!dc_remove_plane_from_context(
6441 				dc,
6442 				dm_old_crtc_state->stream,
6443 				dm_old_plane_state->dc_state,
6444 				dm_state->context)) {
6445 
6446 			ret = EINVAL;
6447 			return ret;
6448 		}
6449 
6450 
6451 		dc_plane_state_release(dm_old_plane_state->dc_state);
6452 		dm_new_plane_state->dc_state = NULL;
6453 
6454 		*lock_and_validation_needed = true;
6455 
6456 	} else { /* Add new planes */
6457 		struct dc_plane_state *dc_new_plane_state;
6458 
6459 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
6460 			return 0;
6461 
6462 		if (!new_plane_crtc)
6463 			return 0;
6464 
6465 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
6466 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6467 
6468 		if (!dm_new_crtc_state->stream)
6469 			return 0;
6470 
6471 		if (!needs_reset)
6472 			return 0;
6473 
6474 		WARN_ON(dm_new_plane_state->dc_state);
6475 
6476 		dc_new_plane_state = dc_create_plane_state(dc);
6477 		if (!dc_new_plane_state)
6478 			return -ENOMEM;
6479 
6480 		DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
6481 				plane->base.id, new_plane_crtc->base.id);
6482 
6483 		ret = fill_dc_plane_attributes(
6484 			new_plane_crtc->dev->dev_private,
6485 			dc_new_plane_state,
6486 			new_plane_state,
6487 			new_crtc_state);
6488 		if (ret) {
6489 			dc_plane_state_release(dc_new_plane_state);
6490 			return ret;
6491 		}
6492 
6493 		ret = dm_atomic_get_state(state, &dm_state);
6494 		if (ret) {
6495 			dc_plane_state_release(dc_new_plane_state);
6496 			return ret;
6497 		}
6498 
6499 		/*
6500 		 * Any atomic check errors that occur after this will
6501 		 * not need a release. The plane state will be attached
6502 		 * to the stream, and therefore part of the atomic
6503 		 * state. It'll be released when the atomic state is
6504 		 * cleaned.
6505 		 */
6506 		if (!dc_add_plane_to_context(
6507 				dc,
6508 				dm_new_crtc_state->stream,
6509 				dc_new_plane_state,
6510 				dm_state->context)) {
6511 
6512 			dc_plane_state_release(dc_new_plane_state);
6513 			return -EINVAL;
6514 		}
6515 
6516 		dm_new_plane_state->dc_state = dc_new_plane_state;
6517 
6518 		/* Tell DC to do a full surface update every time there
6519 		 * is a plane change. Inefficient, but works for now.
6520 		 */
6521 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
6522 
6523 		*lock_and_validation_needed = true;
6524 	}
6525 
6526 
6527 	return ret;
6528 }
6529 
6530 static int
6531 dm_determine_update_type_for_commit(struct amdgpu_display_manager *dm,
6532 				    struct drm_atomic_state *state,
6533 				    enum surface_update_type *out_type)
6534 {
6535 	struct dc *dc = dm->dc;
6536 	struct dm_atomic_state *dm_state = NULL, *old_dm_state = NULL;
6537 	int i, j, num_plane, ret = 0;
6538 	struct drm_plane_state *old_plane_state, *new_plane_state;
6539 	struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
6540 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6541 	struct drm_plane *plane;
6542 
6543 	struct drm_crtc *crtc;
6544 	struct drm_crtc_state *new_crtc_state, *old_crtc_state;
6545 	struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
6546 	struct dc_stream_status *status = NULL;
6547 
6548 	struct dc_surface_update *updates;
6549 	enum surface_update_type update_type = UPDATE_TYPE_FAST;
6550 
6551 	updates = kcalloc(MAX_SURFACES, sizeof(*updates), GFP_KERNEL);
6552 
6553 	if (!updates) {
6554 		DRM_ERROR("Failed to allocate plane updates\n");
6555 		/* Set type to FULL to avoid crashing in DC*/
6556 		update_type = UPDATE_TYPE_FULL;
6557 		goto cleanup;
6558 	}
6559 
6560 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6561 		struct dc_scaling_info scaling_info;
6562 		struct dc_stream_update stream_update;
6563 
6564 		memset(&stream_update, 0, sizeof(stream_update));
6565 
6566 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
6567 		old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
6568 		num_plane = 0;
6569 
6570 		if (new_dm_crtc_state->stream != old_dm_crtc_state->stream) {
6571 			update_type = UPDATE_TYPE_FULL;
6572 			goto cleanup;
6573 		}
6574 
6575 		if (!new_dm_crtc_state->stream)
6576 			continue;
6577 
6578 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
6579 			new_plane_crtc = new_plane_state->crtc;
6580 			old_plane_crtc = old_plane_state->crtc;
6581 			new_dm_plane_state = to_dm_plane_state(new_plane_state);
6582 			old_dm_plane_state = to_dm_plane_state(old_plane_state);
6583 
6584 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6585 				continue;
6586 
6587 			if (new_dm_plane_state->dc_state != old_dm_plane_state->dc_state) {
6588 				update_type = UPDATE_TYPE_FULL;
6589 				goto cleanup;
6590 			}
6591 
6592 			if (crtc != new_plane_crtc)
6593 				continue;
6594 
6595 			updates[num_plane].surface = new_dm_plane_state->dc_state;
6596 
6597 			if (new_crtc_state->mode_changed) {
6598 				stream_update.dst = new_dm_crtc_state->stream->dst;
6599 				stream_update.src = new_dm_crtc_state->stream->src;
6600 			}
6601 
6602 			if (new_crtc_state->color_mgmt_changed) {
6603 				updates[num_plane].gamma =
6604 						new_dm_plane_state->dc_state->gamma_correction;
6605 				updates[num_plane].in_transfer_func =
6606 						new_dm_plane_state->dc_state->in_transfer_func;
6607 				stream_update.gamut_remap =
6608 						&new_dm_crtc_state->stream->gamut_remap_matrix;
6609 				stream_update.out_transfer_func =
6610 						new_dm_crtc_state->stream->out_transfer_func;
6611 			}
6612 
6613 			ret = fill_dc_scaling_info(new_plane_state,
6614 						   &scaling_info);
6615 			if (ret)
6616 				goto cleanup;
6617 
6618 			updates[num_plane].scaling_info = &scaling_info;
6619 
6620 			num_plane++;
6621 		}
6622 
6623 		if (num_plane == 0)
6624 			continue;
6625 
6626 		ret = dm_atomic_get_state(state, &dm_state);
6627 		if (ret)
6628 			goto cleanup;
6629 
6630 		old_dm_state = dm_atomic_get_old_state(state);
6631 		if (!old_dm_state) {
6632 			ret = -EINVAL;
6633 			goto cleanup;
6634 		}
6635 
6636 		status = dc_stream_get_status_from_state(old_dm_state->context,
6637 							 new_dm_crtc_state->stream);
6638 
6639 		/*
6640 		 * TODO: DC modifies the surface during this call so we need
6641 		 * to lock here - find a way to do this without locking.
6642 		 */
6643 		mutex_lock(&dm->dc_lock);
6644 		update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
6645 								  &stream_update, status);
6646 		mutex_unlock(&dm->dc_lock);
6647 
6648 		if (update_type > UPDATE_TYPE_MED) {
6649 			update_type = UPDATE_TYPE_FULL;
6650 			goto cleanup;
6651 		}
6652 	}
6653 
6654 cleanup:
6655 	kfree(updates);
6656 
6657 	*out_type = update_type;
6658 	return ret;
6659 }
6660 
6661 /**
6662  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
6663  * @dev: The DRM device
6664  * @state: The atomic state to commit
6665  *
6666  * Validate that the given atomic state is programmable by DC into hardware.
6667  * This involves constructing a &struct dc_state reflecting the new hardware
6668  * state we wish to commit, then querying DC to see if it is programmable. It's
6669  * important not to modify the existing DC state. Otherwise, atomic_check
6670  * may unexpectedly commit hardware changes.
6671  *
6672  * When validating the DC state, it's important that the right locks are
6673  * acquired. For full updates case which removes/adds/updates streams on one
6674  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
6675  * that any such full update commit will wait for completion of any outstanding
6676  * flip using DRMs synchronization events. See
6677  * dm_determine_update_type_for_commit()
6678  *
6679  * Note that DM adds the affected connectors for all CRTCs in state, when that
6680  * might not seem necessary. This is because DC stream creation requires the
6681  * DC sink, which is tied to the DRM connector state. Cleaning this up should
6682  * be possible but non-trivial - a possible TODO item.
6683  *
6684  * Return: -Error code if validation failed.
6685  */
6686 static int amdgpu_dm_atomic_check(struct drm_device *dev,
6687 				  struct drm_atomic_state *state)
6688 {
6689 	struct amdgpu_device *adev = dev->dev_private;
6690 	struct dm_atomic_state *dm_state = NULL;
6691 	struct dc *dc = adev->dm.dc;
6692 	struct drm_connector *connector;
6693 	struct drm_connector_state *old_con_state, *new_con_state;
6694 	struct drm_crtc *crtc;
6695 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6696 	struct drm_plane *plane;
6697 	struct drm_plane_state *old_plane_state, *new_plane_state;
6698 	enum surface_update_type update_type = UPDATE_TYPE_FAST;
6699 	enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
6700 
6701 	int ret, i;
6702 
6703 	/*
6704 	 * This bool will be set for true for any modeset/reset
6705 	 * or plane update which implies non fast surface update.
6706 	 */
6707 	bool lock_and_validation_needed = false;
6708 
6709 	ret = drm_atomic_helper_check_modeset(dev, state);
6710 	if (ret)
6711 		goto fail;
6712 
6713 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6714 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
6715 		    !new_crtc_state->color_mgmt_changed &&
6716 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled)
6717 			continue;
6718 
6719 		if (!new_crtc_state->enable)
6720 			continue;
6721 
6722 		ret = drm_atomic_add_affected_connectors(state, crtc);
6723 		if (ret)
6724 			return ret;
6725 
6726 		ret = drm_atomic_add_affected_planes(state, crtc);
6727 		if (ret)
6728 			goto fail;
6729 	}
6730 
6731 	/*
6732 	 * Add all primary and overlay planes on the CRTC to the state
6733 	 * whenever a plane is enabled to maintain correct z-ordering
6734 	 * and to enable fast surface updates.
6735 	 */
6736 	drm_for_each_crtc(crtc, dev) {
6737 		bool modified = false;
6738 
6739 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
6740 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6741 				continue;
6742 
6743 			if (new_plane_state->crtc == crtc ||
6744 			    old_plane_state->crtc == crtc) {
6745 				modified = true;
6746 				break;
6747 			}
6748 		}
6749 
6750 		if (!modified)
6751 			continue;
6752 
6753 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
6754 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6755 				continue;
6756 
6757 			new_plane_state =
6758 				drm_atomic_get_plane_state(state, plane);
6759 
6760 			if (IS_ERR(new_plane_state)) {
6761 				ret = PTR_ERR(new_plane_state);
6762 				goto fail;
6763 			}
6764 		}
6765 	}
6766 
6767 	/* Remove exiting planes if they are modified */
6768 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
6769 		ret = dm_update_plane_state(dc, state, plane,
6770 					    old_plane_state,
6771 					    new_plane_state,
6772 					    false,
6773 					    &lock_and_validation_needed);
6774 		if (ret)
6775 			goto fail;
6776 	}
6777 
6778 	/* Disable all crtcs which require disable */
6779 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6780 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6781 					   old_crtc_state,
6782 					   new_crtc_state,
6783 					   false,
6784 					   &lock_and_validation_needed);
6785 		if (ret)
6786 			goto fail;
6787 	}
6788 
6789 	/* Enable all crtcs which require enable */
6790 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6791 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6792 					   old_crtc_state,
6793 					   new_crtc_state,
6794 					   true,
6795 					   &lock_and_validation_needed);
6796 		if (ret)
6797 			goto fail;
6798 	}
6799 
6800 	/* Add new/modified planes */
6801 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
6802 		ret = dm_update_plane_state(dc, state, plane,
6803 					    old_plane_state,
6804 					    new_plane_state,
6805 					    true,
6806 					    &lock_and_validation_needed);
6807 		if (ret)
6808 			goto fail;
6809 	}
6810 
6811 	/* Run this here since we want to validate the streams we created */
6812 	ret = drm_atomic_helper_check_planes(dev, state);
6813 	if (ret)
6814 		goto fail;
6815 
6816 	/* Check scaling and underscan changes*/
6817 	/* TODO Removed scaling changes validation due to inability to commit
6818 	 * new stream into context w\o causing full reset. Need to
6819 	 * decide how to handle.
6820 	 */
6821 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6822 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6823 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6824 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6825 
6826 		/* Skip any modesets/resets */
6827 		if (!acrtc || drm_atomic_crtc_needs_modeset(
6828 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
6829 			continue;
6830 
6831 		/* Skip any thing not scale or underscan changes */
6832 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
6833 			continue;
6834 
6835 		overall_update_type = UPDATE_TYPE_FULL;
6836 		lock_and_validation_needed = true;
6837 	}
6838 
6839 	ret = dm_determine_update_type_for_commit(&adev->dm, state, &update_type);
6840 	if (ret)
6841 		goto fail;
6842 
6843 	if (overall_update_type < update_type)
6844 		overall_update_type = update_type;
6845 
6846 	/*
6847 	 * lock_and_validation_needed was an old way to determine if we need to set
6848 	 * the global lock. Leaving it in to check if we broke any corner cases
6849 	 * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
6850 	 * lock_and_validation_needed false = UPDATE_TYPE_FAST
6851 	 */
6852 	if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
6853 		WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
6854 
6855 	if (overall_update_type > UPDATE_TYPE_FAST) {
6856 		ret = dm_atomic_get_state(state, &dm_state);
6857 		if (ret)
6858 			goto fail;
6859 
6860 		ret = do_aquire_global_lock(dev, state);
6861 		if (ret)
6862 			goto fail;
6863 
6864 		if (dc_validate_global_state(dc, dm_state->context, false) != DC_OK) {
6865 			ret = -EINVAL;
6866 			goto fail;
6867 		}
6868 	} else if (state->legacy_cursor_update) {
6869 		/*
6870 		 * This is a fast cursor update coming from the plane update
6871 		 * helper, check if it can be done asynchronously for better
6872 		 * performance.
6873 		 */
6874 		state->async_update = !drm_atomic_helper_async_check(dev, state);
6875 	}
6876 
6877 	/* Must be success */
6878 	WARN_ON(ret);
6879 	return ret;
6880 
6881 fail:
6882 	if (ret == -EDEADLK)
6883 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
6884 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
6885 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
6886 	else
6887 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
6888 
6889 	return ret;
6890 }
6891 
6892 static bool is_dp_capable_without_timing_msa(struct dc *dc,
6893 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
6894 {
6895 	uint8_t dpcd_data;
6896 	bool capable = false;
6897 
6898 	if (amdgpu_dm_connector->dc_link &&
6899 		dm_helpers_dp_read_dpcd(
6900 				NULL,
6901 				amdgpu_dm_connector->dc_link,
6902 				DP_DOWN_STREAM_PORT_COUNT,
6903 				&dpcd_data,
6904 				sizeof(dpcd_data))) {
6905 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
6906 	}
6907 
6908 	return capable;
6909 }
6910 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
6911 					struct edid *edid)
6912 {
6913 	int i;
6914 	bool edid_check_required;
6915 	struct detailed_timing *timing;
6916 	struct detailed_non_pixel *data;
6917 	struct detailed_data_monitor_range *range;
6918 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6919 			to_amdgpu_dm_connector(connector);
6920 	struct dm_connector_state *dm_con_state = NULL;
6921 
6922 	struct drm_device *dev = connector->dev;
6923 	struct amdgpu_device *adev = dev->dev_private;
6924 	bool freesync_capable = false;
6925 
6926 	if (!connector->state) {
6927 		DRM_ERROR("%s - Connector has no state", __func__);
6928 		goto update;
6929 	}
6930 
6931 	if (!edid) {
6932 		dm_con_state = to_dm_connector_state(connector->state);
6933 
6934 		amdgpu_dm_connector->min_vfreq = 0;
6935 		amdgpu_dm_connector->max_vfreq = 0;
6936 		amdgpu_dm_connector->pixel_clock_mhz = 0;
6937 
6938 		goto update;
6939 	}
6940 
6941 	dm_con_state = to_dm_connector_state(connector->state);
6942 
6943 	edid_check_required = false;
6944 	if (!amdgpu_dm_connector->dc_sink) {
6945 		DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
6946 		goto update;
6947 	}
6948 	if (!adev->dm.freesync_module)
6949 		goto update;
6950 	/*
6951 	 * if edid non zero restrict freesync only for dp and edp
6952 	 */
6953 	if (edid) {
6954 		if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
6955 			|| amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
6956 			edid_check_required = is_dp_capable_without_timing_msa(
6957 						adev->dm.dc,
6958 						amdgpu_dm_connector);
6959 		}
6960 	}
6961 	if (edid_check_required == true && (edid->version > 1 ||
6962 	   (edid->version == 1 && edid->revision > 1))) {
6963 		for (i = 0; i < 4; i++) {
6964 
6965 			timing	= &edid->detailed_timings[i];
6966 			data	= &timing->data.other_data;
6967 			range	= &data->data.range;
6968 			/*
6969 			 * Check if monitor has continuous frequency mode
6970 			 */
6971 			if (data->type != EDID_DETAIL_MONITOR_RANGE)
6972 				continue;
6973 			/*
6974 			 * Check for flag range limits only. If flag == 1 then
6975 			 * no additional timing information provided.
6976 			 * Default GTF, GTF Secondary curve and CVT are not
6977 			 * supported
6978 			 */
6979 			if (range->flags != 1)
6980 				continue;
6981 
6982 			amdgpu_dm_connector->min_vfreq = range->min_vfreq;
6983 			amdgpu_dm_connector->max_vfreq = range->max_vfreq;
6984 			amdgpu_dm_connector->pixel_clock_mhz =
6985 				range->pixel_clock_mhz * 10;
6986 			break;
6987 		}
6988 
6989 		if (amdgpu_dm_connector->max_vfreq -
6990 		    amdgpu_dm_connector->min_vfreq > 10) {
6991 
6992 			freesync_capable = true;
6993 		}
6994 	}
6995 
6996 update:
6997 	if (dm_con_state)
6998 		dm_con_state->freesync_capable = freesync_capable;
6999 
7000 	if (connector->vrr_capable_property)
7001 		drm_connector_set_vrr_capable_property(connector,
7002 						       freesync_capable);
7003 }
7004 
7005