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 #include "dm_services_types.h"
27 #include "dc.h"
28 #include "dc/inc/core_types.h"
29 
30 #include "vid.h"
31 #include "amdgpu.h"
32 #include "amdgpu_display.h"
33 #include "atom.h"
34 #include "amdgpu_dm.h"
35 #include "amdgpu_pm.h"
36 
37 #include "amd_shared.h"
38 #include "amdgpu_dm_irq.h"
39 #include "dm_helpers.h"
40 #include "dm_services_types.h"
41 #include "amdgpu_dm_mst_types.h"
42 
43 #include "ivsrcid/ivsrcid_vislands30.h"
44 
45 #include <linux/module.h>
46 #include <linux/moduleparam.h>
47 #include <linux/version.h>
48 #include <linux/types.h>
49 
50 #include <drm/drmP.h>
51 #include <drm/drm_atomic.h>
52 #include <drm/drm_atomic_helper.h>
53 #include <drm/drm_dp_mst_helper.h>
54 #include <drm/drm_fb_helper.h>
55 #include <drm/drm_edid.h>
56 
57 #include "modules/inc/mod_freesync.h"
58 
59 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
60 #include "ivsrcid/irqsrcs_dcn_1_0.h"
61 
62 #include "dcn/dcn_1_0_offset.h"
63 #include "dcn/dcn_1_0_sh_mask.h"
64 #include "soc15_hw_ip.h"
65 #include "vega10_ip_offset.h"
66 
67 #include "soc15_common.h"
68 #endif
69 
70 #include "modules/inc/mod_freesync.h"
71 
72 #include "i2caux_interface.h"
73 
74 /* basic init/fini API */
75 static int amdgpu_dm_init(struct amdgpu_device *adev);
76 static void amdgpu_dm_fini(struct amdgpu_device *adev);
77 
78 /* initializes drm_device display related structures, based on the information
79  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
80  * drm_encoder, drm_mode_config
81  *
82  * Returns 0 on success
83  */
84 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
85 /* removes and deallocates the drm structures, created by the above function */
86 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
87 
88 static void
89 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
90 
91 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
92 				struct amdgpu_plane *aplane,
93 				unsigned long possible_crtcs);
94 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
95 			       struct drm_plane *plane,
96 			       uint32_t link_index);
97 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
98 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
99 				    uint32_t link_index,
100 				    struct amdgpu_encoder *amdgpu_encoder);
101 static int amdgpu_dm_encoder_init(struct drm_device *dev,
102 				  struct amdgpu_encoder *aencoder,
103 				  uint32_t link_index);
104 
105 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
106 
107 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
108 				   struct drm_atomic_state *state,
109 				   bool nonblock);
110 
111 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
112 
113 static int amdgpu_dm_atomic_check(struct drm_device *dev,
114 				  struct drm_atomic_state *state);
115 
116 
117 
118 
119 static const enum drm_plane_type dm_plane_type_default[AMDGPU_MAX_PLANES] = {
120 	DRM_PLANE_TYPE_PRIMARY,
121 	DRM_PLANE_TYPE_PRIMARY,
122 	DRM_PLANE_TYPE_PRIMARY,
123 	DRM_PLANE_TYPE_PRIMARY,
124 	DRM_PLANE_TYPE_PRIMARY,
125 	DRM_PLANE_TYPE_PRIMARY,
126 };
127 
128 static const enum drm_plane_type dm_plane_type_carizzo[AMDGPU_MAX_PLANES] = {
129 	DRM_PLANE_TYPE_PRIMARY,
130 	DRM_PLANE_TYPE_PRIMARY,
131 	DRM_PLANE_TYPE_PRIMARY,
132 	DRM_PLANE_TYPE_OVERLAY,/* YUV Capable Underlay */
133 };
134 
135 static const enum drm_plane_type dm_plane_type_stoney[AMDGPU_MAX_PLANES] = {
136 	DRM_PLANE_TYPE_PRIMARY,
137 	DRM_PLANE_TYPE_PRIMARY,
138 	DRM_PLANE_TYPE_OVERLAY, /* YUV Capable Underlay */
139 };
140 
141 /*
142  * dm_vblank_get_counter
143  *
144  * @brief
145  * Get counter for number of vertical blanks
146  *
147  * @param
148  * struct amdgpu_device *adev - [in] desired amdgpu device
149  * int disp_idx - [in] which CRTC to get the counter from
150  *
151  * @return
152  * Counter for vertical blanks
153  */
154 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
155 {
156 	if (crtc >= adev->mode_info.num_crtc)
157 		return 0;
158 	else {
159 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
160 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
161 				acrtc->base.state);
162 
163 
164 		if (acrtc_state->stream == NULL) {
165 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
166 				  crtc);
167 			return 0;
168 		}
169 
170 		return dc_stream_get_vblank_counter(acrtc_state->stream);
171 	}
172 }
173 
174 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
175 				  u32 *vbl, u32 *position)
176 {
177 	uint32_t v_blank_start, v_blank_end, h_position, v_position;
178 
179 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
180 		return -EINVAL;
181 	else {
182 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
183 		struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
184 						acrtc->base.state);
185 
186 		if (acrtc_state->stream ==  NULL) {
187 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
188 				  crtc);
189 			return 0;
190 		}
191 
192 		/*
193 		 * TODO rework base driver to use values directly.
194 		 * for now parse it back into reg-format
195 		 */
196 		dc_stream_get_scanoutpos(acrtc_state->stream,
197 					 &v_blank_start,
198 					 &v_blank_end,
199 					 &h_position,
200 					 &v_position);
201 
202 		*position = v_position | (h_position << 16);
203 		*vbl = v_blank_start | (v_blank_end << 16);
204 	}
205 
206 	return 0;
207 }
208 
209 static bool dm_is_idle(void *handle)
210 {
211 	/* XXX todo */
212 	return true;
213 }
214 
215 static int dm_wait_for_idle(void *handle)
216 {
217 	/* XXX todo */
218 	return 0;
219 }
220 
221 static bool dm_check_soft_reset(void *handle)
222 {
223 	return false;
224 }
225 
226 static int dm_soft_reset(void *handle)
227 {
228 	/* XXX todo */
229 	return 0;
230 }
231 
232 static struct amdgpu_crtc *
233 get_crtc_by_otg_inst(struct amdgpu_device *adev,
234 		     int otg_inst)
235 {
236 	struct drm_device *dev = adev->ddev;
237 	struct drm_crtc *crtc;
238 	struct amdgpu_crtc *amdgpu_crtc;
239 
240 	/*
241 	 * following if is check inherited from both functions where this one is
242 	 * used now. Need to be checked why it could happen.
243 	 */
244 	if (otg_inst == -1) {
245 		WARN_ON(1);
246 		return adev->mode_info.crtcs[0];
247 	}
248 
249 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
250 		amdgpu_crtc = to_amdgpu_crtc(crtc);
251 
252 		if (amdgpu_crtc->otg_inst == otg_inst)
253 			return amdgpu_crtc;
254 	}
255 
256 	return NULL;
257 }
258 
259 static void dm_pflip_high_irq(void *interrupt_params)
260 {
261 	struct amdgpu_crtc *amdgpu_crtc;
262 	struct common_irq_params *irq_params = interrupt_params;
263 	struct amdgpu_device *adev = irq_params->adev;
264 	unsigned long flags;
265 
266 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
267 
268 	/* IRQ could occur when in initial stage */
269 	/*TODO work and BO cleanup */
270 	if (amdgpu_crtc == NULL) {
271 		DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
272 		return;
273 	}
274 
275 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
276 
277 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
278 		DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
279 						 amdgpu_crtc->pflip_status,
280 						 AMDGPU_FLIP_SUBMITTED,
281 						 amdgpu_crtc->crtc_id,
282 						 amdgpu_crtc);
283 		spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
284 		return;
285 	}
286 
287 
288 	/* wakeup usersapce */
289 	if (amdgpu_crtc->event) {
290 		/* Update to correct count/ts if racing with vblank irq */
291 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
292 
293 		drm_crtc_send_vblank_event(&amdgpu_crtc->base, amdgpu_crtc->event);
294 
295 		/* page flip completed. clean up */
296 		amdgpu_crtc->event = NULL;
297 
298 	} else
299 		WARN_ON(1);
300 
301 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
302 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
303 
304 	DRM_DEBUG_DRIVER("%s - crtc :%d[%p], pflip_stat:AMDGPU_FLIP_NONE\n",
305 					__func__, amdgpu_crtc->crtc_id, amdgpu_crtc);
306 
307 	drm_crtc_vblank_put(&amdgpu_crtc->base);
308 }
309 
310 static void dm_crtc_high_irq(void *interrupt_params)
311 {
312 	struct common_irq_params *irq_params = interrupt_params;
313 	struct amdgpu_device *adev = irq_params->adev;
314 	uint8_t crtc_index = 0;
315 	struct amdgpu_crtc *acrtc;
316 
317 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
318 
319 	if (acrtc)
320 		crtc_index = acrtc->crtc_id;
321 
322 	drm_handle_vblank(adev->ddev, crtc_index);
323 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
324 }
325 
326 static int dm_set_clockgating_state(void *handle,
327 		  enum amd_clockgating_state state)
328 {
329 	return 0;
330 }
331 
332 static int dm_set_powergating_state(void *handle,
333 		  enum amd_powergating_state state)
334 {
335 	return 0;
336 }
337 
338 /* Prototypes of private functions */
339 static int dm_early_init(void* handle);
340 
341 static void hotplug_notify_work_func(struct work_struct *work)
342 {
343 	struct amdgpu_display_manager *dm = container_of(work, struct amdgpu_display_manager, mst_hotplug_work);
344 	struct drm_device *dev = dm->ddev;
345 
346 	drm_kms_helper_hotplug_event(dev);
347 }
348 
349 #if defined(CONFIG_DRM_AMD_DC_FBC)
350 /* Allocate memory for FBC compressed data  */
351 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
352 {
353 	struct drm_device *dev = connector->dev;
354 	struct amdgpu_device *adev = dev->dev_private;
355 	struct dm_comressor_info *compressor = &adev->dm.compressor;
356 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
357 	struct drm_display_mode *mode;
358 	unsigned long max_size = 0;
359 
360 	if (adev->dm.dc->fbc_compressor == NULL)
361 		return;
362 
363 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
364 		return;
365 
366 	if (compressor->bo_ptr)
367 		return;
368 
369 
370 	list_for_each_entry(mode, &connector->modes, head) {
371 		if (max_size < mode->htotal * mode->vtotal)
372 			max_size = mode->htotal * mode->vtotal;
373 	}
374 
375 	if (max_size) {
376 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
377 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
378 			    &compressor->gpu_addr, &compressor->cpu_addr);
379 
380 		if (r)
381 			DRM_ERROR("DM: Failed to initialize FBC\n");
382 		else {
383 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
384 			DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
385 		}
386 
387 	}
388 
389 }
390 #endif
391 
392 
393 /* Init display KMS
394  *
395  * Returns 0 on success
396  */
397 static int amdgpu_dm_init(struct amdgpu_device *adev)
398 {
399 	struct dc_init_data init_data;
400 	adev->dm.ddev = adev->ddev;
401 	adev->dm.adev = adev;
402 
403 	/* Zero all the fields */
404 	memset(&init_data, 0, sizeof(init_data));
405 
406 	if(amdgpu_dm_irq_init(adev)) {
407 		DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
408 		goto error;
409 	}
410 
411 	init_data.asic_id.chip_family = adev->family;
412 
413 	init_data.asic_id.pci_revision_id = adev->rev_id;
414 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
415 
416 	init_data.asic_id.vram_width = adev->gmc.vram_width;
417 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
418 	init_data.asic_id.atombios_base_address =
419 		adev->mode_info.atom_context->bios;
420 
421 	init_data.driver = adev;
422 
423 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
424 
425 	if (!adev->dm.cgs_device) {
426 		DRM_ERROR("amdgpu: failed to create cgs device.\n");
427 		goto error;
428 	}
429 
430 	init_data.cgs_device = adev->dm.cgs_device;
431 
432 	adev->dm.dal = NULL;
433 
434 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
435 
436 	if (amdgpu_dc_log)
437 		init_data.log_mask = DC_DEFAULT_LOG_MASK;
438 	else
439 		init_data.log_mask = DC_MIN_LOG_MASK;
440 
441 	/*
442 	 * TODO debug why this doesn't work on Raven
443 	 */
444 	if (adev->flags & AMD_IS_APU &&
445 	    adev->asic_type >= CHIP_CARRIZO &&
446 	    adev->asic_type < CHIP_RAVEN)
447 		init_data.flags.gpu_vm_support = true;
448 
449 	/* Display Core create. */
450 	adev->dm.dc = dc_create(&init_data);
451 
452 	if (adev->dm.dc) {
453 		DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
454 	} else {
455 		DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
456 		goto error;
457 	}
458 
459 	INIT_WORK(&adev->dm.mst_hotplug_work, hotplug_notify_work_func);
460 
461 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
462 	if (!adev->dm.freesync_module) {
463 		DRM_ERROR(
464 		"amdgpu: failed to initialize freesync_module.\n");
465 	} else
466 		DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
467 				adev->dm.freesync_module);
468 
469 	amdgpu_dm_init_color_mod();
470 
471 	if (amdgpu_dm_initialize_drm_device(adev)) {
472 		DRM_ERROR(
473 		"amdgpu: failed to initialize sw for display support.\n");
474 		goto error;
475 	}
476 
477 	/* Update the actual used number of crtc */
478 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
479 
480 	/* TODO: Add_display_info? */
481 
482 	/* TODO use dynamic cursor width */
483 	adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
484 	adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
485 
486 	if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
487 		DRM_ERROR(
488 		"amdgpu: failed to initialize sw for display support.\n");
489 		goto error;
490 	}
491 
492 	DRM_DEBUG_DRIVER("KMS initialized.\n");
493 
494 	return 0;
495 error:
496 	amdgpu_dm_fini(adev);
497 
498 	return -1;
499 }
500 
501 static void amdgpu_dm_fini(struct amdgpu_device *adev)
502 {
503 	amdgpu_dm_destroy_drm_device(&adev->dm);
504 	/*
505 	 * TODO: pageflip, vlank interrupt
506 	 *
507 	 * amdgpu_dm_irq_fini(adev);
508 	 */
509 
510 	if (adev->dm.cgs_device) {
511 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
512 		adev->dm.cgs_device = NULL;
513 	}
514 	if (adev->dm.freesync_module) {
515 		mod_freesync_destroy(adev->dm.freesync_module);
516 		adev->dm.freesync_module = NULL;
517 	}
518 	/* DC Destroy TODO: Replace destroy DAL */
519 	if (adev->dm.dc)
520 		dc_destroy(&adev->dm.dc);
521 	return;
522 }
523 
524 static int dm_sw_init(void *handle)
525 {
526 	return 0;
527 }
528 
529 static int dm_sw_fini(void *handle)
530 {
531 	return 0;
532 }
533 
534 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
535 {
536 	struct amdgpu_dm_connector *aconnector;
537 	struct drm_connector *connector;
538 	int ret = 0;
539 
540 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
541 
542 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
543 		aconnector = to_amdgpu_dm_connector(connector);
544 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
545 		    aconnector->mst_mgr.aux) {
546 			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
547 					aconnector, aconnector->base.base.id);
548 
549 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
550 			if (ret < 0) {
551 				DRM_ERROR("DM_MST: Failed to start MST\n");
552 				((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
553 				return ret;
554 				}
555 			}
556 	}
557 
558 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
559 	return ret;
560 }
561 
562 static int dm_late_init(void *handle)
563 {
564 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
565 
566 	return detect_mst_link_for_all_connectors(adev->ddev);
567 }
568 
569 static void s3_handle_mst(struct drm_device *dev, bool suspend)
570 {
571 	struct amdgpu_dm_connector *aconnector;
572 	struct drm_connector *connector;
573 
574 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
575 
576 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
577 		   aconnector = to_amdgpu_dm_connector(connector);
578 		   if (aconnector->dc_link->type == dc_connection_mst_branch &&
579 				   !aconnector->mst_port) {
580 
581 			   if (suspend)
582 				   drm_dp_mst_topology_mgr_suspend(&aconnector->mst_mgr);
583 			   else
584 				   drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr);
585 		   }
586 	}
587 
588 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
589 }
590 
591 static int dm_hw_init(void *handle)
592 {
593 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
594 	/* Create DAL display manager */
595 	amdgpu_dm_init(adev);
596 	amdgpu_dm_hpd_init(adev);
597 
598 	return 0;
599 }
600 
601 static int dm_hw_fini(void *handle)
602 {
603 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
604 
605 	amdgpu_dm_hpd_fini(adev);
606 
607 	amdgpu_dm_irq_fini(adev);
608 	amdgpu_dm_fini(adev);
609 	return 0;
610 }
611 
612 static int dm_suspend(void *handle)
613 {
614 	struct amdgpu_device *adev = handle;
615 	struct amdgpu_display_manager *dm = &adev->dm;
616 	int ret = 0;
617 
618 	s3_handle_mst(adev->ddev, true);
619 
620 	amdgpu_dm_irq_suspend(adev);
621 
622 	WARN_ON(adev->dm.cached_state);
623 	adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
624 
625 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
626 
627 	return ret;
628 }
629 
630 static struct amdgpu_dm_connector *
631 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
632 					     struct drm_crtc *crtc)
633 {
634 	uint32_t i;
635 	struct drm_connector_state *new_con_state;
636 	struct drm_connector *connector;
637 	struct drm_crtc *crtc_from_state;
638 
639 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
640 		crtc_from_state = new_con_state->crtc;
641 
642 		if (crtc_from_state == crtc)
643 			return to_amdgpu_dm_connector(connector);
644 	}
645 
646 	return NULL;
647 }
648 
649 static int dm_resume(void *handle)
650 {
651 	struct amdgpu_device *adev = handle;
652 	struct amdgpu_display_manager *dm = &adev->dm;
653 	int ret = 0;
654 
655 	/* power on hardware */
656 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
657 
658 	ret = amdgpu_dm_display_resume(adev);
659 	return ret;
660 }
661 
662 int amdgpu_dm_display_resume(struct amdgpu_device *adev)
663 {
664 	struct drm_device *ddev = adev->ddev;
665 	struct amdgpu_display_manager *dm = &adev->dm;
666 	struct amdgpu_dm_connector *aconnector;
667 	struct drm_connector *connector;
668 	struct drm_crtc *crtc;
669 	struct drm_crtc_state *new_crtc_state;
670 	struct dm_crtc_state *dm_new_crtc_state;
671 	struct drm_plane *plane;
672 	struct drm_plane_state *new_plane_state;
673 	struct dm_plane_state *dm_new_plane_state;
674 
675 	int ret = 0;
676 	int i;
677 
678 	/* program HPD filter */
679 	dc_resume(dm->dc);
680 
681 	/* On resume we need to  rewrite the MSTM control bits to enamble MST*/
682 	s3_handle_mst(ddev, false);
683 
684 	/*
685 	 * early enable HPD Rx IRQ, should be done before set mode as short
686 	 * pulse interrupts are used for MST
687 	 */
688 	amdgpu_dm_irq_resume_early(adev);
689 
690 	/* Do detection*/
691 	list_for_each_entry(connector,
692 			&ddev->mode_config.connector_list, head) {
693 		aconnector = to_amdgpu_dm_connector(connector);
694 
695 		/*
696 		 * this is the case when traversing through already created
697 		 * MST connectors, should be skipped
698 		 */
699 		if (aconnector->mst_port)
700 			continue;
701 
702 		mutex_lock(&aconnector->hpd_lock);
703 		dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
704 
705 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
706 			aconnector->fake_enable = false;
707 
708 		aconnector->dc_sink = NULL;
709 		amdgpu_dm_update_connector_after_detect(aconnector);
710 		mutex_unlock(&aconnector->hpd_lock);
711 	}
712 
713 	/* Force mode set in atomic comit */
714 	for_each_new_crtc_in_state(adev->dm.cached_state, crtc, new_crtc_state, i)
715 		new_crtc_state->active_changed = true;
716 
717 	/*
718 	 * atomic_check is expected to create the dc states. We need to release
719 	 * them here, since they were duplicated as part of the suspend
720 	 * procedure.
721 	 */
722 	for_each_new_crtc_in_state(adev->dm.cached_state, crtc, new_crtc_state, i) {
723 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
724 		if (dm_new_crtc_state->stream) {
725 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
726 			dc_stream_release(dm_new_crtc_state->stream);
727 			dm_new_crtc_state->stream = NULL;
728 		}
729 	}
730 
731 	for_each_new_plane_in_state(adev->dm.cached_state, plane, new_plane_state, i) {
732 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
733 		if (dm_new_plane_state->dc_state) {
734 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
735 			dc_plane_state_release(dm_new_plane_state->dc_state);
736 			dm_new_plane_state->dc_state = NULL;
737 		}
738 	}
739 
740 	ret = drm_atomic_helper_resume(ddev, adev->dm.cached_state);
741 
742 	adev->dm.cached_state = NULL;
743 
744 	amdgpu_dm_irq_resume_late(adev);
745 
746 	return ret;
747 }
748 
749 static const struct amd_ip_funcs amdgpu_dm_funcs = {
750 	.name = "dm",
751 	.early_init = dm_early_init,
752 	.late_init = dm_late_init,
753 	.sw_init = dm_sw_init,
754 	.sw_fini = dm_sw_fini,
755 	.hw_init = dm_hw_init,
756 	.hw_fini = dm_hw_fini,
757 	.suspend = dm_suspend,
758 	.resume = dm_resume,
759 	.is_idle = dm_is_idle,
760 	.wait_for_idle = dm_wait_for_idle,
761 	.check_soft_reset = dm_check_soft_reset,
762 	.soft_reset = dm_soft_reset,
763 	.set_clockgating_state = dm_set_clockgating_state,
764 	.set_powergating_state = dm_set_powergating_state,
765 };
766 
767 const struct amdgpu_ip_block_version dm_ip_block =
768 {
769 	.type = AMD_IP_BLOCK_TYPE_DCE,
770 	.major = 1,
771 	.minor = 0,
772 	.rev = 0,
773 	.funcs = &amdgpu_dm_funcs,
774 };
775 
776 
777 static struct drm_atomic_state *
778 dm_atomic_state_alloc(struct drm_device *dev)
779 {
780 	struct dm_atomic_state *state = kzalloc(sizeof(*state), GFP_KERNEL);
781 
782 	if (!state)
783 		return NULL;
784 
785 	if (drm_atomic_state_init(dev, &state->base) < 0)
786 		goto fail;
787 
788 	return &state->base;
789 
790 fail:
791 	kfree(state);
792 	return NULL;
793 }
794 
795 static void
796 dm_atomic_state_clear(struct drm_atomic_state *state)
797 {
798 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
799 
800 	if (dm_state->context) {
801 		dc_release_state(dm_state->context);
802 		dm_state->context = NULL;
803 	}
804 
805 	drm_atomic_state_default_clear(state);
806 }
807 
808 static void
809 dm_atomic_state_alloc_free(struct drm_atomic_state *state)
810 {
811 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
812 	drm_atomic_state_default_release(state);
813 	kfree(dm_state);
814 }
815 
816 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
817 	.fb_create = amdgpu_display_user_framebuffer_create,
818 	.output_poll_changed = drm_fb_helper_output_poll_changed,
819 	.atomic_check = amdgpu_dm_atomic_check,
820 	.atomic_commit = amdgpu_dm_atomic_commit,
821 	.atomic_state_alloc = dm_atomic_state_alloc,
822 	.atomic_state_clear = dm_atomic_state_clear,
823 	.atomic_state_free = dm_atomic_state_alloc_free
824 };
825 
826 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
827 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail
828 };
829 
830 static void
831 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
832 {
833 	struct drm_connector *connector = &aconnector->base;
834 	struct drm_device *dev = connector->dev;
835 	struct dc_sink *sink;
836 
837 	/* MST handled by drm_mst framework */
838 	if (aconnector->mst_mgr.mst_state == true)
839 		return;
840 
841 
842 	sink = aconnector->dc_link->local_sink;
843 
844 	/* Edid mgmt connector gets first update only in mode_valid hook and then
845 	 * the connector sink is set to either fake or physical sink depends on link status.
846 	 * don't do it here if u are during boot
847 	 */
848 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
849 			&& aconnector->dc_em_sink) {
850 
851 		/* For S3 resume with headless use eml_sink to fake stream
852 		 * because on resume connecotr->sink is set ti NULL
853 		 */
854 		mutex_lock(&dev->mode_config.mutex);
855 
856 		if (sink) {
857 			if (aconnector->dc_sink) {
858 				amdgpu_dm_remove_sink_from_freesync_module(
859 								connector);
860 				/* retain and release bellow are used for
861 				 * bump up refcount for sink because the link don't point
862 				 * to it anymore after disconnect so on next crtc to connector
863 				 * reshuffle by UMD we will get into unwanted dc_sink release
864 				 */
865 				if (aconnector->dc_sink != aconnector->dc_em_sink)
866 					dc_sink_release(aconnector->dc_sink);
867 			}
868 			aconnector->dc_sink = sink;
869 			amdgpu_dm_add_sink_to_freesync_module(
870 						connector, aconnector->edid);
871 		} else {
872 			amdgpu_dm_remove_sink_from_freesync_module(connector);
873 			if (!aconnector->dc_sink)
874 				aconnector->dc_sink = aconnector->dc_em_sink;
875 			else if (aconnector->dc_sink != aconnector->dc_em_sink)
876 				dc_sink_retain(aconnector->dc_sink);
877 		}
878 
879 		mutex_unlock(&dev->mode_config.mutex);
880 		return;
881 	}
882 
883 	/*
884 	 * TODO: temporary guard to look for proper fix
885 	 * if this sink is MST sink, we should not do anything
886 	 */
887 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
888 		return;
889 
890 	if (aconnector->dc_sink == sink) {
891 		/* We got a DP short pulse (Link Loss, DP CTS, etc...).
892 		 * Do nothing!! */
893 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
894 				aconnector->connector_id);
895 		return;
896 	}
897 
898 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
899 		aconnector->connector_id, aconnector->dc_sink, sink);
900 
901 	mutex_lock(&dev->mode_config.mutex);
902 
903 	/* 1. Update status of the drm connector
904 	 * 2. Send an event and let userspace tell us what to do */
905 	if (sink) {
906 		/* TODO: check if we still need the S3 mode update workaround.
907 		 * If yes, put it here. */
908 		if (aconnector->dc_sink)
909 			amdgpu_dm_remove_sink_from_freesync_module(
910 							connector);
911 
912 		aconnector->dc_sink = sink;
913 		if (sink->dc_edid.length == 0) {
914 			aconnector->edid = NULL;
915 		} else {
916 			aconnector->edid =
917 				(struct edid *) sink->dc_edid.raw_edid;
918 
919 
920 			drm_mode_connector_update_edid_property(connector,
921 					aconnector->edid);
922 		}
923 		amdgpu_dm_add_sink_to_freesync_module(connector, aconnector->edid);
924 
925 	} else {
926 		amdgpu_dm_remove_sink_from_freesync_module(connector);
927 		drm_mode_connector_update_edid_property(connector, NULL);
928 		aconnector->num_modes = 0;
929 		aconnector->dc_sink = NULL;
930 	}
931 
932 	mutex_unlock(&dev->mode_config.mutex);
933 }
934 
935 static void handle_hpd_irq(void *param)
936 {
937 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
938 	struct drm_connector *connector = &aconnector->base;
939 	struct drm_device *dev = connector->dev;
940 
941 	/* In case of failure or MST no need to update connector status or notify the OS
942 	 * since (for MST case) MST does this in it's own context.
943 	 */
944 	mutex_lock(&aconnector->hpd_lock);
945 
946 	if (aconnector->fake_enable)
947 		aconnector->fake_enable = false;
948 
949 	if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
950 		amdgpu_dm_update_connector_after_detect(aconnector);
951 
952 
953 		drm_modeset_lock_all(dev);
954 		dm_restore_drm_connector_state(dev, connector);
955 		drm_modeset_unlock_all(dev);
956 
957 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
958 			drm_kms_helper_hotplug_event(dev);
959 	}
960 	mutex_unlock(&aconnector->hpd_lock);
961 
962 }
963 
964 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
965 {
966 	uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
967 	uint8_t dret;
968 	bool new_irq_handled = false;
969 	int dpcd_addr;
970 	int dpcd_bytes_to_read;
971 
972 	const int max_process_count = 30;
973 	int process_count = 0;
974 
975 	const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
976 
977 	if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
978 		dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
979 		/* DPCD 0x200 - 0x201 for downstream IRQ */
980 		dpcd_addr = DP_SINK_COUNT;
981 	} else {
982 		dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
983 		/* DPCD 0x2002 - 0x2005 for downstream IRQ */
984 		dpcd_addr = DP_SINK_COUNT_ESI;
985 	}
986 
987 	dret = drm_dp_dpcd_read(
988 		&aconnector->dm_dp_aux.aux,
989 		dpcd_addr,
990 		esi,
991 		dpcd_bytes_to_read);
992 
993 	while (dret == dpcd_bytes_to_read &&
994 		process_count < max_process_count) {
995 		uint8_t retry;
996 		dret = 0;
997 
998 		process_count++;
999 
1000 		DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1001 		/* handle HPD short pulse irq */
1002 		if (aconnector->mst_mgr.mst_state)
1003 			drm_dp_mst_hpd_irq(
1004 				&aconnector->mst_mgr,
1005 				esi,
1006 				&new_irq_handled);
1007 
1008 		if (new_irq_handled) {
1009 			/* ACK at DPCD to notify down stream */
1010 			const int ack_dpcd_bytes_to_write =
1011 				dpcd_bytes_to_read - 1;
1012 
1013 			for (retry = 0; retry < 3; retry++) {
1014 				uint8_t wret;
1015 
1016 				wret = drm_dp_dpcd_write(
1017 					&aconnector->dm_dp_aux.aux,
1018 					dpcd_addr + 1,
1019 					&esi[1],
1020 					ack_dpcd_bytes_to_write);
1021 				if (wret == ack_dpcd_bytes_to_write)
1022 					break;
1023 			}
1024 
1025 			/* check if there is new irq to be handle */
1026 			dret = drm_dp_dpcd_read(
1027 				&aconnector->dm_dp_aux.aux,
1028 				dpcd_addr,
1029 				esi,
1030 				dpcd_bytes_to_read);
1031 
1032 			new_irq_handled = false;
1033 		} else {
1034 			break;
1035 		}
1036 	}
1037 
1038 	if (process_count == max_process_count)
1039 		DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1040 }
1041 
1042 static void handle_hpd_rx_irq(void *param)
1043 {
1044 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1045 	struct drm_connector *connector = &aconnector->base;
1046 	struct drm_device *dev = connector->dev;
1047 	struct dc_link *dc_link = aconnector->dc_link;
1048 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1049 
1050 	/* TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1051 	 * conflict, after implement i2c helper, this mutex should be
1052 	 * retired.
1053 	 */
1054 	if (dc_link->type != dc_connection_mst_branch)
1055 		mutex_lock(&aconnector->hpd_lock);
1056 
1057 	if (dc_link_handle_hpd_rx_irq(dc_link, NULL) &&
1058 			!is_mst_root_connector) {
1059 		/* Downstream Port status changed. */
1060 		if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1061 
1062 			if (aconnector->fake_enable)
1063 				aconnector->fake_enable = false;
1064 
1065 			amdgpu_dm_update_connector_after_detect(aconnector);
1066 
1067 
1068 			drm_modeset_lock_all(dev);
1069 			dm_restore_drm_connector_state(dev, connector);
1070 			drm_modeset_unlock_all(dev);
1071 
1072 			drm_kms_helper_hotplug_event(dev);
1073 		}
1074 	}
1075 	if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1076 	    (dc_link->type == dc_connection_mst_branch))
1077 		dm_handle_hpd_rx_irq(aconnector);
1078 
1079 	if (dc_link->type != dc_connection_mst_branch)
1080 		mutex_unlock(&aconnector->hpd_lock);
1081 }
1082 
1083 static void register_hpd_handlers(struct amdgpu_device *adev)
1084 {
1085 	struct drm_device *dev = adev->ddev;
1086 	struct drm_connector *connector;
1087 	struct amdgpu_dm_connector *aconnector;
1088 	const struct dc_link *dc_link;
1089 	struct dc_interrupt_params int_params = {0};
1090 
1091 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1092 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1093 
1094 	list_for_each_entry(connector,
1095 			&dev->mode_config.connector_list, head)	{
1096 
1097 		aconnector = to_amdgpu_dm_connector(connector);
1098 		dc_link = aconnector->dc_link;
1099 
1100 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1101 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1102 			int_params.irq_source = dc_link->irq_source_hpd;
1103 
1104 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1105 					handle_hpd_irq,
1106 					(void *) aconnector);
1107 		}
1108 
1109 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1110 
1111 			/* Also register for DP short pulse (hpd_rx). */
1112 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1113 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
1114 
1115 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
1116 					handle_hpd_rx_irq,
1117 					(void *) aconnector);
1118 		}
1119 	}
1120 }
1121 
1122 /* Register IRQ sources and initialize IRQ callbacks */
1123 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1124 {
1125 	struct dc *dc = adev->dm.dc;
1126 	struct common_irq_params *c_irq_params;
1127 	struct dc_interrupt_params int_params = {0};
1128 	int r;
1129 	int i;
1130 	unsigned client_id = AMDGPU_IH_CLIENTID_LEGACY;
1131 
1132 	if (adev->asic_type == CHIP_VEGA10 ||
1133 	    adev->asic_type == CHIP_RAVEN)
1134 		client_id = SOC15_IH_CLIENTID_DCE;
1135 
1136 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1137 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1138 
1139 	/* Actions of amdgpu_irq_add_id():
1140 	 * 1. Register a set() function with base driver.
1141 	 *    Base driver will call set() function to enable/disable an
1142 	 *    interrupt in DC hardware.
1143 	 * 2. Register amdgpu_dm_irq_handler().
1144 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1145 	 *    coming from DC hardware.
1146 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1147 	 *    for acknowledging and handling. */
1148 
1149 	/* Use VBLANK interrupt */
1150 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1151 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1152 		if (r) {
1153 			DRM_ERROR("Failed to add crtc irq id!\n");
1154 			return r;
1155 		}
1156 
1157 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1158 		int_params.irq_source =
1159 			dc_interrupt_to_irq_source(dc, i, 0);
1160 
1161 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1162 
1163 		c_irq_params->adev = adev;
1164 		c_irq_params->irq_src = int_params.irq_source;
1165 
1166 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1167 				dm_crtc_high_irq, c_irq_params);
1168 	}
1169 
1170 	/* Use GRPH_PFLIP interrupt */
1171 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1172 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1173 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1174 		if (r) {
1175 			DRM_ERROR("Failed to add page flip irq id!\n");
1176 			return r;
1177 		}
1178 
1179 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1180 		int_params.irq_source =
1181 			dc_interrupt_to_irq_source(dc, i, 0);
1182 
1183 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1184 
1185 		c_irq_params->adev = adev;
1186 		c_irq_params->irq_src = int_params.irq_source;
1187 
1188 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1189 				dm_pflip_high_irq, c_irq_params);
1190 
1191 	}
1192 
1193 	/* HPD */
1194 	r = amdgpu_irq_add_id(adev, client_id,
1195 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1196 	if (r) {
1197 		DRM_ERROR("Failed to add hpd irq id!\n");
1198 		return r;
1199 	}
1200 
1201 	register_hpd_handlers(adev);
1202 
1203 	return 0;
1204 }
1205 
1206 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1207 /* Register IRQ sources and initialize IRQ callbacks */
1208 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1209 {
1210 	struct dc *dc = adev->dm.dc;
1211 	struct common_irq_params *c_irq_params;
1212 	struct dc_interrupt_params int_params = {0};
1213 	int r;
1214 	int i;
1215 
1216 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1217 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1218 
1219 	/* Actions of amdgpu_irq_add_id():
1220 	 * 1. Register a set() function with base driver.
1221 	 *    Base driver will call set() function to enable/disable an
1222 	 *    interrupt in DC hardware.
1223 	 * 2. Register amdgpu_dm_irq_handler().
1224 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1225 	 *    coming from DC hardware.
1226 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1227 	 *    for acknowledging and handling.
1228 	 * */
1229 
1230 	/* Use VSTARTUP interrupt */
1231 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1232 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1233 			i++) {
1234 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1235 
1236 		if (r) {
1237 			DRM_ERROR("Failed to add crtc irq id!\n");
1238 			return r;
1239 		}
1240 
1241 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1242 		int_params.irq_source =
1243 			dc_interrupt_to_irq_source(dc, i, 0);
1244 
1245 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1246 
1247 		c_irq_params->adev = adev;
1248 		c_irq_params->irq_src = int_params.irq_source;
1249 
1250 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1251 				dm_crtc_high_irq, c_irq_params);
1252 	}
1253 
1254 	/* Use GRPH_PFLIP interrupt */
1255 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1256 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1257 			i++) {
1258 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1259 		if (r) {
1260 			DRM_ERROR("Failed to add page flip irq id!\n");
1261 			return r;
1262 		}
1263 
1264 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1265 		int_params.irq_source =
1266 			dc_interrupt_to_irq_source(dc, i, 0);
1267 
1268 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1269 
1270 		c_irq_params->adev = adev;
1271 		c_irq_params->irq_src = int_params.irq_source;
1272 
1273 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
1274 				dm_pflip_high_irq, c_irq_params);
1275 
1276 	}
1277 
1278 	/* HPD */
1279 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1280 			&adev->hpd_irq);
1281 	if (r) {
1282 		DRM_ERROR("Failed to add hpd irq id!\n");
1283 		return r;
1284 	}
1285 
1286 	register_hpd_handlers(adev);
1287 
1288 	return 0;
1289 }
1290 #endif
1291 
1292 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1293 {
1294 	int r;
1295 
1296 	adev->mode_info.mode_config_initialized = true;
1297 
1298 	adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1299 	adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1300 
1301 	adev->ddev->mode_config.max_width = 16384;
1302 	adev->ddev->mode_config.max_height = 16384;
1303 
1304 	adev->ddev->mode_config.preferred_depth = 24;
1305 	adev->ddev->mode_config.prefer_shadow = 1;
1306 	/* indicate support of immediate flip */
1307 	adev->ddev->mode_config.async_page_flip = true;
1308 
1309 	adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1310 
1311 	r = amdgpu_display_modeset_create_props(adev);
1312 	if (r)
1313 		return r;
1314 
1315 	return 0;
1316 }
1317 
1318 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1319 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1320 
1321 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1322 {
1323 	struct amdgpu_display_manager *dm = bl_get_data(bd);
1324 
1325 	if (dc_link_set_backlight_level(dm->backlight_link,
1326 			bd->props.brightness, 0, 0))
1327 		return 0;
1328 	else
1329 		return 1;
1330 }
1331 
1332 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1333 {
1334 	return bd->props.brightness;
1335 }
1336 
1337 static const struct backlight_ops amdgpu_dm_backlight_ops = {
1338 	.get_brightness = amdgpu_dm_backlight_get_brightness,
1339 	.update_status	= amdgpu_dm_backlight_update_status,
1340 };
1341 
1342 static void
1343 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1344 {
1345 	char bl_name[16];
1346 	struct backlight_properties props = { 0 };
1347 
1348 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1349 	props.type = BACKLIGHT_RAW;
1350 
1351 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1352 			dm->adev->ddev->primary->index);
1353 
1354 	dm->backlight_dev = backlight_device_register(bl_name,
1355 			dm->adev->ddev->dev,
1356 			dm,
1357 			&amdgpu_dm_backlight_ops,
1358 			&props);
1359 
1360 	if (IS_ERR(dm->backlight_dev))
1361 		DRM_ERROR("DM: Backlight registration failed!\n");
1362 	else
1363 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1364 }
1365 
1366 #endif
1367 
1368 static int initialize_plane(struct amdgpu_display_manager *dm,
1369 			     struct amdgpu_mode_info *mode_info,
1370 			     int plane_id)
1371 {
1372 	struct amdgpu_plane *plane;
1373 	unsigned long possible_crtcs;
1374 	int ret = 0;
1375 
1376 	plane = kzalloc(sizeof(struct amdgpu_plane), GFP_KERNEL);
1377 	mode_info->planes[plane_id] = plane;
1378 
1379 	if (!plane) {
1380 		DRM_ERROR("KMS: Failed to allocate plane\n");
1381 		return -ENOMEM;
1382 	}
1383 	plane->base.type = mode_info->plane_type[plane_id];
1384 
1385 	/*
1386 	 * HACK: IGT tests expect that each plane can only have one
1387 	 * one possible CRTC. For now, set one CRTC for each
1388 	 * plane that is not an underlay, but still allow multiple
1389 	 * CRTCs for underlay planes.
1390 	 */
1391 	possible_crtcs = 1 << plane_id;
1392 	if (plane_id >= dm->dc->caps.max_streams)
1393 		possible_crtcs = 0xff;
1394 
1395 	ret = amdgpu_dm_plane_init(dm, mode_info->planes[plane_id], possible_crtcs);
1396 
1397 	if (ret) {
1398 		DRM_ERROR("KMS: Failed to initialize plane\n");
1399 		return ret;
1400 	}
1401 
1402 	return ret;
1403 }
1404 
1405 /* In this architecture, the association
1406  * connector -> encoder -> crtc
1407  * id not really requried. The crtc and connector will hold the
1408  * display_index as an abstraction to use with DAL component
1409  *
1410  * Returns 0 on success
1411  */
1412 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
1413 {
1414 	struct amdgpu_display_manager *dm = &adev->dm;
1415 	int32_t i;
1416 	struct amdgpu_dm_connector *aconnector = NULL;
1417 	struct amdgpu_encoder *aencoder = NULL;
1418 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
1419 	uint32_t link_cnt;
1420 	int32_t total_overlay_planes, total_primary_planes;
1421 
1422 	link_cnt = dm->dc->caps.max_links;
1423 	if (amdgpu_dm_mode_config_init(dm->adev)) {
1424 		DRM_ERROR("DM: Failed to initialize mode config\n");
1425 		return -1;
1426 	}
1427 
1428 	/* Identify the number of planes to be initialized */
1429 	total_overlay_planes = dm->dc->caps.max_slave_planes;
1430 	total_primary_planes = dm->dc->caps.max_planes - dm->dc->caps.max_slave_planes;
1431 
1432 	/* First initialize overlay planes, index starting after primary planes */
1433 	for (i = (total_overlay_planes - 1); i >= 0; i--) {
1434 		if (initialize_plane(dm, mode_info, (total_primary_planes + i))) {
1435 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
1436 			goto fail;
1437 		}
1438 	}
1439 
1440 	/* Initialize primary planes */
1441 	for (i = (total_primary_planes - 1); i >= 0; i--) {
1442 		if (initialize_plane(dm, mode_info, i)) {
1443 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
1444 			goto fail;
1445 		}
1446 	}
1447 
1448 	for (i = 0; i < dm->dc->caps.max_streams; i++)
1449 		if (amdgpu_dm_crtc_init(dm, &mode_info->planes[i]->base, i)) {
1450 			DRM_ERROR("KMS: Failed to initialize crtc\n");
1451 			goto fail;
1452 		}
1453 
1454 	dm->display_indexes_num = dm->dc->caps.max_streams;
1455 
1456 	/* loops over all connectors on the board */
1457 	for (i = 0; i < link_cnt; i++) {
1458 
1459 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
1460 			DRM_ERROR(
1461 				"KMS: Cannot support more than %d display indexes\n",
1462 					AMDGPU_DM_MAX_DISPLAY_INDEX);
1463 			continue;
1464 		}
1465 
1466 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
1467 		if (!aconnector)
1468 			goto fail;
1469 
1470 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
1471 		if (!aencoder)
1472 			goto fail;
1473 
1474 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
1475 			DRM_ERROR("KMS: Failed to initialize encoder\n");
1476 			goto fail;
1477 		}
1478 
1479 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
1480 			DRM_ERROR("KMS: Failed to initialize connector\n");
1481 			goto fail;
1482 		}
1483 
1484 		if (dc_link_detect(dc_get_link_at_index(dm->dc, i),
1485 				DETECT_REASON_BOOT))
1486 			amdgpu_dm_update_connector_after_detect(aconnector);
1487 	}
1488 
1489 	/* Software is initialized. Now we can register interrupt handlers. */
1490 	switch (adev->asic_type) {
1491 	case CHIP_BONAIRE:
1492 	case CHIP_HAWAII:
1493 	case CHIP_KAVERI:
1494 	case CHIP_KABINI:
1495 	case CHIP_MULLINS:
1496 	case CHIP_TONGA:
1497 	case CHIP_FIJI:
1498 	case CHIP_CARRIZO:
1499 	case CHIP_STONEY:
1500 	case CHIP_POLARIS11:
1501 	case CHIP_POLARIS10:
1502 	case CHIP_POLARIS12:
1503 	case CHIP_VEGA10:
1504 		if (dce110_register_irq_handlers(dm->adev)) {
1505 			DRM_ERROR("DM: Failed to initialize IRQ\n");
1506 			goto fail;
1507 		}
1508 		break;
1509 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1510 	case CHIP_RAVEN:
1511 		if (dcn10_register_irq_handlers(dm->adev)) {
1512 			DRM_ERROR("DM: Failed to initialize IRQ\n");
1513 			goto fail;
1514 		}
1515 		/*
1516 		 * Temporary disable until pplib/smu interaction is implemented
1517 		 */
1518 		dm->dc->debug.disable_stutter = true;
1519 		break;
1520 #endif
1521 	default:
1522 		DRM_ERROR("Usupported ASIC type: 0x%X\n", adev->asic_type);
1523 		goto fail;
1524 	}
1525 
1526 	return 0;
1527 fail:
1528 	kfree(aencoder);
1529 	kfree(aconnector);
1530 	for (i = 0; i < dm->dc->caps.max_planes; i++)
1531 		kfree(mode_info->planes[i]);
1532 	return -1;
1533 }
1534 
1535 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
1536 {
1537 	drm_mode_config_cleanup(dm->ddev);
1538 	return;
1539 }
1540 
1541 /******************************************************************************
1542  * amdgpu_display_funcs functions
1543  *****************************************************************************/
1544 
1545 /**
1546  * dm_bandwidth_update - program display watermarks
1547  *
1548  * @adev: amdgpu_device pointer
1549  *
1550  * Calculate and program the display watermarks and line buffer allocation.
1551  */
1552 static void dm_bandwidth_update(struct amdgpu_device *adev)
1553 {
1554 	/* TODO: implement later */
1555 }
1556 
1557 static void dm_set_backlight_level(struct amdgpu_encoder *amdgpu_encoder,
1558 				     u8 level)
1559 {
1560 	/* TODO: translate amdgpu_encoder to display_index and call DAL */
1561 }
1562 
1563 static u8 dm_get_backlight_level(struct amdgpu_encoder *amdgpu_encoder)
1564 {
1565 	/* TODO: translate amdgpu_encoder to display_index and call DAL */
1566 	return 0;
1567 }
1568 
1569 static int amdgpu_notify_freesync(struct drm_device *dev, void *data,
1570 				struct drm_file *filp)
1571 {
1572 	struct mod_freesync_params freesync_params;
1573 	uint8_t num_streams;
1574 	uint8_t i;
1575 
1576 	struct amdgpu_device *adev = dev->dev_private;
1577 	int r = 0;
1578 
1579 	/* Get freesync enable flag from DRM */
1580 
1581 	num_streams = dc_get_current_stream_count(adev->dm.dc);
1582 
1583 	for (i = 0; i < num_streams; i++) {
1584 		struct dc_stream_state *stream;
1585 		stream = dc_get_stream_at_index(adev->dm.dc, i);
1586 
1587 		mod_freesync_update_state(adev->dm.freesync_module,
1588 					  &stream, 1, &freesync_params);
1589 	}
1590 
1591 	return r;
1592 }
1593 
1594 static const struct amdgpu_display_funcs dm_display_funcs = {
1595 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
1596 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
1597 	.backlight_set_level =
1598 		dm_set_backlight_level,/* called unconditionally */
1599 	.backlight_get_level =
1600 		dm_get_backlight_level,/* called unconditionally */
1601 	.hpd_sense = NULL,/* called unconditionally */
1602 	.hpd_set_polarity = NULL, /* called unconditionally */
1603 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
1604 	.page_flip_get_scanoutpos =
1605 		dm_crtc_get_scanoutpos,/* called unconditionally */
1606 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
1607 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
1608 	.notify_freesync = amdgpu_notify_freesync,
1609 
1610 };
1611 
1612 #if defined(CONFIG_DEBUG_KERNEL_DC)
1613 
1614 static ssize_t s3_debug_store(struct device *device,
1615 			      struct device_attribute *attr,
1616 			      const char *buf,
1617 			      size_t count)
1618 {
1619 	int ret;
1620 	int s3_state;
1621 	struct pci_dev *pdev = to_pci_dev(device);
1622 	struct drm_device *drm_dev = pci_get_drvdata(pdev);
1623 	struct amdgpu_device *adev = drm_dev->dev_private;
1624 
1625 	ret = kstrtoint(buf, 0, &s3_state);
1626 
1627 	if (ret == 0) {
1628 		if (s3_state) {
1629 			dm_resume(adev);
1630 			amdgpu_dm_display_resume(adev);
1631 			drm_kms_helper_hotplug_event(adev->ddev);
1632 		} else
1633 			dm_suspend(adev);
1634 	}
1635 
1636 	return ret == 0 ? count : 0;
1637 }
1638 
1639 DEVICE_ATTR_WO(s3_debug);
1640 
1641 #endif
1642 
1643 static int dm_early_init(void *handle)
1644 {
1645 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1646 
1647 	switch (adev->asic_type) {
1648 	case CHIP_BONAIRE:
1649 	case CHIP_HAWAII:
1650 		adev->mode_info.num_crtc = 6;
1651 		adev->mode_info.num_hpd = 6;
1652 		adev->mode_info.num_dig = 6;
1653 		adev->mode_info.plane_type = dm_plane_type_default;
1654 		break;
1655 	case CHIP_KAVERI:
1656 		adev->mode_info.num_crtc = 4;
1657 		adev->mode_info.num_hpd = 6;
1658 		adev->mode_info.num_dig = 7;
1659 		adev->mode_info.plane_type = dm_plane_type_default;
1660 		break;
1661 	case CHIP_KABINI:
1662 	case CHIP_MULLINS:
1663 		adev->mode_info.num_crtc = 2;
1664 		adev->mode_info.num_hpd = 6;
1665 		adev->mode_info.num_dig = 6;
1666 		adev->mode_info.plane_type = dm_plane_type_default;
1667 		break;
1668 	case CHIP_FIJI:
1669 	case CHIP_TONGA:
1670 		adev->mode_info.num_crtc = 6;
1671 		adev->mode_info.num_hpd = 6;
1672 		adev->mode_info.num_dig = 7;
1673 		adev->mode_info.plane_type = dm_plane_type_default;
1674 		break;
1675 	case CHIP_CARRIZO:
1676 		adev->mode_info.num_crtc = 3;
1677 		adev->mode_info.num_hpd = 6;
1678 		adev->mode_info.num_dig = 9;
1679 		adev->mode_info.plane_type = dm_plane_type_carizzo;
1680 		break;
1681 	case CHIP_STONEY:
1682 		adev->mode_info.num_crtc = 2;
1683 		adev->mode_info.num_hpd = 6;
1684 		adev->mode_info.num_dig = 9;
1685 		adev->mode_info.plane_type = dm_plane_type_stoney;
1686 		break;
1687 	case CHIP_POLARIS11:
1688 	case CHIP_POLARIS12:
1689 		adev->mode_info.num_crtc = 5;
1690 		adev->mode_info.num_hpd = 5;
1691 		adev->mode_info.num_dig = 5;
1692 		adev->mode_info.plane_type = dm_plane_type_default;
1693 		break;
1694 	case CHIP_POLARIS10:
1695 		adev->mode_info.num_crtc = 6;
1696 		adev->mode_info.num_hpd = 6;
1697 		adev->mode_info.num_dig = 6;
1698 		adev->mode_info.plane_type = dm_plane_type_default;
1699 		break;
1700 	case CHIP_VEGA10:
1701 		adev->mode_info.num_crtc = 6;
1702 		adev->mode_info.num_hpd = 6;
1703 		adev->mode_info.num_dig = 6;
1704 		adev->mode_info.plane_type = dm_plane_type_default;
1705 		break;
1706 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1707 	case CHIP_RAVEN:
1708 		adev->mode_info.num_crtc = 4;
1709 		adev->mode_info.num_hpd = 4;
1710 		adev->mode_info.num_dig = 4;
1711 		adev->mode_info.plane_type = dm_plane_type_default;
1712 		break;
1713 #endif
1714 	default:
1715 		DRM_ERROR("Usupported ASIC type: 0x%X\n", adev->asic_type);
1716 		return -EINVAL;
1717 	}
1718 
1719 	amdgpu_dm_set_irq_funcs(adev);
1720 
1721 	if (adev->mode_info.funcs == NULL)
1722 		adev->mode_info.funcs = &dm_display_funcs;
1723 
1724 	/* Note: Do NOT change adev->audio_endpt_rreg and
1725 	 * adev->audio_endpt_wreg because they are initialised in
1726 	 * amdgpu_device_init() */
1727 #if defined(CONFIG_DEBUG_KERNEL_DC)
1728 	device_create_file(
1729 		adev->ddev->dev,
1730 		&dev_attr_s3_debug);
1731 #endif
1732 
1733 	return 0;
1734 }
1735 
1736 static bool modeset_required(struct drm_crtc_state *crtc_state,
1737 			     struct dc_stream_state *new_stream,
1738 			     struct dc_stream_state *old_stream)
1739 {
1740 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
1741 		return false;
1742 
1743 	if (!crtc_state->enable)
1744 		return false;
1745 
1746 	return crtc_state->active;
1747 }
1748 
1749 static bool modereset_required(struct drm_crtc_state *crtc_state)
1750 {
1751 	if (!drm_atomic_crtc_needs_modeset(crtc_state))
1752 		return false;
1753 
1754 	return !crtc_state->enable || !crtc_state->active;
1755 }
1756 
1757 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
1758 {
1759 	drm_encoder_cleanup(encoder);
1760 	kfree(encoder);
1761 }
1762 
1763 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
1764 	.destroy = amdgpu_dm_encoder_destroy,
1765 };
1766 
1767 static bool fill_rects_from_plane_state(const struct drm_plane_state *state,
1768 					struct dc_plane_state *plane_state)
1769 {
1770 	plane_state->src_rect.x = state->src_x >> 16;
1771 	plane_state->src_rect.y = state->src_y >> 16;
1772 	/*we ignore for now mantissa and do not to deal with floating pixels :(*/
1773 	plane_state->src_rect.width = state->src_w >> 16;
1774 
1775 	if (plane_state->src_rect.width == 0)
1776 		return false;
1777 
1778 	plane_state->src_rect.height = state->src_h >> 16;
1779 	if (plane_state->src_rect.height == 0)
1780 		return false;
1781 
1782 	plane_state->dst_rect.x = state->crtc_x;
1783 	plane_state->dst_rect.y = state->crtc_y;
1784 
1785 	if (state->crtc_w == 0)
1786 		return false;
1787 
1788 	plane_state->dst_rect.width = state->crtc_w;
1789 
1790 	if (state->crtc_h == 0)
1791 		return false;
1792 
1793 	plane_state->dst_rect.height = state->crtc_h;
1794 
1795 	plane_state->clip_rect = plane_state->dst_rect;
1796 
1797 	switch (state->rotation & DRM_MODE_ROTATE_MASK) {
1798 	case DRM_MODE_ROTATE_0:
1799 		plane_state->rotation = ROTATION_ANGLE_0;
1800 		break;
1801 	case DRM_MODE_ROTATE_90:
1802 		plane_state->rotation = ROTATION_ANGLE_90;
1803 		break;
1804 	case DRM_MODE_ROTATE_180:
1805 		plane_state->rotation = ROTATION_ANGLE_180;
1806 		break;
1807 	case DRM_MODE_ROTATE_270:
1808 		plane_state->rotation = ROTATION_ANGLE_270;
1809 		break;
1810 	default:
1811 		plane_state->rotation = ROTATION_ANGLE_0;
1812 		break;
1813 	}
1814 
1815 	return true;
1816 }
1817 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
1818 		       uint64_t *tiling_flags)
1819 {
1820 	struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->obj);
1821 	int r = amdgpu_bo_reserve(rbo, false);
1822 
1823 	if (unlikely(r)) {
1824 		// Don't show error msg. when return -ERESTARTSYS
1825 		if (r != -ERESTARTSYS)
1826 			DRM_ERROR("Unable to reserve buffer: %d\n", r);
1827 		return r;
1828 	}
1829 
1830 	if (tiling_flags)
1831 		amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
1832 
1833 	amdgpu_bo_unreserve(rbo);
1834 
1835 	return r;
1836 }
1837 
1838 static int fill_plane_attributes_from_fb(struct amdgpu_device *adev,
1839 					 struct dc_plane_state *plane_state,
1840 					 const struct amdgpu_framebuffer *amdgpu_fb)
1841 {
1842 	uint64_t tiling_flags;
1843 	unsigned int awidth;
1844 	const struct drm_framebuffer *fb = &amdgpu_fb->base;
1845 	int ret = 0;
1846 	struct drm_format_name_buf format_name;
1847 
1848 	ret = get_fb_info(
1849 		amdgpu_fb,
1850 		&tiling_flags);
1851 
1852 	if (ret)
1853 		return ret;
1854 
1855 	switch (fb->format->format) {
1856 	case DRM_FORMAT_C8:
1857 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
1858 		break;
1859 	case DRM_FORMAT_RGB565:
1860 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
1861 		break;
1862 	case DRM_FORMAT_XRGB8888:
1863 	case DRM_FORMAT_ARGB8888:
1864 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
1865 		break;
1866 	case DRM_FORMAT_XRGB2101010:
1867 	case DRM_FORMAT_ARGB2101010:
1868 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
1869 		break;
1870 	case DRM_FORMAT_XBGR2101010:
1871 	case DRM_FORMAT_ABGR2101010:
1872 		plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
1873 		break;
1874 	case DRM_FORMAT_NV21:
1875 		plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
1876 		break;
1877 	case DRM_FORMAT_NV12:
1878 		plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
1879 		break;
1880 	default:
1881 		DRM_ERROR("Unsupported screen format %s\n",
1882 			  drm_get_format_name(fb->format->format, &format_name));
1883 		return -EINVAL;
1884 	}
1885 
1886 	if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
1887 		plane_state->address.type = PLN_ADDR_TYPE_GRAPHICS;
1888 		plane_state->plane_size.grph.surface_size.x = 0;
1889 		plane_state->plane_size.grph.surface_size.y = 0;
1890 		plane_state->plane_size.grph.surface_size.width = fb->width;
1891 		plane_state->plane_size.grph.surface_size.height = fb->height;
1892 		plane_state->plane_size.grph.surface_pitch =
1893 				fb->pitches[0] / fb->format->cpp[0];
1894 		/* TODO: unhardcode */
1895 		plane_state->color_space = COLOR_SPACE_SRGB;
1896 
1897 	} else {
1898 		awidth = ALIGN(fb->width, 64);
1899 		plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
1900 		plane_state->plane_size.video.luma_size.x = 0;
1901 		plane_state->plane_size.video.luma_size.y = 0;
1902 		plane_state->plane_size.video.luma_size.width = awidth;
1903 		plane_state->plane_size.video.luma_size.height = fb->height;
1904 		/* TODO: unhardcode */
1905 		plane_state->plane_size.video.luma_pitch = awidth;
1906 
1907 		plane_state->plane_size.video.chroma_size.x = 0;
1908 		plane_state->plane_size.video.chroma_size.y = 0;
1909 		plane_state->plane_size.video.chroma_size.width = awidth;
1910 		plane_state->plane_size.video.chroma_size.height = fb->height;
1911 		plane_state->plane_size.video.chroma_pitch = awidth / 2;
1912 
1913 		/* TODO: unhardcode */
1914 		plane_state->color_space = COLOR_SPACE_YCBCR709;
1915 	}
1916 
1917 	memset(&plane_state->tiling_info, 0, sizeof(plane_state->tiling_info));
1918 
1919 	/* Fill GFX8 params */
1920 	if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
1921 		unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
1922 
1923 		bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
1924 		bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
1925 		mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
1926 		tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
1927 		num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
1928 
1929 		/* XXX fix me for VI */
1930 		plane_state->tiling_info.gfx8.num_banks = num_banks;
1931 		plane_state->tiling_info.gfx8.array_mode =
1932 				DC_ARRAY_2D_TILED_THIN1;
1933 		plane_state->tiling_info.gfx8.tile_split = tile_split;
1934 		plane_state->tiling_info.gfx8.bank_width = bankw;
1935 		plane_state->tiling_info.gfx8.bank_height = bankh;
1936 		plane_state->tiling_info.gfx8.tile_aspect = mtaspect;
1937 		plane_state->tiling_info.gfx8.tile_mode =
1938 				DC_ADDR_SURF_MICRO_TILING_DISPLAY;
1939 	} else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
1940 			== DC_ARRAY_1D_TILED_THIN1) {
1941 		plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
1942 	}
1943 
1944 	plane_state->tiling_info.gfx8.pipe_config =
1945 			AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
1946 
1947 	if (adev->asic_type == CHIP_VEGA10 ||
1948 	    adev->asic_type == CHIP_RAVEN) {
1949 		/* Fill GFX9 params */
1950 		plane_state->tiling_info.gfx9.num_pipes =
1951 			adev->gfx.config.gb_addr_config_fields.num_pipes;
1952 		plane_state->tiling_info.gfx9.num_banks =
1953 			adev->gfx.config.gb_addr_config_fields.num_banks;
1954 		plane_state->tiling_info.gfx9.pipe_interleave =
1955 			adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
1956 		plane_state->tiling_info.gfx9.num_shader_engines =
1957 			adev->gfx.config.gb_addr_config_fields.num_se;
1958 		plane_state->tiling_info.gfx9.max_compressed_frags =
1959 			adev->gfx.config.gb_addr_config_fields.max_compress_frags;
1960 		plane_state->tiling_info.gfx9.num_rb_per_se =
1961 			adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
1962 		plane_state->tiling_info.gfx9.swizzle =
1963 			AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
1964 		plane_state->tiling_info.gfx9.shaderEnable = 1;
1965 	}
1966 
1967 	plane_state->visible = true;
1968 	plane_state->scaling_quality.h_taps_c = 0;
1969 	plane_state->scaling_quality.v_taps_c = 0;
1970 
1971 	/* is this needed? is plane_state zeroed at allocation? */
1972 	plane_state->scaling_quality.h_taps = 0;
1973 	plane_state->scaling_quality.v_taps = 0;
1974 	plane_state->stereo_format = PLANE_STEREO_FORMAT_NONE;
1975 
1976 	return ret;
1977 
1978 }
1979 
1980 static int fill_plane_attributes(struct amdgpu_device *adev,
1981 				 struct dc_plane_state *dc_plane_state,
1982 				 struct drm_plane_state *plane_state,
1983 				 struct drm_crtc_state *crtc_state)
1984 {
1985 	const struct amdgpu_framebuffer *amdgpu_fb =
1986 		to_amdgpu_framebuffer(plane_state->fb);
1987 	const struct drm_crtc *crtc = plane_state->crtc;
1988 	struct dc_transfer_func *input_tf;
1989 	int ret = 0;
1990 
1991 	if (!fill_rects_from_plane_state(plane_state, dc_plane_state))
1992 		return -EINVAL;
1993 
1994 	ret = fill_plane_attributes_from_fb(
1995 		crtc->dev->dev_private,
1996 		dc_plane_state,
1997 		amdgpu_fb);
1998 
1999 	if (ret)
2000 		return ret;
2001 
2002 	input_tf = dc_create_transfer_func();
2003 
2004 	if (input_tf == NULL)
2005 		return -ENOMEM;
2006 
2007 	dc_plane_state->in_transfer_func = input_tf;
2008 
2009 	/*
2010 	 * Always set input transfer function, since plane state is refreshed
2011 	 * every time.
2012 	 */
2013 	ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2014 	if (ret) {
2015 		dc_transfer_func_release(dc_plane_state->in_transfer_func);
2016 		dc_plane_state->in_transfer_func = NULL;
2017 	}
2018 
2019 	return ret;
2020 }
2021 
2022 /*****************************************************************************/
2023 
2024 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2025 					   const struct dm_connector_state *dm_state,
2026 					   struct dc_stream_state *stream)
2027 {
2028 	enum amdgpu_rmx_type rmx_type;
2029 
2030 	struct rect src = { 0 }; /* viewport in composition space*/
2031 	struct rect dst = { 0 }; /* stream addressable area */
2032 
2033 	/* no mode. nothing to be done */
2034 	if (!mode)
2035 		return;
2036 
2037 	/* Full screen scaling by default */
2038 	src.width = mode->hdisplay;
2039 	src.height = mode->vdisplay;
2040 	dst.width = stream->timing.h_addressable;
2041 	dst.height = stream->timing.v_addressable;
2042 
2043 	if (dm_state) {
2044 		rmx_type = dm_state->scaling;
2045 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2046 			if (src.width * dst.height <
2047 					src.height * dst.width) {
2048 				/* height needs less upscaling/more downscaling */
2049 				dst.width = src.width *
2050 						dst.height / src.height;
2051 			} else {
2052 				/* width needs less upscaling/more downscaling */
2053 				dst.height = src.height *
2054 						dst.width / src.width;
2055 			}
2056 		} else if (rmx_type == RMX_CENTER) {
2057 			dst = src;
2058 		}
2059 
2060 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
2061 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
2062 
2063 		if (dm_state->underscan_enable) {
2064 			dst.x += dm_state->underscan_hborder / 2;
2065 			dst.y += dm_state->underscan_vborder / 2;
2066 			dst.width -= dm_state->underscan_hborder;
2067 			dst.height -= dm_state->underscan_vborder;
2068 		}
2069 	}
2070 
2071 	stream->src = src;
2072 	stream->dst = dst;
2073 
2074 	DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2075 			dst.x, dst.y, dst.width, dst.height);
2076 
2077 }
2078 
2079 static enum dc_color_depth
2080 convert_color_depth_from_display_info(const struct drm_connector *connector)
2081 {
2082 	uint32_t bpc = connector->display_info.bpc;
2083 
2084 	/* Limited color depth to 8bit
2085 	 * TODO: Still need to handle deep color
2086 	 */
2087 	if (bpc > 8)
2088 		bpc = 8;
2089 
2090 	switch (bpc) {
2091 	case 0:
2092 		/* Temporary Work around, DRM don't parse color depth for
2093 		 * EDID revision before 1.4
2094 		 * TODO: Fix edid parsing
2095 		 */
2096 		return COLOR_DEPTH_888;
2097 	case 6:
2098 		return COLOR_DEPTH_666;
2099 	case 8:
2100 		return COLOR_DEPTH_888;
2101 	case 10:
2102 		return COLOR_DEPTH_101010;
2103 	case 12:
2104 		return COLOR_DEPTH_121212;
2105 	case 14:
2106 		return COLOR_DEPTH_141414;
2107 	case 16:
2108 		return COLOR_DEPTH_161616;
2109 	default:
2110 		return COLOR_DEPTH_UNDEFINED;
2111 	}
2112 }
2113 
2114 static enum dc_aspect_ratio
2115 get_aspect_ratio(const struct drm_display_mode *mode_in)
2116 {
2117 	int32_t width = mode_in->crtc_hdisplay * 9;
2118 	int32_t height = mode_in->crtc_vdisplay * 16;
2119 
2120 	if ((width - height) < 10 && (width - height) > -10)
2121 		return ASPECT_RATIO_16_9;
2122 	else
2123 		return ASPECT_RATIO_4_3;
2124 }
2125 
2126 static enum dc_color_space
2127 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
2128 {
2129 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
2130 
2131 	switch (dc_crtc_timing->pixel_encoding)	{
2132 	case PIXEL_ENCODING_YCBCR422:
2133 	case PIXEL_ENCODING_YCBCR444:
2134 	case PIXEL_ENCODING_YCBCR420:
2135 	{
2136 		/*
2137 		 * 27030khz is the separation point between HDTV and SDTV
2138 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
2139 		 * respectively
2140 		 */
2141 		if (dc_crtc_timing->pix_clk_khz > 27030) {
2142 			if (dc_crtc_timing->flags.Y_ONLY)
2143 				color_space =
2144 					COLOR_SPACE_YCBCR709_LIMITED;
2145 			else
2146 				color_space = COLOR_SPACE_YCBCR709;
2147 		} else {
2148 			if (dc_crtc_timing->flags.Y_ONLY)
2149 				color_space =
2150 					COLOR_SPACE_YCBCR601_LIMITED;
2151 			else
2152 				color_space = COLOR_SPACE_YCBCR601;
2153 		}
2154 
2155 	}
2156 	break;
2157 	case PIXEL_ENCODING_RGB:
2158 		color_space = COLOR_SPACE_SRGB;
2159 		break;
2160 
2161 	default:
2162 		WARN_ON(1);
2163 		break;
2164 	}
2165 
2166 	return color_space;
2167 }
2168 
2169 /*****************************************************************************/
2170 
2171 static void
2172 fill_stream_properties_from_drm_display_mode(struct dc_stream_state *stream,
2173 					     const struct drm_display_mode *mode_in,
2174 					     const struct drm_connector *connector)
2175 {
2176 	struct dc_crtc_timing *timing_out = &stream->timing;
2177 	struct dc_transfer_func *tf = dc_create_transfer_func();
2178 
2179 	memset(timing_out, 0, sizeof(struct dc_crtc_timing));
2180 
2181 	timing_out->h_border_left = 0;
2182 	timing_out->h_border_right = 0;
2183 	timing_out->v_border_top = 0;
2184 	timing_out->v_border_bottom = 0;
2185 	/* TODO: un-hardcode */
2186 
2187 	if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
2188 			&& stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2189 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
2190 	else
2191 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
2192 
2193 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
2194 	timing_out->display_color_depth = convert_color_depth_from_display_info(
2195 			connector);
2196 	timing_out->scan_type = SCANNING_TYPE_NODATA;
2197 	timing_out->hdmi_vic = 0;
2198 	timing_out->vic = drm_match_cea_mode(mode_in);
2199 
2200 	timing_out->h_addressable = mode_in->crtc_hdisplay;
2201 	timing_out->h_total = mode_in->crtc_htotal;
2202 	timing_out->h_sync_width =
2203 		mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
2204 	timing_out->h_front_porch =
2205 		mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
2206 	timing_out->v_total = mode_in->crtc_vtotal;
2207 	timing_out->v_addressable = mode_in->crtc_vdisplay;
2208 	timing_out->v_front_porch =
2209 		mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
2210 	timing_out->v_sync_width =
2211 		mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
2212 	timing_out->pix_clk_khz = mode_in->crtc_clock;
2213 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
2214 	if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
2215 		timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
2216 	if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
2217 		timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
2218 
2219 	stream->output_color_space = get_output_color_space(timing_out);
2220 
2221 	tf->type = TF_TYPE_PREDEFINED;
2222 	tf->tf = TRANSFER_FUNCTION_SRGB;
2223 	stream->out_transfer_func = tf;
2224 }
2225 
2226 static void fill_audio_info(struct audio_info *audio_info,
2227 			    const struct drm_connector *drm_connector,
2228 			    const struct dc_sink *dc_sink)
2229 {
2230 	int i = 0;
2231 	int cea_revision = 0;
2232 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
2233 
2234 	audio_info->manufacture_id = edid_caps->manufacturer_id;
2235 	audio_info->product_id = edid_caps->product_id;
2236 
2237 	cea_revision = drm_connector->display_info.cea_rev;
2238 
2239 	strncpy(audio_info->display_name,
2240 		edid_caps->display_name,
2241 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS - 1);
2242 
2243 	if (cea_revision >= 3) {
2244 		audio_info->mode_count = edid_caps->audio_mode_count;
2245 
2246 		for (i = 0; i < audio_info->mode_count; ++i) {
2247 			audio_info->modes[i].format_code =
2248 					(enum audio_format_code)
2249 					(edid_caps->audio_modes[i].format_code);
2250 			audio_info->modes[i].channel_count =
2251 					edid_caps->audio_modes[i].channel_count;
2252 			audio_info->modes[i].sample_rates.all =
2253 					edid_caps->audio_modes[i].sample_rate;
2254 			audio_info->modes[i].sample_size =
2255 					edid_caps->audio_modes[i].sample_size;
2256 		}
2257 	}
2258 
2259 	audio_info->flags.all = edid_caps->speaker_flags;
2260 
2261 	/* TODO: We only check for the progressive mode, check for interlace mode too */
2262 	if (drm_connector->latency_present[0]) {
2263 		audio_info->video_latency = drm_connector->video_latency[0];
2264 		audio_info->audio_latency = drm_connector->audio_latency[0];
2265 	}
2266 
2267 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
2268 
2269 }
2270 
2271 static void
2272 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
2273 				      struct drm_display_mode *dst_mode)
2274 {
2275 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
2276 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
2277 	dst_mode->crtc_clock = src_mode->crtc_clock;
2278 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
2279 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
2280 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
2281 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
2282 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
2283 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
2284 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
2285 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
2286 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
2287 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
2288 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
2289 }
2290 
2291 static void
2292 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
2293 					const struct drm_display_mode *native_mode,
2294 					bool scale_enabled)
2295 {
2296 	if (scale_enabled) {
2297 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2298 	} else if (native_mode->clock == drm_mode->clock &&
2299 			native_mode->htotal == drm_mode->htotal &&
2300 			native_mode->vtotal == drm_mode->vtotal) {
2301 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2302 	} else {
2303 		/* no scaling nor amdgpu inserted, no need to patch */
2304 	}
2305 }
2306 
2307 static int create_fake_sink(struct amdgpu_dm_connector *aconnector)
2308 {
2309 	struct dc_sink *sink = NULL;
2310 	struct dc_sink_init_data sink_init_data = { 0 };
2311 
2312 	sink_init_data.link = aconnector->dc_link;
2313 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
2314 
2315 	sink = dc_sink_create(&sink_init_data);
2316 	if (!sink) {
2317 		DRM_ERROR("Failed to create sink!\n");
2318 		return -ENOMEM;
2319 	}
2320 
2321 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
2322 	aconnector->fake_enable = true;
2323 
2324 	aconnector->dc_sink = sink;
2325 	aconnector->dc_link->local_sink = sink;
2326 
2327 	return 0;
2328 }
2329 
2330 static void set_multisync_trigger_params(
2331 		struct dc_stream_state *stream)
2332 {
2333 	if (stream->triggered_crtc_reset.enabled) {
2334 		stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
2335 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
2336 	}
2337 }
2338 
2339 static void set_master_stream(struct dc_stream_state *stream_set[],
2340 			      int stream_count)
2341 {
2342 	int j, highest_rfr = 0, master_stream = 0;
2343 
2344 	for (j = 0;  j < stream_count; j++) {
2345 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
2346 			int refresh_rate = 0;
2347 
2348 			refresh_rate = (stream_set[j]->timing.pix_clk_khz*1000)/
2349 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
2350 			if (refresh_rate > highest_rfr) {
2351 				highest_rfr = refresh_rate;
2352 				master_stream = j;
2353 			}
2354 		}
2355 	}
2356 	for (j = 0;  j < stream_count; j++) {
2357 		if (stream_set[j])
2358 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
2359 	}
2360 }
2361 
2362 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
2363 {
2364 	int i = 0;
2365 
2366 	if (context->stream_count < 2)
2367 		return;
2368 	for (i = 0; i < context->stream_count ; i++) {
2369 		if (!context->streams[i])
2370 			continue;
2371 		/* TODO: add a function to read AMD VSDB bits and will set
2372 		 * crtc_sync_master.multi_sync_enabled flag
2373 		 * For now its set to false
2374 		 */
2375 		set_multisync_trigger_params(context->streams[i]);
2376 	}
2377 	set_master_stream(context->streams, context->stream_count);
2378 }
2379 
2380 static struct dc_stream_state *
2381 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
2382 		       const struct drm_display_mode *drm_mode,
2383 		       const struct dm_connector_state *dm_state)
2384 {
2385 	struct drm_display_mode *preferred_mode = NULL;
2386 	struct drm_connector *drm_connector;
2387 	struct dc_stream_state *stream = NULL;
2388 	struct drm_display_mode mode = *drm_mode;
2389 	bool native_mode_found = false;
2390 
2391 	if (aconnector == NULL) {
2392 		DRM_ERROR("aconnector is NULL!\n");
2393 		return stream;
2394 	}
2395 
2396 	drm_connector = &aconnector->base;
2397 
2398 	if (!aconnector->dc_sink) {
2399 		/*
2400 		 * Create dc_sink when necessary to MST
2401 		 * Don't apply fake_sink to MST
2402 		 */
2403 		if (aconnector->mst_port) {
2404 			dm_dp_mst_dc_sink_create(drm_connector);
2405 			return stream;
2406 		}
2407 
2408 		if (create_fake_sink(aconnector))
2409 			return stream;
2410 	}
2411 
2412 	stream = dc_create_stream_for_sink(aconnector->dc_sink);
2413 
2414 	if (stream == NULL) {
2415 		DRM_ERROR("Failed to create stream for sink!\n");
2416 		return stream;
2417 	}
2418 
2419 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
2420 		/* Search for preferred mode */
2421 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
2422 			native_mode_found = true;
2423 			break;
2424 		}
2425 	}
2426 	if (!native_mode_found)
2427 		preferred_mode = list_first_entry_or_null(
2428 				&aconnector->base.modes,
2429 				struct drm_display_mode,
2430 				head);
2431 
2432 	if (preferred_mode == NULL) {
2433 		/* This may not be an error, the use case is when we we have no
2434 		 * usermode calls to reset and set mode upon hotplug. In this
2435 		 * case, we call set mode ourselves to restore the previous mode
2436 		 * and the modelist may not be filled in in time.
2437 		 */
2438 		DRM_DEBUG_DRIVER("No preferred mode found\n");
2439 	} else {
2440 		decide_crtc_timing_for_drm_display_mode(
2441 				&mode, preferred_mode,
2442 				dm_state ? (dm_state->scaling != RMX_OFF) : false);
2443 	}
2444 
2445 	if (!dm_state)
2446 		drm_mode_set_crtcinfo(&mode, 0);
2447 
2448 	fill_stream_properties_from_drm_display_mode(stream,
2449 			&mode, &aconnector->base);
2450 	update_stream_scaling_settings(&mode, dm_state, stream);
2451 
2452 	fill_audio_info(
2453 		&stream->audio_info,
2454 		drm_connector,
2455 		aconnector->dc_sink);
2456 
2457 	update_stream_signal(stream);
2458 
2459 	return stream;
2460 }
2461 
2462 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
2463 {
2464 	drm_crtc_cleanup(crtc);
2465 	kfree(crtc);
2466 }
2467 
2468 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
2469 				  struct drm_crtc_state *state)
2470 {
2471 	struct dm_crtc_state *cur = to_dm_crtc_state(state);
2472 
2473 	/* TODO Destroy dc_stream objects are stream object is flattened */
2474 	if (cur->stream)
2475 		dc_stream_release(cur->stream);
2476 
2477 
2478 	__drm_atomic_helper_crtc_destroy_state(state);
2479 
2480 
2481 	kfree(state);
2482 }
2483 
2484 static void dm_crtc_reset_state(struct drm_crtc *crtc)
2485 {
2486 	struct dm_crtc_state *state;
2487 
2488 	if (crtc->state)
2489 		dm_crtc_destroy_state(crtc, crtc->state);
2490 
2491 	state = kzalloc(sizeof(*state), GFP_KERNEL);
2492 	if (WARN_ON(!state))
2493 		return;
2494 
2495 	crtc->state = &state->base;
2496 	crtc->state->crtc = crtc;
2497 
2498 }
2499 
2500 static struct drm_crtc_state *
2501 dm_crtc_duplicate_state(struct drm_crtc *crtc)
2502 {
2503 	struct dm_crtc_state *state, *cur;
2504 
2505 	cur = to_dm_crtc_state(crtc->state);
2506 
2507 	if (WARN_ON(!crtc->state))
2508 		return NULL;
2509 
2510 	state = kzalloc(sizeof(*state), GFP_KERNEL);
2511 	if (!state)
2512 		return NULL;
2513 
2514 	__drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
2515 
2516 	if (cur->stream) {
2517 		state->stream = cur->stream;
2518 		dc_stream_retain(state->stream);
2519 	}
2520 
2521 	/* TODO Duplicate dc_stream after objects are stream object is flattened */
2522 
2523 	return &state->base;
2524 }
2525 
2526 
2527 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
2528 {
2529 	enum dc_irq_source irq_source;
2530 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
2531 	struct amdgpu_device *adev = crtc->dev->dev_private;
2532 
2533 	irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
2534 	return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2535 }
2536 
2537 static int dm_enable_vblank(struct drm_crtc *crtc)
2538 {
2539 	return dm_set_vblank(crtc, true);
2540 }
2541 
2542 static void dm_disable_vblank(struct drm_crtc *crtc)
2543 {
2544 	dm_set_vblank(crtc, false);
2545 }
2546 
2547 /* Implemented only the options currently availible for the driver */
2548 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
2549 	.reset = dm_crtc_reset_state,
2550 	.destroy = amdgpu_dm_crtc_destroy,
2551 	.gamma_set = drm_atomic_helper_legacy_gamma_set,
2552 	.set_config = drm_atomic_helper_set_config,
2553 	.page_flip = drm_atomic_helper_page_flip,
2554 	.atomic_duplicate_state = dm_crtc_duplicate_state,
2555 	.atomic_destroy_state = dm_crtc_destroy_state,
2556 	.set_crc_source = amdgpu_dm_crtc_set_crc_source,
2557 	.enable_vblank = dm_enable_vblank,
2558 	.disable_vblank = dm_disable_vblank,
2559 };
2560 
2561 static enum drm_connector_status
2562 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
2563 {
2564 	bool connected;
2565 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2566 
2567 	/* Notes:
2568 	 * 1. This interface is NOT called in context of HPD irq.
2569 	 * 2. This interface *is called* in context of user-mode ioctl. Which
2570 	 * makes it a bad place for *any* MST-related activit. */
2571 
2572 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
2573 	    !aconnector->fake_enable)
2574 		connected = (aconnector->dc_sink != NULL);
2575 	else
2576 		connected = (aconnector->base.force == DRM_FORCE_ON);
2577 
2578 	return (connected ? connector_status_connected :
2579 			connector_status_disconnected);
2580 }
2581 
2582 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
2583 					    struct drm_connector_state *connector_state,
2584 					    struct drm_property *property,
2585 					    uint64_t val)
2586 {
2587 	struct drm_device *dev = connector->dev;
2588 	struct amdgpu_device *adev = dev->dev_private;
2589 	struct dm_connector_state *dm_old_state =
2590 		to_dm_connector_state(connector->state);
2591 	struct dm_connector_state *dm_new_state =
2592 		to_dm_connector_state(connector_state);
2593 
2594 	int ret = -EINVAL;
2595 
2596 	if (property == dev->mode_config.scaling_mode_property) {
2597 		enum amdgpu_rmx_type rmx_type;
2598 
2599 		switch (val) {
2600 		case DRM_MODE_SCALE_CENTER:
2601 			rmx_type = RMX_CENTER;
2602 			break;
2603 		case DRM_MODE_SCALE_ASPECT:
2604 			rmx_type = RMX_ASPECT;
2605 			break;
2606 		case DRM_MODE_SCALE_FULLSCREEN:
2607 			rmx_type = RMX_FULL;
2608 			break;
2609 		case DRM_MODE_SCALE_NONE:
2610 		default:
2611 			rmx_type = RMX_OFF;
2612 			break;
2613 		}
2614 
2615 		if (dm_old_state->scaling == rmx_type)
2616 			return 0;
2617 
2618 		dm_new_state->scaling = rmx_type;
2619 		ret = 0;
2620 	} else if (property == adev->mode_info.underscan_hborder_property) {
2621 		dm_new_state->underscan_hborder = val;
2622 		ret = 0;
2623 	} else if (property == adev->mode_info.underscan_vborder_property) {
2624 		dm_new_state->underscan_vborder = val;
2625 		ret = 0;
2626 	} else if (property == adev->mode_info.underscan_property) {
2627 		dm_new_state->underscan_enable = val;
2628 		ret = 0;
2629 	}
2630 
2631 	return ret;
2632 }
2633 
2634 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
2635 					    const struct drm_connector_state *state,
2636 					    struct drm_property *property,
2637 					    uint64_t *val)
2638 {
2639 	struct drm_device *dev = connector->dev;
2640 	struct amdgpu_device *adev = dev->dev_private;
2641 	struct dm_connector_state *dm_state =
2642 		to_dm_connector_state(state);
2643 	int ret = -EINVAL;
2644 
2645 	if (property == dev->mode_config.scaling_mode_property) {
2646 		switch (dm_state->scaling) {
2647 		case RMX_CENTER:
2648 			*val = DRM_MODE_SCALE_CENTER;
2649 			break;
2650 		case RMX_ASPECT:
2651 			*val = DRM_MODE_SCALE_ASPECT;
2652 			break;
2653 		case RMX_FULL:
2654 			*val = DRM_MODE_SCALE_FULLSCREEN;
2655 			break;
2656 		case RMX_OFF:
2657 		default:
2658 			*val = DRM_MODE_SCALE_NONE;
2659 			break;
2660 		}
2661 		ret = 0;
2662 	} else if (property == adev->mode_info.underscan_hborder_property) {
2663 		*val = dm_state->underscan_hborder;
2664 		ret = 0;
2665 	} else if (property == adev->mode_info.underscan_vborder_property) {
2666 		*val = dm_state->underscan_vborder;
2667 		ret = 0;
2668 	} else if (property == adev->mode_info.underscan_property) {
2669 		*val = dm_state->underscan_enable;
2670 		ret = 0;
2671 	}
2672 	return ret;
2673 }
2674 
2675 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
2676 {
2677 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2678 	const struct dc_link *link = aconnector->dc_link;
2679 	struct amdgpu_device *adev = connector->dev->dev_private;
2680 	struct amdgpu_display_manager *dm = &adev->dm;
2681 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2682 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2683 
2684 	if (link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) {
2685 		amdgpu_dm_register_backlight_device(dm);
2686 
2687 		if (dm->backlight_dev) {
2688 			backlight_device_unregister(dm->backlight_dev);
2689 			dm->backlight_dev = NULL;
2690 		}
2691 
2692 	}
2693 #endif
2694 	drm_connector_unregister(connector);
2695 	drm_connector_cleanup(connector);
2696 	kfree(connector);
2697 }
2698 
2699 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
2700 {
2701 	struct dm_connector_state *state =
2702 		to_dm_connector_state(connector->state);
2703 
2704 	kfree(state);
2705 
2706 	state = kzalloc(sizeof(*state), GFP_KERNEL);
2707 
2708 	if (state) {
2709 		state->scaling = RMX_OFF;
2710 		state->underscan_enable = false;
2711 		state->underscan_hborder = 0;
2712 		state->underscan_vborder = 0;
2713 
2714 		connector->state = &state->base;
2715 		connector->state->connector = connector;
2716 	}
2717 }
2718 
2719 struct drm_connector_state *
2720 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
2721 {
2722 	struct dm_connector_state *state =
2723 		to_dm_connector_state(connector->state);
2724 
2725 	struct dm_connector_state *new_state =
2726 			kmemdup(state, sizeof(*state), GFP_KERNEL);
2727 
2728 	if (new_state) {
2729 		__drm_atomic_helper_connector_duplicate_state(connector,
2730 							      &new_state->base);
2731 		return &new_state->base;
2732 	}
2733 
2734 	return NULL;
2735 }
2736 
2737 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
2738 	.reset = amdgpu_dm_connector_funcs_reset,
2739 	.detect = amdgpu_dm_connector_detect,
2740 	.fill_modes = drm_helper_probe_single_connector_modes,
2741 	.destroy = amdgpu_dm_connector_destroy,
2742 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
2743 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
2744 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
2745 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property
2746 };
2747 
2748 static struct drm_encoder *best_encoder(struct drm_connector *connector)
2749 {
2750 	int enc_id = connector->encoder_ids[0];
2751 	struct drm_mode_object *obj;
2752 	struct drm_encoder *encoder;
2753 
2754 	DRM_DEBUG_DRIVER("Finding the best encoder\n");
2755 
2756 	/* pick the encoder ids */
2757 	if (enc_id) {
2758 		obj = drm_mode_object_find(connector->dev, NULL, enc_id, DRM_MODE_OBJECT_ENCODER);
2759 		if (!obj) {
2760 			DRM_ERROR("Couldn't find a matching encoder for our connector\n");
2761 			return NULL;
2762 		}
2763 		encoder = obj_to_encoder(obj);
2764 		return encoder;
2765 	}
2766 	DRM_ERROR("No encoder id\n");
2767 	return NULL;
2768 }
2769 
2770 static int get_modes(struct drm_connector *connector)
2771 {
2772 	return amdgpu_dm_connector_get_modes(connector);
2773 }
2774 
2775 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
2776 {
2777 	struct dc_sink_init_data init_params = {
2778 			.link = aconnector->dc_link,
2779 			.sink_signal = SIGNAL_TYPE_VIRTUAL
2780 	};
2781 	struct edid *edid;
2782 
2783 	if (!aconnector->base.edid_blob_ptr) {
2784 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
2785 				aconnector->base.name);
2786 
2787 		aconnector->base.force = DRM_FORCE_OFF;
2788 		aconnector->base.override_edid = false;
2789 		return;
2790 	}
2791 
2792 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
2793 
2794 	aconnector->edid = edid;
2795 
2796 	aconnector->dc_em_sink = dc_link_add_remote_sink(
2797 		aconnector->dc_link,
2798 		(uint8_t *)edid,
2799 		(edid->extensions + 1) * EDID_LENGTH,
2800 		&init_params);
2801 
2802 	if (aconnector->base.force == DRM_FORCE_ON)
2803 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
2804 		aconnector->dc_link->local_sink :
2805 		aconnector->dc_em_sink;
2806 }
2807 
2808 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
2809 {
2810 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
2811 
2812 	/* In case of headless boot with force on for DP managed connector
2813 	 * Those settings have to be != 0 to get initial modeset
2814 	 */
2815 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
2816 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
2817 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
2818 	}
2819 
2820 
2821 	aconnector->base.override_edid = true;
2822 	create_eml_sink(aconnector);
2823 }
2824 
2825 int amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
2826 				   struct drm_display_mode *mode)
2827 {
2828 	int result = MODE_ERROR;
2829 	struct dc_sink *dc_sink;
2830 	struct amdgpu_device *adev = connector->dev->dev_private;
2831 	/* TODO: Unhardcode stream count */
2832 	struct dc_stream_state *stream;
2833 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2834 	enum dc_status dc_result = DC_OK;
2835 
2836 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
2837 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
2838 		return result;
2839 
2840 	/* Only run this the first time mode_valid is called to initilialize
2841 	 * EDID mgmt
2842 	 */
2843 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
2844 		!aconnector->dc_em_sink)
2845 		handle_edid_mgmt(aconnector);
2846 
2847 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
2848 
2849 	if (dc_sink == NULL) {
2850 		DRM_ERROR("dc_sink is NULL!\n");
2851 		goto fail;
2852 	}
2853 
2854 	stream = create_stream_for_sink(aconnector, mode, NULL);
2855 	if (stream == NULL) {
2856 		DRM_ERROR("Failed to create stream for sink!\n");
2857 		goto fail;
2858 	}
2859 
2860 	dc_result = dc_validate_stream(adev->dm.dc, stream);
2861 
2862 	if (dc_result == DC_OK)
2863 		result = MODE_OK;
2864 	else
2865 		DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
2866 			      mode->vdisplay,
2867 			      mode->hdisplay,
2868 			      mode->clock,
2869 			      dc_result);
2870 
2871 	dc_stream_release(stream);
2872 
2873 fail:
2874 	/* TODO: error handling*/
2875 	return result;
2876 }
2877 
2878 static const struct drm_connector_helper_funcs
2879 amdgpu_dm_connector_helper_funcs = {
2880 	/*
2881 	 * If hotplug a second bigger display in FB Con mode, bigger resolution
2882 	 * modes will be filtered by drm_mode_validate_size(), and those modes
2883 	 * is missing after user start lightdm. So we need to renew modes list.
2884 	 * in get_modes call back, not just return the modes count
2885 	 */
2886 	.get_modes = get_modes,
2887 	.mode_valid = amdgpu_dm_connector_mode_valid,
2888 	.best_encoder = best_encoder
2889 };
2890 
2891 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
2892 {
2893 }
2894 
2895 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
2896 				       struct drm_crtc_state *state)
2897 {
2898 	struct amdgpu_device *adev = crtc->dev->dev_private;
2899 	struct dc *dc = adev->dm.dc;
2900 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
2901 	int ret = -EINVAL;
2902 
2903 	if (unlikely(!dm_crtc_state->stream &&
2904 		     modeset_required(state, NULL, dm_crtc_state->stream))) {
2905 		WARN_ON(1);
2906 		return ret;
2907 	}
2908 
2909 	/* In some use cases, like reset, no stream  is attached */
2910 	if (!dm_crtc_state->stream)
2911 		return 0;
2912 
2913 	if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
2914 		return 0;
2915 
2916 	return ret;
2917 }
2918 
2919 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
2920 				      const struct drm_display_mode *mode,
2921 				      struct drm_display_mode *adjusted_mode)
2922 {
2923 	return true;
2924 }
2925 
2926 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
2927 	.disable = dm_crtc_helper_disable,
2928 	.atomic_check = dm_crtc_helper_atomic_check,
2929 	.mode_fixup = dm_crtc_helper_mode_fixup
2930 };
2931 
2932 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
2933 {
2934 
2935 }
2936 
2937 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
2938 					  struct drm_crtc_state *crtc_state,
2939 					  struct drm_connector_state *conn_state)
2940 {
2941 	return 0;
2942 }
2943 
2944 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
2945 	.disable = dm_encoder_helper_disable,
2946 	.atomic_check = dm_encoder_helper_atomic_check
2947 };
2948 
2949 static void dm_drm_plane_reset(struct drm_plane *plane)
2950 {
2951 	struct dm_plane_state *amdgpu_state = NULL;
2952 
2953 	if (plane->state)
2954 		plane->funcs->atomic_destroy_state(plane, plane->state);
2955 
2956 	amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
2957 	WARN_ON(amdgpu_state == NULL);
2958 
2959 	if (amdgpu_state) {
2960 		plane->state = &amdgpu_state->base;
2961 		plane->state->plane = plane;
2962 		plane->state->rotation = DRM_MODE_ROTATE_0;
2963 	}
2964 }
2965 
2966 static struct drm_plane_state *
2967 dm_drm_plane_duplicate_state(struct drm_plane *plane)
2968 {
2969 	struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
2970 
2971 	old_dm_plane_state = to_dm_plane_state(plane->state);
2972 	dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
2973 	if (!dm_plane_state)
2974 		return NULL;
2975 
2976 	__drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
2977 
2978 	if (old_dm_plane_state->dc_state) {
2979 		dm_plane_state->dc_state = old_dm_plane_state->dc_state;
2980 		dc_plane_state_retain(dm_plane_state->dc_state);
2981 	}
2982 
2983 	return &dm_plane_state->base;
2984 }
2985 
2986 void dm_drm_plane_destroy_state(struct drm_plane *plane,
2987 				struct drm_plane_state *state)
2988 {
2989 	struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
2990 
2991 	if (dm_plane_state->dc_state)
2992 		dc_plane_state_release(dm_plane_state->dc_state);
2993 
2994 	drm_atomic_helper_plane_destroy_state(plane, state);
2995 }
2996 
2997 static const struct drm_plane_funcs dm_plane_funcs = {
2998 	.update_plane	= drm_atomic_helper_update_plane,
2999 	.disable_plane	= drm_atomic_helper_disable_plane,
3000 	.destroy	= drm_plane_cleanup,
3001 	.reset = dm_drm_plane_reset,
3002 	.atomic_duplicate_state = dm_drm_plane_duplicate_state,
3003 	.atomic_destroy_state = dm_drm_plane_destroy_state,
3004 };
3005 
3006 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
3007 				      struct drm_plane_state *new_state)
3008 {
3009 	struct amdgpu_framebuffer *afb;
3010 	struct drm_gem_object *obj;
3011 	struct amdgpu_device *adev;
3012 	struct amdgpu_bo *rbo;
3013 	uint64_t chroma_addr = 0;
3014 	struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
3015 	unsigned int awidth;
3016 	uint32_t domain;
3017 	int r;
3018 
3019 	dm_plane_state_old = to_dm_plane_state(plane->state);
3020 	dm_plane_state_new = to_dm_plane_state(new_state);
3021 
3022 	if (!new_state->fb) {
3023 		DRM_DEBUG_DRIVER("No FB bound\n");
3024 		return 0;
3025 	}
3026 
3027 	afb = to_amdgpu_framebuffer(new_state->fb);
3028 
3029 	obj = afb->obj;
3030 	rbo = gem_to_amdgpu_bo(obj);
3031 	adev = amdgpu_ttm_adev(rbo->tbo.bdev);
3032 	r = amdgpu_bo_reserve(rbo, false);
3033 	if (unlikely(r != 0))
3034 		return r;
3035 
3036 	if (plane->type != DRM_PLANE_TYPE_CURSOR)
3037 		domain = amdgpu_display_framebuffer_domains(adev);
3038 	else
3039 		domain = AMDGPU_GEM_DOMAIN_VRAM;
3040 
3041 	r = amdgpu_bo_pin(rbo, domain, &afb->address);
3042 
3043 	amdgpu_bo_unreserve(rbo);
3044 
3045 	if (unlikely(r != 0)) {
3046 		if (r != -ERESTARTSYS)
3047 			DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
3048 		return r;
3049 	}
3050 
3051 	amdgpu_bo_ref(rbo);
3052 
3053 	if (dm_plane_state_new->dc_state &&
3054 			dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
3055 		struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
3056 
3057 		if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
3058 			plane_state->address.grph.addr.low_part = lower_32_bits(afb->address);
3059 			plane_state->address.grph.addr.high_part = upper_32_bits(afb->address);
3060 		} else {
3061 			awidth = ALIGN(new_state->fb->width, 64);
3062 			plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
3063 			plane_state->address.video_progressive.luma_addr.low_part
3064 							= lower_32_bits(afb->address);
3065 			plane_state->address.video_progressive.luma_addr.high_part
3066 							= upper_32_bits(afb->address);
3067 			chroma_addr = afb->address + (u64)awidth * new_state->fb->height;
3068 			plane_state->address.video_progressive.chroma_addr.low_part
3069 							= lower_32_bits(chroma_addr);
3070 			plane_state->address.video_progressive.chroma_addr.high_part
3071 							= upper_32_bits(chroma_addr);
3072 		}
3073 	}
3074 
3075 	/* It's a hack for s3 since in 4.9 kernel filter out cursor buffer
3076 	 * prepare and cleanup in drm_atomic_helper_prepare_planes
3077 	 * and drm_atomic_helper_cleanup_planes because fb doens't in s3.
3078 	 * IN 4.10 kernel this code should be removed and amdgpu_device_suspend
3079 	 * code touching fram buffers should be avoided for DC.
3080 	 */
3081 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
3082 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_state->crtc);
3083 
3084 		acrtc->cursor_bo = obj;
3085 	}
3086 	return 0;
3087 }
3088 
3089 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
3090 				       struct drm_plane_state *old_state)
3091 {
3092 	struct amdgpu_bo *rbo;
3093 	struct amdgpu_framebuffer *afb;
3094 	int r;
3095 
3096 	if (!old_state->fb)
3097 		return;
3098 
3099 	afb = to_amdgpu_framebuffer(old_state->fb);
3100 	rbo = gem_to_amdgpu_bo(afb->obj);
3101 	r = amdgpu_bo_reserve(rbo, false);
3102 	if (unlikely(r)) {
3103 		DRM_ERROR("failed to reserve rbo before unpin\n");
3104 		return;
3105 	}
3106 
3107 	amdgpu_bo_unpin(rbo);
3108 	amdgpu_bo_unreserve(rbo);
3109 	amdgpu_bo_unref(&rbo);
3110 }
3111 
3112 static int dm_plane_atomic_check(struct drm_plane *plane,
3113 				 struct drm_plane_state *state)
3114 {
3115 	struct amdgpu_device *adev = plane->dev->dev_private;
3116 	struct dc *dc = adev->dm.dc;
3117 	struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3118 
3119 	if (!dm_plane_state->dc_state)
3120 		return 0;
3121 
3122 	if (!fill_rects_from_plane_state(state, dm_plane_state->dc_state))
3123 		return -EINVAL;
3124 
3125 	if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
3126 		return 0;
3127 
3128 	return -EINVAL;
3129 }
3130 
3131 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
3132 	.prepare_fb = dm_plane_helper_prepare_fb,
3133 	.cleanup_fb = dm_plane_helper_cleanup_fb,
3134 	.atomic_check = dm_plane_atomic_check,
3135 };
3136 
3137 /*
3138  * TODO: these are currently initialized to rgb formats only.
3139  * For future use cases we should either initialize them dynamically based on
3140  * plane capabilities, or initialize this array to all formats, so internal drm
3141  * check will succeed, and let DC to implement proper check
3142  */
3143 static const uint32_t rgb_formats[] = {
3144 	DRM_FORMAT_RGB888,
3145 	DRM_FORMAT_XRGB8888,
3146 	DRM_FORMAT_ARGB8888,
3147 	DRM_FORMAT_RGBA8888,
3148 	DRM_FORMAT_XRGB2101010,
3149 	DRM_FORMAT_XBGR2101010,
3150 	DRM_FORMAT_ARGB2101010,
3151 	DRM_FORMAT_ABGR2101010,
3152 };
3153 
3154 static const uint32_t yuv_formats[] = {
3155 	DRM_FORMAT_NV12,
3156 	DRM_FORMAT_NV21,
3157 };
3158 
3159 static const u32 cursor_formats[] = {
3160 	DRM_FORMAT_ARGB8888
3161 };
3162 
3163 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
3164 				struct amdgpu_plane *aplane,
3165 				unsigned long possible_crtcs)
3166 {
3167 	int res = -EPERM;
3168 
3169 	switch (aplane->base.type) {
3170 	case DRM_PLANE_TYPE_PRIMARY:
3171 		aplane->base.format_default = true;
3172 
3173 		res = drm_universal_plane_init(
3174 				dm->adev->ddev,
3175 				&aplane->base,
3176 				possible_crtcs,
3177 				&dm_plane_funcs,
3178 				rgb_formats,
3179 				ARRAY_SIZE(rgb_formats),
3180 				NULL, aplane->base.type, NULL);
3181 		break;
3182 	case DRM_PLANE_TYPE_OVERLAY:
3183 		res = drm_universal_plane_init(
3184 				dm->adev->ddev,
3185 				&aplane->base,
3186 				possible_crtcs,
3187 				&dm_plane_funcs,
3188 				yuv_formats,
3189 				ARRAY_SIZE(yuv_formats),
3190 				NULL, aplane->base.type, NULL);
3191 		break;
3192 	case DRM_PLANE_TYPE_CURSOR:
3193 		res = drm_universal_plane_init(
3194 				dm->adev->ddev,
3195 				&aplane->base,
3196 				possible_crtcs,
3197 				&dm_plane_funcs,
3198 				cursor_formats,
3199 				ARRAY_SIZE(cursor_formats),
3200 				NULL, aplane->base.type, NULL);
3201 		break;
3202 	}
3203 
3204 	drm_plane_helper_add(&aplane->base, &dm_plane_helper_funcs);
3205 
3206 	/* Create (reset) the plane state */
3207 	if (aplane->base.funcs->reset)
3208 		aplane->base.funcs->reset(&aplane->base);
3209 
3210 
3211 	return res;
3212 }
3213 
3214 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
3215 			       struct drm_plane *plane,
3216 			       uint32_t crtc_index)
3217 {
3218 	struct amdgpu_crtc *acrtc = NULL;
3219 	struct amdgpu_plane *cursor_plane;
3220 
3221 	int res = -ENOMEM;
3222 
3223 	cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
3224 	if (!cursor_plane)
3225 		goto fail;
3226 
3227 	cursor_plane->base.type = DRM_PLANE_TYPE_CURSOR;
3228 	res = amdgpu_dm_plane_init(dm, cursor_plane, 0);
3229 
3230 	acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
3231 	if (!acrtc)
3232 		goto fail;
3233 
3234 	res = drm_crtc_init_with_planes(
3235 			dm->ddev,
3236 			&acrtc->base,
3237 			plane,
3238 			&cursor_plane->base,
3239 			&amdgpu_dm_crtc_funcs, NULL);
3240 
3241 	if (res)
3242 		goto fail;
3243 
3244 	drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
3245 
3246 	/* Create (reset) the plane state */
3247 	if (acrtc->base.funcs->reset)
3248 		acrtc->base.funcs->reset(&acrtc->base);
3249 
3250 	acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
3251 	acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
3252 
3253 	acrtc->crtc_id = crtc_index;
3254 	acrtc->base.enabled = false;
3255 
3256 	dm->adev->mode_info.crtcs[crtc_index] = acrtc;
3257 	drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
3258 				   true, MAX_COLOR_LUT_ENTRIES);
3259 	drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
3260 
3261 	return 0;
3262 
3263 fail:
3264 	kfree(acrtc);
3265 	kfree(cursor_plane);
3266 	return res;
3267 }
3268 
3269 
3270 static int to_drm_connector_type(enum signal_type st)
3271 {
3272 	switch (st) {
3273 	case SIGNAL_TYPE_HDMI_TYPE_A:
3274 		return DRM_MODE_CONNECTOR_HDMIA;
3275 	case SIGNAL_TYPE_EDP:
3276 		return DRM_MODE_CONNECTOR_eDP;
3277 	case SIGNAL_TYPE_RGB:
3278 		return DRM_MODE_CONNECTOR_VGA;
3279 	case SIGNAL_TYPE_DISPLAY_PORT:
3280 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
3281 		return DRM_MODE_CONNECTOR_DisplayPort;
3282 	case SIGNAL_TYPE_DVI_DUAL_LINK:
3283 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
3284 		return DRM_MODE_CONNECTOR_DVID;
3285 	case SIGNAL_TYPE_VIRTUAL:
3286 		return DRM_MODE_CONNECTOR_VIRTUAL;
3287 
3288 	default:
3289 		return DRM_MODE_CONNECTOR_Unknown;
3290 	}
3291 }
3292 
3293 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
3294 {
3295 	const struct drm_connector_helper_funcs *helper =
3296 		connector->helper_private;
3297 	struct drm_encoder *encoder;
3298 	struct amdgpu_encoder *amdgpu_encoder;
3299 
3300 	encoder = helper->best_encoder(connector);
3301 
3302 	if (encoder == NULL)
3303 		return;
3304 
3305 	amdgpu_encoder = to_amdgpu_encoder(encoder);
3306 
3307 	amdgpu_encoder->native_mode.clock = 0;
3308 
3309 	if (!list_empty(&connector->probed_modes)) {
3310 		struct drm_display_mode *preferred_mode = NULL;
3311 
3312 		list_for_each_entry(preferred_mode,
3313 				    &connector->probed_modes,
3314 				    head) {
3315 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
3316 				amdgpu_encoder->native_mode = *preferred_mode;
3317 
3318 			break;
3319 		}
3320 
3321 	}
3322 }
3323 
3324 static struct drm_display_mode *
3325 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
3326 			     char *name,
3327 			     int hdisplay, int vdisplay)
3328 {
3329 	struct drm_device *dev = encoder->dev;
3330 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3331 	struct drm_display_mode *mode = NULL;
3332 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3333 
3334 	mode = drm_mode_duplicate(dev, native_mode);
3335 
3336 	if (mode == NULL)
3337 		return NULL;
3338 
3339 	mode->hdisplay = hdisplay;
3340 	mode->vdisplay = vdisplay;
3341 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
3342 	strncpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
3343 
3344 	return mode;
3345 
3346 }
3347 
3348 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
3349 						 struct drm_connector *connector)
3350 {
3351 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3352 	struct drm_display_mode *mode = NULL;
3353 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3354 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3355 				to_amdgpu_dm_connector(connector);
3356 	int i;
3357 	int n;
3358 	struct mode_size {
3359 		char name[DRM_DISPLAY_MODE_LEN];
3360 		int w;
3361 		int h;
3362 	} common_modes[] = {
3363 		{  "640x480",  640,  480},
3364 		{  "800x600",  800,  600},
3365 		{ "1024x768", 1024,  768},
3366 		{ "1280x720", 1280,  720},
3367 		{ "1280x800", 1280,  800},
3368 		{"1280x1024", 1280, 1024},
3369 		{ "1440x900", 1440,  900},
3370 		{"1680x1050", 1680, 1050},
3371 		{"1600x1200", 1600, 1200},
3372 		{"1920x1080", 1920, 1080},
3373 		{"1920x1200", 1920, 1200}
3374 	};
3375 
3376 	n = ARRAY_SIZE(common_modes);
3377 
3378 	for (i = 0; i < n; i++) {
3379 		struct drm_display_mode *curmode = NULL;
3380 		bool mode_existed = false;
3381 
3382 		if (common_modes[i].w > native_mode->hdisplay ||
3383 		    common_modes[i].h > native_mode->vdisplay ||
3384 		   (common_modes[i].w == native_mode->hdisplay &&
3385 		    common_modes[i].h == native_mode->vdisplay))
3386 			continue;
3387 
3388 		list_for_each_entry(curmode, &connector->probed_modes, head) {
3389 			if (common_modes[i].w == curmode->hdisplay &&
3390 			    common_modes[i].h == curmode->vdisplay) {
3391 				mode_existed = true;
3392 				break;
3393 			}
3394 		}
3395 
3396 		if (mode_existed)
3397 			continue;
3398 
3399 		mode = amdgpu_dm_create_common_mode(encoder,
3400 				common_modes[i].name, common_modes[i].w,
3401 				common_modes[i].h);
3402 		drm_mode_probed_add(connector, mode);
3403 		amdgpu_dm_connector->num_modes++;
3404 	}
3405 }
3406 
3407 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
3408 					      struct edid *edid)
3409 {
3410 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3411 			to_amdgpu_dm_connector(connector);
3412 
3413 	if (edid) {
3414 		/* empty probed_modes */
3415 		INIT_LIST_HEAD(&connector->probed_modes);
3416 		amdgpu_dm_connector->num_modes =
3417 				drm_add_edid_modes(connector, edid);
3418 
3419 		amdgpu_dm_get_native_mode(connector);
3420 	} else {
3421 		amdgpu_dm_connector->num_modes = 0;
3422 	}
3423 }
3424 
3425 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
3426 {
3427 	const struct drm_connector_helper_funcs *helper =
3428 			connector->helper_private;
3429 	struct amdgpu_dm_connector *amdgpu_dm_connector =
3430 			to_amdgpu_dm_connector(connector);
3431 	struct drm_encoder *encoder;
3432 	struct edid *edid = amdgpu_dm_connector->edid;
3433 
3434 	encoder = helper->best_encoder(connector);
3435 	amdgpu_dm_connector_ddc_get_modes(connector, edid);
3436 	amdgpu_dm_connector_add_common_modes(encoder, connector);
3437 
3438 #if defined(CONFIG_DRM_AMD_DC_FBC)
3439 	amdgpu_dm_fbc_init(connector);
3440 #endif
3441 	return amdgpu_dm_connector->num_modes;
3442 }
3443 
3444 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
3445 				     struct amdgpu_dm_connector *aconnector,
3446 				     int connector_type,
3447 				     struct dc_link *link,
3448 				     int link_index)
3449 {
3450 	struct amdgpu_device *adev = dm->ddev->dev_private;
3451 
3452 	aconnector->connector_id = link_index;
3453 	aconnector->dc_link = link;
3454 	aconnector->base.interlace_allowed = false;
3455 	aconnector->base.doublescan_allowed = false;
3456 	aconnector->base.stereo_allowed = false;
3457 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
3458 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
3459 
3460 	mutex_init(&aconnector->hpd_lock);
3461 
3462 	/* configure support HPD hot plug connector_>polled default value is 0
3463 	 * which means HPD hot plug not supported
3464 	 */
3465 	switch (connector_type) {
3466 	case DRM_MODE_CONNECTOR_HDMIA:
3467 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3468 		break;
3469 	case DRM_MODE_CONNECTOR_DisplayPort:
3470 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3471 		break;
3472 	case DRM_MODE_CONNECTOR_DVID:
3473 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3474 		break;
3475 	default:
3476 		break;
3477 	}
3478 
3479 	drm_object_attach_property(&aconnector->base.base,
3480 				dm->ddev->mode_config.scaling_mode_property,
3481 				DRM_MODE_SCALE_NONE);
3482 
3483 	drm_object_attach_property(&aconnector->base.base,
3484 				adev->mode_info.underscan_property,
3485 				UNDERSCAN_OFF);
3486 	drm_object_attach_property(&aconnector->base.base,
3487 				adev->mode_info.underscan_hborder_property,
3488 				0);
3489 	drm_object_attach_property(&aconnector->base.base,
3490 				adev->mode_info.underscan_vborder_property,
3491 				0);
3492 
3493 }
3494 
3495 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
3496 			      struct i2c_msg *msgs, int num)
3497 {
3498 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
3499 	struct ddc_service *ddc_service = i2c->ddc_service;
3500 	struct i2c_command cmd;
3501 	int i;
3502 	int result = -EIO;
3503 
3504 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
3505 
3506 	if (!cmd.payloads)
3507 		return result;
3508 
3509 	cmd.number_of_payloads = num;
3510 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
3511 	cmd.speed = 100;
3512 
3513 	for (i = 0; i < num; i++) {
3514 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
3515 		cmd.payloads[i].address = msgs[i].addr;
3516 		cmd.payloads[i].length = msgs[i].len;
3517 		cmd.payloads[i].data = msgs[i].buf;
3518 	}
3519 
3520 	if (dal_i2caux_submit_i2c_command(
3521 			ddc_service->ctx->i2caux,
3522 			ddc_service->ddc_pin,
3523 			&cmd))
3524 		result = num;
3525 
3526 	kfree(cmd.payloads);
3527 	return result;
3528 }
3529 
3530 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
3531 {
3532 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
3533 }
3534 
3535 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
3536 	.master_xfer = amdgpu_dm_i2c_xfer,
3537 	.functionality = amdgpu_dm_i2c_func,
3538 };
3539 
3540 static struct amdgpu_i2c_adapter *
3541 create_i2c(struct ddc_service *ddc_service,
3542 	   int link_index,
3543 	   int *res)
3544 {
3545 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
3546 	struct amdgpu_i2c_adapter *i2c;
3547 
3548 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
3549 	if (!i2c)
3550 		return NULL;
3551 	i2c->base.owner = THIS_MODULE;
3552 	i2c->base.class = I2C_CLASS_DDC;
3553 	i2c->base.dev.parent = &adev->pdev->dev;
3554 	i2c->base.algo = &amdgpu_dm_i2c_algo;
3555 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
3556 	i2c_set_adapdata(&i2c->base, i2c);
3557 	i2c->ddc_service = ddc_service;
3558 
3559 	return i2c;
3560 }
3561 
3562 /* Note: this function assumes that dc_link_detect() was called for the
3563  * dc_link which will be represented by this aconnector.
3564  */
3565 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
3566 				    struct amdgpu_dm_connector *aconnector,
3567 				    uint32_t link_index,
3568 				    struct amdgpu_encoder *aencoder)
3569 {
3570 	int res = 0;
3571 	int connector_type;
3572 	struct dc *dc = dm->dc;
3573 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
3574 	struct amdgpu_i2c_adapter *i2c;
3575 
3576 	link->priv = aconnector;
3577 
3578 	DRM_DEBUG_DRIVER("%s()\n", __func__);
3579 
3580 	i2c = create_i2c(link->ddc, link->link_index, &res);
3581 	if (!i2c) {
3582 		DRM_ERROR("Failed to create i2c adapter data\n");
3583 		return -ENOMEM;
3584 	}
3585 
3586 	aconnector->i2c = i2c;
3587 	res = i2c_add_adapter(&i2c->base);
3588 
3589 	if (res) {
3590 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
3591 		goto out_free;
3592 	}
3593 
3594 	connector_type = to_drm_connector_type(link->connector_signal);
3595 
3596 	res = drm_connector_init(
3597 			dm->ddev,
3598 			&aconnector->base,
3599 			&amdgpu_dm_connector_funcs,
3600 			connector_type);
3601 
3602 	if (res) {
3603 		DRM_ERROR("connector_init failed\n");
3604 		aconnector->connector_id = -1;
3605 		goto out_free;
3606 	}
3607 
3608 	drm_connector_helper_add(
3609 			&aconnector->base,
3610 			&amdgpu_dm_connector_helper_funcs);
3611 
3612 	if (aconnector->base.funcs->reset)
3613 		aconnector->base.funcs->reset(&aconnector->base);
3614 
3615 	amdgpu_dm_connector_init_helper(
3616 		dm,
3617 		aconnector,
3618 		connector_type,
3619 		link,
3620 		link_index);
3621 
3622 	drm_mode_connector_attach_encoder(
3623 		&aconnector->base, &aencoder->base);
3624 
3625 	drm_connector_register(&aconnector->base);
3626 
3627 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
3628 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
3629 		amdgpu_dm_initialize_dp_connector(dm, aconnector);
3630 
3631 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3632 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3633 
3634 	/* NOTE: this currently will create backlight device even if a panel
3635 	 * is not connected to the eDP/LVDS connector.
3636 	 *
3637 	 * This is less than ideal but we don't have sink information at this
3638 	 * stage since detection happens after. We can't do detection earlier
3639 	 * since MST detection needs connectors to be created first.
3640 	 */
3641 	if (link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) {
3642 		/* Event if registration failed, we should continue with
3643 		 * DM initialization because not having a backlight control
3644 		 * is better then a black screen.
3645 		 */
3646 		amdgpu_dm_register_backlight_device(dm);
3647 
3648 		if (dm->backlight_dev)
3649 			dm->backlight_link = link;
3650 	}
3651 #endif
3652 
3653 out_free:
3654 	if (res) {
3655 		kfree(i2c);
3656 		aconnector->i2c = NULL;
3657 	}
3658 	return res;
3659 }
3660 
3661 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
3662 {
3663 	switch (adev->mode_info.num_crtc) {
3664 	case 1:
3665 		return 0x1;
3666 	case 2:
3667 		return 0x3;
3668 	case 3:
3669 		return 0x7;
3670 	case 4:
3671 		return 0xf;
3672 	case 5:
3673 		return 0x1f;
3674 	case 6:
3675 	default:
3676 		return 0x3f;
3677 	}
3678 }
3679 
3680 static int amdgpu_dm_encoder_init(struct drm_device *dev,
3681 				  struct amdgpu_encoder *aencoder,
3682 				  uint32_t link_index)
3683 {
3684 	struct amdgpu_device *adev = dev->dev_private;
3685 
3686 	int res = drm_encoder_init(dev,
3687 				   &aencoder->base,
3688 				   &amdgpu_dm_encoder_funcs,
3689 				   DRM_MODE_ENCODER_TMDS,
3690 				   NULL);
3691 
3692 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
3693 
3694 	if (!res)
3695 		aencoder->encoder_id = link_index;
3696 	else
3697 		aencoder->encoder_id = -1;
3698 
3699 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
3700 
3701 	return res;
3702 }
3703 
3704 static void manage_dm_interrupts(struct amdgpu_device *adev,
3705 				 struct amdgpu_crtc *acrtc,
3706 				 bool enable)
3707 {
3708 	/*
3709 	 * this is not correct translation but will work as soon as VBLANK
3710 	 * constant is the same as PFLIP
3711 	 */
3712 	int irq_type =
3713 		amdgpu_display_crtc_idx_to_irq_type(
3714 			adev,
3715 			acrtc->crtc_id);
3716 
3717 	if (enable) {
3718 		drm_crtc_vblank_on(&acrtc->base);
3719 		amdgpu_irq_get(
3720 			adev,
3721 			&adev->pageflip_irq,
3722 			irq_type);
3723 	} else {
3724 
3725 		amdgpu_irq_put(
3726 			adev,
3727 			&adev->pageflip_irq,
3728 			irq_type);
3729 		drm_crtc_vblank_off(&acrtc->base);
3730 	}
3731 }
3732 
3733 static bool
3734 is_scaling_state_different(const struct dm_connector_state *dm_state,
3735 			   const struct dm_connector_state *old_dm_state)
3736 {
3737 	if (dm_state->scaling != old_dm_state->scaling)
3738 		return true;
3739 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
3740 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
3741 			return true;
3742 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
3743 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
3744 			return true;
3745 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
3746 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
3747 		return true;
3748 	return false;
3749 }
3750 
3751 static void remove_stream(struct amdgpu_device *adev,
3752 			  struct amdgpu_crtc *acrtc,
3753 			  struct dc_stream_state *stream)
3754 {
3755 	/* this is the update mode case */
3756 	if (adev->dm.freesync_module)
3757 		mod_freesync_remove_stream(adev->dm.freesync_module, stream);
3758 
3759 	acrtc->otg_inst = -1;
3760 	acrtc->enabled = false;
3761 }
3762 
3763 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
3764 			       struct dc_cursor_position *position)
3765 {
3766 	struct amdgpu_crtc *amdgpu_crtc = amdgpu_crtc = to_amdgpu_crtc(crtc);
3767 	int x, y;
3768 	int xorigin = 0, yorigin = 0;
3769 
3770 	if (!crtc || !plane->state->fb) {
3771 		position->enable = false;
3772 		position->x = 0;
3773 		position->y = 0;
3774 		return 0;
3775 	}
3776 
3777 	if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
3778 	    (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
3779 		DRM_ERROR("%s: bad cursor width or height %d x %d\n",
3780 			  __func__,
3781 			  plane->state->crtc_w,
3782 			  plane->state->crtc_h);
3783 		return -EINVAL;
3784 	}
3785 
3786 	x = plane->state->crtc_x;
3787 	y = plane->state->crtc_y;
3788 	/* avivo cursor are offset into the total surface */
3789 	x += crtc->primary->state->src_x >> 16;
3790 	y += crtc->primary->state->src_y >> 16;
3791 	if (x < 0) {
3792 		xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
3793 		x = 0;
3794 	}
3795 	if (y < 0) {
3796 		yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
3797 		y = 0;
3798 	}
3799 	position->enable = true;
3800 	position->x = x;
3801 	position->y = y;
3802 	position->x_hotspot = xorigin;
3803 	position->y_hotspot = yorigin;
3804 
3805 	return 0;
3806 }
3807 
3808 static void handle_cursor_update(struct drm_plane *plane,
3809 				 struct drm_plane_state *old_plane_state)
3810 {
3811 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
3812 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
3813 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
3814 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3815 	uint64_t address = afb ? afb->address : 0;
3816 	struct dc_cursor_position position;
3817 	struct dc_cursor_attributes attributes;
3818 	int ret;
3819 
3820 	if (!plane->state->fb && !old_plane_state->fb)
3821 		return;
3822 
3823 	DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
3824 			 __func__,
3825 			 amdgpu_crtc->crtc_id,
3826 			 plane->state->crtc_w,
3827 			 plane->state->crtc_h);
3828 
3829 	ret = get_cursor_position(plane, crtc, &position);
3830 	if (ret)
3831 		return;
3832 
3833 	if (!position.enable) {
3834 		/* turn off cursor */
3835 		if (crtc_state && crtc_state->stream)
3836 			dc_stream_set_cursor_position(crtc_state->stream,
3837 						      &position);
3838 		return;
3839 	}
3840 
3841 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
3842 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
3843 
3844 	attributes.address.high_part = upper_32_bits(address);
3845 	attributes.address.low_part  = lower_32_bits(address);
3846 	attributes.width             = plane->state->crtc_w;
3847 	attributes.height            = plane->state->crtc_h;
3848 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
3849 	attributes.rotation_angle    = 0;
3850 	attributes.attribute_flags.value = 0;
3851 
3852 	attributes.pitch = attributes.width;
3853 
3854 	if (crtc_state->stream) {
3855 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
3856 							 &attributes))
3857 			DRM_ERROR("DC failed to set cursor attributes\n");
3858 
3859 		if (!dc_stream_set_cursor_position(crtc_state->stream,
3860 						   &position))
3861 			DRM_ERROR("DC failed to set cursor position\n");
3862 	}
3863 }
3864 
3865 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
3866 {
3867 
3868 	assert_spin_locked(&acrtc->base.dev->event_lock);
3869 	WARN_ON(acrtc->event);
3870 
3871 	acrtc->event = acrtc->base.state->event;
3872 
3873 	/* Set the flip status */
3874 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
3875 
3876 	/* Mark this event as consumed */
3877 	acrtc->base.state->event = NULL;
3878 
3879 	DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
3880 						 acrtc->crtc_id);
3881 }
3882 
3883 /*
3884  * Executes flip
3885  *
3886  * Waits on all BO's fences and for proper vblank count
3887  */
3888 static void amdgpu_dm_do_flip(struct drm_crtc *crtc,
3889 			      struct drm_framebuffer *fb,
3890 			      uint32_t target,
3891 			      struct dc_state *state)
3892 {
3893 	unsigned long flags;
3894 	uint32_t target_vblank;
3895 	int r, vpos, hpos;
3896 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3897 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
3898 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(afb->obj);
3899 	struct amdgpu_device *adev = crtc->dev->dev_private;
3900 	bool async_flip = (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
3901 	struct dc_flip_addrs addr = { {0} };
3902 	/* TODO eliminate or rename surface_update */
3903 	struct dc_surface_update surface_updates[1] = { {0} };
3904 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3905 
3906 
3907 	/* Prepare wait for target vblank early - before the fence-waits */
3908 	target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
3909 			amdgpu_get_vblank_counter_kms(crtc->dev, acrtc->crtc_id);
3910 
3911 	/* TODO This might fail and hence better not used, wait
3912 	 * explicitly on fences instead
3913 	 * and in general should be called for
3914 	 * blocking commit to as per framework helpers
3915 	 */
3916 	r = amdgpu_bo_reserve(abo, true);
3917 	if (unlikely(r != 0)) {
3918 		DRM_ERROR("failed to reserve buffer before flip\n");
3919 		WARN_ON(1);
3920 	}
3921 
3922 	/* Wait for all fences on this FB */
3923 	WARN_ON(reservation_object_wait_timeout_rcu(abo->tbo.resv, true, false,
3924 								    MAX_SCHEDULE_TIMEOUT) < 0);
3925 
3926 	amdgpu_bo_unreserve(abo);
3927 
3928 	/* Wait until we're out of the vertical blank period before the one
3929 	 * targeted by the flip
3930 	 */
3931 	while ((acrtc->enabled &&
3932 		(amdgpu_display_get_crtc_scanoutpos(adev->ddev, acrtc->crtc_id,
3933 						    0, &vpos, &hpos, NULL,
3934 						    NULL, &crtc->hwmode)
3935 		 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
3936 		(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
3937 		(int)(target_vblank -
3938 		  amdgpu_get_vblank_counter_kms(adev->ddev, acrtc->crtc_id)) > 0)) {
3939 		usleep_range(1000, 1100);
3940 	}
3941 
3942 	/* Flip */
3943 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
3944 	/* update crtc fb */
3945 	crtc->primary->fb = fb;
3946 
3947 	WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
3948 	WARN_ON(!acrtc_state->stream);
3949 
3950 	addr.address.grph.addr.low_part = lower_32_bits(afb->address);
3951 	addr.address.grph.addr.high_part = upper_32_bits(afb->address);
3952 	addr.flip_immediate = async_flip;
3953 
3954 
3955 	if (acrtc->base.state->event)
3956 		prepare_flip_isr(acrtc);
3957 
3958 	surface_updates->surface = dc_stream_get_status(acrtc_state->stream)->plane_states[0];
3959 	surface_updates->flip_addr = &addr;
3960 
3961 
3962 	dc_commit_updates_for_stream(adev->dm.dc,
3963 					     surface_updates,
3964 					     1,
3965 					     acrtc_state->stream,
3966 					     NULL,
3967 					     &surface_updates->surface,
3968 					     state);
3969 
3970 	DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x \n",
3971 			 __func__,
3972 			 addr.address.grph.addr.high_part,
3973 			 addr.address.grph.addr.low_part);
3974 
3975 
3976 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
3977 }
3978 
3979 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
3980 				    struct drm_device *dev,
3981 				    struct amdgpu_display_manager *dm,
3982 				    struct drm_crtc *pcrtc,
3983 				    bool *wait_for_vblank)
3984 {
3985 	uint32_t i;
3986 	struct drm_plane *plane;
3987 	struct drm_plane_state *old_plane_state, *new_plane_state;
3988 	struct dc_stream_state *dc_stream_attach;
3989 	struct dc_plane_state *plane_states_constructed[MAX_SURFACES];
3990 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
3991 	struct drm_crtc_state *new_pcrtc_state =
3992 			drm_atomic_get_new_crtc_state(state, pcrtc);
3993 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
3994 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3995 	int planes_count = 0;
3996 	unsigned long flags;
3997 
3998 	/* update planes when needed */
3999 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
4000 		struct drm_crtc *crtc = new_plane_state->crtc;
4001 		struct drm_crtc_state *new_crtc_state;
4002 		struct drm_framebuffer *fb = new_plane_state->fb;
4003 		bool pflip_needed;
4004 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
4005 
4006 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
4007 			handle_cursor_update(plane, old_plane_state);
4008 			continue;
4009 		}
4010 
4011 		if (!fb || !crtc || pcrtc != crtc)
4012 			continue;
4013 
4014 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
4015 		if (!new_crtc_state->active)
4016 			continue;
4017 
4018 		pflip_needed = !state->allow_modeset;
4019 
4020 		spin_lock_irqsave(&crtc->dev->event_lock, flags);
4021 		if (acrtc_attach->pflip_status != AMDGPU_FLIP_NONE) {
4022 			DRM_ERROR("%s: acrtc %d, already busy\n",
4023 				  __func__,
4024 				  acrtc_attach->crtc_id);
4025 			/* In commit tail framework this cannot happen */
4026 			WARN_ON(1);
4027 		}
4028 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4029 
4030 		if (!pflip_needed) {
4031 			WARN_ON(!dm_new_plane_state->dc_state);
4032 
4033 			plane_states_constructed[planes_count] = dm_new_plane_state->dc_state;
4034 
4035 			dc_stream_attach = acrtc_state->stream;
4036 			planes_count++;
4037 
4038 		} else if (new_crtc_state->planes_changed) {
4039 			/* Assume even ONE crtc with immediate flip means
4040 			 * entire can't wait for VBLANK
4041 			 * TODO Check if it's correct
4042 			 */
4043 			*wait_for_vblank =
4044 					new_pcrtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC ?
4045 				false : true;
4046 
4047 			/* TODO: Needs rework for multiplane flip */
4048 			if (plane->type == DRM_PLANE_TYPE_PRIMARY)
4049 				drm_crtc_vblank_get(crtc);
4050 
4051 			amdgpu_dm_do_flip(
4052 				crtc,
4053 				fb,
4054 				(uint32_t)drm_crtc_vblank_count(crtc) + *wait_for_vblank,
4055 				dm_state->context);
4056 		}
4057 
4058 	}
4059 
4060 	if (planes_count) {
4061 		unsigned long flags;
4062 
4063 		if (new_pcrtc_state->event) {
4064 
4065 			drm_crtc_vblank_get(pcrtc);
4066 
4067 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4068 			prepare_flip_isr(acrtc_attach);
4069 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4070 		}
4071 
4072 		if (false == dc_commit_planes_to_stream(dm->dc,
4073 							plane_states_constructed,
4074 							planes_count,
4075 							dc_stream_attach,
4076 							dm_state->context))
4077 			dm_error("%s: Failed to attach plane!\n", __func__);
4078 	} else {
4079 		/*TODO BUG Here should go disable planes on CRTC. */
4080 	}
4081 }
4082 
4083 /**
4084  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4085  * @crtc_state: the DRM CRTC state
4086  * @stream_state: the DC stream state.
4087  *
4088  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4089  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4090  */
4091 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4092 						struct dc_stream_state *stream_state)
4093 {
4094 	stream_state->mode_changed = crtc_state->mode_changed;
4095 }
4096 
4097 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
4098 				   struct drm_atomic_state *state,
4099 				   bool nonblock)
4100 {
4101 	struct drm_crtc *crtc;
4102 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4103 	struct amdgpu_device *adev = dev->dev_private;
4104 	int i;
4105 
4106 	/*
4107 	 * We evade vblanks and pflips on crtc that
4108 	 * should be changed. We do it here to flush & disable
4109 	 * interrupts before drm_swap_state is called in drm_atomic_helper_commit
4110 	 * it will update crtc->dm_crtc_state->stream pointer which is used in
4111 	 * the ISRs.
4112 	 */
4113 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4114 		struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4115 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4116 
4117 		if (drm_atomic_crtc_needs_modeset(new_crtc_state) && dm_old_crtc_state->stream)
4118 			manage_dm_interrupts(adev, acrtc, false);
4119 	}
4120 	/* Add check here for SoC's that support hardware cursor plane, to
4121 	 * unset legacy_cursor_update */
4122 
4123 	return drm_atomic_helper_commit(dev, state, nonblock);
4124 
4125 	/*TODO Handle EINTR, reenable IRQ*/
4126 }
4127 
4128 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
4129 {
4130 	struct drm_device *dev = state->dev;
4131 	struct amdgpu_device *adev = dev->dev_private;
4132 	struct amdgpu_display_manager *dm = &adev->dm;
4133 	struct dm_atomic_state *dm_state;
4134 	uint32_t i, j;
4135 	struct drm_crtc *crtc;
4136 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4137 	unsigned long flags;
4138 	bool wait_for_vblank = true;
4139 	struct drm_connector *connector;
4140 	struct drm_connector_state *old_con_state, *new_con_state;
4141 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4142 
4143 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
4144 
4145 	dm_state = to_dm_atomic_state(state);
4146 
4147 	/* update changed items */
4148 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4149 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4150 
4151 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4152 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4153 
4154 		DRM_DEBUG_DRIVER(
4155 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4156 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
4157 			"connectors_changed:%d\n",
4158 			acrtc->crtc_id,
4159 			new_crtc_state->enable,
4160 			new_crtc_state->active,
4161 			new_crtc_state->planes_changed,
4162 			new_crtc_state->mode_changed,
4163 			new_crtc_state->active_changed,
4164 			new_crtc_state->connectors_changed);
4165 
4166 		/* Copy all transient state flags into dc state */
4167 		if (dm_new_crtc_state->stream) {
4168 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4169 							    dm_new_crtc_state->stream);
4170 		}
4171 
4172 		/* handles headless hotplug case, updating new_state and
4173 		 * aconnector as needed
4174 		 */
4175 
4176 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4177 
4178 			DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
4179 
4180 			if (!dm_new_crtc_state->stream) {
4181 				/*
4182 				 * this could happen because of issues with
4183 				 * userspace notifications delivery.
4184 				 * In this case userspace tries to set mode on
4185 				 * display which is disconnect in fact.
4186 				 * dc_sink in NULL in this case on aconnector.
4187 				 * We expect reset mode will come soon.
4188 				 *
4189 				 * This can also happen when unplug is done
4190 				 * during resume sequence ended
4191 				 *
4192 				 * In this case, we want to pretend we still
4193 				 * have a sink to keep the pipe running so that
4194 				 * hw state is consistent with the sw state
4195 				 */
4196 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4197 						__func__, acrtc->base.base.id);
4198 				continue;
4199 			}
4200 
4201 			if (dm_old_crtc_state->stream)
4202 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4203 
4204 			acrtc->enabled = true;
4205 			acrtc->hw_mode = new_crtc_state->mode;
4206 			crtc->hwmode = new_crtc_state->mode;
4207 		} else if (modereset_required(new_crtc_state)) {
4208 			DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
4209 
4210 			/* i.e. reset mode */
4211 			if (dm_old_crtc_state->stream)
4212 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4213 		}
4214 	} /* for_each_crtc_in_state() */
4215 
4216 	/*
4217 	 * Add streams after required streams from new and replaced streams
4218 	 * are removed from freesync module
4219 	 */
4220 	if (adev->dm.freesync_module) {
4221 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4222 					      new_crtc_state, i) {
4223 			struct amdgpu_dm_connector *aconnector = NULL;
4224 			struct dm_connector_state *dm_new_con_state = NULL;
4225 			struct amdgpu_crtc *acrtc = NULL;
4226 			bool modeset_needed;
4227 
4228 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4229 			dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4230 			modeset_needed = modeset_required(
4231 					new_crtc_state,
4232 					dm_new_crtc_state->stream,
4233 					dm_old_crtc_state->stream);
4234 			/* We add stream to freesync if:
4235 			 * 1. Said stream is not null, and
4236 			 * 2. A modeset is requested. This means that the
4237 			 *    stream was removed previously, and needs to be
4238 			 *    replaced.
4239 			 */
4240 			if (dm_new_crtc_state->stream == NULL ||
4241 					!modeset_needed)
4242 				continue;
4243 
4244 			acrtc = to_amdgpu_crtc(crtc);
4245 
4246 			aconnector =
4247 				amdgpu_dm_find_first_crtc_matching_connector(
4248 					state, crtc);
4249 			if (!aconnector) {
4250 				DRM_DEBUG_DRIVER("Atomic commit: Failed to "
4251 						 "find connector for acrtc "
4252 						 "id:%d skipping freesync "
4253 						 "init\n",
4254 						 acrtc->crtc_id);
4255 				continue;
4256 			}
4257 
4258 			mod_freesync_add_stream(adev->dm.freesync_module,
4259 						dm_new_crtc_state->stream,
4260 						&aconnector->caps);
4261 			new_con_state = drm_atomic_get_new_connector_state(
4262 					state, &aconnector->base);
4263 			dm_new_con_state = to_dm_connector_state(new_con_state);
4264 
4265 			mod_freesync_set_user_enable(adev->dm.freesync_module,
4266 						     &dm_new_crtc_state->stream,
4267 						     1,
4268 						     &dm_new_con_state->user_enable);
4269 		}
4270 	}
4271 
4272 	if (dm_state->context) {
4273 		dm_enable_per_frame_crtc_master_sync(dm_state->context);
4274 		WARN_ON(!dc_commit_state(dm->dc, dm_state->context));
4275 	}
4276 
4277 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4278 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4279 
4280 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4281 
4282 		if (dm_new_crtc_state->stream != NULL) {
4283 			const struct dc_stream_status *status =
4284 					dc_stream_get_status(dm_new_crtc_state->stream);
4285 
4286 			if (!status)
4287 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
4288 			else
4289 				acrtc->otg_inst = status->primary_otg_inst;
4290 		}
4291 	}
4292 
4293 	/* Handle scaling and underscan changes*/
4294 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4295 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4296 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
4297 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4298 		struct dc_stream_status *status = NULL;
4299 
4300 		if (acrtc)
4301 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
4302 
4303 		/* Skip any modesets/resets */
4304 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
4305 			continue;
4306 
4307 		/* Skip any thing not scale or underscan changes */
4308 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
4309 			continue;
4310 
4311 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4312 
4313 		update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
4314 				dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
4315 
4316 		if (!dm_new_crtc_state->stream)
4317 			continue;
4318 
4319 		status = dc_stream_get_status(dm_new_crtc_state->stream);
4320 		WARN_ON(!status);
4321 		WARN_ON(!status->plane_count);
4322 
4323 		/*TODO How it works with MPO ?*/
4324 		if (!dc_commit_planes_to_stream(
4325 				dm->dc,
4326 				status->plane_states,
4327 				status->plane_count,
4328 				dm_new_crtc_state->stream,
4329 				dm_state->context))
4330 			dm_error("%s: Failed to update stream scaling!\n", __func__);
4331 	}
4332 
4333 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4334 			new_crtc_state, i) {
4335 		/*
4336 		 * loop to enable interrupts on newly arrived crtc
4337 		 */
4338 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4339 		bool modeset_needed;
4340 
4341 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4342 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4343 		modeset_needed = modeset_required(
4344 				new_crtc_state,
4345 				dm_new_crtc_state->stream,
4346 				dm_old_crtc_state->stream);
4347 
4348 		if (dm_new_crtc_state->stream == NULL || !modeset_needed)
4349 			continue;
4350 
4351 		if (adev->dm.freesync_module)
4352 			mod_freesync_notify_mode_change(
4353 				adev->dm.freesync_module,
4354 				&dm_new_crtc_state->stream, 1);
4355 
4356 		manage_dm_interrupts(adev, acrtc, true);
4357 	}
4358 
4359 	/* update planes when needed per crtc*/
4360 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
4361 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4362 
4363 		if (dm_new_crtc_state->stream)
4364 			amdgpu_dm_commit_planes(state, dev, dm, crtc, &wait_for_vblank);
4365 	}
4366 
4367 
4368 	/*
4369 	 * send vblank event on all events not handled in flip and
4370 	 * mark consumed event for drm_atomic_helper_commit_hw_done
4371 	 */
4372 	spin_lock_irqsave(&adev->ddev->event_lock, flags);
4373 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4374 
4375 		if (new_crtc_state->event)
4376 			drm_send_event_locked(dev, &new_crtc_state->event->base);
4377 
4378 		new_crtc_state->event = NULL;
4379 	}
4380 	spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
4381 
4382 	/* Signal HW programming completion */
4383 	drm_atomic_helper_commit_hw_done(state);
4384 
4385 	if (wait_for_vblank)
4386 		drm_atomic_helper_wait_for_flip_done(dev, state);
4387 
4388 	drm_atomic_helper_cleanup_planes(dev, state);
4389 }
4390 
4391 
4392 static int dm_force_atomic_commit(struct drm_connector *connector)
4393 {
4394 	int ret = 0;
4395 	struct drm_device *ddev = connector->dev;
4396 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
4397 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4398 	struct drm_plane *plane = disconnected_acrtc->base.primary;
4399 	struct drm_connector_state *conn_state;
4400 	struct drm_crtc_state *crtc_state;
4401 	struct drm_plane_state *plane_state;
4402 
4403 	if (!state)
4404 		return -ENOMEM;
4405 
4406 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
4407 
4408 	/* Construct an atomic state to restore previous display setting */
4409 
4410 	/*
4411 	 * Attach connectors to drm_atomic_state
4412 	 */
4413 	conn_state = drm_atomic_get_connector_state(state, connector);
4414 
4415 	ret = PTR_ERR_OR_ZERO(conn_state);
4416 	if (ret)
4417 		goto err;
4418 
4419 	/* Attach crtc to drm_atomic_state*/
4420 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
4421 
4422 	ret = PTR_ERR_OR_ZERO(crtc_state);
4423 	if (ret)
4424 		goto err;
4425 
4426 	/* force a restore */
4427 	crtc_state->mode_changed = true;
4428 
4429 	/* Attach plane to drm_atomic_state */
4430 	plane_state = drm_atomic_get_plane_state(state, plane);
4431 
4432 	ret = PTR_ERR_OR_ZERO(plane_state);
4433 	if (ret)
4434 		goto err;
4435 
4436 
4437 	/* Call commit internally with the state we just constructed */
4438 	ret = drm_atomic_commit(state);
4439 	if (!ret)
4440 		return 0;
4441 
4442 err:
4443 	DRM_ERROR("Restoring old state failed with %i\n", ret);
4444 	drm_atomic_state_put(state);
4445 
4446 	return ret;
4447 }
4448 
4449 /*
4450  * This functions handle all cases when set mode does not come upon hotplug.
4451  * This include when the same display is unplugged then plugged back into the
4452  * same port and when we are running without usermode desktop manager supprot
4453  */
4454 void dm_restore_drm_connector_state(struct drm_device *dev,
4455 				    struct drm_connector *connector)
4456 {
4457 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4458 	struct amdgpu_crtc *disconnected_acrtc;
4459 	struct dm_crtc_state *acrtc_state;
4460 
4461 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
4462 		return;
4463 
4464 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4465 	if (!disconnected_acrtc)
4466 		return;
4467 
4468 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
4469 	if (!acrtc_state->stream)
4470 		return;
4471 
4472 	/*
4473 	 * If the previous sink is not released and different from the current,
4474 	 * we deduce we are in a state where we can not rely on usermode call
4475 	 * to turn on the display, so we do it here
4476 	 */
4477 	if (acrtc_state->stream->sink != aconnector->dc_sink)
4478 		dm_force_atomic_commit(&aconnector->base);
4479 }
4480 
4481 /*`
4482  * Grabs all modesetting locks to serialize against any blocking commits,
4483  * Waits for completion of all non blocking commits.
4484  */
4485 static int do_aquire_global_lock(struct drm_device *dev,
4486 				 struct drm_atomic_state *state)
4487 {
4488 	struct drm_crtc *crtc;
4489 	struct drm_crtc_commit *commit;
4490 	long ret;
4491 
4492 	/* Adding all modeset locks to aquire_ctx will
4493 	 * ensure that when the framework release it the
4494 	 * extra locks we are locking here will get released to
4495 	 */
4496 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
4497 	if (ret)
4498 		return ret;
4499 
4500 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
4501 		spin_lock(&crtc->commit_lock);
4502 		commit = list_first_entry_or_null(&crtc->commit_list,
4503 				struct drm_crtc_commit, commit_entry);
4504 		if (commit)
4505 			drm_crtc_commit_get(commit);
4506 		spin_unlock(&crtc->commit_lock);
4507 
4508 		if (!commit)
4509 			continue;
4510 
4511 		/* Make sure all pending HW programming completed and
4512 		 * page flips done
4513 		 */
4514 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
4515 
4516 		if (ret > 0)
4517 			ret = wait_for_completion_interruptible_timeout(
4518 					&commit->flip_done, 10*HZ);
4519 
4520 		if (ret == 0)
4521 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
4522 				  "timed out\n", crtc->base.id, crtc->name);
4523 
4524 		drm_crtc_commit_put(commit);
4525 	}
4526 
4527 	return ret < 0 ? ret : 0;
4528 }
4529 
4530 static int dm_update_crtcs_state(struct dc *dc,
4531 				 struct drm_atomic_state *state,
4532 				 bool enable,
4533 				 bool *lock_and_validation_needed)
4534 {
4535 	struct drm_crtc *crtc;
4536 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4537 	int i;
4538 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4539 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4540 	struct dc_stream_state *new_stream;
4541 	int ret = 0;
4542 
4543 	/*TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set */
4544 	/* update changed items */
4545 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4546 		struct amdgpu_crtc *acrtc = NULL;
4547 		struct amdgpu_dm_connector *aconnector = NULL;
4548 		struct drm_connector_state *new_con_state = NULL;
4549 		struct dm_connector_state *dm_conn_state = NULL;
4550 
4551 		new_stream = NULL;
4552 
4553 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4554 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4555 		acrtc = to_amdgpu_crtc(crtc);
4556 
4557 		aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
4558 
4559 		/* TODO This hack should go away */
4560 		if (aconnector && enable) {
4561 			// Make sure fake sink is created in plug-in scenario
4562 			new_con_state = drm_atomic_get_connector_state(state,
4563  								    &aconnector->base);
4564 
4565 			if (IS_ERR(new_con_state)) {
4566 				ret = PTR_ERR_OR_ZERO(new_con_state);
4567 				break;
4568 			}
4569 
4570 			dm_conn_state = to_dm_connector_state(new_con_state);
4571 
4572 			new_stream = create_stream_for_sink(aconnector,
4573 							     &new_crtc_state->mode,
4574 							    dm_conn_state);
4575 
4576 			/*
4577 			 * we can have no stream on ACTION_SET if a display
4578 			 * was disconnected during S3, in this case it not and
4579 			 * error, the OS will be updated after detection, and
4580 			 * do the right thing on next atomic commit
4581 			 */
4582 
4583 			if (!new_stream) {
4584 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4585 						__func__, acrtc->base.base.id);
4586 				break;
4587 			}
4588 
4589 			if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
4590 			    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
4591 				new_crtc_state->mode_changed = false;
4592 				DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
4593 						 new_crtc_state->mode_changed);
4594 			}
4595 		}
4596 
4597 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4598 			goto next_crtc;
4599 
4600 		DRM_DEBUG_DRIVER(
4601 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4602 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
4603 			"connectors_changed:%d\n",
4604 			acrtc->crtc_id,
4605 			new_crtc_state->enable,
4606 			new_crtc_state->active,
4607 			new_crtc_state->planes_changed,
4608 			new_crtc_state->mode_changed,
4609 			new_crtc_state->active_changed,
4610 			new_crtc_state->connectors_changed);
4611 
4612 		/* Remove stream for any changed/disabled CRTC */
4613 		if (!enable) {
4614 
4615 			if (!dm_old_crtc_state->stream)
4616 				goto next_crtc;
4617 
4618 			DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
4619 					crtc->base.id);
4620 
4621 			/* i.e. reset mode */
4622 			if (dc_remove_stream_from_ctx(
4623 					dc,
4624 					dm_state->context,
4625 					dm_old_crtc_state->stream) != DC_OK) {
4626 				ret = -EINVAL;
4627 				goto fail;
4628 			}
4629 
4630 			dc_stream_release(dm_old_crtc_state->stream);
4631 			dm_new_crtc_state->stream = NULL;
4632 
4633 			*lock_and_validation_needed = true;
4634 
4635 		} else {/* Add stream for any updated/enabled CRTC */
4636 			/*
4637 			 * Quick fix to prevent NULL pointer on new_stream when
4638 			 * added MST connectors not found in existing crtc_state in the chained mode
4639 			 * TODO: need to dig out the root cause of that
4640 			 */
4641 			if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
4642 				goto next_crtc;
4643 
4644 			if (modereset_required(new_crtc_state))
4645 				goto next_crtc;
4646 
4647 			if (modeset_required(new_crtc_state, new_stream,
4648 					     dm_old_crtc_state->stream)) {
4649 
4650 				WARN_ON(dm_new_crtc_state->stream);
4651 
4652 				dm_new_crtc_state->stream = new_stream;
4653 
4654 				dc_stream_retain(new_stream);
4655 
4656 				DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
4657 							crtc->base.id);
4658 
4659 				if (dc_add_stream_to_ctx(
4660 						dc,
4661 						dm_state->context,
4662 						dm_new_crtc_state->stream) != DC_OK) {
4663 					ret = -EINVAL;
4664 					goto fail;
4665 				}
4666 
4667 				*lock_and_validation_needed = true;
4668 			}
4669 		}
4670 
4671 next_crtc:
4672 		/* Release extra reference */
4673 		if (new_stream)
4674 			 dc_stream_release(new_stream);
4675 
4676 		/*
4677 		 * We want to do dc stream updates that do not require a
4678 		 * full modeset below.
4679 		 */
4680 		if (!enable || !aconnector || modereset_required(new_crtc_state))
4681 			continue;
4682 		/*
4683 		 * Given above conditions, the dc state cannot be NULL because:
4684 		 * 1. We're attempting to enable a CRTC. Which has a...
4685 		 * 2. Valid connector attached, and
4686 		 * 3. User does not want to reset it (disable or mark inactive,
4687 		 *    which can happen on a CRTC that's already disabled).
4688 		 * => It currently exists.
4689 		 */
4690 		BUG_ON(dm_new_crtc_state->stream == NULL);
4691 
4692 		/* Color managment settings */
4693 		if (dm_new_crtc_state->base.color_mgmt_changed) {
4694 			ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
4695 			if (ret)
4696 				goto fail;
4697 			amdgpu_dm_set_ctm(dm_new_crtc_state);
4698 		}
4699 	}
4700 
4701 	return ret;
4702 
4703 fail:
4704 	if (new_stream)
4705 		dc_stream_release(new_stream);
4706 	return ret;
4707 }
4708 
4709 static int dm_update_planes_state(struct dc *dc,
4710 				  struct drm_atomic_state *state,
4711 				  bool enable,
4712 				  bool *lock_and_validation_needed)
4713 {
4714 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
4715 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4716 	struct drm_plane *plane;
4717 	struct drm_plane_state *old_plane_state, *new_plane_state;
4718 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
4719 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4720 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
4721 	int i ;
4722 	/* TODO return page_flip_needed() function */
4723 	bool pflip_needed  = !state->allow_modeset;
4724 	int ret = 0;
4725 
4726 
4727 	/* Add new planes, in reverse order as DC expectation */
4728 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
4729 		new_plane_crtc = new_plane_state->crtc;
4730 		old_plane_crtc = old_plane_state->crtc;
4731 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
4732 		dm_old_plane_state = to_dm_plane_state(old_plane_state);
4733 
4734 		/*TODO Implement atomic check for cursor plane */
4735 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
4736 			continue;
4737 
4738 		/* Remove any changed/removed planes */
4739 		if (!enable) {
4740 			if (pflip_needed)
4741 				continue;
4742 
4743 			if (!old_plane_crtc)
4744 				continue;
4745 
4746 			old_crtc_state = drm_atomic_get_old_crtc_state(
4747 					state, old_plane_crtc);
4748 			dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4749 
4750 			if (!dm_old_crtc_state->stream)
4751 				continue;
4752 
4753 			DRM_DEBUG_DRIVER("Disabling DRM plane: %d on DRM crtc %d\n",
4754 					plane->base.id, old_plane_crtc->base.id);
4755 
4756 			if (!dc_remove_plane_from_context(
4757 					dc,
4758 					dm_old_crtc_state->stream,
4759 					dm_old_plane_state->dc_state,
4760 					dm_state->context)) {
4761 
4762 				ret = EINVAL;
4763 				return ret;
4764 			}
4765 
4766 
4767 			dc_plane_state_release(dm_old_plane_state->dc_state);
4768 			dm_new_plane_state->dc_state = NULL;
4769 
4770 			*lock_and_validation_needed = true;
4771 
4772 		} else { /* Add new planes */
4773 			struct dc_plane_state *dc_new_plane_state;
4774 
4775 			if (drm_atomic_plane_disabling(plane->state, new_plane_state))
4776 				continue;
4777 
4778 			if (!new_plane_crtc)
4779 				continue;
4780 
4781 			new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
4782 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4783 
4784 			if (!dm_new_crtc_state->stream)
4785 				continue;
4786 
4787 			if (pflip_needed)
4788 				continue;
4789 
4790 			WARN_ON(dm_new_plane_state->dc_state);
4791 
4792 			dc_new_plane_state = dc_create_plane_state(dc);
4793 			if (!dc_new_plane_state)
4794 				return -ENOMEM;
4795 
4796 			DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
4797 					plane->base.id, new_plane_crtc->base.id);
4798 
4799 			ret = fill_plane_attributes(
4800 				new_plane_crtc->dev->dev_private,
4801 				dc_new_plane_state,
4802 				new_plane_state,
4803 				new_crtc_state);
4804 			if (ret) {
4805 				dc_plane_state_release(dc_new_plane_state);
4806 				return ret;
4807 			}
4808 
4809 			/*
4810 			 * Any atomic check errors that occur after this will
4811 			 * not need a release. The plane state will be attached
4812 			 * to the stream, and therefore part of the atomic
4813 			 * state. It'll be released when the atomic state is
4814 			 * cleaned.
4815 			 */
4816 			if (!dc_add_plane_to_context(
4817 					dc,
4818 					dm_new_crtc_state->stream,
4819 					dc_new_plane_state,
4820 					dm_state->context)) {
4821 
4822 				dc_plane_state_release(dc_new_plane_state);
4823 				return -EINVAL;
4824 			}
4825 
4826 			dm_new_plane_state->dc_state = dc_new_plane_state;
4827 
4828 			/* Tell DC to do a full surface update every time there
4829 			 * is a plane change. Inefficient, but works for now.
4830 			 */
4831 			dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
4832 
4833 			*lock_and_validation_needed = true;
4834 		}
4835 	}
4836 
4837 
4838 	return ret;
4839 }
4840 
4841 static int dm_atomic_check_plane_state_fb(struct drm_atomic_state *state,
4842 					  struct drm_crtc *crtc)
4843 {
4844 	struct drm_plane *plane;
4845 	struct drm_crtc_state *crtc_state;
4846 
4847 	WARN_ON(!drm_atomic_get_new_crtc_state(state, crtc));
4848 
4849 	drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
4850 		struct drm_plane_state *plane_state =
4851 			drm_atomic_get_plane_state(state, plane);
4852 
4853 		if (IS_ERR(plane_state))
4854 			return -EDEADLK;
4855 
4856 		crtc_state = drm_atomic_get_crtc_state(plane_state->state, crtc);
4857 		if (IS_ERR(crtc_state))
4858 			return PTR_ERR(crtc_state);
4859 
4860 		if (crtc->primary == plane && crtc_state->active) {
4861 			if (!plane_state->fb)
4862 				return -EINVAL;
4863 		}
4864 	}
4865 	return 0;
4866 }
4867 
4868 static int amdgpu_dm_atomic_check(struct drm_device *dev,
4869 				  struct drm_atomic_state *state)
4870 {
4871 	struct amdgpu_device *adev = dev->dev_private;
4872 	struct dc *dc = adev->dm.dc;
4873 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4874 	struct drm_connector *connector;
4875 	struct drm_connector_state *old_con_state, *new_con_state;
4876 	struct drm_crtc *crtc;
4877 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4878 	int ret, i;
4879 
4880 	/*
4881 	 * This bool will be set for true for any modeset/reset
4882 	 * or plane update which implies non fast surface update.
4883 	 */
4884 	bool lock_and_validation_needed = false;
4885 
4886 	ret = drm_atomic_helper_check_modeset(dev, state);
4887 	if (ret)
4888 		goto fail;
4889 
4890 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4891 		ret = dm_atomic_check_plane_state_fb(state, crtc);
4892 		if (ret)
4893 			goto fail;
4894 
4895 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
4896 		    !new_crtc_state->color_mgmt_changed)
4897 			continue;
4898 
4899 		if (!new_crtc_state->enable)
4900 			continue;
4901 
4902 		ret = drm_atomic_add_affected_connectors(state, crtc);
4903 		if (ret)
4904 			return ret;
4905 
4906 		ret = drm_atomic_add_affected_planes(state, crtc);
4907 		if (ret)
4908 			goto fail;
4909 	}
4910 
4911 	dm_state->context = dc_create_state();
4912 	ASSERT(dm_state->context);
4913 	dc_resource_state_copy_construct_current(dc, dm_state->context);
4914 
4915 	/* Remove exiting planes if they are modified */
4916 	ret = dm_update_planes_state(dc, state, false, &lock_and_validation_needed);
4917 	if (ret) {
4918 		goto fail;
4919 	}
4920 
4921 	/* Disable all crtcs which require disable */
4922 	ret = dm_update_crtcs_state(dc, state, false, &lock_and_validation_needed);
4923 	if (ret) {
4924 		goto fail;
4925 	}
4926 
4927 	/* Enable all crtcs which require enable */
4928 	ret = dm_update_crtcs_state(dc, state, true, &lock_and_validation_needed);
4929 	if (ret) {
4930 		goto fail;
4931 	}
4932 
4933 	/* Add new/modified planes */
4934 	ret = dm_update_planes_state(dc, state, true, &lock_and_validation_needed);
4935 	if (ret) {
4936 		goto fail;
4937 	}
4938 
4939 	/* Run this here since we want to validate the streams we created */
4940 	ret = drm_atomic_helper_check_planes(dev, state);
4941 	if (ret)
4942 		goto fail;
4943 
4944 	/* Check scaling and underscan changes*/
4945 	/*TODO Removed scaling changes validation due to inability to commit
4946 	 * new stream into context w\o causing full reset. Need to
4947 	 * decide how to handle.
4948 	 */
4949 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4950 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
4951 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4952 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4953 
4954 		/* Skip any modesets/resets */
4955 		if (!acrtc || drm_atomic_crtc_needs_modeset(
4956 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
4957 			continue;
4958 
4959 		/* Skip any thing not scale or underscan changes */
4960 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
4961 			continue;
4962 
4963 		lock_and_validation_needed = true;
4964 	}
4965 
4966 	/*
4967 	 * For full updates case when
4968 	 * removing/adding/updating  streams on once CRTC while flipping
4969 	 * on another CRTC,
4970 	 * acquiring global lock  will guarantee that any such full
4971 	 * update commit
4972 	 * will wait for completion of any outstanding flip using DRMs
4973 	 * synchronization events.
4974 	 */
4975 
4976 	if (lock_and_validation_needed) {
4977 
4978 		ret = do_aquire_global_lock(dev, state);
4979 		if (ret)
4980 			goto fail;
4981 
4982 		if (dc_validate_global_state(dc, dm_state->context) != DC_OK) {
4983 			ret = -EINVAL;
4984 			goto fail;
4985 		}
4986 	}
4987 
4988 	/* Must be success */
4989 	WARN_ON(ret);
4990 	return ret;
4991 
4992 fail:
4993 	if (ret == -EDEADLK)
4994 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
4995 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
4996 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
4997 	else
4998 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
4999 
5000 	return ret;
5001 }
5002 
5003 static bool is_dp_capable_without_timing_msa(struct dc *dc,
5004 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
5005 {
5006 	uint8_t dpcd_data;
5007 	bool capable = false;
5008 
5009 	if (amdgpu_dm_connector->dc_link &&
5010 		dm_helpers_dp_read_dpcd(
5011 				NULL,
5012 				amdgpu_dm_connector->dc_link,
5013 				DP_DOWN_STREAM_PORT_COUNT,
5014 				&dpcd_data,
5015 				sizeof(dpcd_data))) {
5016 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
5017 	}
5018 
5019 	return capable;
5020 }
5021 void amdgpu_dm_add_sink_to_freesync_module(struct drm_connector *connector,
5022 					   struct edid *edid)
5023 {
5024 	int i;
5025 	uint64_t val_capable;
5026 	bool edid_check_required;
5027 	struct detailed_timing *timing;
5028 	struct detailed_non_pixel *data;
5029 	struct detailed_data_monitor_range *range;
5030 	struct amdgpu_dm_connector *amdgpu_dm_connector =
5031 			to_amdgpu_dm_connector(connector);
5032 
5033 	struct drm_device *dev = connector->dev;
5034 	struct amdgpu_device *adev = dev->dev_private;
5035 
5036 	edid_check_required = false;
5037 	if (!amdgpu_dm_connector->dc_sink) {
5038 		DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
5039 		return;
5040 	}
5041 	if (!adev->dm.freesync_module)
5042 		return;
5043 	/*
5044 	 * if edid non zero restrict freesync only for dp and edp
5045 	 */
5046 	if (edid) {
5047 		if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
5048 			|| amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
5049 			edid_check_required = is_dp_capable_without_timing_msa(
5050 						adev->dm.dc,
5051 						amdgpu_dm_connector);
5052 		}
5053 	}
5054 	val_capable = 0;
5055 	if (edid_check_required == true && (edid->version > 1 ||
5056 	   (edid->version == 1 && edid->revision > 1))) {
5057 		for (i = 0; i < 4; i++) {
5058 
5059 			timing	= &edid->detailed_timings[i];
5060 			data	= &timing->data.other_data;
5061 			range	= &data->data.range;
5062 			/*
5063 			 * Check if monitor has continuous frequency mode
5064 			 */
5065 			if (data->type != EDID_DETAIL_MONITOR_RANGE)
5066 				continue;
5067 			/*
5068 			 * Check for flag range limits only. If flag == 1 then
5069 			 * no additional timing information provided.
5070 			 * Default GTF, GTF Secondary curve and CVT are not
5071 			 * supported
5072 			 */
5073 			if (range->flags != 1)
5074 				continue;
5075 
5076 			amdgpu_dm_connector->min_vfreq = range->min_vfreq;
5077 			amdgpu_dm_connector->max_vfreq = range->max_vfreq;
5078 			amdgpu_dm_connector->pixel_clock_mhz =
5079 				range->pixel_clock_mhz * 10;
5080 			break;
5081 		}
5082 
5083 		if (amdgpu_dm_connector->max_vfreq -
5084 				amdgpu_dm_connector->min_vfreq > 10) {
5085 			amdgpu_dm_connector->caps.supported = true;
5086 			amdgpu_dm_connector->caps.min_refresh_in_micro_hz =
5087 					amdgpu_dm_connector->min_vfreq * 1000000;
5088 			amdgpu_dm_connector->caps.max_refresh_in_micro_hz =
5089 					amdgpu_dm_connector->max_vfreq * 1000000;
5090 				val_capable = 1;
5091 		}
5092 	}
5093 
5094 	/*
5095 	 * TODO figure out how to notify user-mode or DRM of freesync caps
5096 	 * once we figure out how to deal with freesync in an upstreamable
5097 	 * fashion
5098 	 */
5099 
5100 }
5101 
5102 void amdgpu_dm_remove_sink_from_freesync_module(struct drm_connector *connector)
5103 {
5104 	/*
5105 	 * TODO fill in once we figure out how to deal with freesync in
5106 	 * an upstreamable fashion
5107 	 */
5108 }
5109