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