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