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