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