]> Git Repo - linux.git/blob - drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c
dma-buf: Discard old fence_excl on retrying get_fences_rcu for realloc
[linux.git] / drivers / gpu / drm / amd / display / amdgpu_dm / amdgpu_dm.c
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 /* The caprices of the preprocessor require that this be declared right here */
27 #define CREATE_TRACE_POINTS
28
29 #include "dm_services_types.h"
30 #include "dc.h"
31 #include "dc/inc/core_types.h"
32
33 #include "vid.h"
34 #include "amdgpu.h"
35 #include "amdgpu_display.h"
36 #include "amdgpu_ucode.h"
37 #include "atom.h"
38 #include "amdgpu_dm.h"
39 #include "amdgpu_pm.h"
40
41 #include "amd_shared.h"
42 #include "amdgpu_dm_irq.h"
43 #include "dm_helpers.h"
44 #include "amdgpu_dm_mst_types.h"
45 #if defined(CONFIG_DEBUG_FS)
46 #include "amdgpu_dm_debugfs.h"
47 #endif
48
49 #include "ivsrcid/ivsrcid_vislands30.h"
50
51 #include <linux/module.h>
52 #include <linux/moduleparam.h>
53 #include <linux/version.h>
54 #include <linux/types.h>
55 #include <linux/pm_runtime.h>
56 #include <linux/firmware.h>
57
58 #include <drm/drmP.h>
59 #include <drm/drm_atomic.h>
60 #include <drm/drm_atomic_uapi.h>
61 #include <drm/drm_atomic_helper.h>
62 #include <drm/drm_dp_mst_helper.h>
63 #include <drm/drm_fb_helper.h>
64 #include <drm/drm_edid.h>
65
66 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
67 #include "ivsrcid/irqsrcs_dcn_1_0.h"
68
69 #include "dcn/dcn_1_0_offset.h"
70 #include "dcn/dcn_1_0_sh_mask.h"
71 #include "soc15_hw_ip.h"
72 #include "vega10_ip_offset.h"
73
74 #include "soc15_common.h"
75 #endif
76
77 #include "modules/inc/mod_freesync.h"
78 #include "modules/power/power_helpers.h"
79 #include "modules/inc/mod_info_packet.h"
80
81 #define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
82 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
83
84 /**
85  * DOC: overview
86  *
87  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
88  * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
89  * requests into DC requests, and DC responses into DRM responses.
90  *
91  * The root control structure is &struct amdgpu_display_manager.
92  */
93
94 /* basic init/fini API */
95 static int amdgpu_dm_init(struct amdgpu_device *adev);
96 static void amdgpu_dm_fini(struct amdgpu_device *adev);
97
98 /*
99  * initializes drm_device display related structures, based on the information
100  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
101  * drm_encoder, drm_mode_config
102  *
103  * Returns 0 on success
104  */
105 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
106 /* removes and deallocates the drm structures, created by the above function */
107 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
108
109 static void
110 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
111
112 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
113                                 struct drm_plane *plane,
114                                 unsigned long possible_crtcs,
115                                 const struct dc_plane_cap *plane_cap);
116 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
117                                struct drm_plane *plane,
118                                uint32_t link_index);
119 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
120                                     struct amdgpu_dm_connector *amdgpu_dm_connector,
121                                     uint32_t link_index,
122                                     struct amdgpu_encoder *amdgpu_encoder);
123 static int amdgpu_dm_encoder_init(struct drm_device *dev,
124                                   struct amdgpu_encoder *aencoder,
125                                   uint32_t link_index);
126
127 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
128
129 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
130                                    struct drm_atomic_state *state,
131                                    bool nonblock);
132
133 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
134
135 static int amdgpu_dm_atomic_check(struct drm_device *dev,
136                                   struct drm_atomic_state *state);
137
138 static void handle_cursor_update(struct drm_plane *plane,
139                                  struct drm_plane_state *old_plane_state);
140
141 /*
142  * dm_vblank_get_counter
143  *
144  * @brief
145  * Get counter for number of vertical blanks
146  *
147  * @param
148  * struct amdgpu_device *adev - [in] desired amdgpu device
149  * int disp_idx - [in] which CRTC to get the counter from
150  *
151  * @return
152  * Counter for vertical blanks
153  */
154 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
155 {
156         if (crtc >= adev->mode_info.num_crtc)
157                 return 0;
158         else {
159                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
160                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
161                                 acrtc->base.state);
162
163
164                 if (acrtc_state->stream == NULL) {
165                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
166                                   crtc);
167                         return 0;
168                 }
169
170                 return dc_stream_get_vblank_counter(acrtc_state->stream);
171         }
172 }
173
174 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
175                                   u32 *vbl, u32 *position)
176 {
177         uint32_t v_blank_start, v_blank_end, h_position, v_position;
178
179         if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
180                 return -EINVAL;
181         else {
182                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
183                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
184                                                 acrtc->base.state);
185
186                 if (acrtc_state->stream ==  NULL) {
187                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
188                                   crtc);
189                         return 0;
190                 }
191
192                 /*
193                  * TODO rework base driver to use values directly.
194                  * for now parse it back into reg-format
195                  */
196                 dc_stream_get_scanoutpos(acrtc_state->stream,
197                                          &v_blank_start,
198                                          &v_blank_end,
199                                          &h_position,
200                                          &v_position);
201
202                 *position = v_position | (h_position << 16);
203                 *vbl = v_blank_start | (v_blank_end << 16);
204         }
205
206         return 0;
207 }
208
209 static bool dm_is_idle(void *handle)
210 {
211         /* XXX todo */
212         return true;
213 }
214
215 static int dm_wait_for_idle(void *handle)
216 {
217         /* XXX todo */
218         return 0;
219 }
220
221 static bool dm_check_soft_reset(void *handle)
222 {
223         return false;
224 }
225
226 static int dm_soft_reset(void *handle)
227 {
228         /* XXX todo */
229         return 0;
230 }
231
232 static struct amdgpu_crtc *
233 get_crtc_by_otg_inst(struct amdgpu_device *adev,
234                      int otg_inst)
235 {
236         struct drm_device *dev = adev->ddev;
237         struct drm_crtc *crtc;
238         struct amdgpu_crtc *amdgpu_crtc;
239
240         if (otg_inst == -1) {
241                 WARN_ON(1);
242                 return adev->mode_info.crtcs[0];
243         }
244
245         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
246                 amdgpu_crtc = to_amdgpu_crtc(crtc);
247
248                 if (amdgpu_crtc->otg_inst == otg_inst)
249                         return amdgpu_crtc;
250         }
251
252         return NULL;
253 }
254
255 static inline bool amdgpu_dm_vrr_active(struct dm_crtc_state *dm_state)
256 {
257         return dm_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE ||
258                dm_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
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         struct drm_pending_vblank_event *e;
268         struct dm_crtc_state *acrtc_state;
269         uint32_t vpos, hpos, v_blank_start, v_blank_end;
270         bool vrr_active;
271
272         amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
273
274         /* IRQ could occur when in initial stage */
275         /* TODO work and BO cleanup */
276         if (amdgpu_crtc == NULL) {
277                 DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
278                 return;
279         }
280
281         spin_lock_irqsave(&adev->ddev->event_lock, flags);
282
283         if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
284                 DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
285                                                  amdgpu_crtc->pflip_status,
286                                                  AMDGPU_FLIP_SUBMITTED,
287                                                  amdgpu_crtc->crtc_id,
288                                                  amdgpu_crtc);
289                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
290                 return;
291         }
292
293         /* page flip completed. */
294         e = amdgpu_crtc->event;
295         amdgpu_crtc->event = NULL;
296
297         if (!e)
298                 WARN_ON(1);
299
300         acrtc_state = to_dm_crtc_state(amdgpu_crtc->base.state);
301         vrr_active = amdgpu_dm_vrr_active(acrtc_state);
302
303         /* Fixed refresh rate, or VRR scanout position outside front-porch? */
304         if (!vrr_active ||
305             !dc_stream_get_scanoutpos(acrtc_state->stream, &v_blank_start,
306                                       &v_blank_end, &hpos, &vpos) ||
307             (vpos < v_blank_start)) {
308                 /* Update to correct count and vblank timestamp if racing with
309                  * vblank irq. This also updates to the correct vblank timestamp
310                  * even in VRR mode, as scanout is past the front-porch atm.
311                  */
312                 drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
313
314                 /* Wake up userspace by sending the pageflip event with proper
315                  * count and timestamp of vblank of flip completion.
316                  */
317                 if (e) {
318                         drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
319
320                         /* Event sent, so done with vblank for this flip */
321                         drm_crtc_vblank_put(&amdgpu_crtc->base);
322                 }
323         } else if (e) {
324                 /* VRR active and inside front-porch: vblank count and
325                  * timestamp for pageflip event will only be up to date after
326                  * drm_crtc_handle_vblank() has been executed from late vblank
327                  * irq handler after start of back-porch (vline 0). We queue the
328                  * pageflip event for send-out by drm_crtc_handle_vblank() with
329                  * updated timestamp and count, once it runs after us.
330                  *
331                  * We need to open-code this instead of using the helper
332                  * drm_crtc_arm_vblank_event(), as that helper would
333                  * call drm_crtc_accurate_vblank_count(), which we must
334                  * not call in VRR mode while we are in front-porch!
335                  */
336
337                 /* sequence will be replaced by real count during send-out. */
338                 e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
339                 e->pipe = amdgpu_crtc->crtc_id;
340
341                 list_add_tail(&e->base.link, &adev->ddev->vblank_event_list);
342                 e = NULL;
343         }
344
345         /* Keep track of vblank of this flip for flip throttling. We use the
346          * cooked hw counter, as that one incremented at start of this vblank
347          * of pageflip completion, so last_flip_vblank is the forbidden count
348          * for queueing new pageflips if vsync + VRR is enabled.
349          */
350         amdgpu_crtc->last_flip_vblank = amdgpu_get_vblank_counter_kms(adev->ddev,
351                                                         amdgpu_crtc->crtc_id);
352
353         amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
354         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
355
356         DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
357                          amdgpu_crtc->crtc_id, amdgpu_crtc,
358                          vrr_active, (int) !e);
359 }
360
361 static void dm_vupdate_high_irq(void *interrupt_params)
362 {
363         struct common_irq_params *irq_params = interrupt_params;
364         struct amdgpu_device *adev = irq_params->adev;
365         struct amdgpu_crtc *acrtc;
366         struct dm_crtc_state *acrtc_state;
367         unsigned long flags;
368
369         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
370
371         if (acrtc) {
372                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
373
374                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
375                                  amdgpu_dm_vrr_active(acrtc_state));
376
377                 /* Core vblank handling is done here after end of front-porch in
378                  * vrr mode, as vblank timestamping will give valid results
379                  * while now done after front-porch. This will also deliver
380                  * page-flip completion events that have been queued to us
381                  * if a pageflip happened inside front-porch.
382                  */
383                 if (amdgpu_dm_vrr_active(acrtc_state)) {
384                         drm_crtc_handle_vblank(&acrtc->base);
385
386                         /* BTR processing for pre-DCE12 ASICs */
387                         if (acrtc_state->stream &&
388                             adev->family < AMDGPU_FAMILY_AI) {
389                                 spin_lock_irqsave(&adev->ddev->event_lock, flags);
390                                 mod_freesync_handle_v_update(
391                                     adev->dm.freesync_module,
392                                     acrtc_state->stream,
393                                     &acrtc_state->vrr_params);
394
395                                 dc_stream_adjust_vmin_vmax(
396                                     adev->dm.dc,
397                                     acrtc_state->stream,
398                                     &acrtc_state->vrr_params.adjust);
399                                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
400                         }
401                 }
402         }
403 }
404
405 static void dm_crtc_high_irq(void *interrupt_params)
406 {
407         struct common_irq_params *irq_params = interrupt_params;
408         struct amdgpu_device *adev = irq_params->adev;
409         struct amdgpu_crtc *acrtc;
410         struct dm_crtc_state *acrtc_state;
411         unsigned long flags;
412
413         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
414
415         if (acrtc) {
416                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
417
418                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
419                                  amdgpu_dm_vrr_active(acrtc_state));
420
421                 /* Core vblank handling at start of front-porch is only possible
422                  * in non-vrr mode, as only there vblank timestamping will give
423                  * valid results while done in front-porch. Otherwise defer it
424                  * to dm_vupdate_high_irq after end of front-porch.
425                  */
426                 if (!amdgpu_dm_vrr_active(acrtc_state))
427                         drm_crtc_handle_vblank(&acrtc->base);
428
429                 /* Following stuff must happen at start of vblank, for crc
430                  * computation and below-the-range btr support in vrr mode.
431                  */
432                 amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
433
434                 if (acrtc_state->stream && adev->family >= AMDGPU_FAMILY_AI &&
435                     acrtc_state->vrr_params.supported &&
436                     acrtc_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE) {
437                         spin_lock_irqsave(&adev->ddev->event_lock, flags);
438                         mod_freesync_handle_v_update(
439                                 adev->dm.freesync_module,
440                                 acrtc_state->stream,
441                                 &acrtc_state->vrr_params);
442
443                         dc_stream_adjust_vmin_vmax(
444                                 adev->dm.dc,
445                                 acrtc_state->stream,
446                                 &acrtc_state->vrr_params.adjust);
447                         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
448                 }
449         }
450 }
451
452 static int dm_set_clockgating_state(void *handle,
453                   enum amd_clockgating_state state)
454 {
455         return 0;
456 }
457
458 static int dm_set_powergating_state(void *handle,
459                   enum amd_powergating_state state)
460 {
461         return 0;
462 }
463
464 /* Prototypes of private functions */
465 static int dm_early_init(void* handle);
466
467 /* Allocate memory for FBC compressed data  */
468 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
469 {
470         struct drm_device *dev = connector->dev;
471         struct amdgpu_device *adev = dev->dev_private;
472         struct dm_comressor_info *compressor = &adev->dm.compressor;
473         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
474         struct drm_display_mode *mode;
475         unsigned long max_size = 0;
476
477         if (adev->dm.dc->fbc_compressor == NULL)
478                 return;
479
480         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
481                 return;
482
483         if (compressor->bo_ptr)
484                 return;
485
486
487         list_for_each_entry(mode, &connector->modes, head) {
488                 if (max_size < mode->htotal * mode->vtotal)
489                         max_size = mode->htotal * mode->vtotal;
490         }
491
492         if (max_size) {
493                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
494                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
495                             &compressor->gpu_addr, &compressor->cpu_addr);
496
497                 if (r)
498                         DRM_ERROR("DM: Failed to initialize FBC\n");
499                 else {
500                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
501                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
502                 }
503
504         }
505
506 }
507
508 static int amdgpu_dm_init(struct amdgpu_device *adev)
509 {
510         struct dc_init_data init_data;
511         adev->dm.ddev = adev->ddev;
512         adev->dm.adev = adev;
513
514         /* Zero all the fields */
515         memset(&init_data, 0, sizeof(init_data));
516
517         mutex_init(&adev->dm.dc_lock);
518
519         if(amdgpu_dm_irq_init(adev)) {
520                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
521                 goto error;
522         }
523
524         init_data.asic_id.chip_family = adev->family;
525
526         init_data.asic_id.pci_revision_id = adev->rev_id;
527         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
528
529         init_data.asic_id.vram_width = adev->gmc.vram_width;
530         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
531         init_data.asic_id.atombios_base_address =
532                 adev->mode_info.atom_context->bios;
533
534         init_data.driver = adev;
535
536         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
537
538         if (!adev->dm.cgs_device) {
539                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
540                 goto error;
541         }
542
543         init_data.cgs_device = adev->dm.cgs_device;
544
545         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
546
547         /*
548          * TODO debug why this doesn't work on Raven
549          */
550         if (adev->flags & AMD_IS_APU &&
551             adev->asic_type >= CHIP_CARRIZO &&
552             adev->asic_type < CHIP_RAVEN)
553                 init_data.flags.gpu_vm_support = true;
554
555         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
556                 init_data.flags.fbc_support = true;
557
558         init_data.flags.power_down_display_on_boot = true;
559
560         /* Display Core create. */
561         adev->dm.dc = dc_create(&init_data);
562
563         if (adev->dm.dc) {
564                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
565         } else {
566                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
567                 goto error;
568         }
569
570         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
571         if (!adev->dm.freesync_module) {
572                 DRM_ERROR(
573                 "amdgpu: failed to initialize freesync_module.\n");
574         } else
575                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
576                                 adev->dm.freesync_module);
577
578         amdgpu_dm_init_color_mod();
579
580         if (amdgpu_dm_initialize_drm_device(adev)) {
581                 DRM_ERROR(
582                 "amdgpu: failed to initialize sw for display support.\n");
583                 goto error;
584         }
585
586         /* Update the actual used number of crtc */
587         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
588
589         /* TODO: Add_display_info? */
590
591         /* TODO use dynamic cursor width */
592         adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
593         adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
594
595         if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
596                 DRM_ERROR(
597                 "amdgpu: failed to initialize sw for display support.\n");
598                 goto error;
599         }
600
601 #if defined(CONFIG_DEBUG_FS)
602         if (dtn_debugfs_init(adev))
603                 DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
604 #endif
605
606         DRM_DEBUG_DRIVER("KMS initialized.\n");
607
608         return 0;
609 error:
610         amdgpu_dm_fini(adev);
611
612         return -EINVAL;
613 }
614
615 static void amdgpu_dm_fini(struct amdgpu_device *adev)
616 {
617         amdgpu_dm_destroy_drm_device(&adev->dm);
618         /*
619          * TODO: pageflip, vlank interrupt
620          *
621          * amdgpu_dm_irq_fini(adev);
622          */
623
624         if (adev->dm.cgs_device) {
625                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
626                 adev->dm.cgs_device = NULL;
627         }
628         if (adev->dm.freesync_module) {
629                 mod_freesync_destroy(adev->dm.freesync_module);
630                 adev->dm.freesync_module = NULL;
631         }
632         /* DC Destroy TODO: Replace destroy DAL */
633         if (adev->dm.dc)
634                 dc_destroy(&adev->dm.dc);
635
636         mutex_destroy(&adev->dm.dc_lock);
637
638         return;
639 }
640
641 static int load_dmcu_fw(struct amdgpu_device *adev)
642 {
643         const char *fw_name_dmcu;
644         int r;
645         const struct dmcu_firmware_header_v1_0 *hdr;
646
647         switch(adev->asic_type) {
648         case CHIP_BONAIRE:
649         case CHIP_HAWAII:
650         case CHIP_KAVERI:
651         case CHIP_KABINI:
652         case CHIP_MULLINS:
653         case CHIP_TONGA:
654         case CHIP_FIJI:
655         case CHIP_CARRIZO:
656         case CHIP_STONEY:
657         case CHIP_POLARIS11:
658         case CHIP_POLARIS10:
659         case CHIP_POLARIS12:
660         case CHIP_VEGAM:
661         case CHIP_VEGA10:
662         case CHIP_VEGA12:
663         case CHIP_VEGA20:
664                 return 0;
665         case CHIP_RAVEN:
666                 fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
667                 break;
668         default:
669                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
670                 return -EINVAL;
671         }
672
673         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
674                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
675                 return 0;
676         }
677
678         r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
679         if (r == -ENOENT) {
680                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
681                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
682                 adev->dm.fw_dmcu = NULL;
683                 return 0;
684         }
685         if (r) {
686                 dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
687                         fw_name_dmcu);
688                 return r;
689         }
690
691         r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
692         if (r) {
693                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
694                         fw_name_dmcu);
695                 release_firmware(adev->dm.fw_dmcu);
696                 adev->dm.fw_dmcu = NULL;
697                 return r;
698         }
699
700         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
701         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
702         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
703         adev->firmware.fw_size +=
704                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
705
706         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
707         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
708         adev->firmware.fw_size +=
709                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
710
711         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
712
713         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
714
715         return 0;
716 }
717
718 static int dm_sw_init(void *handle)
719 {
720         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
721
722         return load_dmcu_fw(adev);
723 }
724
725 static int dm_sw_fini(void *handle)
726 {
727         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
728
729         if(adev->dm.fw_dmcu) {
730                 release_firmware(adev->dm.fw_dmcu);
731                 adev->dm.fw_dmcu = NULL;
732         }
733
734         return 0;
735 }
736
737 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
738 {
739         struct amdgpu_dm_connector *aconnector;
740         struct drm_connector *connector;
741         int ret = 0;
742
743         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
744
745         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
746                 aconnector = to_amdgpu_dm_connector(connector);
747                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
748                     aconnector->mst_mgr.aux) {
749                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
750                                         aconnector, aconnector->base.base.id);
751
752                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
753                         if (ret < 0) {
754                                 DRM_ERROR("DM_MST: Failed to start MST\n");
755                                 ((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
756                                 return ret;
757                                 }
758                         }
759         }
760
761         drm_modeset_unlock(&dev->mode_config.connection_mutex);
762         return ret;
763 }
764
765 static int dm_late_init(void *handle)
766 {
767         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
768
769         struct dmcu_iram_parameters params;
770         unsigned int linear_lut[16];
771         int i;
772         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
773         bool ret;
774
775         for (i = 0; i < 16; i++)
776                 linear_lut[i] = 0xFFFF * i / 15;
777
778         params.set = 0;
779         params.backlight_ramping_start = 0xCCCC;
780         params.backlight_ramping_reduction = 0xCCCCCCCC;
781         params.backlight_lut_array_size = 16;
782         params.backlight_lut_array = linear_lut;
783
784         ret = dmcu_load_iram(dmcu, params);
785
786         if (!ret)
787                 return -EINVAL;
788
789         return detect_mst_link_for_all_connectors(adev->ddev);
790 }
791
792 static void s3_handle_mst(struct drm_device *dev, bool suspend)
793 {
794         struct amdgpu_dm_connector *aconnector;
795         struct drm_connector *connector;
796         struct drm_dp_mst_topology_mgr *mgr;
797         int ret;
798         bool need_hotplug = false;
799
800         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
801
802         list_for_each_entry(connector, &dev->mode_config.connector_list,
803                             head) {
804                 aconnector = to_amdgpu_dm_connector(connector);
805                 if (aconnector->dc_link->type != dc_connection_mst_branch ||
806                     aconnector->mst_port)
807                         continue;
808
809                 mgr = &aconnector->mst_mgr;
810
811                 if (suspend) {
812                         drm_dp_mst_topology_mgr_suspend(mgr);
813                 } else {
814                         ret = drm_dp_mst_topology_mgr_resume(mgr);
815                         if (ret < 0) {
816                                 drm_dp_mst_topology_mgr_set_mst(mgr, false);
817                                 need_hotplug = true;
818                         }
819                 }
820         }
821
822         drm_modeset_unlock(&dev->mode_config.connection_mutex);
823
824         if (need_hotplug)
825                 drm_kms_helper_hotplug_event(dev);
826 }
827
828 /**
829  * dm_hw_init() - Initialize DC device
830  * @handle: The base driver device containing the amdpgu_dm device.
831  *
832  * Initialize the &struct amdgpu_display_manager device. This involves calling
833  * the initializers of each DM component, then populating the struct with them.
834  *
835  * Although the function implies hardware initialization, both hardware and
836  * software are initialized here. Splitting them out to their relevant init
837  * hooks is a future TODO item.
838  *
839  * Some notable things that are initialized here:
840  *
841  * - Display Core, both software and hardware
842  * - DC modules that we need (freesync and color management)
843  * - DRM software states
844  * - Interrupt sources and handlers
845  * - Vblank support
846  * - Debug FS entries, if enabled
847  */
848 static int dm_hw_init(void *handle)
849 {
850         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
851         /* Create DAL display manager */
852         amdgpu_dm_init(adev);
853         amdgpu_dm_hpd_init(adev);
854
855         return 0;
856 }
857
858 /**
859  * dm_hw_fini() - Teardown DC device
860  * @handle: The base driver device containing the amdpgu_dm device.
861  *
862  * Teardown components within &struct amdgpu_display_manager that require
863  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
864  * were loaded. Also flush IRQ workqueues and disable them.
865  */
866 static int dm_hw_fini(void *handle)
867 {
868         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
869
870         amdgpu_dm_hpd_fini(adev);
871
872         amdgpu_dm_irq_fini(adev);
873         amdgpu_dm_fini(adev);
874         return 0;
875 }
876
877 static int dm_suspend(void *handle)
878 {
879         struct amdgpu_device *adev = handle;
880         struct amdgpu_display_manager *dm = &adev->dm;
881         int ret = 0;
882
883         WARN_ON(adev->dm.cached_state);
884         adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
885
886         s3_handle_mst(adev->ddev, true);
887
888         amdgpu_dm_irq_suspend(adev);
889
890
891         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
892
893         return ret;
894 }
895
896 static struct amdgpu_dm_connector *
897 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
898                                              struct drm_crtc *crtc)
899 {
900         uint32_t i;
901         struct drm_connector_state *new_con_state;
902         struct drm_connector *connector;
903         struct drm_crtc *crtc_from_state;
904
905         for_each_new_connector_in_state(state, connector, new_con_state, i) {
906                 crtc_from_state = new_con_state->crtc;
907
908                 if (crtc_from_state == crtc)
909                         return to_amdgpu_dm_connector(connector);
910         }
911
912         return NULL;
913 }
914
915 static void emulated_link_detect(struct dc_link *link)
916 {
917         struct dc_sink_init_data sink_init_data = { 0 };
918         struct display_sink_capability sink_caps = { 0 };
919         enum dc_edid_status edid_status;
920         struct dc_context *dc_ctx = link->ctx;
921         struct dc_sink *sink = NULL;
922         struct dc_sink *prev_sink = NULL;
923
924         link->type = dc_connection_none;
925         prev_sink = link->local_sink;
926
927         if (prev_sink != NULL)
928                 dc_sink_retain(prev_sink);
929
930         switch (link->connector_signal) {
931         case SIGNAL_TYPE_HDMI_TYPE_A: {
932                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
933                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
934                 break;
935         }
936
937         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
938                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
939                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
940                 break;
941         }
942
943         case SIGNAL_TYPE_DVI_DUAL_LINK: {
944                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
945                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
946                 break;
947         }
948
949         case SIGNAL_TYPE_LVDS: {
950                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
951                 sink_caps.signal = SIGNAL_TYPE_LVDS;
952                 break;
953         }
954
955         case SIGNAL_TYPE_EDP: {
956                 sink_caps.transaction_type =
957                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
958                 sink_caps.signal = SIGNAL_TYPE_EDP;
959                 break;
960         }
961
962         case SIGNAL_TYPE_DISPLAY_PORT: {
963                 sink_caps.transaction_type =
964                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
965                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
966                 break;
967         }
968
969         default:
970                 DC_ERROR("Invalid connector type! signal:%d\n",
971                         link->connector_signal);
972                 return;
973         }
974
975         sink_init_data.link = link;
976         sink_init_data.sink_signal = sink_caps.signal;
977
978         sink = dc_sink_create(&sink_init_data);
979         if (!sink) {
980                 DC_ERROR("Failed to create sink!\n");
981                 return;
982         }
983
984         /* dc_sink_create returns a new reference */
985         link->local_sink = sink;
986
987         edid_status = dm_helpers_read_local_edid(
988                         link->ctx,
989                         link,
990                         sink);
991
992         if (edid_status != EDID_OK)
993                 DC_ERROR("Failed to read EDID");
994
995 }
996
997 static int dm_resume(void *handle)
998 {
999         struct amdgpu_device *adev = handle;
1000         struct drm_device *ddev = adev->ddev;
1001         struct amdgpu_display_manager *dm = &adev->dm;
1002         struct amdgpu_dm_connector *aconnector;
1003         struct drm_connector *connector;
1004         struct drm_crtc *crtc;
1005         struct drm_crtc_state *new_crtc_state;
1006         struct dm_crtc_state *dm_new_crtc_state;
1007         struct drm_plane *plane;
1008         struct drm_plane_state *new_plane_state;
1009         struct dm_plane_state *dm_new_plane_state;
1010         struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1011         enum dc_connection_type new_connection_type = dc_connection_none;
1012         int i;
1013
1014         /* Recreate dc_state - DC invalidates it when setting power state to S3. */
1015         dc_release_state(dm_state->context);
1016         dm_state->context = dc_create_state(dm->dc);
1017         /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1018         dc_resource_state_construct(dm->dc, dm_state->context);
1019
1020         /* power on hardware */
1021         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1022
1023         /* program HPD filter */
1024         dc_resume(dm->dc);
1025
1026         /* On resume we need to  rewrite the MSTM control bits to enamble MST*/
1027         s3_handle_mst(ddev, false);
1028
1029         /*
1030          * early enable HPD Rx IRQ, should be done before set mode as short
1031          * pulse interrupts are used for MST
1032          */
1033         amdgpu_dm_irq_resume_early(adev);
1034
1035         /* Do detection*/
1036         list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
1037                 aconnector = to_amdgpu_dm_connector(connector);
1038
1039                 /*
1040                  * this is the case when traversing through already created
1041                  * MST connectors, should be skipped
1042                  */
1043                 if (aconnector->mst_port)
1044                         continue;
1045
1046                 mutex_lock(&aconnector->hpd_lock);
1047                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1048                         DRM_ERROR("KMS: Failed to detect connector\n");
1049
1050                 if (aconnector->base.force && new_connection_type == dc_connection_none)
1051                         emulated_link_detect(aconnector->dc_link);
1052                 else
1053                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
1054
1055                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
1056                         aconnector->fake_enable = false;
1057
1058                 if (aconnector->dc_sink)
1059                         dc_sink_release(aconnector->dc_sink);
1060                 aconnector->dc_sink = NULL;
1061                 amdgpu_dm_update_connector_after_detect(aconnector);
1062                 mutex_unlock(&aconnector->hpd_lock);
1063         }
1064
1065         /* Force mode set in atomic commit */
1066         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
1067                 new_crtc_state->active_changed = true;
1068
1069         /*
1070          * atomic_check is expected to create the dc states. We need to release
1071          * them here, since they were duplicated as part of the suspend
1072          * procedure.
1073          */
1074         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1075                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1076                 if (dm_new_crtc_state->stream) {
1077                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1078                         dc_stream_release(dm_new_crtc_state->stream);
1079                         dm_new_crtc_state->stream = NULL;
1080                 }
1081         }
1082
1083         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1084                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
1085                 if (dm_new_plane_state->dc_state) {
1086                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1087                         dc_plane_state_release(dm_new_plane_state->dc_state);
1088                         dm_new_plane_state->dc_state = NULL;
1089                 }
1090         }
1091
1092         drm_atomic_helper_resume(ddev, dm->cached_state);
1093
1094         dm->cached_state = NULL;
1095
1096         amdgpu_dm_irq_resume_late(adev);
1097
1098         return 0;
1099 }
1100
1101 /**
1102  * DOC: DM Lifecycle
1103  *
1104  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
1105  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
1106  * the base driver's device list to be initialized and torn down accordingly.
1107  *
1108  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
1109  */
1110
1111 static const struct amd_ip_funcs amdgpu_dm_funcs = {
1112         .name = "dm",
1113         .early_init = dm_early_init,
1114         .late_init = dm_late_init,
1115         .sw_init = dm_sw_init,
1116         .sw_fini = dm_sw_fini,
1117         .hw_init = dm_hw_init,
1118         .hw_fini = dm_hw_fini,
1119         .suspend = dm_suspend,
1120         .resume = dm_resume,
1121         .is_idle = dm_is_idle,
1122         .wait_for_idle = dm_wait_for_idle,
1123         .check_soft_reset = dm_check_soft_reset,
1124         .soft_reset = dm_soft_reset,
1125         .set_clockgating_state = dm_set_clockgating_state,
1126         .set_powergating_state = dm_set_powergating_state,
1127 };
1128
1129 const struct amdgpu_ip_block_version dm_ip_block =
1130 {
1131         .type = AMD_IP_BLOCK_TYPE_DCE,
1132         .major = 1,
1133         .minor = 0,
1134         .rev = 0,
1135         .funcs = &amdgpu_dm_funcs,
1136 };
1137
1138
1139 /**
1140  * DOC: atomic
1141  *
1142  * *WIP*
1143  */
1144
1145 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1146         .fb_create = amdgpu_display_user_framebuffer_create,
1147         .output_poll_changed = drm_fb_helper_output_poll_changed,
1148         .atomic_check = amdgpu_dm_atomic_check,
1149         .atomic_commit = amdgpu_dm_atomic_commit,
1150 };
1151
1152 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1153         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1154 };
1155
1156 static void
1157 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1158 {
1159         struct drm_connector *connector = &aconnector->base;
1160         struct drm_device *dev = connector->dev;
1161         struct dc_sink *sink;
1162
1163         /* MST handled by drm_mst framework */
1164         if (aconnector->mst_mgr.mst_state == true)
1165                 return;
1166
1167
1168         sink = aconnector->dc_link->local_sink;
1169         if (sink)
1170                 dc_sink_retain(sink);
1171
1172         /*
1173          * Edid mgmt connector gets first update only in mode_valid hook and then
1174          * the connector sink is set to either fake or physical sink depends on link status.
1175          * Skip if already done during boot.
1176          */
1177         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1178                         && aconnector->dc_em_sink) {
1179
1180                 /*
1181                  * For S3 resume with headless use eml_sink to fake stream
1182                  * because on resume connector->sink is set to NULL
1183                  */
1184                 mutex_lock(&dev->mode_config.mutex);
1185
1186                 if (sink) {
1187                         if (aconnector->dc_sink) {
1188                                 amdgpu_dm_update_freesync_caps(connector, NULL);
1189                                 /*
1190                                  * retain and release below are used to
1191                                  * bump up refcount for sink because the link doesn't point
1192                                  * to it anymore after disconnect, so on next crtc to connector
1193                                  * reshuffle by UMD we will get into unwanted dc_sink release
1194                                  */
1195                                 dc_sink_release(aconnector->dc_sink);
1196                         }
1197                         aconnector->dc_sink = sink;
1198                         dc_sink_retain(aconnector->dc_sink);
1199                         amdgpu_dm_update_freesync_caps(connector,
1200                                         aconnector->edid);
1201                 } else {
1202                         amdgpu_dm_update_freesync_caps(connector, NULL);
1203                         if (!aconnector->dc_sink) {
1204                                 aconnector->dc_sink = aconnector->dc_em_sink;
1205                                 dc_sink_retain(aconnector->dc_sink);
1206                         }
1207                 }
1208
1209                 mutex_unlock(&dev->mode_config.mutex);
1210
1211                 if (sink)
1212                         dc_sink_release(sink);
1213                 return;
1214         }
1215
1216         /*
1217          * TODO: temporary guard to look for proper fix
1218          * if this sink is MST sink, we should not do anything
1219          */
1220         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
1221                 dc_sink_release(sink);
1222                 return;
1223         }
1224
1225         if (aconnector->dc_sink == sink) {
1226                 /*
1227                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
1228                  * Do nothing!!
1229                  */
1230                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1231                                 aconnector->connector_id);
1232                 if (sink)
1233                         dc_sink_release(sink);
1234                 return;
1235         }
1236
1237         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1238                 aconnector->connector_id, aconnector->dc_sink, sink);
1239
1240         mutex_lock(&dev->mode_config.mutex);
1241
1242         /*
1243          * 1. Update status of the drm connector
1244          * 2. Send an event and let userspace tell us what to do
1245          */
1246         if (sink) {
1247                 /*
1248                  * TODO: check if we still need the S3 mode update workaround.
1249                  * If yes, put it here.
1250                  */
1251                 if (aconnector->dc_sink)
1252                         amdgpu_dm_update_freesync_caps(connector, NULL);
1253
1254                 aconnector->dc_sink = sink;
1255                 dc_sink_retain(aconnector->dc_sink);
1256                 if (sink->dc_edid.length == 0) {
1257                         aconnector->edid = NULL;
1258                         drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1259                 } else {
1260                         aconnector->edid =
1261                                 (struct edid *) sink->dc_edid.raw_edid;
1262
1263
1264                         drm_connector_update_edid_property(connector,
1265                                         aconnector->edid);
1266                         drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1267                                             aconnector->edid);
1268                 }
1269                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1270
1271         } else {
1272                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1273                 amdgpu_dm_update_freesync_caps(connector, NULL);
1274                 drm_connector_update_edid_property(connector, NULL);
1275                 aconnector->num_modes = 0;
1276                 dc_sink_release(aconnector->dc_sink);
1277                 aconnector->dc_sink = NULL;
1278                 aconnector->edid = NULL;
1279         }
1280
1281         mutex_unlock(&dev->mode_config.mutex);
1282
1283         if (sink)
1284                 dc_sink_release(sink);
1285 }
1286
1287 static void handle_hpd_irq(void *param)
1288 {
1289         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1290         struct drm_connector *connector = &aconnector->base;
1291         struct drm_device *dev = connector->dev;
1292         enum dc_connection_type new_connection_type = dc_connection_none;
1293
1294         /*
1295          * In case of failure or MST no need to update connector status or notify the OS
1296          * since (for MST case) MST does this in its own context.
1297          */
1298         mutex_lock(&aconnector->hpd_lock);
1299
1300         if (aconnector->fake_enable)
1301                 aconnector->fake_enable = false;
1302
1303         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1304                 DRM_ERROR("KMS: Failed to detect connector\n");
1305
1306         if (aconnector->base.force && new_connection_type == dc_connection_none) {
1307                 emulated_link_detect(aconnector->dc_link);
1308
1309
1310                 drm_modeset_lock_all(dev);
1311                 dm_restore_drm_connector_state(dev, connector);
1312                 drm_modeset_unlock_all(dev);
1313
1314                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1315                         drm_kms_helper_hotplug_event(dev);
1316
1317         } else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1318                 amdgpu_dm_update_connector_after_detect(aconnector);
1319
1320
1321                 drm_modeset_lock_all(dev);
1322                 dm_restore_drm_connector_state(dev, connector);
1323                 drm_modeset_unlock_all(dev);
1324
1325                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1326                         drm_kms_helper_hotplug_event(dev);
1327         }
1328         mutex_unlock(&aconnector->hpd_lock);
1329
1330 }
1331
1332 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1333 {
1334         uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1335         uint8_t dret;
1336         bool new_irq_handled = false;
1337         int dpcd_addr;
1338         int dpcd_bytes_to_read;
1339
1340         const int max_process_count = 30;
1341         int process_count = 0;
1342
1343         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1344
1345         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1346                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1347                 /* DPCD 0x200 - 0x201 for downstream IRQ */
1348                 dpcd_addr = DP_SINK_COUNT;
1349         } else {
1350                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1351                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
1352                 dpcd_addr = DP_SINK_COUNT_ESI;
1353         }
1354
1355         dret = drm_dp_dpcd_read(
1356                 &aconnector->dm_dp_aux.aux,
1357                 dpcd_addr,
1358                 esi,
1359                 dpcd_bytes_to_read);
1360
1361         while (dret == dpcd_bytes_to_read &&
1362                 process_count < max_process_count) {
1363                 uint8_t retry;
1364                 dret = 0;
1365
1366                 process_count++;
1367
1368                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1369                 /* handle HPD short pulse irq */
1370                 if (aconnector->mst_mgr.mst_state)
1371                         drm_dp_mst_hpd_irq(
1372                                 &aconnector->mst_mgr,
1373                                 esi,
1374                                 &new_irq_handled);
1375
1376                 if (new_irq_handled) {
1377                         /* ACK at DPCD to notify down stream */
1378                         const int ack_dpcd_bytes_to_write =
1379                                 dpcd_bytes_to_read - 1;
1380
1381                         for (retry = 0; retry < 3; retry++) {
1382                                 uint8_t wret;
1383
1384                                 wret = drm_dp_dpcd_write(
1385                                         &aconnector->dm_dp_aux.aux,
1386                                         dpcd_addr + 1,
1387                                         &esi[1],
1388                                         ack_dpcd_bytes_to_write);
1389                                 if (wret == ack_dpcd_bytes_to_write)
1390                                         break;
1391                         }
1392
1393                         /* check if there is new irq to be handled */
1394                         dret = drm_dp_dpcd_read(
1395                                 &aconnector->dm_dp_aux.aux,
1396                                 dpcd_addr,
1397                                 esi,
1398                                 dpcd_bytes_to_read);
1399
1400                         new_irq_handled = false;
1401                 } else {
1402                         break;
1403                 }
1404         }
1405
1406         if (process_count == max_process_count)
1407                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1408 }
1409
1410 static void handle_hpd_rx_irq(void *param)
1411 {
1412         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1413         struct drm_connector *connector = &aconnector->base;
1414         struct drm_device *dev = connector->dev;
1415         struct dc_link *dc_link = aconnector->dc_link;
1416         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1417         enum dc_connection_type new_connection_type = dc_connection_none;
1418
1419         /*
1420          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1421          * conflict, after implement i2c helper, this mutex should be
1422          * retired.
1423          */
1424         if (dc_link->type != dc_connection_mst_branch)
1425                 mutex_lock(&aconnector->hpd_lock);
1426
1427         if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1428                         !is_mst_root_connector) {
1429                 /* Downstream Port status changed. */
1430                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
1431                         DRM_ERROR("KMS: Failed to detect connector\n");
1432
1433                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
1434                         emulated_link_detect(dc_link);
1435
1436                         if (aconnector->fake_enable)
1437                                 aconnector->fake_enable = false;
1438
1439                         amdgpu_dm_update_connector_after_detect(aconnector);
1440
1441
1442                         drm_modeset_lock_all(dev);
1443                         dm_restore_drm_connector_state(dev, connector);
1444                         drm_modeset_unlock_all(dev);
1445
1446                         drm_kms_helper_hotplug_event(dev);
1447                 } else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1448
1449                         if (aconnector->fake_enable)
1450                                 aconnector->fake_enable = false;
1451
1452                         amdgpu_dm_update_connector_after_detect(aconnector);
1453
1454
1455                         drm_modeset_lock_all(dev);
1456                         dm_restore_drm_connector_state(dev, connector);
1457                         drm_modeset_unlock_all(dev);
1458
1459                         drm_kms_helper_hotplug_event(dev);
1460                 }
1461         }
1462         if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1463             (dc_link->type == dc_connection_mst_branch))
1464                 dm_handle_hpd_rx_irq(aconnector);
1465
1466         if (dc_link->type != dc_connection_mst_branch) {
1467                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1468                 mutex_unlock(&aconnector->hpd_lock);
1469         }
1470 }
1471
1472 static void register_hpd_handlers(struct amdgpu_device *adev)
1473 {
1474         struct drm_device *dev = adev->ddev;
1475         struct drm_connector *connector;
1476         struct amdgpu_dm_connector *aconnector;
1477         const struct dc_link *dc_link;
1478         struct dc_interrupt_params int_params = {0};
1479
1480         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1481         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1482
1483         list_for_each_entry(connector,
1484                         &dev->mode_config.connector_list, head) {
1485
1486                 aconnector = to_amdgpu_dm_connector(connector);
1487                 dc_link = aconnector->dc_link;
1488
1489                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1490                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1491                         int_params.irq_source = dc_link->irq_source_hpd;
1492
1493                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1494                                         handle_hpd_irq,
1495                                         (void *) aconnector);
1496                 }
1497
1498                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1499
1500                         /* Also register for DP short pulse (hpd_rx). */
1501                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1502                         int_params.irq_source = dc_link->irq_source_hpd_rx;
1503
1504                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1505                                         handle_hpd_rx_irq,
1506                                         (void *) aconnector);
1507                 }
1508         }
1509 }
1510
1511 /* Register IRQ sources and initialize IRQ callbacks */
1512 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1513 {
1514         struct dc *dc = adev->dm.dc;
1515         struct common_irq_params *c_irq_params;
1516         struct dc_interrupt_params int_params = {0};
1517         int r;
1518         int i;
1519         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1520
1521         if (adev->asic_type == CHIP_VEGA10 ||
1522             adev->asic_type == CHIP_VEGA12 ||
1523             adev->asic_type == CHIP_VEGA20 ||
1524             adev->asic_type == CHIP_RAVEN)
1525                 client_id = SOC15_IH_CLIENTID_DCE;
1526
1527         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1528         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1529
1530         /*
1531          * Actions of amdgpu_irq_add_id():
1532          * 1. Register a set() function with base driver.
1533          *    Base driver will call set() function to enable/disable an
1534          *    interrupt in DC hardware.
1535          * 2. Register amdgpu_dm_irq_handler().
1536          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1537          *    coming from DC hardware.
1538          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1539          *    for acknowledging and handling. */
1540
1541         /* Use VBLANK interrupt */
1542         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1543                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1544                 if (r) {
1545                         DRM_ERROR("Failed to add crtc irq id!\n");
1546                         return r;
1547                 }
1548
1549                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1550                 int_params.irq_source =
1551                         dc_interrupt_to_irq_source(dc, i, 0);
1552
1553                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1554
1555                 c_irq_params->adev = adev;
1556                 c_irq_params->irq_src = int_params.irq_source;
1557
1558                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1559                                 dm_crtc_high_irq, c_irq_params);
1560         }
1561
1562         /* Use VUPDATE interrupt */
1563         for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
1564                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
1565                 if (r) {
1566                         DRM_ERROR("Failed to add vupdate irq id!\n");
1567                         return r;
1568                 }
1569
1570                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1571                 int_params.irq_source =
1572                         dc_interrupt_to_irq_source(dc, i, 0);
1573
1574                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1575
1576                 c_irq_params->adev = adev;
1577                 c_irq_params->irq_src = int_params.irq_source;
1578
1579                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1580                                 dm_vupdate_high_irq, c_irq_params);
1581         }
1582
1583         /* Use GRPH_PFLIP interrupt */
1584         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1585                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1586                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1587                 if (r) {
1588                         DRM_ERROR("Failed to add page flip irq id!\n");
1589                         return r;
1590                 }
1591
1592                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1593                 int_params.irq_source =
1594                         dc_interrupt_to_irq_source(dc, i, 0);
1595
1596                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1597
1598                 c_irq_params->adev = adev;
1599                 c_irq_params->irq_src = int_params.irq_source;
1600
1601                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1602                                 dm_pflip_high_irq, c_irq_params);
1603
1604         }
1605
1606         /* HPD */
1607         r = amdgpu_irq_add_id(adev, client_id,
1608                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1609         if (r) {
1610                 DRM_ERROR("Failed to add hpd irq id!\n");
1611                 return r;
1612         }
1613
1614         register_hpd_handlers(adev);
1615
1616         return 0;
1617 }
1618
1619 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1620 /* Register IRQ sources and initialize IRQ callbacks */
1621 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1622 {
1623         struct dc *dc = adev->dm.dc;
1624         struct common_irq_params *c_irq_params;
1625         struct dc_interrupt_params int_params = {0};
1626         int r;
1627         int i;
1628
1629         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1630         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1631
1632         /*
1633          * Actions of amdgpu_irq_add_id():
1634          * 1. Register a set() function with base driver.
1635          *    Base driver will call set() function to enable/disable an
1636          *    interrupt in DC hardware.
1637          * 2. Register amdgpu_dm_irq_handler().
1638          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1639          *    coming from DC hardware.
1640          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1641          *    for acknowledging and handling.
1642          */
1643
1644         /* Use VSTARTUP interrupt */
1645         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1646                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1647                         i++) {
1648                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1649
1650                 if (r) {
1651                         DRM_ERROR("Failed to add crtc irq id!\n");
1652                         return r;
1653                 }
1654
1655                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1656                 int_params.irq_source =
1657                         dc_interrupt_to_irq_source(dc, i, 0);
1658
1659                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1660
1661                 c_irq_params->adev = adev;
1662                 c_irq_params->irq_src = int_params.irq_source;
1663
1664                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1665                                 dm_crtc_high_irq, c_irq_params);
1666         }
1667
1668         /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
1669          * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
1670          * to trigger at end of each vblank, regardless of state of the lock,
1671          * matching DCE behaviour.
1672          */
1673         for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
1674              i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
1675              i++) {
1676                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
1677
1678                 if (r) {
1679                         DRM_ERROR("Failed to add vupdate irq id!\n");
1680                         return r;
1681                 }
1682
1683                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1684                 int_params.irq_source =
1685                         dc_interrupt_to_irq_source(dc, i, 0);
1686
1687                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1688
1689                 c_irq_params->adev = adev;
1690                 c_irq_params->irq_src = int_params.irq_source;
1691
1692                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1693                                 dm_vupdate_high_irq, c_irq_params);
1694         }
1695
1696         /* Use GRPH_PFLIP interrupt */
1697         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1698                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1699                         i++) {
1700                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1701                 if (r) {
1702                         DRM_ERROR("Failed to add page flip irq id!\n");
1703                         return r;
1704                 }
1705
1706                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1707                 int_params.irq_source =
1708                         dc_interrupt_to_irq_source(dc, i, 0);
1709
1710                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1711
1712                 c_irq_params->adev = adev;
1713                 c_irq_params->irq_src = int_params.irq_source;
1714
1715                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1716                                 dm_pflip_high_irq, c_irq_params);
1717
1718         }
1719
1720         /* HPD */
1721         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1722                         &adev->hpd_irq);
1723         if (r) {
1724                 DRM_ERROR("Failed to add hpd irq id!\n");
1725                 return r;
1726         }
1727
1728         register_hpd_handlers(adev);
1729
1730         return 0;
1731 }
1732 #endif
1733
1734 /*
1735  * Acquires the lock for the atomic state object and returns
1736  * the new atomic state.
1737  *
1738  * This should only be called during atomic check.
1739  */
1740 static int dm_atomic_get_state(struct drm_atomic_state *state,
1741                                struct dm_atomic_state **dm_state)
1742 {
1743         struct drm_device *dev = state->dev;
1744         struct amdgpu_device *adev = dev->dev_private;
1745         struct amdgpu_display_manager *dm = &adev->dm;
1746         struct drm_private_state *priv_state;
1747
1748         if (*dm_state)
1749                 return 0;
1750
1751         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
1752         if (IS_ERR(priv_state))
1753                 return PTR_ERR(priv_state);
1754
1755         *dm_state = to_dm_atomic_state(priv_state);
1756
1757         return 0;
1758 }
1759
1760 struct dm_atomic_state *
1761 dm_atomic_get_new_state(struct drm_atomic_state *state)
1762 {
1763         struct drm_device *dev = state->dev;
1764         struct amdgpu_device *adev = dev->dev_private;
1765         struct amdgpu_display_manager *dm = &adev->dm;
1766         struct drm_private_obj *obj;
1767         struct drm_private_state *new_obj_state;
1768         int i;
1769
1770         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
1771                 if (obj->funcs == dm->atomic_obj.funcs)
1772                         return to_dm_atomic_state(new_obj_state);
1773         }
1774
1775         return NULL;
1776 }
1777
1778 struct dm_atomic_state *
1779 dm_atomic_get_old_state(struct drm_atomic_state *state)
1780 {
1781         struct drm_device *dev = state->dev;
1782         struct amdgpu_device *adev = dev->dev_private;
1783         struct amdgpu_display_manager *dm = &adev->dm;
1784         struct drm_private_obj *obj;
1785         struct drm_private_state *old_obj_state;
1786         int i;
1787
1788         for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
1789                 if (obj->funcs == dm->atomic_obj.funcs)
1790                         return to_dm_atomic_state(old_obj_state);
1791         }
1792
1793         return NULL;
1794 }
1795
1796 static struct drm_private_state *
1797 dm_atomic_duplicate_state(struct drm_private_obj *obj)
1798 {
1799         struct dm_atomic_state *old_state, *new_state;
1800
1801         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
1802         if (!new_state)
1803                 return NULL;
1804
1805         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
1806
1807         old_state = to_dm_atomic_state(obj->state);
1808
1809         if (old_state && old_state->context)
1810                 new_state->context = dc_copy_state(old_state->context);
1811
1812         if (!new_state->context) {
1813                 kfree(new_state);
1814                 return NULL;
1815         }
1816
1817         return &new_state->base;
1818 }
1819
1820 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
1821                                     struct drm_private_state *state)
1822 {
1823         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1824
1825         if (dm_state && dm_state->context)
1826                 dc_release_state(dm_state->context);
1827
1828         kfree(dm_state);
1829 }
1830
1831 static struct drm_private_state_funcs dm_atomic_state_funcs = {
1832         .atomic_duplicate_state = dm_atomic_duplicate_state,
1833         .atomic_destroy_state = dm_atomic_destroy_state,
1834 };
1835
1836 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1837 {
1838         struct dm_atomic_state *state;
1839         int r;
1840
1841         adev->mode_info.mode_config_initialized = true;
1842
1843         adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1844         adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1845
1846         adev->ddev->mode_config.max_width = 16384;
1847         adev->ddev->mode_config.max_height = 16384;
1848
1849         adev->ddev->mode_config.preferred_depth = 24;
1850         adev->ddev->mode_config.prefer_shadow = 1;
1851         /* indicates support for immediate flip */
1852         adev->ddev->mode_config.async_page_flip = true;
1853
1854         adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1855
1856         state = kzalloc(sizeof(*state), GFP_KERNEL);
1857         if (!state)
1858                 return -ENOMEM;
1859
1860         state->context = dc_create_state(adev->dm.dc);
1861         if (!state->context) {
1862                 kfree(state);
1863                 return -ENOMEM;
1864         }
1865
1866         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
1867
1868         drm_atomic_private_obj_init(adev->ddev,
1869                                     &adev->dm.atomic_obj,
1870                                     &state->base,
1871                                     &dm_atomic_state_funcs);
1872
1873         r = amdgpu_display_modeset_create_props(adev);
1874         if (r)
1875                 return r;
1876
1877         return 0;
1878 }
1879
1880 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
1881 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
1882
1883 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1884         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1885
1886 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
1887 {
1888 #if defined(CONFIG_ACPI)
1889         struct amdgpu_dm_backlight_caps caps;
1890
1891         if (dm->backlight_caps.caps_valid)
1892                 return;
1893
1894         amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
1895         if (caps.caps_valid) {
1896                 dm->backlight_caps.min_input_signal = caps.min_input_signal;
1897                 dm->backlight_caps.max_input_signal = caps.max_input_signal;
1898                 dm->backlight_caps.caps_valid = true;
1899         } else {
1900                 dm->backlight_caps.min_input_signal =
1901                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1902                 dm->backlight_caps.max_input_signal =
1903                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1904         }
1905 #else
1906         dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1907         dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1908 #endif
1909 }
1910
1911 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1912 {
1913         struct amdgpu_display_manager *dm = bl_get_data(bd);
1914         struct amdgpu_dm_backlight_caps caps;
1915         uint32_t brightness = bd->props.brightness;
1916
1917         amdgpu_dm_update_backlight_caps(dm);
1918         caps = dm->backlight_caps;
1919         /*
1920          * The brightness input is in the range 0-255
1921          * It needs to be rescaled to be between the
1922          * requested min and max input signal
1923          *
1924          * It also needs to be scaled up by 0x101 to
1925          * match the DC interface which has a range of
1926          * 0 to 0xffff
1927          */
1928         brightness =
1929                 brightness
1930                 * 0x101
1931                 * (caps.max_input_signal - caps.min_input_signal)
1932                 / AMDGPU_MAX_BL_LEVEL
1933                 + caps.min_input_signal * 0x101;
1934
1935         if (dc_link_set_backlight_level(dm->backlight_link,
1936                         brightness, 0))
1937                 return 0;
1938         else
1939                 return 1;
1940 }
1941
1942 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1943 {
1944         struct amdgpu_display_manager *dm = bl_get_data(bd);
1945         int ret = dc_link_get_backlight_level(dm->backlight_link);
1946
1947         if (ret == DC_ERROR_UNEXPECTED)
1948                 return bd->props.brightness;
1949         return ret;
1950 }
1951
1952 static const struct backlight_ops amdgpu_dm_backlight_ops = {
1953         .get_brightness = amdgpu_dm_backlight_get_brightness,
1954         .update_status  = amdgpu_dm_backlight_update_status,
1955 };
1956
1957 static void
1958 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1959 {
1960         char bl_name[16];
1961         struct backlight_properties props = { 0 };
1962
1963         amdgpu_dm_update_backlight_caps(dm);
1964
1965         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1966         props.brightness = AMDGPU_MAX_BL_LEVEL;
1967         props.type = BACKLIGHT_RAW;
1968
1969         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1970                         dm->adev->ddev->primary->index);
1971
1972         dm->backlight_dev = backlight_device_register(bl_name,
1973                         dm->adev->ddev->dev,
1974                         dm,
1975                         &amdgpu_dm_backlight_ops,
1976                         &props);
1977
1978         if (IS_ERR(dm->backlight_dev))
1979                 DRM_ERROR("DM: Backlight registration failed!\n");
1980         else
1981                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1982 }
1983
1984 #endif
1985
1986 static int initialize_plane(struct amdgpu_display_manager *dm,
1987                             struct amdgpu_mode_info *mode_info, int plane_id,
1988                             enum drm_plane_type plane_type,
1989                             const struct dc_plane_cap *plane_cap)
1990 {
1991         struct drm_plane *plane;
1992         unsigned long possible_crtcs;
1993         int ret = 0;
1994
1995         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
1996         if (!plane) {
1997                 DRM_ERROR("KMS: Failed to allocate plane\n");
1998                 return -ENOMEM;
1999         }
2000         plane->type = plane_type;
2001
2002         /*
2003          * HACK: IGT tests expect that the primary plane for a CRTC
2004          * can only have one possible CRTC. Only expose support for
2005          * any CRTC if they're not going to be used as a primary plane
2006          * for a CRTC - like overlay or underlay planes.
2007          */
2008         possible_crtcs = 1 << plane_id;
2009         if (plane_id >= dm->dc->caps.max_streams)
2010                 possible_crtcs = 0xff;
2011
2012         ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2013
2014         if (ret) {
2015                 DRM_ERROR("KMS: Failed to initialize plane\n");
2016                 kfree(plane);
2017                 return ret;
2018         }
2019
2020         if (mode_info)
2021                 mode_info->planes[plane_id] = plane;
2022
2023         return ret;
2024 }
2025
2026
2027 static void register_backlight_device(struct amdgpu_display_manager *dm,
2028                                       struct dc_link *link)
2029 {
2030 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2031         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2032
2033         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2034             link->type != dc_connection_none) {
2035                 /*
2036                  * Event if registration failed, we should continue with
2037                  * DM initialization because not having a backlight control
2038                  * is better then a black screen.
2039                  */
2040                 amdgpu_dm_register_backlight_device(dm);
2041
2042                 if (dm->backlight_dev)
2043                         dm->backlight_link = link;
2044         }
2045 #endif
2046 }
2047
2048
2049 /*
2050  * In this architecture, the association
2051  * connector -> encoder -> crtc
2052  * id not really requried. The crtc and connector will hold the
2053  * display_index as an abstraction to use with DAL component
2054  *
2055  * Returns 0 on success
2056  */
2057 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2058 {
2059         struct amdgpu_display_manager *dm = &adev->dm;
2060         int32_t i;
2061         struct amdgpu_dm_connector *aconnector = NULL;
2062         struct amdgpu_encoder *aencoder = NULL;
2063         struct amdgpu_mode_info *mode_info = &adev->mode_info;
2064         uint32_t link_cnt;
2065         int32_t primary_planes;
2066         enum dc_connection_type new_connection_type = dc_connection_none;
2067         const struct dc_plane_cap *plane;
2068
2069         link_cnt = dm->dc->caps.max_links;
2070         if (amdgpu_dm_mode_config_init(dm->adev)) {
2071                 DRM_ERROR("DM: Failed to initialize mode config\n");
2072                 return -EINVAL;
2073         }
2074
2075         /* There is one primary plane per CRTC */
2076         primary_planes = dm->dc->caps.max_streams;
2077         ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
2078
2079         /*
2080          * Initialize primary planes, implicit planes for legacy IOCTLS.
2081          * Order is reversed to match iteration order in atomic check.
2082          */
2083         for (i = (primary_planes - 1); i >= 0; i--) {
2084                 plane = &dm->dc->caps.planes[i];
2085
2086                 if (initialize_plane(dm, mode_info, i,
2087                                      DRM_PLANE_TYPE_PRIMARY, plane)) {
2088                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
2089                         goto fail;
2090                 }
2091         }
2092
2093         /*
2094          * Initialize overlay planes, index starting after primary planes.
2095          * These planes have a higher DRM index than the primary planes since
2096          * they should be considered as having a higher z-order.
2097          * Order is reversed to match iteration order in atomic check.
2098          *
2099          * Only support DCN for now, and only expose one so we don't encourage
2100          * userspace to use up all the pipes.
2101          */
2102         for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2103                 struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2104
2105                 if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2106                         continue;
2107
2108                 if (!plane->blends_with_above || !plane->blends_with_below)
2109                         continue;
2110
2111                 if (!plane->pixel_format_support.argb8888)
2112                         continue;
2113
2114                 if (initialize_plane(dm, NULL, primary_planes + i,
2115                                      DRM_PLANE_TYPE_OVERLAY, plane)) {
2116                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
2117                         goto fail;
2118                 }
2119
2120                 /* Only create one overlay plane. */
2121                 break;
2122         }
2123
2124         for (i = 0; i < dm->dc->caps.max_streams; i++)
2125                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2126                         DRM_ERROR("KMS: Failed to initialize crtc\n");
2127                         goto fail;
2128                 }
2129
2130         dm->display_indexes_num = dm->dc->caps.max_streams;
2131
2132         /* loops over all connectors on the board */
2133         for (i = 0; i < link_cnt; i++) {
2134                 struct dc_link *link = NULL;
2135
2136                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
2137                         DRM_ERROR(
2138                                 "KMS: Cannot support more than %d display indexes\n",
2139                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
2140                         continue;
2141                 }
2142
2143                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
2144                 if (!aconnector)
2145                         goto fail;
2146
2147                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
2148                 if (!aencoder)
2149                         goto fail;
2150
2151                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2152                         DRM_ERROR("KMS: Failed to initialize encoder\n");
2153                         goto fail;
2154                 }
2155
2156                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2157                         DRM_ERROR("KMS: Failed to initialize connector\n");
2158                         goto fail;
2159                 }
2160
2161                 link = dc_get_link_at_index(dm->dc, i);
2162
2163                 if (!dc_link_detect_sink(link, &new_connection_type))
2164                         DRM_ERROR("KMS: Failed to detect connector\n");
2165
2166                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
2167                         emulated_link_detect(link);
2168                         amdgpu_dm_update_connector_after_detect(aconnector);
2169
2170                 } else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
2171                         amdgpu_dm_update_connector_after_detect(aconnector);
2172                         register_backlight_device(dm, link);
2173                 }
2174
2175
2176         }
2177
2178         /* Software is initialized. Now we can register interrupt handlers. */
2179         switch (adev->asic_type) {
2180         case CHIP_BONAIRE:
2181         case CHIP_HAWAII:
2182         case CHIP_KAVERI:
2183         case CHIP_KABINI:
2184         case CHIP_MULLINS:
2185         case CHIP_TONGA:
2186         case CHIP_FIJI:
2187         case CHIP_CARRIZO:
2188         case CHIP_STONEY:
2189         case CHIP_POLARIS11:
2190         case CHIP_POLARIS10:
2191         case CHIP_POLARIS12:
2192         case CHIP_VEGAM:
2193         case CHIP_VEGA10:
2194         case CHIP_VEGA12:
2195         case CHIP_VEGA20:
2196                 if (dce110_register_irq_handlers(dm->adev)) {
2197                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2198                         goto fail;
2199                 }
2200                 break;
2201 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2202         case CHIP_RAVEN:
2203                 if (dcn10_register_irq_handlers(dm->adev)) {
2204                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2205                         goto fail;
2206                 }
2207                 break;
2208 #endif
2209         default:
2210                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2211                 goto fail;
2212         }
2213
2214         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2215                 dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2216
2217         return 0;
2218 fail:
2219         kfree(aencoder);
2220         kfree(aconnector);
2221
2222         return -EINVAL;
2223 }
2224
2225 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2226 {
2227         drm_mode_config_cleanup(dm->ddev);
2228         drm_atomic_private_obj_fini(&dm->atomic_obj);
2229         return;
2230 }
2231
2232 /******************************************************************************
2233  * amdgpu_display_funcs functions
2234  *****************************************************************************/
2235
2236 /*
2237  * dm_bandwidth_update - program display watermarks
2238  *
2239  * @adev: amdgpu_device pointer
2240  *
2241  * Calculate and program the display watermarks and line buffer allocation.
2242  */
2243 static void dm_bandwidth_update(struct amdgpu_device *adev)
2244 {
2245         /* TODO: implement later */
2246 }
2247
2248 static const struct amdgpu_display_funcs dm_display_funcs = {
2249         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2250         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2251         .backlight_set_level = NULL, /* never called for DC */
2252         .backlight_get_level = NULL, /* never called for DC */
2253         .hpd_sense = NULL,/* called unconditionally */
2254         .hpd_set_polarity = NULL, /* called unconditionally */
2255         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2256         .page_flip_get_scanoutpos =
2257                 dm_crtc_get_scanoutpos,/* called unconditionally */
2258         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2259         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
2260 };
2261
2262 #if defined(CONFIG_DEBUG_KERNEL_DC)
2263
2264 static ssize_t s3_debug_store(struct device *device,
2265                               struct device_attribute *attr,
2266                               const char *buf,
2267                               size_t count)
2268 {
2269         int ret;
2270         int s3_state;
2271         struct pci_dev *pdev = to_pci_dev(device);
2272         struct drm_device *drm_dev = pci_get_drvdata(pdev);
2273         struct amdgpu_device *adev = drm_dev->dev_private;
2274
2275         ret = kstrtoint(buf, 0, &s3_state);
2276
2277         if (ret == 0) {
2278                 if (s3_state) {
2279                         dm_resume(adev);
2280                         drm_kms_helper_hotplug_event(adev->ddev);
2281                 } else
2282                         dm_suspend(adev);
2283         }
2284
2285         return ret == 0 ? count : 0;
2286 }
2287
2288 DEVICE_ATTR_WO(s3_debug);
2289
2290 #endif
2291
2292 static int dm_early_init(void *handle)
2293 {
2294         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2295
2296         switch (adev->asic_type) {
2297         case CHIP_BONAIRE:
2298         case CHIP_HAWAII:
2299                 adev->mode_info.num_crtc = 6;
2300                 adev->mode_info.num_hpd = 6;
2301                 adev->mode_info.num_dig = 6;
2302                 break;
2303         case CHIP_KAVERI:
2304                 adev->mode_info.num_crtc = 4;
2305                 adev->mode_info.num_hpd = 6;
2306                 adev->mode_info.num_dig = 7;
2307                 break;
2308         case CHIP_KABINI:
2309         case CHIP_MULLINS:
2310                 adev->mode_info.num_crtc = 2;
2311                 adev->mode_info.num_hpd = 6;
2312                 adev->mode_info.num_dig = 6;
2313                 break;
2314         case CHIP_FIJI:
2315         case CHIP_TONGA:
2316                 adev->mode_info.num_crtc = 6;
2317                 adev->mode_info.num_hpd = 6;
2318                 adev->mode_info.num_dig = 7;
2319                 break;
2320         case CHIP_CARRIZO:
2321                 adev->mode_info.num_crtc = 3;
2322                 adev->mode_info.num_hpd = 6;
2323                 adev->mode_info.num_dig = 9;
2324                 break;
2325         case CHIP_STONEY:
2326                 adev->mode_info.num_crtc = 2;
2327                 adev->mode_info.num_hpd = 6;
2328                 adev->mode_info.num_dig = 9;
2329                 break;
2330         case CHIP_POLARIS11:
2331         case CHIP_POLARIS12:
2332                 adev->mode_info.num_crtc = 5;
2333                 adev->mode_info.num_hpd = 5;
2334                 adev->mode_info.num_dig = 5;
2335                 break;
2336         case CHIP_POLARIS10:
2337         case CHIP_VEGAM:
2338                 adev->mode_info.num_crtc = 6;
2339                 adev->mode_info.num_hpd = 6;
2340                 adev->mode_info.num_dig = 6;
2341                 break;
2342         case CHIP_VEGA10:
2343         case CHIP_VEGA12:
2344         case CHIP_VEGA20:
2345                 adev->mode_info.num_crtc = 6;
2346                 adev->mode_info.num_hpd = 6;
2347                 adev->mode_info.num_dig = 6;
2348                 break;
2349 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2350         case CHIP_RAVEN:
2351                 adev->mode_info.num_crtc = 4;
2352                 adev->mode_info.num_hpd = 4;
2353                 adev->mode_info.num_dig = 4;
2354                 break;
2355 #endif
2356         default:
2357                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2358                 return -EINVAL;
2359         }
2360
2361         amdgpu_dm_set_irq_funcs(adev);
2362
2363         if (adev->mode_info.funcs == NULL)
2364                 adev->mode_info.funcs = &dm_display_funcs;
2365
2366         /*
2367          * Note: Do NOT change adev->audio_endpt_rreg and
2368          * adev->audio_endpt_wreg because they are initialised in
2369          * amdgpu_device_init()
2370          */
2371 #if defined(CONFIG_DEBUG_KERNEL_DC)
2372         device_create_file(
2373                 adev->ddev->dev,
2374                 &dev_attr_s3_debug);
2375 #endif
2376
2377         return 0;
2378 }
2379
2380 static bool modeset_required(struct drm_crtc_state *crtc_state,
2381                              struct dc_stream_state *new_stream,
2382                              struct dc_stream_state *old_stream)
2383 {
2384         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2385                 return false;
2386
2387         if (!crtc_state->enable)
2388                 return false;
2389
2390         return crtc_state->active;
2391 }
2392
2393 static bool modereset_required(struct drm_crtc_state *crtc_state)
2394 {
2395         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2396                 return false;
2397
2398         return !crtc_state->enable || !crtc_state->active;
2399 }
2400
2401 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2402 {
2403         drm_encoder_cleanup(encoder);
2404         kfree(encoder);
2405 }
2406
2407 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2408         .destroy = amdgpu_dm_encoder_destroy,
2409 };
2410
2411
2412 static int fill_dc_scaling_info(const struct drm_plane_state *state,
2413                                 struct dc_scaling_info *scaling_info)
2414 {
2415         int scale_w, scale_h;
2416
2417         memset(scaling_info, 0, sizeof(*scaling_info));
2418
2419         /* Source is fixed 16.16 but we ignore mantissa for now... */
2420         scaling_info->src_rect.x = state->src_x >> 16;
2421         scaling_info->src_rect.y = state->src_y >> 16;
2422
2423         scaling_info->src_rect.width = state->src_w >> 16;
2424         if (scaling_info->src_rect.width == 0)
2425                 return -EINVAL;
2426
2427         scaling_info->src_rect.height = state->src_h >> 16;
2428         if (scaling_info->src_rect.height == 0)
2429                 return -EINVAL;
2430
2431         scaling_info->dst_rect.x = state->crtc_x;
2432         scaling_info->dst_rect.y = state->crtc_y;
2433
2434         if (state->crtc_w == 0)
2435                 return -EINVAL;
2436
2437         scaling_info->dst_rect.width = state->crtc_w;
2438
2439         if (state->crtc_h == 0)
2440                 return -EINVAL;
2441
2442         scaling_info->dst_rect.height = state->crtc_h;
2443
2444         /* DRM doesn't specify clipping on destination output. */
2445         scaling_info->clip_rect = scaling_info->dst_rect;
2446
2447         /* TODO: Validate scaling per-format with DC plane caps */
2448         scale_w = scaling_info->dst_rect.width * 1000 /
2449                   scaling_info->src_rect.width;
2450
2451         if (scale_w < 250 || scale_w > 16000)
2452                 return -EINVAL;
2453
2454         scale_h = scaling_info->dst_rect.height * 1000 /
2455                   scaling_info->src_rect.height;
2456
2457         if (scale_h < 250 || scale_h > 16000)
2458                 return -EINVAL;
2459
2460         /*
2461          * The "scaling_quality" can be ignored for now, quality = 0 has DC
2462          * assume reasonable defaults based on the format.
2463          */
2464
2465         return 0;
2466 }
2467
2468 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2469                        uint64_t *tiling_flags)
2470 {
2471         struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2472         int r = amdgpu_bo_reserve(rbo, false);
2473
2474         if (unlikely(r)) {
2475                 /* Don't show error message when returning -ERESTARTSYS */
2476                 if (r != -ERESTARTSYS)
2477                         DRM_ERROR("Unable to reserve buffer: %d\n", r);
2478                 return r;
2479         }
2480
2481         if (tiling_flags)
2482                 amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2483
2484         amdgpu_bo_unreserve(rbo);
2485
2486         return r;
2487 }
2488
2489 static inline uint64_t get_dcc_address(uint64_t address, uint64_t tiling_flags)
2490 {
2491         uint32_t offset = AMDGPU_TILING_GET(tiling_flags, DCC_OFFSET_256B);
2492
2493         return offset ? (address + offset * 256) : 0;
2494 }
2495
2496 static int
2497 fill_plane_dcc_attributes(struct amdgpu_device *adev,
2498                           const struct amdgpu_framebuffer *afb,
2499                           const enum surface_pixel_format format,
2500                           const enum dc_rotation_angle rotation,
2501                           const union plane_size *plane_size,
2502                           const union dc_tiling_info *tiling_info,
2503                           const uint64_t info,
2504                           struct dc_plane_dcc_param *dcc,
2505                           struct dc_plane_address *address)
2506 {
2507         struct dc *dc = adev->dm.dc;
2508         struct dc_dcc_surface_param input;
2509         struct dc_surface_dcc_cap output;
2510         uint32_t offset = AMDGPU_TILING_GET(info, DCC_OFFSET_256B);
2511         uint32_t i64b = AMDGPU_TILING_GET(info, DCC_INDEPENDENT_64B) != 0;
2512         uint64_t dcc_address;
2513
2514         memset(&input, 0, sizeof(input));
2515         memset(&output, 0, sizeof(output));
2516
2517         if (!offset)
2518                 return 0;
2519
2520         if (format >= SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2521                 return 0;
2522
2523         if (!dc->cap_funcs.get_dcc_compression_cap)
2524                 return -EINVAL;
2525
2526         input.format = format;
2527         input.surface_size.width = plane_size->grph.surface_size.width;
2528         input.surface_size.height = plane_size->grph.surface_size.height;
2529         input.swizzle_mode = tiling_info->gfx9.swizzle;
2530
2531         if (rotation == ROTATION_ANGLE_0 || rotation == ROTATION_ANGLE_180)
2532                 input.scan = SCAN_DIRECTION_HORIZONTAL;
2533         else if (rotation == ROTATION_ANGLE_90 || rotation == ROTATION_ANGLE_270)
2534                 input.scan = SCAN_DIRECTION_VERTICAL;
2535
2536         if (!dc->cap_funcs.get_dcc_compression_cap(dc, &input, &output))
2537                 return -EINVAL;
2538
2539         if (!output.capable)
2540                 return -EINVAL;
2541
2542         if (i64b == 0 && output.grph.rgb.independent_64b_blks != 0)
2543                 return -EINVAL;
2544
2545         dcc->enable = 1;
2546         dcc->grph.meta_pitch =
2547                 AMDGPU_TILING_GET(info, DCC_PITCH_MAX) + 1;
2548         dcc->grph.independent_64b_blks = i64b;
2549
2550         dcc_address = get_dcc_address(afb->address, info);
2551         address->grph.meta_addr.low_part = lower_32_bits(dcc_address);
2552         address->grph.meta_addr.high_part = upper_32_bits(dcc_address);
2553
2554         return 0;
2555 }
2556
2557 static int
2558 fill_plane_buffer_attributes(struct amdgpu_device *adev,
2559                              const struct amdgpu_framebuffer *afb,
2560                              const enum surface_pixel_format format,
2561                              const enum dc_rotation_angle rotation,
2562                              const uint64_t tiling_flags,
2563                              union dc_tiling_info *tiling_info,
2564                              union plane_size *plane_size,
2565                              struct dc_plane_dcc_param *dcc,
2566                              struct dc_plane_address *address)
2567 {
2568         const struct drm_framebuffer *fb = &afb->base;
2569         int ret;
2570
2571         memset(tiling_info, 0, sizeof(*tiling_info));
2572         memset(plane_size, 0, sizeof(*plane_size));
2573         memset(dcc, 0, sizeof(*dcc));
2574         memset(address, 0, sizeof(*address));
2575
2576         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2577                 plane_size->grph.surface_size.x = 0;
2578                 plane_size->grph.surface_size.y = 0;
2579                 plane_size->grph.surface_size.width = fb->width;
2580                 plane_size->grph.surface_size.height = fb->height;
2581                 plane_size->grph.surface_pitch =
2582                         fb->pitches[0] / fb->format->cpp[0];
2583
2584                 address->type = PLN_ADDR_TYPE_GRAPHICS;
2585                 address->grph.addr.low_part = lower_32_bits(afb->address);
2586                 address->grph.addr.high_part = upper_32_bits(afb->address);
2587         } else {
2588                 uint64_t chroma_addr = afb->address + fb->offsets[1];
2589
2590                 plane_size->video.luma_size.x = 0;
2591                 plane_size->video.luma_size.y = 0;
2592                 plane_size->video.luma_size.width = fb->width;
2593                 plane_size->video.luma_size.height = fb->height;
2594                 plane_size->video.luma_pitch =
2595                         fb->pitches[0] / fb->format->cpp[0];
2596
2597                 plane_size->video.chroma_size.x = 0;
2598                 plane_size->video.chroma_size.y = 0;
2599                 /* TODO: set these based on surface format */
2600                 plane_size->video.chroma_size.width = fb->width / 2;
2601                 plane_size->video.chroma_size.height = fb->height / 2;
2602
2603                 plane_size->video.chroma_pitch =
2604                         fb->pitches[1] / fb->format->cpp[1];
2605
2606                 address->type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2607                 address->video_progressive.luma_addr.low_part =
2608                         lower_32_bits(afb->address);
2609                 address->video_progressive.luma_addr.high_part =
2610                         upper_32_bits(afb->address);
2611                 address->video_progressive.chroma_addr.low_part =
2612                         lower_32_bits(chroma_addr);
2613                 address->video_progressive.chroma_addr.high_part =
2614                         upper_32_bits(chroma_addr);
2615         }
2616
2617         /* Fill GFX8 params */
2618         if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2619                 unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2620
2621                 bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2622                 bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2623                 mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2624                 tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2625                 num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2626
2627                 /* XXX fix me for VI */
2628                 tiling_info->gfx8.num_banks = num_banks;
2629                 tiling_info->gfx8.array_mode =
2630                                 DC_ARRAY_2D_TILED_THIN1;
2631                 tiling_info->gfx8.tile_split = tile_split;
2632                 tiling_info->gfx8.bank_width = bankw;
2633                 tiling_info->gfx8.bank_height = bankh;
2634                 tiling_info->gfx8.tile_aspect = mtaspect;
2635                 tiling_info->gfx8.tile_mode =
2636                                 DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2637         } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2638                         == DC_ARRAY_1D_TILED_THIN1) {
2639                 tiling_info->gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2640         }
2641
2642         tiling_info->gfx8.pipe_config =
2643                         AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2644
2645         if (adev->asic_type == CHIP_VEGA10 ||
2646             adev->asic_type == CHIP_VEGA12 ||
2647             adev->asic_type == CHIP_VEGA20 ||
2648             adev->asic_type == CHIP_RAVEN) {
2649                 /* Fill GFX9 params */
2650                 tiling_info->gfx9.num_pipes =
2651                         adev->gfx.config.gb_addr_config_fields.num_pipes;
2652                 tiling_info->gfx9.num_banks =
2653                         adev->gfx.config.gb_addr_config_fields.num_banks;
2654                 tiling_info->gfx9.pipe_interleave =
2655                         adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2656                 tiling_info->gfx9.num_shader_engines =
2657                         adev->gfx.config.gb_addr_config_fields.num_se;
2658                 tiling_info->gfx9.max_compressed_frags =
2659                         adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2660                 tiling_info->gfx9.num_rb_per_se =
2661                         adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2662                 tiling_info->gfx9.swizzle =
2663                         AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2664                 tiling_info->gfx9.shaderEnable = 1;
2665
2666                 ret = fill_plane_dcc_attributes(adev, afb, format, rotation,
2667                                                 plane_size, tiling_info,
2668                                                 tiling_flags, dcc, address);
2669                 if (ret)
2670                         return ret;
2671         }
2672
2673         return 0;
2674 }
2675
2676 static void
2677 fill_blending_from_plane_state(const struct drm_plane_state *plane_state,
2678                                bool *per_pixel_alpha, bool *global_alpha,
2679                                int *global_alpha_value)
2680 {
2681         *per_pixel_alpha = false;
2682         *global_alpha = false;
2683         *global_alpha_value = 0xff;
2684
2685         if (plane_state->plane->type != DRM_PLANE_TYPE_OVERLAY)
2686                 return;
2687
2688         if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) {
2689                 static const uint32_t alpha_formats[] = {
2690                         DRM_FORMAT_ARGB8888,
2691                         DRM_FORMAT_RGBA8888,
2692                         DRM_FORMAT_ABGR8888,
2693                 };
2694                 uint32_t format = plane_state->fb->format->format;
2695                 unsigned int i;
2696
2697                 for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
2698                         if (format == alpha_formats[i]) {
2699                                 *per_pixel_alpha = true;
2700                                 break;
2701                         }
2702                 }
2703         }
2704
2705         if (plane_state->alpha < 0xffff) {
2706                 *global_alpha = true;
2707                 *global_alpha_value = plane_state->alpha >> 8;
2708         }
2709 }
2710
2711 static int
2712 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
2713                             const enum surface_pixel_format format,
2714                             enum dc_color_space *color_space)
2715 {
2716         bool full_range;
2717
2718         *color_space = COLOR_SPACE_SRGB;
2719
2720         /* DRM color properties only affect non-RGB formats. */
2721         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2722                 return 0;
2723
2724         full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2725
2726         switch (plane_state->color_encoding) {
2727         case DRM_COLOR_YCBCR_BT601:
2728                 if (full_range)
2729                         *color_space = COLOR_SPACE_YCBCR601;
2730                 else
2731                         *color_space = COLOR_SPACE_YCBCR601_LIMITED;
2732                 break;
2733
2734         case DRM_COLOR_YCBCR_BT709:
2735                 if (full_range)
2736                         *color_space = COLOR_SPACE_YCBCR709;
2737                 else
2738                         *color_space = COLOR_SPACE_YCBCR709_LIMITED;
2739                 break;
2740
2741         case DRM_COLOR_YCBCR_BT2020:
2742                 if (full_range)
2743                         *color_space = COLOR_SPACE_2020_YCBCR;
2744                 else
2745                         return -EINVAL;
2746                 break;
2747
2748         default:
2749                 return -EINVAL;
2750         }
2751
2752         return 0;
2753 }
2754
2755 static int
2756 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2757                             const struct drm_plane_state *plane_state,
2758                             const uint64_t tiling_flags,
2759                             struct dc_plane_info *plane_info,
2760                             struct dc_plane_address *address)
2761 {
2762         const struct drm_framebuffer *fb = plane_state->fb;
2763         const struct amdgpu_framebuffer *afb =
2764                 to_amdgpu_framebuffer(plane_state->fb);
2765         struct drm_format_name_buf format_name;
2766         int ret;
2767
2768         memset(plane_info, 0, sizeof(*plane_info));
2769
2770         switch (fb->format->format) {
2771         case DRM_FORMAT_C8:
2772                 plane_info->format =
2773                         SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2774                 break;
2775         case DRM_FORMAT_RGB565:
2776                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2777                 break;
2778         case DRM_FORMAT_XRGB8888:
2779         case DRM_FORMAT_ARGB8888:
2780                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2781                 break;
2782         case DRM_FORMAT_XRGB2101010:
2783         case DRM_FORMAT_ARGB2101010:
2784                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2785                 break;
2786         case DRM_FORMAT_XBGR2101010:
2787         case DRM_FORMAT_ABGR2101010:
2788                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2789                 break;
2790         case DRM_FORMAT_XBGR8888:
2791         case DRM_FORMAT_ABGR8888:
2792                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2793                 break;
2794         case DRM_FORMAT_NV21:
2795                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2796                 break;
2797         case DRM_FORMAT_NV12:
2798                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2799                 break;
2800         default:
2801                 DRM_ERROR(
2802                         "Unsupported screen format %s\n",
2803                         drm_get_format_name(fb->format->format, &format_name));
2804                 return -EINVAL;
2805         }
2806
2807         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
2808         case DRM_MODE_ROTATE_0:
2809                 plane_info->rotation = ROTATION_ANGLE_0;
2810                 break;
2811         case DRM_MODE_ROTATE_90:
2812                 plane_info->rotation = ROTATION_ANGLE_90;
2813                 break;
2814         case DRM_MODE_ROTATE_180:
2815                 plane_info->rotation = ROTATION_ANGLE_180;
2816                 break;
2817         case DRM_MODE_ROTATE_270:
2818                 plane_info->rotation = ROTATION_ANGLE_270;
2819                 break;
2820         default:
2821                 plane_info->rotation = ROTATION_ANGLE_0;
2822                 break;
2823         }
2824
2825         plane_info->visible = true;
2826         plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
2827
2828         ret = fill_plane_color_attributes(plane_state, plane_info->format,
2829                                           &plane_info->color_space);
2830         if (ret)
2831                 return ret;
2832
2833         ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
2834                                            plane_info->rotation, tiling_flags,
2835                                            &plane_info->tiling_info,
2836                                            &plane_info->plane_size,
2837                                            &plane_info->dcc, address);
2838         if (ret)
2839                 return ret;
2840
2841         fill_blending_from_plane_state(
2842                 plane_state, &plane_info->per_pixel_alpha,
2843                 &plane_info->global_alpha, &plane_info->global_alpha_value);
2844
2845         return 0;
2846 }
2847
2848 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
2849                                     struct dc_plane_state *dc_plane_state,
2850                                     struct drm_plane_state *plane_state,
2851                                     struct drm_crtc_state *crtc_state)
2852 {
2853         const struct amdgpu_framebuffer *amdgpu_fb =
2854                 to_amdgpu_framebuffer(plane_state->fb);
2855         struct dc_scaling_info scaling_info;
2856         struct dc_plane_info plane_info;
2857         uint64_t tiling_flags;
2858         int ret;
2859
2860         ret = fill_dc_scaling_info(plane_state, &scaling_info);
2861         if (ret)
2862                 return ret;
2863
2864         dc_plane_state->src_rect = scaling_info.src_rect;
2865         dc_plane_state->dst_rect = scaling_info.dst_rect;
2866         dc_plane_state->clip_rect = scaling_info.clip_rect;
2867         dc_plane_state->scaling_quality = scaling_info.scaling_quality;
2868
2869         ret = get_fb_info(amdgpu_fb, &tiling_flags);
2870         if (ret)
2871                 return ret;
2872
2873         ret = fill_dc_plane_info_and_addr(adev, plane_state, tiling_flags,
2874                                           &plane_info,
2875                                           &dc_plane_state->address);
2876         if (ret)
2877                 return ret;
2878
2879         dc_plane_state->format = plane_info.format;
2880         dc_plane_state->color_space = plane_info.color_space;
2881         dc_plane_state->format = plane_info.format;
2882         dc_plane_state->plane_size = plane_info.plane_size;
2883         dc_plane_state->rotation = plane_info.rotation;
2884         dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
2885         dc_plane_state->stereo_format = plane_info.stereo_format;
2886         dc_plane_state->tiling_info = plane_info.tiling_info;
2887         dc_plane_state->visible = plane_info.visible;
2888         dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
2889         dc_plane_state->global_alpha = plane_info.global_alpha;
2890         dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
2891         dc_plane_state->dcc = plane_info.dcc;
2892
2893         /*
2894          * Always set input transfer function, since plane state is refreshed
2895          * every time.
2896          */
2897         ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2898         if (ret) {
2899                 dc_transfer_func_release(dc_plane_state->in_transfer_func);
2900                 dc_plane_state->in_transfer_func = NULL;
2901         }
2902
2903         return ret;
2904 }
2905
2906 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2907                                            const struct dm_connector_state *dm_state,
2908                                            struct dc_stream_state *stream)
2909 {
2910         enum amdgpu_rmx_type rmx_type;
2911
2912         struct rect src = { 0 }; /* viewport in composition space*/
2913         struct rect dst = { 0 }; /* stream addressable area */
2914
2915         /* no mode. nothing to be done */
2916         if (!mode)
2917                 return;
2918
2919         /* Full screen scaling by default */
2920         src.width = mode->hdisplay;
2921         src.height = mode->vdisplay;
2922         dst.width = stream->timing.h_addressable;
2923         dst.height = stream->timing.v_addressable;
2924
2925         if (dm_state) {
2926                 rmx_type = dm_state->scaling;
2927                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2928                         if (src.width * dst.height <
2929                                         src.height * dst.width) {
2930                                 /* height needs less upscaling/more downscaling */
2931                                 dst.width = src.width *
2932                                                 dst.height / src.height;
2933                         } else {
2934                                 /* width needs less upscaling/more downscaling */
2935                                 dst.height = src.height *
2936                                                 dst.width / src.width;
2937                         }
2938                 } else if (rmx_type == RMX_CENTER) {
2939                         dst = src;
2940                 }
2941
2942                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
2943                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
2944
2945                 if (dm_state->underscan_enable) {
2946                         dst.x += dm_state->underscan_hborder / 2;
2947                         dst.y += dm_state->underscan_vborder / 2;
2948                         dst.width -= dm_state->underscan_hborder;
2949                         dst.height -= dm_state->underscan_vborder;
2950                 }
2951         }
2952
2953         stream->src = src;
2954         stream->dst = dst;
2955
2956         DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2957                         dst.x, dst.y, dst.width, dst.height);
2958
2959 }
2960
2961 static enum dc_color_depth
2962 convert_color_depth_from_display_info(const struct drm_connector *connector)
2963 {
2964         struct dm_connector_state *dm_conn_state =
2965                 to_dm_connector_state(connector->state);
2966         uint32_t bpc = connector->display_info.bpc;
2967
2968         /* TODO: Remove this when there's support for max_bpc in drm */
2969         if (dm_conn_state && bpc > dm_conn_state->max_bpc)
2970                 /* Round down to nearest even number. */
2971                 bpc = dm_conn_state->max_bpc - (dm_conn_state->max_bpc & 1);
2972
2973         switch (bpc) {
2974         case 0:
2975                 /*
2976                  * Temporary Work around, DRM doesn't parse color depth for
2977                  * EDID revision before 1.4
2978                  * TODO: Fix edid parsing
2979                  */
2980                 return COLOR_DEPTH_888;
2981         case 6:
2982                 return COLOR_DEPTH_666;
2983         case 8:
2984                 return COLOR_DEPTH_888;
2985         case 10:
2986                 return COLOR_DEPTH_101010;
2987         case 12:
2988                 return COLOR_DEPTH_121212;
2989         case 14:
2990                 return COLOR_DEPTH_141414;
2991         case 16:
2992                 return COLOR_DEPTH_161616;
2993         default:
2994                 return COLOR_DEPTH_UNDEFINED;
2995         }
2996 }
2997
2998 static enum dc_aspect_ratio
2999 get_aspect_ratio(const struct drm_display_mode *mode_in)
3000 {
3001         /* 1-1 mapping, since both enums follow the HDMI spec. */
3002         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
3003 }
3004
3005 static enum dc_color_space
3006 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
3007 {
3008         enum dc_color_space color_space = COLOR_SPACE_SRGB;
3009
3010         switch (dc_crtc_timing->pixel_encoding) {
3011         case PIXEL_ENCODING_YCBCR422:
3012         case PIXEL_ENCODING_YCBCR444:
3013         case PIXEL_ENCODING_YCBCR420:
3014         {
3015                 /*
3016                  * 27030khz is the separation point between HDTV and SDTV
3017                  * according to HDMI spec, we use YCbCr709 and YCbCr601
3018                  * respectively
3019                  */
3020                 if (dc_crtc_timing->pix_clk_100hz > 270300) {
3021                         if (dc_crtc_timing->flags.Y_ONLY)
3022                                 color_space =
3023                                         COLOR_SPACE_YCBCR709_LIMITED;
3024                         else
3025                                 color_space = COLOR_SPACE_YCBCR709;
3026                 } else {
3027                         if (dc_crtc_timing->flags.Y_ONLY)
3028                                 color_space =
3029                                         COLOR_SPACE_YCBCR601_LIMITED;
3030                         else
3031                                 color_space = COLOR_SPACE_YCBCR601;
3032                 }
3033
3034         }
3035         break;
3036         case PIXEL_ENCODING_RGB:
3037                 color_space = COLOR_SPACE_SRGB;
3038                 break;
3039
3040         default:
3041                 WARN_ON(1);
3042                 break;
3043         }
3044
3045         return color_space;
3046 }
3047
3048 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
3049 {
3050         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3051                 return;
3052
3053         timing_out->display_color_depth--;
3054 }
3055
3056 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
3057                                                 const struct drm_display_info *info)
3058 {
3059         int normalized_clk;
3060         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3061                 return;
3062         do {
3063                 normalized_clk = timing_out->pix_clk_100hz / 10;
3064                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
3065                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3066                         normalized_clk /= 2;
3067                 /* Adjusting pix clock following on HDMI spec based on colour depth */
3068                 switch (timing_out->display_color_depth) {
3069                 case COLOR_DEPTH_101010:
3070                         normalized_clk = (normalized_clk * 30) / 24;
3071                         break;
3072                 case COLOR_DEPTH_121212:
3073                         normalized_clk = (normalized_clk * 36) / 24;
3074                         break;
3075                 case COLOR_DEPTH_161616:
3076                         normalized_clk = (normalized_clk * 48) / 24;
3077                         break;
3078                 default:
3079                         return;
3080                 }
3081                 if (normalized_clk <= info->max_tmds_clock)
3082                         return;
3083                 reduce_mode_colour_depth(timing_out);
3084
3085         } while (timing_out->display_color_depth > COLOR_DEPTH_888);
3086
3087 }
3088
3089 static void
3090 fill_stream_properties_from_drm_display_mode(struct dc_stream_state *stream,
3091                                              const struct drm_display_mode *mode_in,
3092                                              const struct drm_connector *connector,
3093                                              const struct dc_stream_state *old_stream)
3094 {
3095         struct dc_crtc_timing *timing_out = &stream->timing;
3096         const struct drm_display_info *info = &connector->display_info;
3097
3098         memset(timing_out, 0, sizeof(struct dc_crtc_timing));
3099
3100         timing_out->h_border_left = 0;
3101         timing_out->h_border_right = 0;
3102         timing_out->v_border_top = 0;
3103         timing_out->v_border_bottom = 0;
3104         /* TODO: un-hardcode */
3105         if (drm_mode_is_420_only(info, mode_in)
3106                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3107                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3108         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
3109                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3110                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
3111         else
3112                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
3113
3114         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
3115         timing_out->display_color_depth = convert_color_depth_from_display_info(
3116                         connector);
3117         timing_out->scan_type = SCANNING_TYPE_NODATA;
3118         timing_out->hdmi_vic = 0;
3119
3120         if(old_stream) {
3121                 timing_out->vic = old_stream->timing.vic;
3122                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
3123                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
3124         } else {
3125                 timing_out->vic = drm_match_cea_mode(mode_in);
3126                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
3127                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
3128                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
3129                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
3130         }
3131
3132         timing_out->h_addressable = mode_in->crtc_hdisplay;
3133         timing_out->h_total = mode_in->crtc_htotal;
3134         timing_out->h_sync_width =
3135                 mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
3136         timing_out->h_front_porch =
3137                 mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
3138         timing_out->v_total = mode_in->crtc_vtotal;
3139         timing_out->v_addressable = mode_in->crtc_vdisplay;
3140         timing_out->v_front_porch =
3141                 mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
3142         timing_out->v_sync_width =
3143                 mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
3144         timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
3145         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
3146
3147         stream->output_color_space = get_output_color_space(timing_out);
3148
3149         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
3150         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
3151         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3152                 adjust_colour_depth_from_display_info(timing_out, info);
3153 }
3154
3155 static void fill_audio_info(struct audio_info *audio_info,
3156                             const struct drm_connector *drm_connector,
3157                             const struct dc_sink *dc_sink)
3158 {
3159         int i = 0;
3160         int cea_revision = 0;
3161         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
3162
3163         audio_info->manufacture_id = edid_caps->manufacturer_id;
3164         audio_info->product_id = edid_caps->product_id;
3165
3166         cea_revision = drm_connector->display_info.cea_rev;
3167
3168         strscpy(audio_info->display_name,
3169                 edid_caps->display_name,
3170                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
3171
3172         if (cea_revision >= 3) {
3173                 audio_info->mode_count = edid_caps->audio_mode_count;
3174
3175                 for (i = 0; i < audio_info->mode_count; ++i) {
3176                         audio_info->modes[i].format_code =
3177                                         (enum audio_format_code)
3178                                         (edid_caps->audio_modes[i].format_code);
3179                         audio_info->modes[i].channel_count =
3180                                         edid_caps->audio_modes[i].channel_count;
3181                         audio_info->modes[i].sample_rates.all =
3182                                         edid_caps->audio_modes[i].sample_rate;
3183                         audio_info->modes[i].sample_size =
3184                                         edid_caps->audio_modes[i].sample_size;
3185                 }
3186         }
3187
3188         audio_info->flags.all = edid_caps->speaker_flags;
3189
3190         /* TODO: We only check for the progressive mode, check for interlace mode too */
3191         if (drm_connector->latency_present[0]) {
3192                 audio_info->video_latency = drm_connector->video_latency[0];
3193                 audio_info->audio_latency = drm_connector->audio_latency[0];
3194         }
3195
3196         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
3197
3198 }
3199
3200 static void
3201 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
3202                                       struct drm_display_mode *dst_mode)
3203 {
3204         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
3205         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
3206         dst_mode->crtc_clock = src_mode->crtc_clock;
3207         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
3208         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
3209         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
3210         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
3211         dst_mode->crtc_htotal = src_mode->crtc_htotal;
3212         dst_mode->crtc_hskew = src_mode->crtc_hskew;
3213         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
3214         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
3215         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
3216         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
3217         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
3218 }
3219
3220 static void
3221 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
3222                                         const struct drm_display_mode *native_mode,
3223                                         bool scale_enabled)
3224 {
3225         if (scale_enabled) {
3226                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3227         } else if (native_mode->clock == drm_mode->clock &&
3228                         native_mode->htotal == drm_mode->htotal &&
3229                         native_mode->vtotal == drm_mode->vtotal) {
3230                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3231         } else {
3232                 /* no scaling nor amdgpu inserted, no need to patch */
3233         }
3234 }
3235
3236 static struct dc_sink *
3237 create_fake_sink(struct amdgpu_dm_connector *aconnector)
3238 {
3239         struct dc_sink_init_data sink_init_data = { 0 };
3240         struct dc_sink *sink = NULL;
3241         sink_init_data.link = aconnector->dc_link;
3242         sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
3243
3244         sink = dc_sink_create(&sink_init_data);
3245         if (!sink) {
3246                 DRM_ERROR("Failed to create sink!\n");
3247                 return NULL;
3248         }
3249         sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
3250
3251         return sink;
3252 }
3253
3254 static void set_multisync_trigger_params(
3255                 struct dc_stream_state *stream)
3256 {
3257         if (stream->triggered_crtc_reset.enabled) {
3258                 stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
3259                 stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
3260         }
3261 }
3262
3263 static void set_master_stream(struct dc_stream_state *stream_set[],
3264                               int stream_count)
3265 {
3266         int j, highest_rfr = 0, master_stream = 0;
3267
3268         for (j = 0;  j < stream_count; j++) {
3269                 if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
3270                         int refresh_rate = 0;
3271
3272                         refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
3273                                 (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
3274                         if (refresh_rate > highest_rfr) {
3275                                 highest_rfr = refresh_rate;
3276                                 master_stream = j;
3277                         }
3278                 }
3279         }
3280         for (j = 0;  j < stream_count; j++) {
3281                 if (stream_set[j])
3282                         stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
3283         }
3284 }
3285
3286 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
3287 {
3288         int i = 0;
3289
3290         if (context->stream_count < 2)
3291                 return;
3292         for (i = 0; i < context->stream_count ; i++) {
3293                 if (!context->streams[i])
3294                         continue;
3295                 /*
3296                  * TODO: add a function to read AMD VSDB bits and set
3297                  * crtc_sync_master.multi_sync_enabled flag
3298                  * For now it's set to false
3299                  */
3300                 set_multisync_trigger_params(context->streams[i]);
3301         }
3302         set_master_stream(context->streams, context->stream_count);
3303 }
3304
3305 static struct dc_stream_state *
3306 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
3307                        const struct drm_display_mode *drm_mode,
3308                        const struct dm_connector_state *dm_state,
3309                        const struct dc_stream_state *old_stream)
3310 {
3311         struct drm_display_mode *preferred_mode = NULL;
3312         struct drm_connector *drm_connector;
3313         struct dc_stream_state *stream = NULL;
3314         struct drm_display_mode mode = *drm_mode;
3315         bool native_mode_found = false;
3316         bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
3317         int mode_refresh;
3318         int preferred_refresh = 0;
3319
3320         struct dc_sink *sink = NULL;
3321         if (aconnector == NULL) {
3322                 DRM_ERROR("aconnector is NULL!\n");
3323                 return stream;
3324         }
3325
3326         drm_connector = &aconnector->base;
3327
3328         if (!aconnector->dc_sink) {
3329                 sink = create_fake_sink(aconnector);
3330                 if (!sink)
3331                         return stream;
3332         } else {
3333                 sink = aconnector->dc_sink;
3334                 dc_sink_retain(sink);
3335         }
3336
3337         stream = dc_create_stream_for_sink(sink);
3338
3339         if (stream == NULL) {
3340                 DRM_ERROR("Failed to create stream for sink!\n");
3341                 goto finish;
3342         }
3343
3344         stream->dm_stream_context = aconnector;
3345
3346         list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
3347                 /* Search for preferred mode */
3348                 if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
3349                         native_mode_found = true;
3350                         break;
3351                 }
3352         }
3353         if (!native_mode_found)
3354                 preferred_mode = list_first_entry_or_null(
3355                                 &aconnector->base.modes,
3356                                 struct drm_display_mode,
3357                                 head);
3358
3359         mode_refresh = drm_mode_vrefresh(&mode);
3360
3361         if (preferred_mode == NULL) {
3362                 /*
3363                  * This may not be an error, the use case is when we have no
3364                  * usermode calls to reset and set mode upon hotplug. In this
3365                  * case, we call set mode ourselves to restore the previous mode
3366                  * and the modelist may not be filled in in time.
3367                  */
3368                 DRM_DEBUG_DRIVER("No preferred mode found\n");
3369         } else {
3370                 decide_crtc_timing_for_drm_display_mode(
3371                                 &mode, preferred_mode,
3372                                 dm_state ? (dm_state->scaling != RMX_OFF) : false);
3373                 preferred_refresh = drm_mode_vrefresh(preferred_mode);
3374         }
3375
3376         if (!dm_state)
3377                 drm_mode_set_crtcinfo(&mode, 0);
3378
3379         /*
3380         * If scaling is enabled and refresh rate didn't change
3381         * we copy the vic and polarities of the old timings
3382         */
3383         if (!scale || mode_refresh != preferred_refresh)
3384                 fill_stream_properties_from_drm_display_mode(stream,
3385                         &mode, &aconnector->base, NULL);
3386         else
3387                 fill_stream_properties_from_drm_display_mode(stream,
3388                         &mode, &aconnector->base, old_stream);
3389
3390         update_stream_scaling_settings(&mode, dm_state, stream);
3391
3392         fill_audio_info(
3393                 &stream->audio_info,
3394                 drm_connector,
3395                 sink);
3396
3397         update_stream_signal(stream, sink);
3398
3399 finish:
3400         dc_sink_release(sink);
3401
3402         return stream;
3403 }
3404
3405 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
3406 {
3407         drm_crtc_cleanup(crtc);
3408         kfree(crtc);
3409 }
3410
3411 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
3412                                   struct drm_crtc_state *state)
3413 {
3414         struct dm_crtc_state *cur = to_dm_crtc_state(state);
3415
3416         /* TODO Destroy dc_stream objects are stream object is flattened */
3417         if (cur->stream)
3418                 dc_stream_release(cur->stream);
3419
3420
3421         __drm_atomic_helper_crtc_destroy_state(state);
3422
3423
3424         kfree(state);
3425 }
3426
3427 static void dm_crtc_reset_state(struct drm_crtc *crtc)
3428 {
3429         struct dm_crtc_state *state;
3430
3431         if (crtc->state)
3432                 dm_crtc_destroy_state(crtc, crtc->state);
3433
3434         state = kzalloc(sizeof(*state), GFP_KERNEL);
3435         if (WARN_ON(!state))
3436                 return;
3437
3438         crtc->state = &state->base;
3439         crtc->state->crtc = crtc;
3440
3441 }
3442
3443 static struct drm_crtc_state *
3444 dm_crtc_duplicate_state(struct drm_crtc *crtc)
3445 {
3446         struct dm_crtc_state *state, *cur;
3447
3448         cur = to_dm_crtc_state(crtc->state);
3449
3450         if (WARN_ON(!crtc->state))
3451                 return NULL;
3452
3453         state = kzalloc(sizeof(*state), GFP_KERNEL);
3454         if (!state)
3455                 return NULL;
3456
3457         __drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
3458
3459         if (cur->stream) {
3460                 state->stream = cur->stream;
3461                 dc_stream_retain(state->stream);
3462         }
3463
3464         state->active_planes = cur->active_planes;
3465         state->interrupts_enabled = cur->interrupts_enabled;
3466         state->vrr_params = cur->vrr_params;
3467         state->vrr_infopacket = cur->vrr_infopacket;
3468         state->abm_level = cur->abm_level;
3469         state->vrr_supported = cur->vrr_supported;
3470         state->freesync_config = cur->freesync_config;
3471         state->crc_enabled = cur->crc_enabled;
3472
3473         /* TODO Duplicate dc_stream after objects are stream object is flattened */
3474
3475         return &state->base;
3476 }
3477
3478 static inline int dm_set_vupdate_irq(struct drm_crtc *crtc, bool enable)
3479 {
3480         enum dc_irq_source irq_source;
3481         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3482         struct amdgpu_device *adev = crtc->dev->dev_private;
3483         int rc;
3484
3485         irq_source = IRQ_TYPE_VUPDATE + acrtc->otg_inst;
3486
3487         rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3488
3489         DRM_DEBUG_DRIVER("crtc %d - vupdate irq %sabling: r=%d\n",
3490                          acrtc->crtc_id, enable ? "en" : "dis", rc);
3491         return rc;
3492 }
3493
3494 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
3495 {
3496         enum dc_irq_source irq_source;
3497         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3498         struct amdgpu_device *adev = crtc->dev->dev_private;
3499         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3500         int rc = 0;
3501
3502         if (enable) {
3503                 /* vblank irq on -> Only need vupdate irq in vrr mode */
3504                 if (amdgpu_dm_vrr_active(acrtc_state))
3505                         rc = dm_set_vupdate_irq(crtc, true);
3506         } else {
3507                 /* vblank irq off -> vupdate irq off */
3508                 rc = dm_set_vupdate_irq(crtc, false);
3509         }
3510
3511         if (rc)
3512                 return rc;
3513
3514         irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3515         return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3516 }
3517
3518 static int dm_enable_vblank(struct drm_crtc *crtc)
3519 {
3520         return dm_set_vblank(crtc, true);
3521 }
3522
3523 static void dm_disable_vblank(struct drm_crtc *crtc)
3524 {
3525         dm_set_vblank(crtc, false);
3526 }
3527
3528 /* Implemented only the options currently availible for the driver */
3529 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
3530         .reset = dm_crtc_reset_state,
3531         .destroy = amdgpu_dm_crtc_destroy,
3532         .gamma_set = drm_atomic_helper_legacy_gamma_set,
3533         .set_config = drm_atomic_helper_set_config,
3534         .page_flip = drm_atomic_helper_page_flip,
3535         .atomic_duplicate_state = dm_crtc_duplicate_state,
3536         .atomic_destroy_state = dm_crtc_destroy_state,
3537         .set_crc_source = amdgpu_dm_crtc_set_crc_source,
3538         .verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
3539         .enable_vblank = dm_enable_vblank,
3540         .disable_vblank = dm_disable_vblank,
3541 };
3542
3543 static enum drm_connector_status
3544 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
3545 {
3546         bool connected;
3547         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3548
3549         /*
3550          * Notes:
3551          * 1. This interface is NOT called in context of HPD irq.
3552          * 2. This interface *is called* in context of user-mode ioctl. Which
3553          * makes it a bad place for *any* MST-related activity.
3554          */
3555
3556         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
3557             !aconnector->fake_enable)
3558                 connected = (aconnector->dc_sink != NULL);
3559         else
3560                 connected = (aconnector->base.force == DRM_FORCE_ON);
3561
3562         return (connected ? connector_status_connected :
3563                         connector_status_disconnected);
3564 }
3565
3566 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
3567                                             struct drm_connector_state *connector_state,
3568                                             struct drm_property *property,
3569                                             uint64_t val)
3570 {
3571         struct drm_device *dev = connector->dev;
3572         struct amdgpu_device *adev = dev->dev_private;
3573         struct dm_connector_state *dm_old_state =
3574                 to_dm_connector_state(connector->state);
3575         struct dm_connector_state *dm_new_state =
3576                 to_dm_connector_state(connector_state);
3577
3578         int ret = -EINVAL;
3579
3580         if (property == dev->mode_config.scaling_mode_property) {
3581                 enum amdgpu_rmx_type rmx_type;
3582
3583                 switch (val) {
3584                 case DRM_MODE_SCALE_CENTER:
3585                         rmx_type = RMX_CENTER;
3586                         break;
3587                 case DRM_MODE_SCALE_ASPECT:
3588                         rmx_type = RMX_ASPECT;
3589                         break;
3590                 case DRM_MODE_SCALE_FULLSCREEN:
3591                         rmx_type = RMX_FULL;
3592                         break;
3593                 case DRM_MODE_SCALE_NONE:
3594                 default:
3595                         rmx_type = RMX_OFF;
3596                         break;
3597                 }
3598
3599                 if (dm_old_state->scaling == rmx_type)
3600                         return 0;
3601
3602                 dm_new_state->scaling = rmx_type;
3603                 ret = 0;
3604         } else if (property == adev->mode_info.underscan_hborder_property) {
3605                 dm_new_state->underscan_hborder = val;
3606                 ret = 0;
3607         } else if (property == adev->mode_info.underscan_vborder_property) {
3608                 dm_new_state->underscan_vborder = val;
3609                 ret = 0;
3610         } else if (property == adev->mode_info.underscan_property) {
3611                 dm_new_state->underscan_enable = val;
3612                 ret = 0;
3613         } else if (property == adev->mode_info.max_bpc_property) {
3614                 dm_new_state->max_bpc = val;
3615                 ret = 0;
3616         } else if (property == adev->mode_info.abm_level_property) {
3617                 dm_new_state->abm_level = val;
3618                 ret = 0;
3619         }
3620
3621         return ret;
3622 }
3623
3624 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3625                                             const struct drm_connector_state *state,
3626                                             struct drm_property *property,
3627                                             uint64_t *val)
3628 {
3629         struct drm_device *dev = connector->dev;
3630         struct amdgpu_device *adev = dev->dev_private;
3631         struct dm_connector_state *dm_state =
3632                 to_dm_connector_state(state);
3633         int ret = -EINVAL;
3634
3635         if (property == dev->mode_config.scaling_mode_property) {
3636                 switch (dm_state->scaling) {
3637                 case RMX_CENTER:
3638                         *val = DRM_MODE_SCALE_CENTER;
3639                         break;
3640                 case RMX_ASPECT:
3641                         *val = DRM_MODE_SCALE_ASPECT;
3642                         break;
3643                 case RMX_FULL:
3644                         *val = DRM_MODE_SCALE_FULLSCREEN;
3645                         break;
3646                 case RMX_OFF:
3647                 default:
3648                         *val = DRM_MODE_SCALE_NONE;
3649                         break;
3650                 }
3651                 ret = 0;
3652         } else if (property == adev->mode_info.underscan_hborder_property) {
3653                 *val = dm_state->underscan_hborder;
3654                 ret = 0;
3655         } else if (property == adev->mode_info.underscan_vborder_property) {
3656                 *val = dm_state->underscan_vborder;
3657                 ret = 0;
3658         } else if (property == adev->mode_info.underscan_property) {
3659                 *val = dm_state->underscan_enable;
3660                 ret = 0;
3661         } else if (property == adev->mode_info.max_bpc_property) {
3662                 *val = dm_state->max_bpc;
3663                 ret = 0;
3664         } else if (property == adev->mode_info.abm_level_property) {
3665                 *val = dm_state->abm_level;
3666                 ret = 0;
3667         }
3668
3669         return ret;
3670 }
3671
3672 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
3673 {
3674         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3675         const struct dc_link *link = aconnector->dc_link;
3676         struct amdgpu_device *adev = connector->dev->dev_private;
3677         struct amdgpu_display_manager *dm = &adev->dm;
3678
3679 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3680         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3681
3682         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
3683             link->type != dc_connection_none &&
3684             dm->backlight_dev) {
3685                 backlight_device_unregister(dm->backlight_dev);
3686                 dm->backlight_dev = NULL;
3687         }
3688 #endif
3689
3690         if (aconnector->dc_em_sink)
3691                 dc_sink_release(aconnector->dc_em_sink);
3692         aconnector->dc_em_sink = NULL;
3693         if (aconnector->dc_sink)
3694                 dc_sink_release(aconnector->dc_sink);
3695         aconnector->dc_sink = NULL;
3696
3697         drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
3698         drm_connector_unregister(connector);
3699         drm_connector_cleanup(connector);
3700         kfree(connector);
3701 }
3702
3703 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
3704 {
3705         struct dm_connector_state *state =
3706                 to_dm_connector_state(connector->state);
3707
3708         if (connector->state)
3709                 __drm_atomic_helper_connector_destroy_state(connector->state);
3710
3711         kfree(state);
3712
3713         state = kzalloc(sizeof(*state), GFP_KERNEL);
3714
3715         if (state) {
3716                 state->scaling = RMX_OFF;
3717                 state->underscan_enable = false;
3718                 state->underscan_hborder = 0;
3719                 state->underscan_vborder = 0;
3720                 state->max_bpc = 8;
3721
3722                 __drm_atomic_helper_connector_reset(connector, &state->base);
3723         }
3724 }
3725
3726 struct drm_connector_state *
3727 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
3728 {
3729         struct dm_connector_state *state =
3730                 to_dm_connector_state(connector->state);
3731
3732         struct dm_connector_state *new_state =
3733                         kmemdup(state, sizeof(*state), GFP_KERNEL);
3734
3735         if (!new_state)
3736                 return NULL;
3737
3738         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
3739
3740         new_state->freesync_capable = state->freesync_capable;
3741         new_state->abm_level = state->abm_level;
3742         new_state->scaling = state->scaling;
3743         new_state->underscan_enable = state->underscan_enable;
3744         new_state->underscan_hborder = state->underscan_hborder;
3745         new_state->underscan_vborder = state->underscan_vborder;
3746         new_state->max_bpc = state->max_bpc;
3747
3748         return &new_state->base;
3749 }
3750
3751 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
3752         .reset = amdgpu_dm_connector_funcs_reset,
3753         .detect = amdgpu_dm_connector_detect,
3754         .fill_modes = drm_helper_probe_single_connector_modes,
3755         .destroy = amdgpu_dm_connector_destroy,
3756         .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
3757         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
3758         .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
3759         .atomic_get_property = amdgpu_dm_connector_atomic_get_property
3760 };
3761
3762 static int get_modes(struct drm_connector *connector)
3763 {
3764         return amdgpu_dm_connector_get_modes(connector);
3765 }
3766
3767 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
3768 {
3769         struct dc_sink_init_data init_params = {
3770                         .link = aconnector->dc_link,
3771                         .sink_signal = SIGNAL_TYPE_VIRTUAL
3772         };
3773         struct edid *edid;
3774
3775         if (!aconnector->base.edid_blob_ptr) {
3776                 DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
3777                                 aconnector->base.name);
3778
3779                 aconnector->base.force = DRM_FORCE_OFF;
3780                 aconnector->base.override_edid = false;
3781                 return;
3782         }
3783
3784         edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
3785
3786         aconnector->edid = edid;
3787
3788         aconnector->dc_em_sink = dc_link_add_remote_sink(
3789                 aconnector->dc_link,
3790                 (uint8_t *)edid,
3791                 (edid->extensions + 1) * EDID_LENGTH,
3792                 &init_params);
3793
3794         if (aconnector->base.force == DRM_FORCE_ON) {
3795                 aconnector->dc_sink = aconnector->dc_link->local_sink ?
3796                 aconnector->dc_link->local_sink :
3797                 aconnector->dc_em_sink;
3798                 dc_sink_retain(aconnector->dc_sink);
3799         }
3800 }
3801
3802 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
3803 {
3804         struct dc_link *link = (struct dc_link *)aconnector->dc_link;
3805
3806         /*
3807          * In case of headless boot with force on for DP managed connector
3808          * Those settings have to be != 0 to get initial modeset
3809          */
3810         if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
3811                 link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
3812                 link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
3813         }
3814
3815
3816         aconnector->base.override_edid = true;
3817         create_eml_sink(aconnector);
3818 }
3819
3820 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
3821                                    struct drm_display_mode *mode)
3822 {
3823         int result = MODE_ERROR;
3824         struct dc_sink *dc_sink;
3825         struct amdgpu_device *adev = connector->dev->dev_private;
3826         /* TODO: Unhardcode stream count */
3827         struct dc_stream_state *stream;
3828         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3829         enum dc_status dc_result = DC_OK;
3830
3831         if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
3832                         (mode->flags & DRM_MODE_FLAG_DBLSCAN))
3833                 return result;
3834
3835         /*
3836          * Only run this the first time mode_valid is called to initilialize
3837          * EDID mgmt
3838          */
3839         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
3840                 !aconnector->dc_em_sink)
3841                 handle_edid_mgmt(aconnector);
3842
3843         dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
3844
3845         if (dc_sink == NULL) {
3846                 DRM_ERROR("dc_sink is NULL!\n");
3847                 goto fail;
3848         }
3849
3850         stream = create_stream_for_sink(aconnector, mode, NULL, NULL);
3851         if (stream == NULL) {
3852                 DRM_ERROR("Failed to create stream for sink!\n");
3853                 goto fail;
3854         }
3855
3856         dc_result = dc_validate_stream(adev->dm.dc, stream);
3857
3858         if (dc_result == DC_OK)
3859                 result = MODE_OK;
3860         else
3861                 DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
3862                               mode->vdisplay,
3863                               mode->hdisplay,
3864                               mode->clock,
3865                               dc_result);
3866
3867         dc_stream_release(stream);
3868
3869 fail:
3870         /* TODO: error handling*/
3871         return result;
3872 }
3873
3874 static int fill_hdr_info_packet(const struct drm_connector_state *state,
3875                                 struct dc_info_packet *out)
3876 {
3877         struct hdmi_drm_infoframe frame;
3878         unsigned char buf[30]; /* 26 + 4 */
3879         ssize_t len;
3880         int ret, i;
3881
3882         memset(out, 0, sizeof(*out));
3883
3884         if (!state->hdr_output_metadata)
3885                 return 0;
3886
3887         ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
3888         if (ret)
3889                 return ret;
3890
3891         len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
3892         if (len < 0)
3893                 return (int)len;
3894
3895         /* Static metadata is a fixed 26 bytes + 4 byte header. */
3896         if (len != 30)
3897                 return -EINVAL;
3898
3899         /* Prepare the infopacket for DC. */
3900         switch (state->connector->connector_type) {
3901         case DRM_MODE_CONNECTOR_HDMIA:
3902                 out->hb0 = 0x87; /* type */
3903                 out->hb1 = 0x01; /* version */
3904                 out->hb2 = 0x1A; /* length */
3905                 out->sb[0] = buf[3]; /* checksum */
3906                 i = 1;
3907                 break;
3908
3909         case DRM_MODE_CONNECTOR_DisplayPort:
3910         case DRM_MODE_CONNECTOR_eDP:
3911                 out->hb0 = 0x00; /* sdp id, zero */
3912                 out->hb1 = 0x87; /* type */
3913                 out->hb2 = 0x1D; /* payload len - 1 */
3914                 out->hb3 = (0x13 << 2); /* sdp version */
3915                 out->sb[0] = 0x01; /* version */
3916                 out->sb[1] = 0x1A; /* length */
3917                 i = 2;
3918                 break;
3919
3920         default:
3921                 return -EINVAL;
3922         }
3923
3924         memcpy(&out->sb[i], &buf[4], 26);
3925         out->valid = true;
3926
3927         print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
3928                        sizeof(out->sb), false);
3929
3930         return 0;
3931 }
3932
3933 static bool
3934 is_hdr_metadata_different(const struct drm_connector_state *old_state,
3935                           const struct drm_connector_state *new_state)
3936 {
3937         struct drm_property_blob *old_blob = old_state->hdr_output_metadata;
3938         struct drm_property_blob *new_blob = new_state->hdr_output_metadata;
3939
3940         if (old_blob != new_blob) {
3941                 if (old_blob && new_blob &&
3942                     old_blob->length == new_blob->length)
3943                         return memcmp(old_blob->data, new_blob->data,
3944                                       old_blob->length);
3945
3946                 return true;
3947         }
3948
3949         return false;
3950 }
3951
3952 static int
3953 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
3954                                  struct drm_connector_state *new_con_state)
3955 {
3956         struct drm_atomic_state *state = new_con_state->state;
3957         struct drm_connector_state *old_con_state =
3958                 drm_atomic_get_old_connector_state(state, conn);
3959         struct drm_crtc *crtc = new_con_state->crtc;
3960         struct drm_crtc_state *new_crtc_state;
3961         int ret;
3962
3963         if (!crtc)
3964                 return 0;
3965
3966         if (is_hdr_metadata_different(old_con_state, new_con_state)) {
3967                 struct dc_info_packet hdr_infopacket;
3968
3969                 ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
3970                 if (ret)
3971                         return ret;
3972
3973                 new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
3974                 if (IS_ERR(new_crtc_state))
3975                         return PTR_ERR(new_crtc_state);
3976
3977                 /*
3978                  * DC considers the stream backends changed if the
3979                  * static metadata changes. Forcing the modeset also
3980                  * gives a simple way for userspace to switch from
3981                  * 8bpc to 10bpc when setting the metadata to enter
3982                  * or exit HDR.
3983                  *
3984                  * Changing the static metadata after it's been
3985                  * set is permissible, however. So only force a
3986                  * modeset if we're entering or exiting HDR.
3987                  */
3988                 new_crtc_state->mode_changed =
3989                         !old_con_state->hdr_output_metadata ||
3990                         !new_con_state->hdr_output_metadata;
3991         }
3992
3993         return 0;
3994 }
3995
3996 static const struct drm_connector_helper_funcs
3997 amdgpu_dm_connector_helper_funcs = {
3998         /*
3999          * If hotplugging a second bigger display in FB Con mode, bigger resolution
4000          * modes will be filtered by drm_mode_validate_size(), and those modes
4001          * are missing after user start lightdm. So we need to renew modes list.
4002          * in get_modes call back, not just return the modes count
4003          */
4004         .get_modes = get_modes,
4005         .mode_valid = amdgpu_dm_connector_mode_valid,
4006         .atomic_check = amdgpu_dm_connector_atomic_check,
4007 };
4008
4009 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
4010 {
4011 }
4012
4013 static bool does_crtc_have_active_cursor(struct drm_crtc_state *new_crtc_state)
4014 {
4015         struct drm_device *dev = new_crtc_state->crtc->dev;
4016         struct drm_plane *plane;
4017
4018         drm_for_each_plane_mask(plane, dev, new_crtc_state->plane_mask) {
4019                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
4020                         return true;
4021         }
4022
4023         return false;
4024 }
4025
4026 static int count_crtc_active_planes(struct drm_crtc_state *new_crtc_state)
4027 {
4028         struct drm_atomic_state *state = new_crtc_state->state;
4029         struct drm_plane *plane;
4030         int num_active = 0;
4031
4032         drm_for_each_plane_mask(plane, state->dev, new_crtc_state->plane_mask) {
4033                 struct drm_plane_state *new_plane_state;
4034
4035                 /* Cursor planes are "fake". */
4036                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
4037                         continue;
4038
4039                 new_plane_state = drm_atomic_get_new_plane_state(state, plane);
4040
4041                 if (!new_plane_state) {
4042                         /*
4043                          * The plane is enable on the CRTC and hasn't changed
4044                          * state. This means that it previously passed
4045                          * validation and is therefore enabled.
4046                          */
4047                         num_active += 1;
4048                         continue;
4049                 }
4050
4051                 /* We need a framebuffer to be considered enabled. */
4052                 num_active += (new_plane_state->fb != NULL);
4053         }
4054
4055         return num_active;
4056 }
4057
4058 /*
4059  * Sets whether interrupts should be enabled on a specific CRTC.
4060  * We require that the stream be enabled and that there exist active
4061  * DC planes on the stream.
4062  */
4063 static void
4064 dm_update_crtc_interrupt_state(struct drm_crtc *crtc,
4065                                struct drm_crtc_state *new_crtc_state)
4066 {
4067         struct dm_crtc_state *dm_new_crtc_state =
4068                 to_dm_crtc_state(new_crtc_state);
4069
4070         dm_new_crtc_state->active_planes = 0;
4071         dm_new_crtc_state->interrupts_enabled = false;
4072
4073         if (!dm_new_crtc_state->stream)
4074                 return;
4075
4076         dm_new_crtc_state->active_planes =
4077                 count_crtc_active_planes(new_crtc_state);
4078
4079         dm_new_crtc_state->interrupts_enabled =
4080                 dm_new_crtc_state->active_planes > 0;
4081 }
4082
4083 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
4084                                        struct drm_crtc_state *state)
4085 {
4086         struct amdgpu_device *adev = crtc->dev->dev_private;
4087         struct dc *dc = adev->dm.dc;
4088         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
4089         int ret = -EINVAL;
4090
4091         /*
4092          * Update interrupt state for the CRTC. This needs to happen whenever
4093          * the CRTC has changed or whenever any of its planes have changed.
4094          * Atomic check satisfies both of these requirements since the CRTC
4095          * is added to the state by DRM during drm_atomic_helper_check_planes.
4096          */
4097         dm_update_crtc_interrupt_state(crtc, state);
4098
4099         if (unlikely(!dm_crtc_state->stream &&
4100                      modeset_required(state, NULL, dm_crtc_state->stream))) {
4101                 WARN_ON(1);
4102                 return ret;
4103         }
4104
4105         /* In some use cases, like reset, no stream is attached */
4106         if (!dm_crtc_state->stream)
4107                 return 0;
4108
4109         /*
4110          * We want at least one hardware plane enabled to use
4111          * the stream with a cursor enabled.
4112          */
4113         if (state->enable && state->active &&
4114             does_crtc_have_active_cursor(state) &&
4115             dm_crtc_state->active_planes == 0)
4116                 return -EINVAL;
4117
4118         if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
4119                 return 0;
4120
4121         return ret;
4122 }
4123
4124 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
4125                                       const struct drm_display_mode *mode,
4126                                       struct drm_display_mode *adjusted_mode)
4127 {
4128         return true;
4129 }
4130
4131 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
4132         .disable = dm_crtc_helper_disable,
4133         .atomic_check = dm_crtc_helper_atomic_check,
4134         .mode_fixup = dm_crtc_helper_mode_fixup
4135 };
4136
4137 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
4138 {
4139
4140 }
4141
4142 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
4143                                           struct drm_crtc_state *crtc_state,
4144                                           struct drm_connector_state *conn_state)
4145 {
4146         return 0;
4147 }
4148
4149 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
4150         .disable = dm_encoder_helper_disable,
4151         .atomic_check = dm_encoder_helper_atomic_check
4152 };
4153
4154 static void dm_drm_plane_reset(struct drm_plane *plane)
4155 {
4156         struct dm_plane_state *amdgpu_state = NULL;
4157
4158         if (plane->state)
4159                 plane->funcs->atomic_destroy_state(plane, plane->state);
4160
4161         amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
4162         WARN_ON(amdgpu_state == NULL);
4163
4164         if (amdgpu_state)
4165                 __drm_atomic_helper_plane_reset(plane, &amdgpu_state->base);
4166 }
4167
4168 static struct drm_plane_state *
4169 dm_drm_plane_duplicate_state(struct drm_plane *plane)
4170 {
4171         struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
4172
4173         old_dm_plane_state = to_dm_plane_state(plane->state);
4174         dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
4175         if (!dm_plane_state)
4176                 return NULL;
4177
4178         __drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
4179
4180         if (old_dm_plane_state->dc_state) {
4181                 dm_plane_state->dc_state = old_dm_plane_state->dc_state;
4182                 dc_plane_state_retain(dm_plane_state->dc_state);
4183         }
4184
4185         return &dm_plane_state->base;
4186 }
4187
4188 void dm_drm_plane_destroy_state(struct drm_plane *plane,
4189                                 struct drm_plane_state *state)
4190 {
4191         struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
4192
4193         if (dm_plane_state->dc_state)
4194                 dc_plane_state_release(dm_plane_state->dc_state);
4195
4196         drm_atomic_helper_plane_destroy_state(plane, state);
4197 }
4198
4199 static const struct drm_plane_funcs dm_plane_funcs = {
4200         .update_plane   = drm_atomic_helper_update_plane,
4201         .disable_plane  = drm_atomic_helper_disable_plane,
4202         .destroy        = drm_primary_helper_destroy,
4203         .reset = dm_drm_plane_reset,
4204         .atomic_duplicate_state = dm_drm_plane_duplicate_state,
4205         .atomic_destroy_state = dm_drm_plane_destroy_state,
4206 };
4207
4208 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
4209                                       struct drm_plane_state *new_state)
4210 {
4211         struct amdgpu_framebuffer *afb;
4212         struct drm_gem_object *obj;
4213         struct amdgpu_device *adev;
4214         struct amdgpu_bo *rbo;
4215         struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
4216         uint64_t tiling_flags;
4217         uint32_t domain;
4218         int r;
4219
4220         dm_plane_state_old = to_dm_plane_state(plane->state);
4221         dm_plane_state_new = to_dm_plane_state(new_state);
4222
4223         if (!new_state->fb) {
4224                 DRM_DEBUG_DRIVER("No FB bound\n");
4225                 return 0;
4226         }
4227
4228         afb = to_amdgpu_framebuffer(new_state->fb);
4229         obj = new_state->fb->obj[0];
4230         rbo = gem_to_amdgpu_bo(obj);
4231         adev = amdgpu_ttm_adev(rbo->tbo.bdev);
4232         r = amdgpu_bo_reserve(rbo, false);
4233         if (unlikely(r != 0))
4234                 return r;
4235
4236         if (plane->type != DRM_PLANE_TYPE_CURSOR)
4237                 domain = amdgpu_display_supported_domains(adev);
4238         else
4239                 domain = AMDGPU_GEM_DOMAIN_VRAM;
4240
4241         r = amdgpu_bo_pin(rbo, domain);
4242         if (unlikely(r != 0)) {
4243                 if (r != -ERESTARTSYS)
4244                         DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
4245                 amdgpu_bo_unreserve(rbo);
4246                 return r;
4247         }
4248
4249         r = amdgpu_ttm_alloc_gart(&rbo->tbo);
4250         if (unlikely(r != 0)) {
4251                 amdgpu_bo_unpin(rbo);
4252                 amdgpu_bo_unreserve(rbo);
4253                 DRM_ERROR("%p bind failed\n", rbo);
4254                 return r;
4255         }
4256
4257         amdgpu_bo_get_tiling_flags(rbo, &tiling_flags);
4258
4259         amdgpu_bo_unreserve(rbo);
4260
4261         afb->address = amdgpu_bo_gpu_offset(rbo);
4262
4263         amdgpu_bo_ref(rbo);
4264
4265         if (dm_plane_state_new->dc_state &&
4266                         dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
4267                 struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
4268
4269                 fill_plane_buffer_attributes(
4270                         adev, afb, plane_state->format, plane_state->rotation,
4271                         tiling_flags, &plane_state->tiling_info,
4272                         &plane_state->plane_size, &plane_state->dcc,
4273                         &plane_state->address);
4274         }
4275
4276         return 0;
4277 }
4278
4279 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
4280                                        struct drm_plane_state *old_state)
4281 {
4282         struct amdgpu_bo *rbo;
4283         int r;
4284
4285         if (!old_state->fb)
4286                 return;
4287
4288         rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
4289         r = amdgpu_bo_reserve(rbo, false);
4290         if (unlikely(r)) {
4291                 DRM_ERROR("failed to reserve rbo before unpin\n");
4292                 return;
4293         }
4294
4295         amdgpu_bo_unpin(rbo);
4296         amdgpu_bo_unreserve(rbo);
4297         amdgpu_bo_unref(&rbo);
4298 }
4299
4300 static int dm_plane_atomic_check(struct drm_plane *plane,
4301                                  struct drm_plane_state *state)
4302 {
4303         struct amdgpu_device *adev = plane->dev->dev_private;
4304         struct dc *dc = adev->dm.dc;
4305         struct dm_plane_state *dm_plane_state;
4306         struct dc_scaling_info scaling_info;
4307         int ret;
4308
4309         dm_plane_state = to_dm_plane_state(state);
4310
4311         if (!dm_plane_state->dc_state)
4312                 return 0;
4313
4314         ret = fill_dc_scaling_info(state, &scaling_info);
4315         if (ret)
4316                 return ret;
4317
4318         if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
4319                 return 0;
4320
4321         return -EINVAL;
4322 }
4323
4324 static int dm_plane_atomic_async_check(struct drm_plane *plane,
4325                                        struct drm_plane_state *new_plane_state)
4326 {
4327         struct drm_plane_state *old_plane_state =
4328                 drm_atomic_get_old_plane_state(new_plane_state->state, plane);
4329
4330         /* Only support async updates on cursor planes. */
4331         if (plane->type != DRM_PLANE_TYPE_CURSOR)
4332                 return -EINVAL;
4333
4334         /*
4335          * DRM calls prepare_fb and cleanup_fb on new_plane_state for
4336          * async commits so don't allow fb changes.
4337          */
4338         if (old_plane_state->fb != new_plane_state->fb)
4339                 return -EINVAL;
4340
4341         return 0;
4342 }
4343
4344 static void dm_plane_atomic_async_update(struct drm_plane *plane,
4345                                          struct drm_plane_state *new_state)
4346 {
4347         struct drm_plane_state *old_state =
4348                 drm_atomic_get_old_plane_state(new_state->state, plane);
4349
4350         if (plane->state->fb != new_state->fb)
4351                 drm_atomic_set_fb_for_plane(plane->state, new_state->fb);
4352
4353         plane->state->src_x = new_state->src_x;
4354         plane->state->src_y = new_state->src_y;
4355         plane->state->src_w = new_state->src_w;
4356         plane->state->src_h = new_state->src_h;
4357         plane->state->crtc_x = new_state->crtc_x;
4358         plane->state->crtc_y = new_state->crtc_y;
4359         plane->state->crtc_w = new_state->crtc_w;
4360         plane->state->crtc_h = new_state->crtc_h;
4361
4362         handle_cursor_update(plane, old_state);
4363 }
4364
4365 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
4366         .prepare_fb = dm_plane_helper_prepare_fb,
4367         .cleanup_fb = dm_plane_helper_cleanup_fb,
4368         .atomic_check = dm_plane_atomic_check,
4369         .atomic_async_check = dm_plane_atomic_async_check,
4370         .atomic_async_update = dm_plane_atomic_async_update
4371 };
4372
4373 /*
4374  * TODO: these are currently initialized to rgb formats only.
4375  * For future use cases we should either initialize them dynamically based on
4376  * plane capabilities, or initialize this array to all formats, so internal drm
4377  * check will succeed, and let DC implement proper check
4378  */
4379 static const uint32_t rgb_formats[] = {
4380         DRM_FORMAT_XRGB8888,
4381         DRM_FORMAT_ARGB8888,
4382         DRM_FORMAT_RGBA8888,
4383         DRM_FORMAT_XRGB2101010,
4384         DRM_FORMAT_XBGR2101010,
4385         DRM_FORMAT_ARGB2101010,
4386         DRM_FORMAT_ABGR2101010,
4387         DRM_FORMAT_XBGR8888,
4388         DRM_FORMAT_ABGR8888,
4389         DRM_FORMAT_RGB565,
4390 };
4391
4392 static const uint32_t overlay_formats[] = {
4393         DRM_FORMAT_XRGB8888,
4394         DRM_FORMAT_ARGB8888,
4395         DRM_FORMAT_RGBA8888,
4396         DRM_FORMAT_XBGR8888,
4397         DRM_FORMAT_ABGR8888,
4398         DRM_FORMAT_RGB565
4399 };
4400
4401 static const u32 cursor_formats[] = {
4402         DRM_FORMAT_ARGB8888
4403 };
4404
4405 static int get_plane_formats(const struct drm_plane *plane,
4406                              const struct dc_plane_cap *plane_cap,
4407                              uint32_t *formats, int max_formats)
4408 {
4409         int i, num_formats = 0;
4410
4411         /*
4412          * TODO: Query support for each group of formats directly from
4413          * DC plane caps. This will require adding more formats to the
4414          * caps list.
4415          */
4416
4417         switch (plane->type) {
4418         case DRM_PLANE_TYPE_PRIMARY:
4419                 for (i = 0; i < ARRAY_SIZE(rgb_formats); ++i) {
4420                         if (num_formats >= max_formats)
4421                                 break;
4422
4423                         formats[num_formats++] = rgb_formats[i];
4424                 }
4425
4426                 if (plane_cap && plane_cap->pixel_format_support.nv12)
4427                         formats[num_formats++] = DRM_FORMAT_NV12;
4428                 break;
4429
4430         case DRM_PLANE_TYPE_OVERLAY:
4431                 for (i = 0; i < ARRAY_SIZE(overlay_formats); ++i) {
4432                         if (num_formats >= max_formats)
4433                                 break;
4434
4435                         formats[num_formats++] = overlay_formats[i];
4436                 }
4437                 break;
4438
4439         case DRM_PLANE_TYPE_CURSOR:
4440                 for (i = 0; i < ARRAY_SIZE(cursor_formats); ++i) {
4441                         if (num_formats >= max_formats)
4442                                 break;
4443
4444                         formats[num_formats++] = cursor_formats[i];
4445                 }
4446                 break;
4447         }
4448
4449         return num_formats;
4450 }
4451
4452 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
4453                                 struct drm_plane *plane,
4454                                 unsigned long possible_crtcs,
4455                                 const struct dc_plane_cap *plane_cap)
4456 {
4457         uint32_t formats[32];
4458         int num_formats;
4459         int res = -EPERM;
4460
4461         num_formats = get_plane_formats(plane, plane_cap, formats,
4462                                         ARRAY_SIZE(formats));
4463
4464         res = drm_universal_plane_init(dm->adev->ddev, plane, possible_crtcs,
4465                                        &dm_plane_funcs, formats, num_formats,
4466                                        NULL, plane->type, NULL);
4467         if (res)
4468                 return res;
4469
4470         if (plane->type == DRM_PLANE_TYPE_OVERLAY &&
4471             plane_cap && plane_cap->per_pixel_alpha) {
4472                 unsigned int blend_caps = BIT(DRM_MODE_BLEND_PIXEL_NONE) |
4473                                           BIT(DRM_MODE_BLEND_PREMULTI);
4474
4475                 drm_plane_create_alpha_property(plane);
4476                 drm_plane_create_blend_mode_property(plane, blend_caps);
4477         }
4478
4479         if (plane->type == DRM_PLANE_TYPE_PRIMARY &&
4480             plane_cap && plane_cap->pixel_format_support.nv12) {
4481                 /* This only affects YUV formats. */
4482                 drm_plane_create_color_properties(
4483                         plane,
4484                         BIT(DRM_COLOR_YCBCR_BT601) |
4485                         BIT(DRM_COLOR_YCBCR_BT709),
4486                         BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
4487                         BIT(DRM_COLOR_YCBCR_FULL_RANGE),
4488                         DRM_COLOR_YCBCR_BT709, DRM_COLOR_YCBCR_LIMITED_RANGE);
4489         }
4490
4491         drm_plane_helper_add(plane, &dm_plane_helper_funcs);
4492
4493         /* Create (reset) the plane state */
4494         if (plane->funcs->reset)
4495                 plane->funcs->reset(plane);
4496
4497         return 0;
4498 }
4499
4500 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
4501                                struct drm_plane *plane,
4502                                uint32_t crtc_index)
4503 {
4504         struct amdgpu_crtc *acrtc = NULL;
4505         struct drm_plane *cursor_plane;
4506
4507         int res = -ENOMEM;
4508
4509         cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
4510         if (!cursor_plane)
4511                 goto fail;
4512
4513         cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
4514         res = amdgpu_dm_plane_init(dm, cursor_plane, 0, NULL);
4515
4516         acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
4517         if (!acrtc)
4518                 goto fail;
4519
4520         res = drm_crtc_init_with_planes(
4521                         dm->ddev,
4522                         &acrtc->base,
4523                         plane,
4524                         cursor_plane,
4525                         &amdgpu_dm_crtc_funcs, NULL);
4526
4527         if (res)
4528                 goto fail;
4529
4530         drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
4531
4532         /* Create (reset) the plane state */
4533         if (acrtc->base.funcs->reset)
4534                 acrtc->base.funcs->reset(&acrtc->base);
4535
4536         acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
4537         acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
4538
4539         acrtc->crtc_id = crtc_index;
4540         acrtc->base.enabled = false;
4541         acrtc->otg_inst = -1;
4542
4543         dm->adev->mode_info.crtcs[crtc_index] = acrtc;
4544         drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
4545                                    true, MAX_COLOR_LUT_ENTRIES);
4546         drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
4547
4548         return 0;
4549
4550 fail:
4551         kfree(acrtc);
4552         kfree(cursor_plane);
4553         return res;
4554 }
4555
4556
4557 static int to_drm_connector_type(enum signal_type st)
4558 {
4559         switch (st) {
4560         case SIGNAL_TYPE_HDMI_TYPE_A:
4561                 return DRM_MODE_CONNECTOR_HDMIA;
4562         case SIGNAL_TYPE_EDP:
4563                 return DRM_MODE_CONNECTOR_eDP;
4564         case SIGNAL_TYPE_LVDS:
4565                 return DRM_MODE_CONNECTOR_LVDS;
4566         case SIGNAL_TYPE_RGB:
4567                 return DRM_MODE_CONNECTOR_VGA;
4568         case SIGNAL_TYPE_DISPLAY_PORT:
4569         case SIGNAL_TYPE_DISPLAY_PORT_MST:
4570                 return DRM_MODE_CONNECTOR_DisplayPort;
4571         case SIGNAL_TYPE_DVI_DUAL_LINK:
4572         case SIGNAL_TYPE_DVI_SINGLE_LINK:
4573                 return DRM_MODE_CONNECTOR_DVID;
4574         case SIGNAL_TYPE_VIRTUAL:
4575                 return DRM_MODE_CONNECTOR_VIRTUAL;
4576
4577         default:
4578                 return DRM_MODE_CONNECTOR_Unknown;
4579         }
4580 }
4581
4582 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
4583 {
4584         return drm_encoder_find(connector->dev, NULL, connector->encoder_ids[0]);
4585 }
4586
4587 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
4588 {
4589         struct drm_encoder *encoder;
4590         struct amdgpu_encoder *amdgpu_encoder;
4591
4592         encoder = amdgpu_dm_connector_to_encoder(connector);
4593
4594         if (encoder == NULL)
4595                 return;
4596
4597         amdgpu_encoder = to_amdgpu_encoder(encoder);
4598
4599         amdgpu_encoder->native_mode.clock = 0;
4600
4601         if (!list_empty(&connector->probed_modes)) {
4602                 struct drm_display_mode *preferred_mode = NULL;
4603
4604                 list_for_each_entry(preferred_mode,
4605                                     &connector->probed_modes,
4606                                     head) {
4607                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
4608                                 amdgpu_encoder->native_mode = *preferred_mode;
4609
4610                         break;
4611                 }
4612
4613         }
4614 }
4615
4616 static struct drm_display_mode *
4617 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
4618                              char *name,
4619                              int hdisplay, int vdisplay)
4620 {
4621         struct drm_device *dev = encoder->dev;
4622         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4623         struct drm_display_mode *mode = NULL;
4624         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4625
4626         mode = drm_mode_duplicate(dev, native_mode);
4627
4628         if (mode == NULL)
4629                 return NULL;
4630
4631         mode->hdisplay = hdisplay;
4632         mode->vdisplay = vdisplay;
4633         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
4634         strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
4635
4636         return mode;
4637
4638 }
4639
4640 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
4641                                                  struct drm_connector *connector)
4642 {
4643         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4644         struct drm_display_mode *mode = NULL;
4645         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4646         struct amdgpu_dm_connector *amdgpu_dm_connector =
4647                                 to_amdgpu_dm_connector(connector);
4648         int i;
4649         int n;
4650         struct mode_size {
4651                 char name[DRM_DISPLAY_MODE_LEN];
4652                 int w;
4653                 int h;
4654         } common_modes[] = {
4655                 {  "640x480",  640,  480},
4656                 {  "800x600",  800,  600},
4657                 { "1024x768", 1024,  768},
4658                 { "1280x720", 1280,  720},
4659                 { "1280x800", 1280,  800},
4660                 {"1280x1024", 1280, 1024},
4661                 { "1440x900", 1440,  900},
4662                 {"1680x1050", 1680, 1050},
4663                 {"1600x1200", 1600, 1200},
4664                 {"1920x1080", 1920, 1080},
4665                 {"1920x1200", 1920, 1200}
4666         };
4667
4668         n = ARRAY_SIZE(common_modes);
4669
4670         for (i = 0; i < n; i++) {
4671                 struct drm_display_mode *curmode = NULL;
4672                 bool mode_existed = false;
4673
4674                 if (common_modes[i].w > native_mode->hdisplay ||
4675                     common_modes[i].h > native_mode->vdisplay ||
4676                    (common_modes[i].w == native_mode->hdisplay &&
4677                     common_modes[i].h == native_mode->vdisplay))
4678                         continue;
4679
4680                 list_for_each_entry(curmode, &connector->probed_modes, head) {
4681                         if (common_modes[i].w == curmode->hdisplay &&
4682                             common_modes[i].h == curmode->vdisplay) {
4683                                 mode_existed = true;
4684                                 break;
4685                         }
4686                 }
4687
4688                 if (mode_existed)
4689                         continue;
4690
4691                 mode = amdgpu_dm_create_common_mode(encoder,
4692                                 common_modes[i].name, common_modes[i].w,
4693                                 common_modes[i].h);
4694                 drm_mode_probed_add(connector, mode);
4695                 amdgpu_dm_connector->num_modes++;
4696         }
4697 }
4698
4699 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
4700                                               struct edid *edid)
4701 {
4702         struct amdgpu_dm_connector *amdgpu_dm_connector =
4703                         to_amdgpu_dm_connector(connector);
4704
4705         if (edid) {
4706                 /* empty probed_modes */
4707                 INIT_LIST_HEAD(&connector->probed_modes);
4708                 amdgpu_dm_connector->num_modes =
4709                                 drm_add_edid_modes(connector, edid);
4710
4711                 amdgpu_dm_get_native_mode(connector);
4712         } else {
4713                 amdgpu_dm_connector->num_modes = 0;
4714         }
4715 }
4716
4717 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
4718 {
4719         struct amdgpu_dm_connector *amdgpu_dm_connector =
4720                         to_amdgpu_dm_connector(connector);
4721         struct drm_encoder *encoder;
4722         struct edid *edid = amdgpu_dm_connector->edid;
4723
4724         encoder = amdgpu_dm_connector_to_encoder(connector);
4725
4726         if (!edid || !drm_edid_is_valid(edid)) {
4727                 amdgpu_dm_connector->num_modes =
4728                                 drm_add_modes_noedid(connector, 640, 480);
4729         } else {
4730                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
4731                 amdgpu_dm_connector_add_common_modes(encoder, connector);
4732         }
4733         amdgpu_dm_fbc_init(connector);
4734
4735         return amdgpu_dm_connector->num_modes;
4736 }
4737
4738 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
4739                                      struct amdgpu_dm_connector *aconnector,
4740                                      int connector_type,
4741                                      struct dc_link *link,
4742                                      int link_index)
4743 {
4744         struct amdgpu_device *adev = dm->ddev->dev_private;
4745
4746         aconnector->connector_id = link_index;
4747         aconnector->dc_link = link;
4748         aconnector->base.interlace_allowed = false;
4749         aconnector->base.doublescan_allowed = false;
4750         aconnector->base.stereo_allowed = false;
4751         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
4752         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
4753         mutex_init(&aconnector->hpd_lock);
4754
4755         /*
4756          * configure support HPD hot plug connector_>polled default value is 0
4757          * which means HPD hot plug not supported
4758          */
4759         switch (connector_type) {
4760         case DRM_MODE_CONNECTOR_HDMIA:
4761                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4762                 aconnector->base.ycbcr_420_allowed =
4763                         link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
4764                 break;
4765         case DRM_MODE_CONNECTOR_DisplayPort:
4766                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4767                 aconnector->base.ycbcr_420_allowed =
4768                         link->link_enc->features.dp_ycbcr420_supported ? true : false;
4769                 break;
4770         case DRM_MODE_CONNECTOR_DVID:
4771                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4772                 break;
4773         default:
4774                 break;
4775         }
4776
4777         drm_object_attach_property(&aconnector->base.base,
4778                                 dm->ddev->mode_config.scaling_mode_property,
4779                                 DRM_MODE_SCALE_NONE);
4780
4781         drm_object_attach_property(&aconnector->base.base,
4782                                 adev->mode_info.underscan_property,
4783                                 UNDERSCAN_OFF);
4784         drm_object_attach_property(&aconnector->base.base,
4785                                 adev->mode_info.underscan_hborder_property,
4786                                 0);
4787         drm_object_attach_property(&aconnector->base.base,
4788                                 adev->mode_info.underscan_vborder_property,
4789                                 0);
4790         drm_object_attach_property(&aconnector->base.base,
4791                                 adev->mode_info.max_bpc_property,
4792                                 0);
4793
4794         if (connector_type == DRM_MODE_CONNECTOR_eDP &&
4795             dc_is_dmcu_initialized(adev->dm.dc)) {
4796                 drm_object_attach_property(&aconnector->base.base,
4797                                 adev->mode_info.abm_level_property, 0);
4798         }
4799
4800         if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
4801             connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
4802             connector_type == DRM_MODE_CONNECTOR_eDP) {
4803                 drm_object_attach_property(
4804                         &aconnector->base.base,
4805                         dm->ddev->mode_config.hdr_output_metadata_property, 0);
4806
4807                 drm_connector_attach_vrr_capable_property(
4808                         &aconnector->base);
4809         }
4810 }
4811
4812 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
4813                               struct i2c_msg *msgs, int num)
4814 {
4815         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
4816         struct ddc_service *ddc_service = i2c->ddc_service;
4817         struct i2c_command cmd;
4818         int i;
4819         int result = -EIO;
4820
4821         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
4822
4823         if (!cmd.payloads)
4824                 return result;
4825
4826         cmd.number_of_payloads = num;
4827         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
4828         cmd.speed = 100;
4829
4830         for (i = 0; i < num; i++) {
4831                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
4832                 cmd.payloads[i].address = msgs[i].addr;
4833                 cmd.payloads[i].length = msgs[i].len;
4834                 cmd.payloads[i].data = msgs[i].buf;
4835         }
4836
4837         if (dc_submit_i2c(
4838                         ddc_service->ctx->dc,
4839                         ddc_service->ddc_pin->hw_info.ddc_channel,
4840                         &cmd))
4841                 result = num;
4842
4843         kfree(cmd.payloads);
4844         return result;
4845 }
4846
4847 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
4848 {
4849         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
4850 }
4851
4852 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
4853         .master_xfer = amdgpu_dm_i2c_xfer,
4854         .functionality = amdgpu_dm_i2c_func,
4855 };
4856
4857 static struct amdgpu_i2c_adapter *
4858 create_i2c(struct ddc_service *ddc_service,
4859            int link_index,
4860            int *res)
4861 {
4862         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
4863         struct amdgpu_i2c_adapter *i2c;
4864
4865         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
4866         if (!i2c)
4867                 return NULL;
4868         i2c->base.owner = THIS_MODULE;
4869         i2c->base.class = I2C_CLASS_DDC;
4870         i2c->base.dev.parent = &adev->pdev->dev;
4871         i2c->base.algo = &amdgpu_dm_i2c_algo;
4872         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
4873         i2c_set_adapdata(&i2c->base, i2c);
4874         i2c->ddc_service = ddc_service;
4875         i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
4876
4877         return i2c;
4878 }
4879
4880
4881 /*
4882  * Note: this function assumes that dc_link_detect() was called for the
4883  * dc_link which will be represented by this aconnector.
4884  */
4885 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
4886                                     struct amdgpu_dm_connector *aconnector,
4887                                     uint32_t link_index,
4888                                     struct amdgpu_encoder *aencoder)
4889 {
4890         int res = 0;
4891         int connector_type;
4892         struct dc *dc = dm->dc;
4893         struct dc_link *link = dc_get_link_at_index(dc, link_index);
4894         struct amdgpu_i2c_adapter *i2c;
4895
4896         link->priv = aconnector;
4897
4898         DRM_DEBUG_DRIVER("%s()\n", __func__);
4899
4900         i2c = create_i2c(link->ddc, link->link_index, &res);
4901         if (!i2c) {
4902                 DRM_ERROR("Failed to create i2c adapter data\n");
4903                 return -ENOMEM;
4904         }
4905
4906         aconnector->i2c = i2c;
4907         res = i2c_add_adapter(&i2c->base);
4908
4909         if (res) {
4910                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
4911                 goto out_free;
4912         }
4913
4914         connector_type = to_drm_connector_type(link->connector_signal);
4915
4916         res = drm_connector_init(
4917                         dm->ddev,
4918                         &aconnector->base,
4919                         &amdgpu_dm_connector_funcs,
4920                         connector_type);
4921
4922         if (res) {
4923                 DRM_ERROR("connector_init failed\n");
4924                 aconnector->connector_id = -1;
4925                 goto out_free;
4926         }
4927
4928         drm_connector_helper_add(
4929                         &aconnector->base,
4930                         &amdgpu_dm_connector_helper_funcs);
4931
4932         if (aconnector->base.funcs->reset)
4933                 aconnector->base.funcs->reset(&aconnector->base);
4934
4935         amdgpu_dm_connector_init_helper(
4936                 dm,
4937                 aconnector,
4938                 connector_type,
4939                 link,
4940                 link_index);
4941
4942         drm_connector_attach_encoder(
4943                 &aconnector->base, &aencoder->base);
4944
4945         drm_connector_register(&aconnector->base);
4946 #if defined(CONFIG_DEBUG_FS)
4947         res = connector_debugfs_init(aconnector);
4948         if (res) {
4949                 DRM_ERROR("Failed to create debugfs for connector");
4950                 goto out_free;
4951         }
4952         aconnector->debugfs_dpcd_address = 0;
4953         aconnector->debugfs_dpcd_size = 0;
4954 #endif
4955
4956         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
4957                 || connector_type == DRM_MODE_CONNECTOR_eDP)
4958                 amdgpu_dm_initialize_dp_connector(dm, aconnector);
4959
4960 out_free:
4961         if (res) {
4962                 kfree(i2c);
4963                 aconnector->i2c = NULL;
4964         }
4965         return res;
4966 }
4967
4968 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
4969 {
4970         switch (adev->mode_info.num_crtc) {
4971         case 1:
4972                 return 0x1;
4973         case 2:
4974                 return 0x3;
4975         case 3:
4976                 return 0x7;
4977         case 4:
4978                 return 0xf;
4979         case 5:
4980                 return 0x1f;
4981         case 6:
4982         default:
4983                 return 0x3f;
4984         }
4985 }
4986
4987 static int amdgpu_dm_encoder_init(struct drm_device *dev,
4988                                   struct amdgpu_encoder *aencoder,
4989                                   uint32_t link_index)
4990 {
4991         struct amdgpu_device *adev = dev->dev_private;
4992
4993         int res = drm_encoder_init(dev,
4994                                    &aencoder->base,
4995                                    &amdgpu_dm_encoder_funcs,
4996                                    DRM_MODE_ENCODER_TMDS,
4997                                    NULL);
4998
4999         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
5000
5001         if (!res)
5002                 aencoder->encoder_id = link_index;
5003         else
5004                 aencoder->encoder_id = -1;
5005
5006         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
5007
5008         return res;
5009 }
5010
5011 static void manage_dm_interrupts(struct amdgpu_device *adev,
5012                                  struct amdgpu_crtc *acrtc,
5013                                  bool enable)
5014 {
5015         /*
5016          * this is not correct translation but will work as soon as VBLANK
5017          * constant is the same as PFLIP
5018          */
5019         int irq_type =
5020                 amdgpu_display_crtc_idx_to_irq_type(
5021                         adev,
5022                         acrtc->crtc_id);
5023
5024         if (enable) {
5025                 drm_crtc_vblank_on(&acrtc->base);
5026                 amdgpu_irq_get(
5027                         adev,
5028                         &adev->pageflip_irq,
5029                         irq_type);
5030         } else {
5031
5032                 amdgpu_irq_put(
5033                         adev,
5034                         &adev->pageflip_irq,
5035                         irq_type);
5036                 drm_crtc_vblank_off(&acrtc->base);
5037         }
5038 }
5039
5040 static bool
5041 is_scaling_state_different(const struct dm_connector_state *dm_state,
5042                            const struct dm_connector_state *old_dm_state)
5043 {
5044         if (dm_state->scaling != old_dm_state->scaling)
5045                 return true;
5046         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
5047                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
5048                         return true;
5049         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
5050                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
5051                         return true;
5052         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
5053                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
5054                 return true;
5055         return false;
5056 }
5057
5058 static void remove_stream(struct amdgpu_device *adev,
5059                           struct amdgpu_crtc *acrtc,
5060                           struct dc_stream_state *stream)
5061 {
5062         /* this is the update mode case */
5063
5064         acrtc->otg_inst = -1;
5065         acrtc->enabled = false;
5066 }
5067
5068 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
5069                                struct dc_cursor_position *position)
5070 {
5071         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5072         int x, y;
5073         int xorigin = 0, yorigin = 0;
5074
5075         if (!crtc || !plane->state->fb) {
5076                 position->enable = false;
5077                 position->x = 0;
5078                 position->y = 0;
5079                 return 0;
5080         }
5081
5082         if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
5083             (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
5084                 DRM_ERROR("%s: bad cursor width or height %d x %d\n",
5085                           __func__,
5086                           plane->state->crtc_w,
5087                           plane->state->crtc_h);
5088                 return -EINVAL;
5089         }
5090
5091         x = plane->state->crtc_x;
5092         y = plane->state->crtc_y;
5093
5094         if (crtc->primary->state) {
5095                 /* avivo cursor are offset into the total surface */
5096                 x += crtc->primary->state->src_x >> 16;
5097                 y += crtc->primary->state->src_y >> 16;
5098         }
5099
5100         if (x < 0) {
5101                 xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
5102                 x = 0;
5103         }
5104         if (y < 0) {
5105                 yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
5106                 y = 0;
5107         }
5108         position->enable = true;
5109         position->x = x;
5110         position->y = y;
5111         position->x_hotspot = xorigin;
5112         position->y_hotspot = yorigin;
5113
5114         return 0;
5115 }
5116
5117 static void handle_cursor_update(struct drm_plane *plane,
5118                                  struct drm_plane_state *old_plane_state)
5119 {
5120         struct amdgpu_device *adev = plane->dev->dev_private;
5121         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
5122         struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
5123         struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
5124         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5125         uint64_t address = afb ? afb->address : 0;
5126         struct dc_cursor_position position;
5127         struct dc_cursor_attributes attributes;
5128         int ret;
5129
5130         if (!plane->state->fb && !old_plane_state->fb)
5131                 return;
5132
5133         DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
5134                          __func__,
5135                          amdgpu_crtc->crtc_id,
5136                          plane->state->crtc_w,
5137                          plane->state->crtc_h);
5138
5139         ret = get_cursor_position(plane, crtc, &position);
5140         if (ret)
5141                 return;
5142
5143         if (!position.enable) {
5144                 /* turn off cursor */
5145                 if (crtc_state && crtc_state->stream) {
5146                         mutex_lock(&adev->dm.dc_lock);
5147                         dc_stream_set_cursor_position(crtc_state->stream,
5148                                                       &position);
5149                         mutex_unlock(&adev->dm.dc_lock);
5150                 }
5151                 return;
5152         }
5153
5154         amdgpu_crtc->cursor_width = plane->state->crtc_w;
5155         amdgpu_crtc->cursor_height = plane->state->crtc_h;
5156
5157         memset(&attributes, 0, sizeof(attributes));
5158         attributes.address.high_part = upper_32_bits(address);
5159         attributes.address.low_part  = lower_32_bits(address);
5160         attributes.width             = plane->state->crtc_w;
5161         attributes.height            = plane->state->crtc_h;
5162         attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
5163         attributes.rotation_angle    = 0;
5164         attributes.attribute_flags.value = 0;
5165
5166         attributes.pitch = attributes.width;
5167
5168         if (crtc_state->stream) {
5169                 mutex_lock(&adev->dm.dc_lock);
5170                 if (!dc_stream_set_cursor_attributes(crtc_state->stream,
5171                                                          &attributes))
5172                         DRM_ERROR("DC failed to set cursor attributes\n");
5173
5174                 if (!dc_stream_set_cursor_position(crtc_state->stream,
5175                                                    &position))
5176                         DRM_ERROR("DC failed to set cursor position\n");
5177                 mutex_unlock(&adev->dm.dc_lock);
5178         }
5179 }
5180
5181 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
5182 {
5183
5184         assert_spin_locked(&acrtc->base.dev->event_lock);
5185         WARN_ON(acrtc->event);
5186
5187         acrtc->event = acrtc->base.state->event;
5188
5189         /* Set the flip status */
5190         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
5191
5192         /* Mark this event as consumed */
5193         acrtc->base.state->event = NULL;
5194
5195         DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
5196                                                  acrtc->crtc_id);
5197 }
5198
5199 static void update_freesync_state_on_stream(
5200         struct amdgpu_display_manager *dm,
5201         struct dm_crtc_state *new_crtc_state,
5202         struct dc_stream_state *new_stream,
5203         struct dc_plane_state *surface,
5204         u32 flip_timestamp_in_us)
5205 {
5206         struct mod_vrr_params vrr_params;
5207         struct dc_info_packet vrr_infopacket = {0};
5208         struct amdgpu_device *adev = dm->adev;
5209         unsigned long flags;
5210
5211         if (!new_stream)
5212                 return;
5213
5214         /*
5215          * TODO: Determine why min/max totals and vrefresh can be 0 here.
5216          * For now it's sufficient to just guard against these conditions.
5217          */
5218
5219         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5220                 return;
5221
5222         spin_lock_irqsave(&adev->ddev->event_lock, flags);
5223         vrr_params = new_crtc_state->vrr_params;
5224
5225         if (surface) {
5226                 mod_freesync_handle_preflip(
5227                         dm->freesync_module,
5228                         surface,
5229                         new_stream,
5230                         flip_timestamp_in_us,
5231                         &vrr_params);
5232
5233                 if (adev->family < AMDGPU_FAMILY_AI &&
5234                     amdgpu_dm_vrr_active(new_crtc_state)) {
5235                         mod_freesync_handle_v_update(dm->freesync_module,
5236                                                      new_stream, &vrr_params);
5237                 }
5238         }
5239
5240         mod_freesync_build_vrr_infopacket(
5241                 dm->freesync_module,
5242                 new_stream,
5243                 &vrr_params,
5244                 PACKET_TYPE_VRR,
5245                 TRANSFER_FUNC_UNKNOWN,
5246                 &vrr_infopacket);
5247
5248         new_crtc_state->freesync_timing_changed |=
5249                 (memcmp(&new_crtc_state->vrr_params.adjust,
5250                         &vrr_params.adjust,
5251                         sizeof(vrr_params.adjust)) != 0);
5252
5253         new_crtc_state->freesync_vrr_info_changed |=
5254                 (memcmp(&new_crtc_state->vrr_infopacket,
5255                         &vrr_infopacket,
5256                         sizeof(vrr_infopacket)) != 0);
5257
5258         new_crtc_state->vrr_params = vrr_params;
5259         new_crtc_state->vrr_infopacket = vrr_infopacket;
5260
5261         new_stream->adjust = new_crtc_state->vrr_params.adjust;
5262         new_stream->vrr_infopacket = vrr_infopacket;
5263
5264         if (new_crtc_state->freesync_vrr_info_changed)
5265                 DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
5266                               new_crtc_state->base.crtc->base.id,
5267                               (int)new_crtc_state->base.vrr_enabled,
5268                               (int)vrr_params.state);
5269
5270         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5271 }
5272
5273 static void pre_update_freesync_state_on_stream(
5274         struct amdgpu_display_manager *dm,
5275         struct dm_crtc_state *new_crtc_state)
5276 {
5277         struct dc_stream_state *new_stream = new_crtc_state->stream;
5278         struct mod_vrr_params vrr_params;
5279         struct mod_freesync_config config = new_crtc_state->freesync_config;
5280         struct amdgpu_device *adev = dm->adev;
5281         unsigned long flags;
5282
5283         if (!new_stream)
5284                 return;
5285
5286         /*
5287          * TODO: Determine why min/max totals and vrefresh can be 0 here.
5288          * For now it's sufficient to just guard against these conditions.
5289          */
5290         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5291                 return;
5292
5293         spin_lock_irqsave(&adev->ddev->event_lock, flags);
5294         vrr_params = new_crtc_state->vrr_params;
5295
5296         if (new_crtc_state->vrr_supported &&
5297             config.min_refresh_in_uhz &&
5298             config.max_refresh_in_uhz) {
5299                 config.state = new_crtc_state->base.vrr_enabled ?
5300                         VRR_STATE_ACTIVE_VARIABLE :
5301                         VRR_STATE_INACTIVE;
5302         } else {
5303                 config.state = VRR_STATE_UNSUPPORTED;
5304         }
5305
5306         mod_freesync_build_vrr_params(dm->freesync_module,
5307                                       new_stream,
5308                                       &config, &vrr_params);
5309
5310         new_crtc_state->freesync_timing_changed |=
5311                 (memcmp(&new_crtc_state->vrr_params.adjust,
5312                         &vrr_params.adjust,
5313                         sizeof(vrr_params.adjust)) != 0);
5314
5315         new_crtc_state->vrr_params = vrr_params;
5316         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5317 }
5318
5319 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
5320                                             struct dm_crtc_state *new_state)
5321 {
5322         bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
5323         bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
5324
5325         if (!old_vrr_active && new_vrr_active) {
5326                 /* Transition VRR inactive -> active:
5327                  * While VRR is active, we must not disable vblank irq, as a
5328                  * reenable after disable would compute bogus vblank/pflip
5329                  * timestamps if it likely happened inside display front-porch.
5330                  *
5331                  * We also need vupdate irq for the actual core vblank handling
5332                  * at end of vblank.
5333                  */
5334                 dm_set_vupdate_irq(new_state->base.crtc, true);
5335                 drm_crtc_vblank_get(new_state->base.crtc);
5336                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
5337                                  __func__, new_state->base.crtc->base.id);
5338         } else if (old_vrr_active && !new_vrr_active) {
5339                 /* Transition VRR active -> inactive:
5340                  * Allow vblank irq disable again for fixed refresh rate.
5341                  */
5342                 dm_set_vupdate_irq(new_state->base.crtc, false);
5343                 drm_crtc_vblank_put(new_state->base.crtc);
5344                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
5345                                  __func__, new_state->base.crtc->base.id);
5346         }
5347 }
5348
5349 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
5350 {
5351         struct drm_plane *plane;
5352         struct drm_plane_state *old_plane_state, *new_plane_state;
5353         int i;
5354
5355         /*
5356          * TODO: Make this per-stream so we don't issue redundant updates for
5357          * commits with multiple streams.
5358          */
5359         for_each_oldnew_plane_in_state(state, plane, old_plane_state,
5360                                        new_plane_state, i)
5361                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5362                         handle_cursor_update(plane, old_plane_state);
5363 }
5364
5365 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
5366                                     struct dc_state *dc_state,
5367                                     struct drm_device *dev,
5368                                     struct amdgpu_display_manager *dm,
5369                                     struct drm_crtc *pcrtc,
5370                                     bool wait_for_vblank)
5371 {
5372         uint32_t i;
5373         uint64_t timestamp_ns;
5374         struct drm_plane *plane;
5375         struct drm_plane_state *old_plane_state, *new_plane_state;
5376         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
5377         struct drm_crtc_state *new_pcrtc_state =
5378                         drm_atomic_get_new_crtc_state(state, pcrtc);
5379         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
5380         struct dm_crtc_state *dm_old_crtc_state =
5381                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
5382         int planes_count = 0, vpos, hpos;
5383         long r;
5384         unsigned long flags;
5385         struct amdgpu_bo *abo;
5386         uint64_t tiling_flags;
5387         uint32_t target_vblank, last_flip_vblank;
5388         bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
5389         bool pflip_present = false;
5390         struct {
5391                 struct dc_surface_update surface_updates[MAX_SURFACES];
5392                 struct dc_plane_info plane_infos[MAX_SURFACES];
5393                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
5394                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
5395                 struct dc_stream_update stream_update;
5396         } *bundle;
5397
5398         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
5399
5400         if (!bundle) {
5401                 dm_error("Failed to allocate update bundle\n");
5402                 goto cleanup;
5403         }
5404
5405         /*
5406          * Disable the cursor first if we're disabling all the planes.
5407          * It'll remain on the screen after the planes are re-enabled
5408          * if we don't.
5409          */
5410         if (acrtc_state->active_planes == 0)
5411                 amdgpu_dm_commit_cursors(state);
5412
5413         /* update planes when needed */
5414         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
5415                 struct drm_crtc *crtc = new_plane_state->crtc;
5416                 struct drm_crtc_state *new_crtc_state;
5417                 struct drm_framebuffer *fb = new_plane_state->fb;
5418                 bool plane_needs_flip;
5419                 struct dc_plane_state *dc_plane;
5420                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
5421
5422                 /* Cursor plane is handled after stream updates */
5423                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5424                         continue;
5425
5426                 if (!fb || !crtc || pcrtc != crtc)
5427                         continue;
5428
5429                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
5430                 if (!new_crtc_state->active)
5431                         continue;
5432
5433                 dc_plane = dm_new_plane_state->dc_state;
5434
5435                 bundle->surface_updates[planes_count].surface = dc_plane;
5436                 if (new_pcrtc_state->color_mgmt_changed) {
5437                         bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
5438                         bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
5439                 }
5440
5441                 fill_dc_scaling_info(new_plane_state,
5442                                      &bundle->scaling_infos[planes_count]);
5443
5444                 bundle->surface_updates[planes_count].scaling_info =
5445                         &bundle->scaling_infos[planes_count];
5446
5447                 plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
5448
5449                 pflip_present = pflip_present || plane_needs_flip;
5450
5451                 if (!plane_needs_flip) {
5452                         planes_count += 1;
5453                         continue;
5454                 }
5455
5456                 abo = gem_to_amdgpu_bo(fb->obj[0]);
5457
5458                 /*
5459                  * Wait for all fences on this FB. Do limited wait to avoid
5460                  * deadlock during GPU reset when this fence will not signal
5461                  * but we hold reservation lock for the BO.
5462                  */
5463                 r = reservation_object_wait_timeout_rcu(abo->tbo.resv, true,
5464                                                         false,
5465                                                         msecs_to_jiffies(5000));
5466                 if (unlikely(r <= 0))
5467                         DRM_ERROR("Waiting for fences timed out or interrupted!");
5468
5469                 /*
5470                  * TODO This might fail and hence better not used, wait
5471                  * explicitly on fences instead
5472                  * and in general should be called for
5473                  * blocking commit to as per framework helpers
5474                  */
5475                 r = amdgpu_bo_reserve(abo, true);
5476                 if (unlikely(r != 0))
5477                         DRM_ERROR("failed to reserve buffer before flip\n");
5478
5479                 amdgpu_bo_get_tiling_flags(abo, &tiling_flags);
5480
5481                 amdgpu_bo_unreserve(abo);
5482
5483                 fill_dc_plane_info_and_addr(
5484                         dm->adev, new_plane_state, tiling_flags,
5485                         &bundle->plane_infos[planes_count],
5486                         &bundle->flip_addrs[planes_count].address);
5487
5488                 bundle->surface_updates[planes_count].plane_info =
5489                         &bundle->plane_infos[planes_count];
5490
5491                 bundle->flip_addrs[planes_count].flip_immediate =
5492                                 (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
5493
5494                 timestamp_ns = ktime_get_ns();
5495                 bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
5496                 bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
5497                 bundle->surface_updates[planes_count].surface = dc_plane;
5498
5499                 if (!bundle->surface_updates[planes_count].surface) {
5500                         DRM_ERROR("No surface for CRTC: id=%d\n",
5501                                         acrtc_attach->crtc_id);
5502                         continue;
5503                 }
5504
5505                 if (plane == pcrtc->primary)
5506                         update_freesync_state_on_stream(
5507                                 dm,
5508                                 acrtc_state,
5509                                 acrtc_state->stream,
5510                                 dc_plane,
5511                                 bundle->flip_addrs[planes_count].flip_timestamp_in_us);
5512
5513                 DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x\n",
5514                                  __func__,
5515                                  bundle->flip_addrs[planes_count].address.grph.addr.high_part,
5516                                  bundle->flip_addrs[planes_count].address.grph.addr.low_part);
5517
5518                 planes_count += 1;
5519
5520         }
5521
5522         if (pflip_present) {
5523                 if (!vrr_active) {
5524                         /* Use old throttling in non-vrr fixed refresh rate mode
5525                          * to keep flip scheduling based on target vblank counts
5526                          * working in a backwards compatible way, e.g., for
5527                          * clients using the GLX_OML_sync_control extension or
5528                          * DRI3/Present extension with defined target_msc.
5529                          */
5530                         last_flip_vblank = amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id);
5531                 }
5532                 else {
5533                         /* For variable refresh rate mode only:
5534                          * Get vblank of last completed flip to avoid > 1 vrr
5535                          * flips per video frame by use of throttling, but allow
5536                          * flip programming anywhere in the possibly large
5537                          * variable vrr vblank interval for fine-grained flip
5538                          * timing control and more opportunity to avoid stutter
5539                          * on late submission of flips.
5540                          */
5541                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5542                         last_flip_vblank = acrtc_attach->last_flip_vblank;
5543                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5544                 }
5545
5546                 target_vblank = last_flip_vblank + wait_for_vblank;
5547
5548                 /*
5549                  * Wait until we're out of the vertical blank period before the one
5550                  * targeted by the flip
5551                  */
5552                 while ((acrtc_attach->enabled &&
5553                         (amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
5554                                                             0, &vpos, &hpos, NULL,
5555                                                             NULL, &pcrtc->hwmode)
5556                          & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
5557                         (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
5558                         (int)(target_vblank -
5559                           amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id)) > 0)) {
5560                         usleep_range(1000, 1100);
5561                 }
5562
5563                 if (acrtc_attach->base.state->event) {
5564                         drm_crtc_vblank_get(pcrtc);
5565
5566                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5567
5568                         WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
5569                         prepare_flip_isr(acrtc_attach);
5570
5571                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5572                 }
5573
5574                 if (acrtc_state->stream) {
5575
5576                         if (acrtc_state->freesync_timing_changed)
5577                                 bundle->stream_update.adjust =
5578                                         &acrtc_state->stream->adjust;
5579
5580                         if (acrtc_state->freesync_vrr_info_changed)
5581                                 bundle->stream_update.vrr_infopacket =
5582                                         &acrtc_state->stream->vrr_infopacket;
5583                 }
5584         }
5585
5586         /* Update the planes if changed or disable if we don't have any. */
5587         if (planes_count || acrtc_state->active_planes == 0) {
5588                 if (new_pcrtc_state->mode_changed) {
5589                         bundle->stream_update.src = acrtc_state->stream->src;
5590                         bundle->stream_update.dst = acrtc_state->stream->dst;
5591                 }
5592
5593                 if (new_pcrtc_state->color_mgmt_changed)
5594                         bundle->stream_update.out_transfer_func = acrtc_state->stream->out_transfer_func;
5595
5596                 acrtc_state->stream->abm_level = acrtc_state->abm_level;
5597                 if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
5598                         bundle->stream_update.abm_level = &acrtc_state->abm_level;
5599
5600                 mutex_lock(&dm->dc_lock);
5601                 dc_commit_updates_for_stream(dm->dc,
5602                                                      bundle->surface_updates,
5603                                                      planes_count,
5604                                                      acrtc_state->stream,
5605                                                      &bundle->stream_update,
5606                                                      dc_state);
5607                 mutex_unlock(&dm->dc_lock);
5608         }
5609
5610         /*
5611          * Update cursor state *after* programming all the planes.
5612          * This avoids redundant programming in the case where we're going
5613          * to be disabling a single plane - those pipes are being disabled.
5614          */
5615         if (acrtc_state->active_planes)
5616                 amdgpu_dm_commit_cursors(state);
5617
5618 cleanup:
5619         kfree(bundle);
5620 }
5621
5622 /*
5623  * Enable interrupts on CRTCs that are newly active, undergone
5624  * a modeset, or have active planes again.
5625  *
5626  * Done in two passes, based on the for_modeset flag:
5627  * Pass 1: For CRTCs going through modeset
5628  * Pass 2: For CRTCs going from 0 to n active planes
5629  *
5630  * Interrupts can only be enabled after the planes are programmed,
5631  * so this requires a two-pass approach since we don't want to
5632  * just defer the interrupts until after commit planes every time.
5633  */
5634 static void amdgpu_dm_enable_crtc_interrupts(struct drm_device *dev,
5635                                              struct drm_atomic_state *state,
5636                                              bool for_modeset)
5637 {
5638         struct amdgpu_device *adev = dev->dev_private;
5639         struct drm_crtc *crtc;
5640         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5641         int i;
5642
5643         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5644                                       new_crtc_state, i) {
5645                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5646                 struct dm_crtc_state *dm_new_crtc_state =
5647                         to_dm_crtc_state(new_crtc_state);
5648                 struct dm_crtc_state *dm_old_crtc_state =
5649                         to_dm_crtc_state(old_crtc_state);
5650                 bool modeset = drm_atomic_crtc_needs_modeset(new_crtc_state);
5651                 bool run_pass;
5652
5653                 run_pass = (for_modeset && modeset) ||
5654                            (!for_modeset && !modeset &&
5655                             !dm_old_crtc_state->interrupts_enabled);
5656
5657                 if (!run_pass)
5658                         continue;
5659
5660                 if (!dm_new_crtc_state->interrupts_enabled)
5661                         continue;
5662
5663                 manage_dm_interrupts(adev, acrtc, true);
5664
5665 #ifdef CONFIG_DEBUG_FS
5666                 /* The stream has changed so CRC capture needs to re-enabled. */
5667                 if (dm_new_crtc_state->crc_enabled) {
5668                         dm_new_crtc_state->crc_enabled = false;
5669                         amdgpu_dm_crtc_set_crc_source(crtc, "auto");
5670                 }
5671 #endif
5672         }
5673 }
5674
5675 /*
5676  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
5677  * @crtc_state: the DRM CRTC state
5678  * @stream_state: the DC stream state.
5679  *
5680  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
5681  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
5682  */
5683 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
5684                                                 struct dc_stream_state *stream_state)
5685 {
5686         stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
5687 }
5688
5689 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
5690                                    struct drm_atomic_state *state,
5691                                    bool nonblock)
5692 {
5693         struct drm_crtc *crtc;
5694         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5695         struct amdgpu_device *adev = dev->dev_private;
5696         int i;
5697
5698         /*
5699          * We evade vblank and pflip interrupts on CRTCs that are undergoing
5700          * a modeset, being disabled, or have no active planes.
5701          *
5702          * It's done in atomic commit rather than commit tail for now since
5703          * some of these interrupt handlers access the current CRTC state and
5704          * potentially the stream pointer itself.
5705          *
5706          * Since the atomic state is swapped within atomic commit and not within
5707          * commit tail this would leave to new state (that hasn't been committed yet)
5708          * being accesssed from within the handlers.
5709          *
5710          * TODO: Fix this so we can do this in commit tail and not have to block
5711          * in atomic check.
5712          */
5713         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5714                 struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5715                 struct dm_crtc_state *dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5716                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5717
5718                 if (dm_old_crtc_state->interrupts_enabled &&
5719                     (!dm_new_crtc_state->interrupts_enabled ||
5720                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5721                         /*
5722                          * Drop the extra vblank reference added by CRC
5723                          * capture if applicable.
5724                          */
5725                         if (dm_new_crtc_state->crc_enabled)
5726                                 drm_crtc_vblank_put(crtc);
5727
5728                         /*
5729                          * Only keep CRC capture enabled if there's
5730                          * still a stream for the CRTC.
5731                          */
5732                         if (!dm_new_crtc_state->stream)
5733                                 dm_new_crtc_state->crc_enabled = false;
5734
5735                         manage_dm_interrupts(adev, acrtc, false);
5736                 }
5737         }
5738         /*
5739          * Add check here for SoC's that support hardware cursor plane, to
5740          * unset legacy_cursor_update
5741          */
5742
5743         return drm_atomic_helper_commit(dev, state, nonblock);
5744
5745         /*TODO Handle EINTR, reenable IRQ*/
5746 }
5747
5748 /**
5749  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
5750  * @state: The atomic state to commit
5751  *
5752  * This will tell DC to commit the constructed DC state from atomic_check,
5753  * programming the hardware. Any failures here implies a hardware failure, since
5754  * atomic check should have filtered anything non-kosher.
5755  */
5756 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
5757 {
5758         struct drm_device *dev = state->dev;
5759         struct amdgpu_device *adev = dev->dev_private;
5760         struct amdgpu_display_manager *dm = &adev->dm;
5761         struct dm_atomic_state *dm_state;
5762         struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
5763         uint32_t i, j;
5764         struct drm_crtc *crtc;
5765         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5766         unsigned long flags;
5767         bool wait_for_vblank = true;
5768         struct drm_connector *connector;
5769         struct drm_connector_state *old_con_state, *new_con_state;
5770         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5771         int crtc_disable_count = 0;
5772
5773         drm_atomic_helper_update_legacy_modeset_state(dev, state);
5774
5775         dm_state = dm_atomic_get_new_state(state);
5776         if (dm_state && dm_state->context) {
5777                 dc_state = dm_state->context;
5778         } else {
5779                 /* No state changes, retain current state. */
5780                 dc_state_temp = dc_create_state(dm->dc);
5781                 ASSERT(dc_state_temp);
5782                 dc_state = dc_state_temp;
5783                 dc_resource_state_copy_construct_current(dm->dc, dc_state);
5784         }
5785
5786         /* update changed items */
5787         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5788                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5789
5790                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5791                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5792
5793                 DRM_DEBUG_DRIVER(
5794                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
5795                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
5796                         "connectors_changed:%d\n",
5797                         acrtc->crtc_id,
5798                         new_crtc_state->enable,
5799                         new_crtc_state->active,
5800                         new_crtc_state->planes_changed,
5801                         new_crtc_state->mode_changed,
5802                         new_crtc_state->active_changed,
5803                         new_crtc_state->connectors_changed);
5804
5805                 /* Copy all transient state flags into dc state */
5806                 if (dm_new_crtc_state->stream) {
5807                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
5808                                                             dm_new_crtc_state->stream);
5809                 }
5810
5811                 /* handles headless hotplug case, updating new_state and
5812                  * aconnector as needed
5813                  */
5814
5815                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
5816
5817                         DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
5818
5819                         if (!dm_new_crtc_state->stream) {
5820                                 /*
5821                                  * this could happen because of issues with
5822                                  * userspace notifications delivery.
5823                                  * In this case userspace tries to set mode on
5824                                  * display which is disconnected in fact.
5825                                  * dc_sink is NULL in this case on aconnector.
5826                                  * We expect reset mode will come soon.
5827                                  *
5828                                  * This can also happen when unplug is done
5829                                  * during resume sequence ended
5830                                  *
5831                                  * In this case, we want to pretend we still
5832                                  * have a sink to keep the pipe running so that
5833                                  * hw state is consistent with the sw state
5834                                  */
5835                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
5836                                                 __func__, acrtc->base.base.id);
5837                                 continue;
5838                         }
5839
5840                         if (dm_old_crtc_state->stream)
5841                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
5842
5843                         pm_runtime_get_noresume(dev->dev);
5844
5845                         acrtc->enabled = true;
5846                         acrtc->hw_mode = new_crtc_state->mode;
5847                         crtc->hwmode = new_crtc_state->mode;
5848                 } else if (modereset_required(new_crtc_state)) {
5849                         DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
5850
5851                         /* i.e. reset mode */
5852                         if (dm_old_crtc_state->stream)
5853                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
5854                 }
5855         } /* for_each_crtc_in_state() */
5856
5857         if (dc_state) {
5858                 dm_enable_per_frame_crtc_master_sync(dc_state);
5859                 mutex_lock(&dm->dc_lock);
5860                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
5861                 mutex_unlock(&dm->dc_lock);
5862         }
5863
5864         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5865                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5866
5867                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5868
5869                 if (dm_new_crtc_state->stream != NULL) {
5870                         const struct dc_stream_status *status =
5871                                         dc_stream_get_status(dm_new_crtc_state->stream);
5872
5873                         if (!status)
5874                                 status = dc_stream_get_status_from_state(dc_state,
5875                                                                          dm_new_crtc_state->stream);
5876
5877                         if (!status)
5878                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
5879                         else
5880                                 acrtc->otg_inst = status->primary_otg_inst;
5881                 }
5882         }
5883
5884         /* Handle connector state changes */
5885         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5886                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5887                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5888                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5889                 struct dc_surface_update dummy_updates[MAX_SURFACES];
5890                 struct dc_stream_update stream_update;
5891                 struct dc_info_packet hdr_packet;
5892                 struct dc_stream_status *status = NULL;
5893                 bool abm_changed, hdr_changed, scaling_changed;
5894
5895                 memset(&dummy_updates, 0, sizeof(dummy_updates));
5896                 memset(&stream_update, 0, sizeof(stream_update));
5897
5898                 if (acrtc) {
5899                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5900                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5901                 }
5902
5903                 /* Skip any modesets/resets */
5904                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
5905                         continue;
5906
5907                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5908                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5909
5910                 scaling_changed = is_scaling_state_different(dm_new_con_state,
5911                                                              dm_old_con_state);
5912
5913                 abm_changed = dm_new_crtc_state->abm_level !=
5914                               dm_old_crtc_state->abm_level;
5915
5916                 hdr_changed =
5917                         is_hdr_metadata_different(old_con_state, new_con_state);
5918
5919                 if (!scaling_changed && !abm_changed && !hdr_changed)
5920                         continue;
5921
5922                 if (scaling_changed) {
5923                         update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
5924                                         dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
5925
5926                         stream_update.src = dm_new_crtc_state->stream->src;
5927                         stream_update.dst = dm_new_crtc_state->stream->dst;
5928                 }
5929
5930                 if (abm_changed) {
5931                         dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
5932
5933                         stream_update.abm_level = &dm_new_crtc_state->abm_level;
5934                 }
5935
5936                 if (hdr_changed) {
5937                         fill_hdr_info_packet(new_con_state, &hdr_packet);
5938                         stream_update.hdr_static_metadata = &hdr_packet;
5939                 }
5940
5941                 status = dc_stream_get_status(dm_new_crtc_state->stream);
5942                 WARN_ON(!status);
5943                 WARN_ON(!status->plane_count);
5944
5945                 /*
5946                  * TODO: DC refuses to perform stream updates without a dc_surface_update.
5947                  * Here we create an empty update on each plane.
5948                  * To fix this, DC should permit updating only stream properties.
5949                  */
5950                 for (j = 0; j < status->plane_count; j++)
5951                         dummy_updates[j].surface = status->plane_states[0];
5952
5953
5954                 mutex_lock(&dm->dc_lock);
5955                 dc_commit_updates_for_stream(dm->dc,
5956                                                      dummy_updates,
5957                                                      status->plane_count,
5958                                                      dm_new_crtc_state->stream,
5959                                                      &stream_update,
5960                                                      dc_state);
5961                 mutex_unlock(&dm->dc_lock);
5962         }
5963
5964         /* Count number of newly disabled CRTCs for dropping PM refs later. */
5965         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5966                                       new_crtc_state, i) {
5967                 if (old_crtc_state->active && !new_crtc_state->active)
5968                         crtc_disable_count++;
5969
5970                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5971                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5972
5973                 /* Update freesync active state. */
5974                 pre_update_freesync_state_on_stream(dm, dm_new_crtc_state);
5975
5976                 /* Handle vrr on->off / off->on transitions */
5977                 amdgpu_dm_handle_vrr_transition(dm_old_crtc_state,
5978                                                 dm_new_crtc_state);
5979         }
5980
5981         /* Enable interrupts for CRTCs going through a modeset. */
5982         amdgpu_dm_enable_crtc_interrupts(dev, state, true);
5983
5984         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
5985                 if (new_crtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC)
5986                         wait_for_vblank = false;
5987
5988         /* update planes when needed per crtc*/
5989         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
5990                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5991
5992                 if (dm_new_crtc_state->stream)
5993                         amdgpu_dm_commit_planes(state, dc_state, dev,
5994                                                 dm, crtc, wait_for_vblank);
5995         }
5996
5997         /* Enable interrupts for CRTCs going from 0 to n active planes. */
5998         amdgpu_dm_enable_crtc_interrupts(dev, state, false);
5999
6000         /*
6001          * send vblank event on all events not handled in flip and
6002          * mark consumed event for drm_atomic_helper_commit_hw_done
6003          */
6004         spin_lock_irqsave(&adev->ddev->event_lock, flags);
6005         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6006
6007                 if (new_crtc_state->event)
6008                         drm_send_event_locked(dev, &new_crtc_state->event->base);
6009
6010                 new_crtc_state->event = NULL;
6011         }
6012         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
6013
6014         /* Signal HW programming completion */
6015         drm_atomic_helper_commit_hw_done(state);
6016
6017         if (wait_for_vblank)
6018                 drm_atomic_helper_wait_for_flip_done(dev, state);
6019
6020         drm_atomic_helper_cleanup_planes(dev, state);
6021
6022         /*
6023          * Finally, drop a runtime PM reference for each newly disabled CRTC,
6024          * so we can put the GPU into runtime suspend if we're not driving any
6025          * displays anymore
6026          */
6027         for (i = 0; i < crtc_disable_count; i++)
6028                 pm_runtime_put_autosuspend(dev->dev);
6029         pm_runtime_mark_last_busy(dev->dev);
6030
6031         if (dc_state_temp)
6032                 dc_release_state(dc_state_temp);
6033 }
6034
6035
6036 static int dm_force_atomic_commit(struct drm_connector *connector)
6037 {
6038         int ret = 0;
6039         struct drm_device *ddev = connector->dev;
6040         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
6041         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6042         struct drm_plane *plane = disconnected_acrtc->base.primary;
6043         struct drm_connector_state *conn_state;
6044         struct drm_crtc_state *crtc_state;
6045         struct drm_plane_state *plane_state;
6046
6047         if (!state)
6048                 return -ENOMEM;
6049
6050         state->acquire_ctx = ddev->mode_config.acquire_ctx;
6051
6052         /* Construct an atomic state to restore previous display setting */
6053
6054         /*
6055          * Attach connectors to drm_atomic_state
6056          */
6057         conn_state = drm_atomic_get_connector_state(state, connector);
6058
6059         ret = PTR_ERR_OR_ZERO(conn_state);
6060         if (ret)
6061                 goto err;
6062
6063         /* Attach crtc to drm_atomic_state*/
6064         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
6065
6066         ret = PTR_ERR_OR_ZERO(crtc_state);
6067         if (ret)
6068                 goto err;
6069
6070         /* force a restore */
6071         crtc_state->mode_changed = true;
6072
6073         /* Attach plane to drm_atomic_state */
6074         plane_state = drm_atomic_get_plane_state(state, plane);
6075
6076         ret = PTR_ERR_OR_ZERO(plane_state);
6077         if (ret)
6078                 goto err;
6079
6080
6081         /* Call commit internally with the state we just constructed */
6082         ret = drm_atomic_commit(state);
6083         if (!ret)
6084                 return 0;
6085
6086 err:
6087         DRM_ERROR("Restoring old state failed with %i\n", ret);
6088         drm_atomic_state_put(state);
6089
6090         return ret;
6091 }
6092
6093 /*
6094  * This function handles all cases when set mode does not come upon hotplug.
6095  * This includes when a display is unplugged then plugged back into the
6096  * same port and when running without usermode desktop manager supprot
6097  */
6098 void dm_restore_drm_connector_state(struct drm_device *dev,
6099                                     struct drm_connector *connector)
6100 {
6101         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6102         struct amdgpu_crtc *disconnected_acrtc;
6103         struct dm_crtc_state *acrtc_state;
6104
6105         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
6106                 return;
6107
6108         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6109         if (!disconnected_acrtc)
6110                 return;
6111
6112         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
6113         if (!acrtc_state->stream)
6114                 return;
6115
6116         /*
6117          * If the previous sink is not released and different from the current,
6118          * we deduce we are in a state where we can not rely on usermode call
6119          * to turn on the display, so we do it here
6120          */
6121         if (acrtc_state->stream->sink != aconnector->dc_sink)
6122                 dm_force_atomic_commit(&aconnector->base);
6123 }
6124
6125 /*
6126  * Grabs all modesetting locks to serialize against any blocking commits,
6127  * Waits for completion of all non blocking commits.
6128  */
6129 static int do_aquire_global_lock(struct drm_device *dev,
6130                                  struct drm_atomic_state *state)
6131 {
6132         struct drm_crtc *crtc;
6133         struct drm_crtc_commit *commit;
6134         long ret;
6135
6136         /*
6137          * Adding all modeset locks to aquire_ctx will
6138          * ensure that when the framework release it the
6139          * extra locks we are locking here will get released to
6140          */
6141         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
6142         if (ret)
6143                 return ret;
6144
6145         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6146                 spin_lock(&crtc->commit_lock);
6147                 commit = list_first_entry_or_null(&crtc->commit_list,
6148                                 struct drm_crtc_commit, commit_entry);
6149                 if (commit)
6150                         drm_crtc_commit_get(commit);
6151                 spin_unlock(&crtc->commit_lock);
6152
6153                 if (!commit)
6154                         continue;
6155
6156                 /*
6157                  * Make sure all pending HW programming completed and
6158                  * page flips done
6159                  */
6160                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
6161
6162                 if (ret > 0)
6163                         ret = wait_for_completion_interruptible_timeout(
6164                                         &commit->flip_done, 10*HZ);
6165
6166                 if (ret == 0)
6167                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
6168                                   "timed out\n", crtc->base.id, crtc->name);
6169
6170                 drm_crtc_commit_put(commit);
6171         }
6172
6173         return ret < 0 ? ret : 0;
6174 }
6175
6176 static void get_freesync_config_for_crtc(
6177         struct dm_crtc_state *new_crtc_state,
6178         struct dm_connector_state *new_con_state)
6179 {
6180         struct mod_freesync_config config = {0};
6181         struct amdgpu_dm_connector *aconnector =
6182                         to_amdgpu_dm_connector(new_con_state->base.connector);
6183         struct drm_display_mode *mode = &new_crtc_state->base.mode;
6184         int vrefresh = drm_mode_vrefresh(mode);
6185
6186         new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
6187                                         vrefresh >= aconnector->min_vfreq &&
6188                                         vrefresh <= aconnector->max_vfreq;
6189
6190         if (new_crtc_state->vrr_supported) {
6191                 new_crtc_state->stream->ignore_msa_timing_param = true;
6192                 config.state = new_crtc_state->base.vrr_enabled ?
6193                                 VRR_STATE_ACTIVE_VARIABLE :
6194                                 VRR_STATE_INACTIVE;
6195                 config.min_refresh_in_uhz =
6196                                 aconnector->min_vfreq * 1000000;
6197                 config.max_refresh_in_uhz =
6198                                 aconnector->max_vfreq * 1000000;
6199                 config.vsif_supported = true;
6200                 config.btr = true;
6201         }
6202
6203         new_crtc_state->freesync_config = config;
6204 }
6205
6206 static void reset_freesync_config_for_crtc(
6207         struct dm_crtc_state *new_crtc_state)
6208 {
6209         new_crtc_state->vrr_supported = false;
6210
6211         memset(&new_crtc_state->vrr_params, 0,
6212                sizeof(new_crtc_state->vrr_params));
6213         memset(&new_crtc_state->vrr_infopacket, 0,
6214                sizeof(new_crtc_state->vrr_infopacket));
6215 }
6216
6217 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
6218                                 struct drm_atomic_state *state,
6219                                 struct drm_crtc *crtc,
6220                                 struct drm_crtc_state *old_crtc_state,
6221                                 struct drm_crtc_state *new_crtc_state,
6222                                 bool enable,
6223                                 bool *lock_and_validation_needed)
6224 {
6225         struct dm_atomic_state *dm_state = NULL;
6226         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6227         struct dc_stream_state *new_stream;
6228         int ret = 0;
6229
6230         /*
6231          * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
6232          * update changed items
6233          */
6234         struct amdgpu_crtc *acrtc = NULL;
6235         struct amdgpu_dm_connector *aconnector = NULL;
6236         struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
6237         struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
6238
6239         new_stream = NULL;
6240
6241         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6242         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6243         acrtc = to_amdgpu_crtc(crtc);
6244         aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
6245
6246         /* TODO This hack should go away */
6247         if (aconnector && enable) {
6248                 /* Make sure fake sink is created in plug-in scenario */
6249                 drm_new_conn_state = drm_atomic_get_new_connector_state(state,
6250                                                             &aconnector->base);
6251                 drm_old_conn_state = drm_atomic_get_old_connector_state(state,
6252                                                             &aconnector->base);
6253
6254                 if (IS_ERR(drm_new_conn_state)) {
6255                         ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
6256                         goto fail;
6257                 }
6258
6259                 dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
6260                 dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
6261
6262                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6263                         goto skip_modeset;
6264
6265                 new_stream = create_stream_for_sink(aconnector,
6266                                                      &new_crtc_state->mode,
6267                                                     dm_new_conn_state,
6268                                                     dm_old_crtc_state->stream);
6269
6270                 /*
6271                  * we can have no stream on ACTION_SET if a display
6272                  * was disconnected during S3, in this case it is not an
6273                  * error, the OS will be updated after detection, and
6274                  * will do the right thing on next atomic commit
6275                  */
6276
6277                 if (!new_stream) {
6278                         DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6279                                         __func__, acrtc->base.base.id);
6280                         ret = -ENOMEM;
6281                         goto fail;
6282                 }
6283
6284                 dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6285
6286                 ret = fill_hdr_info_packet(drm_new_conn_state,
6287                                            &new_stream->hdr_static_metadata);
6288                 if (ret)
6289                         goto fail;
6290
6291                 if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
6292                     dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
6293                         new_crtc_state->mode_changed = false;
6294                         DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
6295                                          new_crtc_state->mode_changed);
6296                 }
6297         }
6298
6299         /* mode_changed flag may get updated above, need to check again */
6300         if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6301                 goto skip_modeset;
6302
6303         DRM_DEBUG_DRIVER(
6304                 "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6305                 "planes_changed:%d, mode_changed:%d,active_changed:%d,"
6306                 "connectors_changed:%d\n",
6307                 acrtc->crtc_id,
6308                 new_crtc_state->enable,
6309                 new_crtc_state->active,
6310                 new_crtc_state->planes_changed,
6311                 new_crtc_state->mode_changed,
6312                 new_crtc_state->active_changed,
6313                 new_crtc_state->connectors_changed);
6314
6315         /* Remove stream for any changed/disabled CRTC */
6316         if (!enable) {
6317
6318                 if (!dm_old_crtc_state->stream)
6319                         goto skip_modeset;
6320
6321                 ret = dm_atomic_get_state(state, &dm_state);
6322                 if (ret)
6323                         goto fail;
6324
6325                 DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
6326                                 crtc->base.id);
6327
6328                 /* i.e. reset mode */
6329                 if (dc_remove_stream_from_ctx(
6330                                 dm->dc,
6331                                 dm_state->context,
6332                                 dm_old_crtc_state->stream) != DC_OK) {
6333                         ret = -EINVAL;
6334                         goto fail;
6335                 }
6336
6337                 dc_stream_release(dm_old_crtc_state->stream);
6338                 dm_new_crtc_state->stream = NULL;
6339
6340                 reset_freesync_config_for_crtc(dm_new_crtc_state);
6341
6342                 *lock_and_validation_needed = true;
6343
6344         } else {/* Add stream for any updated/enabled CRTC */
6345                 /*
6346                  * Quick fix to prevent NULL pointer on new_stream when
6347                  * added MST connectors not found in existing crtc_state in the chained mode
6348                  * TODO: need to dig out the root cause of that
6349                  */
6350                 if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
6351                         goto skip_modeset;
6352
6353                 if (modereset_required(new_crtc_state))
6354                         goto skip_modeset;
6355
6356                 if (modeset_required(new_crtc_state, new_stream,
6357                                      dm_old_crtc_state->stream)) {
6358
6359                         WARN_ON(dm_new_crtc_state->stream);
6360
6361                         ret = dm_atomic_get_state(state, &dm_state);
6362                         if (ret)
6363                                 goto fail;
6364
6365                         dm_new_crtc_state->stream = new_stream;
6366
6367                         dc_stream_retain(new_stream);
6368
6369                         DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
6370                                                 crtc->base.id);
6371
6372                         if (dc_add_stream_to_ctx(
6373                                         dm->dc,
6374                                         dm_state->context,
6375                                         dm_new_crtc_state->stream) != DC_OK) {
6376                                 ret = -EINVAL;
6377                                 goto fail;
6378                         }
6379
6380                         *lock_and_validation_needed = true;
6381                 }
6382         }
6383
6384 skip_modeset:
6385         /* Release extra reference */
6386         if (new_stream)
6387                  dc_stream_release(new_stream);
6388
6389         /*
6390          * We want to do dc stream updates that do not require a
6391          * full modeset below.
6392          */
6393         if (!(enable && aconnector && new_crtc_state->enable &&
6394               new_crtc_state->active))
6395                 return 0;
6396         /*
6397          * Given above conditions, the dc state cannot be NULL because:
6398          * 1. We're in the process of enabling CRTCs (just been added
6399          *    to the dc context, or already is on the context)
6400          * 2. Has a valid connector attached, and
6401          * 3. Is currently active and enabled.
6402          * => The dc stream state currently exists.
6403          */
6404         BUG_ON(dm_new_crtc_state->stream == NULL);
6405
6406         /* Scaling or underscan settings */
6407         if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
6408                 update_stream_scaling_settings(
6409                         &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
6410
6411         /* ABM settings */
6412         dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6413
6414         /*
6415          * Color management settings. We also update color properties
6416          * when a modeset is needed, to ensure it gets reprogrammed.
6417          */
6418         if (dm_new_crtc_state->base.color_mgmt_changed ||
6419             drm_atomic_crtc_needs_modeset(new_crtc_state)) {
6420                 ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
6421                 if (ret)
6422                         goto fail;
6423                 amdgpu_dm_set_ctm(dm_new_crtc_state);
6424         }
6425
6426         /* Update Freesync settings. */
6427         get_freesync_config_for_crtc(dm_new_crtc_state,
6428                                      dm_new_conn_state);
6429
6430         return ret;
6431
6432 fail:
6433         if (new_stream)
6434                 dc_stream_release(new_stream);
6435         return ret;
6436 }
6437
6438 static bool should_reset_plane(struct drm_atomic_state *state,
6439                                struct drm_plane *plane,
6440                                struct drm_plane_state *old_plane_state,
6441                                struct drm_plane_state *new_plane_state)
6442 {
6443         struct drm_plane *other;
6444         struct drm_plane_state *old_other_state, *new_other_state;
6445         struct drm_crtc_state *new_crtc_state;
6446         int i;
6447
6448         /*
6449          * TODO: Remove this hack once the checks below are sufficient
6450          * enough to determine when we need to reset all the planes on
6451          * the stream.
6452          */
6453         if (state->allow_modeset)
6454                 return true;
6455
6456         /* Exit early if we know that we're adding or removing the plane. */
6457         if (old_plane_state->crtc != new_plane_state->crtc)
6458                 return true;
6459
6460         /* old crtc == new_crtc == NULL, plane not in context. */
6461         if (!new_plane_state->crtc)
6462                 return false;
6463
6464         new_crtc_state =
6465                 drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
6466
6467         if (!new_crtc_state)
6468                 return true;
6469
6470         if (drm_atomic_crtc_needs_modeset(new_crtc_state))
6471                 return true;
6472
6473         /*
6474          * If there are any new primary or overlay planes being added or
6475          * removed then the z-order can potentially change. To ensure
6476          * correct z-order and pipe acquisition the current DC architecture
6477          * requires us to remove and recreate all existing planes.
6478          *
6479          * TODO: Come up with a more elegant solution for this.
6480          */
6481         for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
6482                 if (other->type == DRM_PLANE_TYPE_CURSOR)
6483                         continue;
6484
6485                 if (old_other_state->crtc != new_plane_state->crtc &&
6486                     new_other_state->crtc != new_plane_state->crtc)
6487                         continue;
6488
6489                 if (old_other_state->crtc != new_other_state->crtc)
6490                         return true;
6491
6492                 /* TODO: Remove this once we can handle fast format changes. */
6493                 if (old_other_state->fb && new_other_state->fb &&
6494                     old_other_state->fb->format != new_other_state->fb->format)
6495                         return true;
6496         }
6497
6498         return false;
6499 }
6500
6501 static int dm_update_plane_state(struct dc *dc,
6502                                  struct drm_atomic_state *state,
6503                                  struct drm_plane *plane,
6504                                  struct drm_plane_state *old_plane_state,
6505                                  struct drm_plane_state *new_plane_state,
6506                                  bool enable,
6507                                  bool *lock_and_validation_needed)
6508 {
6509
6510         struct dm_atomic_state *dm_state = NULL;
6511         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6512         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6513         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
6514         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
6515         bool needs_reset;
6516         int ret = 0;
6517
6518
6519         new_plane_crtc = new_plane_state->crtc;
6520         old_plane_crtc = old_plane_state->crtc;
6521         dm_new_plane_state = to_dm_plane_state(new_plane_state);
6522         dm_old_plane_state = to_dm_plane_state(old_plane_state);
6523
6524         /*TODO Implement atomic check for cursor plane */
6525         if (plane->type == DRM_PLANE_TYPE_CURSOR)
6526                 return 0;
6527
6528         needs_reset = should_reset_plane(state, plane, old_plane_state,
6529                                          new_plane_state);
6530
6531         /* Remove any changed/removed planes */
6532         if (!enable) {
6533                 if (!needs_reset)
6534                         return 0;
6535
6536                 if (!old_plane_crtc)
6537                         return 0;
6538
6539                 old_crtc_state = drm_atomic_get_old_crtc_state(
6540                                 state, old_plane_crtc);
6541                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6542
6543                 if (!dm_old_crtc_state->stream)
6544                         return 0;
6545
6546                 DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
6547                                 plane->base.id, old_plane_crtc->base.id);
6548
6549                 ret = dm_atomic_get_state(state, &dm_state);
6550                 if (ret)
6551                         return ret;
6552
6553                 if (!dc_remove_plane_from_context(
6554                                 dc,
6555                                 dm_old_crtc_state->stream,
6556                                 dm_old_plane_state->dc_state,
6557                                 dm_state->context)) {
6558
6559                         ret = EINVAL;
6560                         return ret;
6561                 }
6562
6563
6564                 dc_plane_state_release(dm_old_plane_state->dc_state);
6565                 dm_new_plane_state->dc_state = NULL;
6566
6567                 *lock_and_validation_needed = true;
6568
6569         } else { /* Add new planes */
6570                 struct dc_plane_state *dc_new_plane_state;
6571
6572                 if (drm_atomic_plane_disabling(plane->state, new_plane_state))
6573                         return 0;
6574
6575                 if (!new_plane_crtc)
6576                         return 0;
6577
6578                 new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
6579                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6580
6581                 if (!dm_new_crtc_state->stream)
6582                         return 0;
6583
6584                 if (!needs_reset)
6585                         return 0;
6586
6587                 WARN_ON(dm_new_plane_state->dc_state);
6588
6589                 dc_new_plane_state = dc_create_plane_state(dc);
6590                 if (!dc_new_plane_state)
6591                         return -ENOMEM;
6592
6593                 DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
6594                                 plane->base.id, new_plane_crtc->base.id);
6595
6596                 ret = fill_dc_plane_attributes(
6597                         new_plane_crtc->dev->dev_private,
6598                         dc_new_plane_state,
6599                         new_plane_state,
6600                         new_crtc_state);
6601                 if (ret) {
6602                         dc_plane_state_release(dc_new_plane_state);
6603                         return ret;
6604                 }
6605
6606                 ret = dm_atomic_get_state(state, &dm_state);
6607                 if (ret) {
6608                         dc_plane_state_release(dc_new_plane_state);
6609                         return ret;
6610                 }
6611
6612                 /*
6613                  * Any atomic check errors that occur after this will
6614                  * not need a release. The plane state will be attached
6615                  * to the stream, and therefore part of the atomic
6616                  * state. It'll be released when the atomic state is
6617                  * cleaned.
6618                  */
6619                 if (!dc_add_plane_to_context(
6620                                 dc,
6621                                 dm_new_crtc_state->stream,
6622                                 dc_new_plane_state,
6623                                 dm_state->context)) {
6624
6625                         dc_plane_state_release(dc_new_plane_state);
6626                         return -EINVAL;
6627                 }
6628
6629                 dm_new_plane_state->dc_state = dc_new_plane_state;
6630
6631                 /* Tell DC to do a full surface update every time there
6632                  * is a plane change. Inefficient, but works for now.
6633                  */
6634                 dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
6635
6636                 *lock_and_validation_needed = true;
6637         }
6638
6639
6640         return ret;
6641 }
6642
6643 static int
6644 dm_determine_update_type_for_commit(struct amdgpu_display_manager *dm,
6645                                     struct drm_atomic_state *state,
6646                                     enum surface_update_type *out_type)
6647 {
6648         struct dc *dc = dm->dc;
6649         struct dm_atomic_state *dm_state = NULL, *old_dm_state = NULL;
6650         int i, j, num_plane, ret = 0;
6651         struct drm_plane_state *old_plane_state, *new_plane_state;
6652         struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
6653         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6654         struct drm_plane *plane;
6655
6656         struct drm_crtc *crtc;
6657         struct drm_crtc_state *new_crtc_state, *old_crtc_state;
6658         struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
6659         struct dc_stream_status *status = NULL;
6660
6661         struct dc_surface_update *updates;
6662         enum surface_update_type update_type = UPDATE_TYPE_FAST;
6663
6664         updates = kcalloc(MAX_SURFACES, sizeof(*updates), GFP_KERNEL);
6665
6666         if (!updates) {
6667                 DRM_ERROR("Failed to allocate plane updates\n");
6668                 /* Set type to FULL to avoid crashing in DC*/
6669                 update_type = UPDATE_TYPE_FULL;
6670                 goto cleanup;
6671         }
6672
6673         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6674                 struct dc_scaling_info scaling_info;
6675                 struct dc_stream_update stream_update;
6676
6677                 memset(&stream_update, 0, sizeof(stream_update));
6678
6679                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
6680                 old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
6681                 num_plane = 0;
6682
6683                 if (new_dm_crtc_state->stream != old_dm_crtc_state->stream) {
6684                         update_type = UPDATE_TYPE_FULL;
6685                         goto cleanup;
6686                 }
6687
6688                 if (!new_dm_crtc_state->stream)
6689                         continue;
6690
6691                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
6692                         new_plane_crtc = new_plane_state->crtc;
6693                         old_plane_crtc = old_plane_state->crtc;
6694                         new_dm_plane_state = to_dm_plane_state(new_plane_state);
6695                         old_dm_plane_state = to_dm_plane_state(old_plane_state);
6696
6697                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
6698                                 continue;
6699
6700                         if (new_dm_plane_state->dc_state != old_dm_plane_state->dc_state) {
6701                                 update_type = UPDATE_TYPE_FULL;
6702                                 goto cleanup;
6703                         }
6704
6705                         if (crtc != new_plane_crtc)
6706                                 continue;
6707
6708                         updates[num_plane].surface = new_dm_plane_state->dc_state;
6709
6710                         if (new_crtc_state->mode_changed) {
6711                                 stream_update.dst = new_dm_crtc_state->stream->dst;
6712                                 stream_update.src = new_dm_crtc_state->stream->src;
6713                         }
6714
6715                         if (new_crtc_state->color_mgmt_changed) {
6716                                 updates[num_plane].gamma =
6717                                                 new_dm_plane_state->dc_state->gamma_correction;
6718                                 updates[num_plane].in_transfer_func =
6719                                                 new_dm_plane_state->dc_state->in_transfer_func;
6720                                 stream_update.gamut_remap =
6721                                                 &new_dm_crtc_state->stream->gamut_remap_matrix;
6722                                 stream_update.out_transfer_func =
6723                                                 new_dm_crtc_state->stream->out_transfer_func;
6724                         }
6725
6726                         ret = fill_dc_scaling_info(new_plane_state,
6727                                                    &scaling_info);
6728                         if (ret)
6729                                 goto cleanup;
6730
6731                         updates[num_plane].scaling_info = &scaling_info;
6732
6733                         num_plane++;
6734                 }
6735
6736                 if (num_plane == 0)
6737                         continue;
6738
6739                 ret = dm_atomic_get_state(state, &dm_state);
6740                 if (ret)
6741                         goto cleanup;
6742
6743                 old_dm_state = dm_atomic_get_old_state(state);
6744                 if (!old_dm_state) {
6745                         ret = -EINVAL;
6746                         goto cleanup;
6747                 }
6748
6749                 status = dc_stream_get_status_from_state(old_dm_state->context,
6750                                                          new_dm_crtc_state->stream);
6751
6752                 /*
6753                  * TODO: DC modifies the surface during this call so we need
6754                  * to lock here - find a way to do this without locking.
6755                  */
6756                 mutex_lock(&dm->dc_lock);
6757                 update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
6758                                                                   &stream_update, status);
6759                 mutex_unlock(&dm->dc_lock);
6760
6761                 if (update_type > UPDATE_TYPE_MED) {
6762                         update_type = UPDATE_TYPE_FULL;
6763                         goto cleanup;
6764                 }
6765         }
6766
6767 cleanup:
6768         kfree(updates);
6769
6770         *out_type = update_type;
6771         return ret;
6772 }
6773
6774 /**
6775  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
6776  * @dev: The DRM device
6777  * @state: The atomic state to commit
6778  *
6779  * Validate that the given atomic state is programmable by DC into hardware.
6780  * This involves constructing a &struct dc_state reflecting the new hardware
6781  * state we wish to commit, then querying DC to see if it is programmable. It's
6782  * important not to modify the existing DC state. Otherwise, atomic_check
6783  * may unexpectedly commit hardware changes.
6784  *
6785  * When validating the DC state, it's important that the right locks are
6786  * acquired. For full updates case which removes/adds/updates streams on one
6787  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
6788  * that any such full update commit will wait for completion of any outstanding
6789  * flip using DRMs synchronization events. See
6790  * dm_determine_update_type_for_commit()
6791  *
6792  * Note that DM adds the affected connectors for all CRTCs in state, when that
6793  * might not seem necessary. This is because DC stream creation requires the
6794  * DC sink, which is tied to the DRM connector state. Cleaning this up should
6795  * be possible but non-trivial - a possible TODO item.
6796  *
6797  * Return: -Error code if validation failed.
6798  */
6799 static int amdgpu_dm_atomic_check(struct drm_device *dev,
6800                                   struct drm_atomic_state *state)
6801 {
6802         struct amdgpu_device *adev = dev->dev_private;
6803         struct dm_atomic_state *dm_state = NULL;
6804         struct dc *dc = adev->dm.dc;
6805         struct drm_connector *connector;
6806         struct drm_connector_state *old_con_state, *new_con_state;
6807         struct drm_crtc *crtc;
6808         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6809         struct drm_plane *plane;
6810         struct drm_plane_state *old_plane_state, *new_plane_state;
6811         enum surface_update_type update_type = UPDATE_TYPE_FAST;
6812         enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
6813
6814         int ret, i;
6815
6816         /*
6817          * This bool will be set for true for any modeset/reset
6818          * or plane update which implies non fast surface update.
6819          */
6820         bool lock_and_validation_needed = false;
6821
6822         ret = drm_atomic_helper_check_modeset(dev, state);
6823         if (ret)
6824                 goto fail;
6825
6826         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6827                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
6828                     !new_crtc_state->color_mgmt_changed &&
6829                     old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled)
6830                         continue;
6831
6832                 if (!new_crtc_state->enable)
6833                         continue;
6834
6835                 ret = drm_atomic_add_affected_connectors(state, crtc);
6836                 if (ret)
6837                         return ret;
6838
6839                 ret = drm_atomic_add_affected_planes(state, crtc);
6840                 if (ret)
6841                         goto fail;
6842         }
6843
6844         /*
6845          * Add all primary and overlay planes on the CRTC to the state
6846          * whenever a plane is enabled to maintain correct z-ordering
6847          * and to enable fast surface updates.
6848          */
6849         drm_for_each_crtc(crtc, dev) {
6850                 bool modified = false;
6851
6852                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
6853                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
6854                                 continue;
6855
6856                         if (new_plane_state->crtc == crtc ||
6857                             old_plane_state->crtc == crtc) {
6858                                 modified = true;
6859                                 break;
6860                         }
6861                 }
6862
6863                 if (!modified)
6864                         continue;
6865
6866                 drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
6867                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
6868                                 continue;
6869
6870                         new_plane_state =
6871                                 drm_atomic_get_plane_state(state, plane);
6872
6873                         if (IS_ERR(new_plane_state)) {
6874                                 ret = PTR_ERR(new_plane_state);
6875                                 goto fail;
6876                         }
6877                 }
6878         }
6879
6880         /* Remove exiting planes if they are modified */
6881         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
6882                 ret = dm_update_plane_state(dc, state, plane,
6883                                             old_plane_state,
6884                                             new_plane_state,
6885                                             false,
6886                                             &lock_and_validation_needed);
6887                 if (ret)
6888                         goto fail;
6889         }
6890
6891         /* Disable all crtcs which require disable */
6892         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6893                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
6894                                            old_crtc_state,
6895                                            new_crtc_state,
6896                                            false,
6897                                            &lock_and_validation_needed);
6898                 if (ret)
6899                         goto fail;
6900         }
6901
6902         /* Enable all crtcs which require enable */
6903         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6904                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
6905                                            old_crtc_state,
6906                                            new_crtc_state,
6907                                            true,
6908                                            &lock_and_validation_needed);
6909                 if (ret)
6910                         goto fail;
6911         }
6912
6913         /* Add new/modified planes */
6914         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
6915                 ret = dm_update_plane_state(dc, state, plane,
6916                                             old_plane_state,
6917                                             new_plane_state,
6918                                             true,
6919                                             &lock_and_validation_needed);
6920                 if (ret)
6921                         goto fail;
6922         }
6923
6924         /* Run this here since we want to validate the streams we created */
6925         ret = drm_atomic_helper_check_planes(dev, state);
6926         if (ret)
6927                 goto fail;
6928
6929         /* Check scaling and underscan changes*/
6930         /* TODO Removed scaling changes validation due to inability to commit
6931          * new stream into context w\o causing full reset. Need to
6932          * decide how to handle.
6933          */
6934         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6935                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6936                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6937                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6938
6939                 /* Skip any modesets/resets */
6940                 if (!acrtc || drm_atomic_crtc_needs_modeset(
6941                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
6942                         continue;
6943
6944                 /* Skip any thing not scale or underscan changes */
6945                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
6946                         continue;
6947
6948                 overall_update_type = UPDATE_TYPE_FULL;
6949                 lock_and_validation_needed = true;
6950         }
6951
6952         ret = dm_determine_update_type_for_commit(&adev->dm, state, &update_type);
6953         if (ret)
6954                 goto fail;
6955
6956         if (overall_update_type < update_type)
6957                 overall_update_type = update_type;
6958
6959         /*
6960          * lock_and_validation_needed was an old way to determine if we need to set
6961          * the global lock. Leaving it in to check if we broke any corner cases
6962          * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
6963          * lock_and_validation_needed false = UPDATE_TYPE_FAST
6964          */
6965         if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
6966                 WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
6967
6968         if (overall_update_type > UPDATE_TYPE_FAST) {
6969                 ret = dm_atomic_get_state(state, &dm_state);
6970                 if (ret)
6971                         goto fail;
6972
6973                 ret = do_aquire_global_lock(dev, state);
6974                 if (ret)
6975                         goto fail;
6976
6977                 if (dc_validate_global_state(dc, dm_state->context, false) != DC_OK) {
6978                         ret = -EINVAL;
6979                         goto fail;
6980                 }
6981         } else if (state->legacy_cursor_update) {
6982                 /*
6983                  * This is a fast cursor update coming from the plane update
6984                  * helper, check if it can be done asynchronously for better
6985                  * performance.
6986                  */
6987                 state->async_update = !drm_atomic_helper_async_check(dev, state);
6988         }
6989
6990         /* Must be success */
6991         WARN_ON(ret);
6992         return ret;
6993
6994 fail:
6995         if (ret == -EDEADLK)
6996                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
6997         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
6998                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
6999         else
7000                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
7001
7002         return ret;
7003 }
7004
7005 static bool is_dp_capable_without_timing_msa(struct dc *dc,
7006                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
7007 {
7008         uint8_t dpcd_data;
7009         bool capable = false;
7010
7011         if (amdgpu_dm_connector->dc_link &&
7012                 dm_helpers_dp_read_dpcd(
7013                                 NULL,
7014                                 amdgpu_dm_connector->dc_link,
7015                                 DP_DOWN_STREAM_PORT_COUNT,
7016                                 &dpcd_data,
7017                                 sizeof(dpcd_data))) {
7018                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
7019         }
7020
7021         return capable;
7022 }
7023 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
7024                                         struct edid *edid)
7025 {
7026         int i;
7027         bool edid_check_required;
7028         struct detailed_timing *timing;
7029         struct detailed_non_pixel *data;
7030         struct detailed_data_monitor_range *range;
7031         struct amdgpu_dm_connector *amdgpu_dm_connector =
7032                         to_amdgpu_dm_connector(connector);
7033         struct dm_connector_state *dm_con_state = NULL;
7034
7035         struct drm_device *dev = connector->dev;
7036         struct amdgpu_device *adev = dev->dev_private;
7037         bool freesync_capable = false;
7038
7039         if (!connector->state) {
7040                 DRM_ERROR("%s - Connector has no state", __func__);
7041                 goto update;
7042         }
7043
7044         if (!edid) {
7045                 dm_con_state = to_dm_connector_state(connector->state);
7046
7047                 amdgpu_dm_connector->min_vfreq = 0;
7048                 amdgpu_dm_connector->max_vfreq = 0;
7049                 amdgpu_dm_connector->pixel_clock_mhz = 0;
7050
7051                 goto update;
7052         }
7053
7054         dm_con_state = to_dm_connector_state(connector->state);
7055
7056         edid_check_required = false;
7057         if (!amdgpu_dm_connector->dc_sink) {
7058                 DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
7059                 goto update;
7060         }
7061         if (!adev->dm.freesync_module)
7062                 goto update;
7063         /*
7064          * if edid non zero restrict freesync only for dp and edp
7065          */
7066         if (edid) {
7067                 if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
7068                         || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
7069                         edid_check_required = is_dp_capable_without_timing_msa(
7070                                                 adev->dm.dc,
7071                                                 amdgpu_dm_connector);
7072                 }
7073         }
7074         if (edid_check_required == true && (edid->version > 1 ||
7075            (edid->version == 1 && edid->revision > 1))) {
7076                 for (i = 0; i < 4; i++) {
7077
7078                         timing  = &edid->detailed_timings[i];
7079                         data    = &timing->data.other_data;
7080                         range   = &data->data.range;
7081                         /*
7082                          * Check if monitor has continuous frequency mode
7083                          */
7084                         if (data->type != EDID_DETAIL_MONITOR_RANGE)
7085                                 continue;
7086                         /*
7087                          * Check for flag range limits only. If flag == 1 then
7088                          * no additional timing information provided.
7089                          * Default GTF, GTF Secondary curve and CVT are not
7090                          * supported
7091                          */
7092                         if (range->flags != 1)
7093                                 continue;
7094
7095                         amdgpu_dm_connector->min_vfreq = range->min_vfreq;
7096                         amdgpu_dm_connector->max_vfreq = range->max_vfreq;
7097                         amdgpu_dm_connector->pixel_clock_mhz =
7098                                 range->pixel_clock_mhz * 10;
7099                         break;
7100                 }
7101
7102                 if (amdgpu_dm_connector->max_vfreq -
7103                     amdgpu_dm_connector->min_vfreq > 10) {
7104
7105                         freesync_capable = true;
7106                 }
7107         }
7108
7109 update:
7110         if (dm_con_state)
7111                 dm_con_state->freesync_capable = freesync_capable;
7112
7113         if (connector->vrr_capable_property)
7114                 drm_connector_set_vrr_capable_property(connector,
7115                                                        freesync_capable);
7116 }
7117
This page took 0.474708 seconds and 4 git commands to generate.