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