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