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