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