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