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