Merge tag 'amd-drm-next-6.3-2023-01-20' of https://gitlab.freedesktop.org/agd5f/linux...
[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_link_dp.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "amdgpu_dm_trace.h"
42
43 #include "vid.h"
44 #include "amdgpu.h"
45 #include "amdgpu_display.h"
46 #include "amdgpu_ucode.h"
47 #include "atom.h"
48 #include "amdgpu_dm.h"
49 #include "amdgpu_dm_plane.h"
50 #include "amdgpu_dm_crtc.h"
51 #ifdef CONFIG_DRM_AMD_DC_HDCP
52 #include "amdgpu_dm_hdcp.h"
53 #include <drm/display/drm_hdcp_helper.h>
54 #endif
55 #include "amdgpu_pm.h"
56 #include "amdgpu_atombios.h"
57
58 #include "amd_shared.h"
59 #include "amdgpu_dm_irq.h"
60 #include "dm_helpers.h"
61 #include "amdgpu_dm_mst_types.h"
62 #if defined(CONFIG_DEBUG_FS)
63 #include "amdgpu_dm_debugfs.h"
64 #endif
65 #include "amdgpu_dm_psr.h"
66
67 #include "ivsrcid/ivsrcid_vislands30.h"
68
69 #include <linux/backlight.h>
70 #include <linux/module.h>
71 #include <linux/moduleparam.h>
72 #include <linux/types.h>
73 #include <linux/pm_runtime.h>
74 #include <linux/pci.h>
75 #include <linux/firmware.h>
76 #include <linux/component.h>
77 #include <linux/dmi.h>
78
79 #include <drm/display/drm_dp_mst_helper.h>
80 #include <drm/display/drm_hdmi_helper.h>
81 #include <drm/drm_atomic.h>
82 #include <drm/drm_atomic_uapi.h>
83 #include <drm/drm_atomic_helper.h>
84 #include <drm/drm_blend.h>
85 #include <drm/drm_fourcc.h>
86 #include <drm/drm_edid.h>
87 #include <drm/drm_vblank.h>
88 #include <drm/drm_audio_component.h>
89 #include <drm/drm_gem_atomic_helper.h>
90 #include <drm/drm_plane_helper.h>
91
92 #include <acpi/video.h>
93
94 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
95
96 #include "dcn/dcn_1_0_offset.h"
97 #include "dcn/dcn_1_0_sh_mask.h"
98 #include "soc15_hw_ip.h"
99 #include "soc15_common.h"
100 #include "vega10_ip_offset.h"
101
102 #include "gc/gc_11_0_0_offset.h"
103 #include "gc/gc_11_0_0_sh_mask.h"
104
105 #include "modules/inc/mod_freesync.h"
106 #include "modules/power/power_helpers.h"
107 #include "modules/inc/mod_info_packet.h"
108
109 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
110 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
111 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
112 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
113 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
114 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
115 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
116 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
117 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
118 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
119 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
120 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
121 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
122 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
123 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
124 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
125 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
126 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
127 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
128 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
129 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
130 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
131
132 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
134 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
135 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
136
137 #define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
138 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
139
140 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
142
143 /* Number of bytes in PSP header for firmware. */
144 #define PSP_HEADER_BYTES 0x100
145
146 /* Number of bytes in PSP footer for firmware. */
147 #define PSP_FOOTER_BYTES 0x100
148
149 /**
150  * DOC: overview
151  *
152  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
153  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
154  * requests into DC requests, and DC responses into DRM responses.
155  *
156  * The root control structure is &struct amdgpu_display_manager.
157  */
158
159 /* basic init/fini API */
160 static int amdgpu_dm_init(struct amdgpu_device *adev);
161 static void amdgpu_dm_fini(struct amdgpu_device *adev);
162 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
163
164 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
165 {
166         switch (link->dpcd_caps.dongle_type) {
167         case DISPLAY_DONGLE_NONE:
168                 return DRM_MODE_SUBCONNECTOR_Native;
169         case DISPLAY_DONGLE_DP_VGA_CONVERTER:
170                 return DRM_MODE_SUBCONNECTOR_VGA;
171         case DISPLAY_DONGLE_DP_DVI_CONVERTER:
172         case DISPLAY_DONGLE_DP_DVI_DONGLE:
173                 return DRM_MODE_SUBCONNECTOR_DVID;
174         case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
175         case DISPLAY_DONGLE_DP_HDMI_DONGLE:
176                 return DRM_MODE_SUBCONNECTOR_HDMIA;
177         case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
178         default:
179                 return DRM_MODE_SUBCONNECTOR_Unknown;
180         }
181 }
182
183 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
184 {
185         struct dc_link *link = aconnector->dc_link;
186         struct drm_connector *connector = &aconnector->base;
187         enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
188
189         if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
190                 return;
191
192         if (aconnector->dc_sink)
193                 subconnector = get_subconnector_type(link);
194
195         drm_object_property_set_value(&connector->base,
196                         connector->dev->mode_config.dp_subconnector_property,
197                         subconnector);
198 }
199
200 /*
201  * initializes drm_device display related structures, based on the information
202  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
203  * drm_encoder, drm_mode_config
204  *
205  * Returns 0 on success
206  */
207 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
208 /* removes and deallocates the drm structures, created by the above function */
209 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
210
211 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
212                                     struct amdgpu_dm_connector *amdgpu_dm_connector,
213                                     u32 link_index,
214                                     struct amdgpu_encoder *amdgpu_encoder);
215 static int amdgpu_dm_encoder_init(struct drm_device *dev,
216                                   struct amdgpu_encoder *aencoder,
217                                   uint32_t link_index);
218
219 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
220
221 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
222
223 static int amdgpu_dm_atomic_check(struct drm_device *dev,
224                                   struct drm_atomic_state *state);
225
226 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
227 static void handle_hpd_rx_irq(void *param);
228
229 static bool
230 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
231                                  struct drm_crtc_state *new_crtc_state);
232 /*
233  * dm_vblank_get_counter
234  *
235  * @brief
236  * Get counter for number of vertical blanks
237  *
238  * @param
239  * struct amdgpu_device *adev - [in] desired amdgpu device
240  * int disp_idx - [in] which CRTC to get the counter from
241  *
242  * @return
243  * Counter for vertical blanks
244  */
245 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
246 {
247         if (crtc >= adev->mode_info.num_crtc)
248                 return 0;
249         else {
250                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
251
252                 if (acrtc->dm_irq_params.stream == NULL) {
253                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
254                                   crtc);
255                         return 0;
256                 }
257
258                 return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
259         }
260 }
261
262 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
263                                   u32 *vbl, u32 *position)
264 {
265         u32 v_blank_start, v_blank_end, h_position, v_position;
266
267         if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
268                 return -EINVAL;
269         else {
270                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
271
272                 if (acrtc->dm_irq_params.stream ==  NULL) {
273                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
274                                   crtc);
275                         return 0;
276                 }
277
278                 /*
279                  * TODO rework base driver to use values directly.
280                  * for now parse it back into reg-format
281                  */
282                 dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
283                                          &v_blank_start,
284                                          &v_blank_end,
285                                          &h_position,
286                                          &v_position);
287
288                 *position = v_position | (h_position << 16);
289                 *vbl = v_blank_start | (v_blank_end << 16);
290         }
291
292         return 0;
293 }
294
295 static bool dm_is_idle(void *handle)
296 {
297         /* XXX todo */
298         return true;
299 }
300
301 static int dm_wait_for_idle(void *handle)
302 {
303         /* XXX todo */
304         return 0;
305 }
306
307 static bool dm_check_soft_reset(void *handle)
308 {
309         return false;
310 }
311
312 static int dm_soft_reset(void *handle)
313 {
314         /* XXX todo */
315         return 0;
316 }
317
318 static struct amdgpu_crtc *
319 get_crtc_by_otg_inst(struct amdgpu_device *adev,
320                      int otg_inst)
321 {
322         struct drm_device *dev = adev_to_drm(adev);
323         struct drm_crtc *crtc;
324         struct amdgpu_crtc *amdgpu_crtc;
325
326         if (WARN_ON(otg_inst == -1))
327                 return adev->mode_info.crtcs[0];
328
329         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
330                 amdgpu_crtc = to_amdgpu_crtc(crtc);
331
332                 if (amdgpu_crtc->otg_inst == otg_inst)
333                         return amdgpu_crtc;
334         }
335
336         return NULL;
337 }
338
339 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
340                                               struct dm_crtc_state *new_state)
341 {
342         if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
343                 return true;
344         else if (amdgpu_dm_vrr_active(old_state) != amdgpu_dm_vrr_active(new_state))
345                 return true;
346         else
347                 return false;
348 }
349
350 /**
351  * dm_pflip_high_irq() - Handle pageflip interrupt
352  * @interrupt_params: ignored
353  *
354  * Handles the pageflip interrupt by notifying all interested parties
355  * that the pageflip has been completed.
356  */
357 static void dm_pflip_high_irq(void *interrupt_params)
358 {
359         struct amdgpu_crtc *amdgpu_crtc;
360         struct common_irq_params *irq_params = interrupt_params;
361         struct amdgpu_device *adev = irq_params->adev;
362         unsigned long flags;
363         struct drm_pending_vblank_event *e;
364         u32 vpos, hpos, v_blank_start, v_blank_end;
365         bool vrr_active;
366
367         amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
368
369         /* IRQ could occur when in initial stage */
370         /* TODO work and BO cleanup */
371         if (amdgpu_crtc == NULL) {
372                 DC_LOG_PFLIP("CRTC is null, returning.\n");
373                 return;
374         }
375
376         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
377
378         if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
379                 DC_LOG_PFLIP("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
380                                                  amdgpu_crtc->pflip_status,
381                                                  AMDGPU_FLIP_SUBMITTED,
382                                                  amdgpu_crtc->crtc_id,
383                                                  amdgpu_crtc);
384                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
385                 return;
386         }
387
388         /* page flip completed. */
389         e = amdgpu_crtc->event;
390         amdgpu_crtc->event = NULL;
391
392         WARN_ON(!e);
393
394         vrr_active = amdgpu_dm_vrr_active_irq(amdgpu_crtc);
395
396         /* Fixed refresh rate, or VRR scanout position outside front-porch? */
397         if (!vrr_active ||
398             !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
399                                       &v_blank_end, &hpos, &vpos) ||
400             (vpos < v_blank_start)) {
401                 /* Update to correct count and vblank timestamp if racing with
402                  * vblank irq. This also updates to the correct vblank timestamp
403                  * even in VRR mode, as scanout is past the front-porch atm.
404                  */
405                 drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
406
407                 /* Wake up userspace by sending the pageflip event with proper
408                  * count and timestamp of vblank of flip completion.
409                  */
410                 if (e) {
411                         drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
412
413                         /* Event sent, so done with vblank for this flip */
414                         drm_crtc_vblank_put(&amdgpu_crtc->base);
415                 }
416         } else if (e) {
417                 /* VRR active and inside front-porch: vblank count and
418                  * timestamp for pageflip event will only be up to date after
419                  * drm_crtc_handle_vblank() has been executed from late vblank
420                  * irq handler after start of back-porch (vline 0). We queue the
421                  * pageflip event for send-out by drm_crtc_handle_vblank() with
422                  * updated timestamp and count, once it runs after us.
423                  *
424                  * We need to open-code this instead of using the helper
425                  * drm_crtc_arm_vblank_event(), as that helper would
426                  * call drm_crtc_accurate_vblank_count(), which we must
427                  * not call in VRR mode while we are in front-porch!
428                  */
429
430                 /* sequence will be replaced by real count during send-out. */
431                 e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
432                 e->pipe = amdgpu_crtc->crtc_id;
433
434                 list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
435                 e = NULL;
436         }
437
438         /* Keep track of vblank of this flip for flip throttling. We use the
439          * cooked hw counter, as that one incremented at start of this vblank
440          * of pageflip completion, so last_flip_vblank is the forbidden count
441          * for queueing new pageflips if vsync + VRR is enabled.
442          */
443         amdgpu_crtc->dm_irq_params.last_flip_vblank =
444                 amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
445
446         amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
447         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
448
449         DC_LOG_PFLIP("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
450                      amdgpu_crtc->crtc_id, amdgpu_crtc,
451                      vrr_active, (int) !e);
452 }
453
454 static void dm_vupdate_high_irq(void *interrupt_params)
455 {
456         struct common_irq_params *irq_params = interrupt_params;
457         struct amdgpu_device *adev = irq_params->adev;
458         struct amdgpu_crtc *acrtc;
459         struct drm_device *drm_dev;
460         struct drm_vblank_crtc *vblank;
461         ktime_t frame_duration_ns, previous_timestamp;
462         unsigned long flags;
463         int vrr_active;
464
465         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
466
467         if (acrtc) {
468                 vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
469                 drm_dev = acrtc->base.dev;
470                 vblank = &drm_dev->vblank[acrtc->base.index];
471                 previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
472                 frame_duration_ns = vblank->time - previous_timestamp;
473
474                 if (frame_duration_ns > 0) {
475                         trace_amdgpu_refresh_rate_track(acrtc->base.index,
476                                                 frame_duration_ns,
477                                                 ktime_divns(NSEC_PER_SEC, frame_duration_ns));
478                         atomic64_set(&irq_params->previous_timestamp, vblank->time);
479                 }
480
481                 DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d\n",
482                               acrtc->crtc_id,
483                               vrr_active);
484
485                 /* Core vblank handling is done here after end of front-porch in
486                  * vrr mode, as vblank timestamping will give valid results
487                  * while now done after front-porch. This will also deliver
488                  * page-flip completion events that have been queued to us
489                  * if a pageflip happened inside front-porch.
490                  */
491                 if (vrr_active) {
492                         dm_crtc_handle_vblank(acrtc);
493
494                         /* BTR processing for pre-DCE12 ASICs */
495                         if (acrtc->dm_irq_params.stream &&
496                             adev->family < AMDGPU_FAMILY_AI) {
497                                 spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
498                                 mod_freesync_handle_v_update(
499                                     adev->dm.freesync_module,
500                                     acrtc->dm_irq_params.stream,
501                                     &acrtc->dm_irq_params.vrr_params);
502
503                                 dc_stream_adjust_vmin_vmax(
504                                     adev->dm.dc,
505                                     acrtc->dm_irq_params.stream,
506                                     &acrtc->dm_irq_params.vrr_params.adjust);
507                                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
508                         }
509                 }
510         }
511 }
512
513 /**
514  * dm_crtc_high_irq() - Handles CRTC interrupt
515  * @interrupt_params: used for determining the CRTC instance
516  *
517  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
518  * event handler.
519  */
520 static void dm_crtc_high_irq(void *interrupt_params)
521 {
522         struct common_irq_params *irq_params = interrupt_params;
523         struct amdgpu_device *adev = irq_params->adev;
524         struct amdgpu_crtc *acrtc;
525         unsigned long flags;
526         int vrr_active;
527
528         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
529         if (!acrtc)
530                 return;
531
532         vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
533
534         DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
535                       vrr_active, acrtc->dm_irq_params.active_planes);
536
537         /**
538          * Core vblank handling at start of front-porch is only possible
539          * in non-vrr mode, as only there vblank timestamping will give
540          * valid results while done in front-porch. Otherwise defer it
541          * to dm_vupdate_high_irq after end of front-porch.
542          */
543         if (!vrr_active)
544                 dm_crtc_handle_vblank(acrtc);
545
546         /**
547          * Following stuff must happen at start of vblank, for crc
548          * computation and below-the-range btr support in vrr mode.
549          */
550         amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
551
552         /* BTR updates need to happen before VUPDATE on Vega and above. */
553         if (adev->family < AMDGPU_FAMILY_AI)
554                 return;
555
556         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
557
558         if (acrtc->dm_irq_params.stream &&
559             acrtc->dm_irq_params.vrr_params.supported &&
560             acrtc->dm_irq_params.freesync_config.state ==
561                     VRR_STATE_ACTIVE_VARIABLE) {
562                 mod_freesync_handle_v_update(adev->dm.freesync_module,
563                                              acrtc->dm_irq_params.stream,
564                                              &acrtc->dm_irq_params.vrr_params);
565
566                 dc_stream_adjust_vmin_vmax(adev->dm.dc, acrtc->dm_irq_params.stream,
567                                            &acrtc->dm_irq_params.vrr_params.adjust);
568         }
569
570         /*
571          * If there aren't any active_planes then DCH HUBP may be clock-gated.
572          * In that case, pageflip completion interrupts won't fire and pageflip
573          * completion events won't get delivered. Prevent this by sending
574          * pending pageflip events from here if a flip is still pending.
575          *
576          * If any planes are enabled, use dm_pflip_high_irq() instead, to
577          * avoid race conditions between flip programming and completion,
578          * which could cause too early flip completion events.
579          */
580         if (adev->family >= AMDGPU_FAMILY_RV &&
581             acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
582             acrtc->dm_irq_params.active_planes == 0) {
583                 if (acrtc->event) {
584                         drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
585                         acrtc->event = NULL;
586                         drm_crtc_vblank_put(&acrtc->base);
587                 }
588                 acrtc->pflip_status = AMDGPU_FLIP_NONE;
589         }
590
591         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
592 }
593
594 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
595 /**
596  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
597  * DCN generation ASICs
598  * @interrupt_params: interrupt parameters
599  *
600  * Used to set crc window/read out crc value at vertical line 0 position
601  */
602 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
603 {
604         struct common_irq_params *irq_params = interrupt_params;
605         struct amdgpu_device *adev = irq_params->adev;
606         struct amdgpu_crtc *acrtc;
607
608         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
609
610         if (!acrtc)
611                 return;
612
613         amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
614 }
615 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
616
617 /**
618  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
619  * @adev: amdgpu_device pointer
620  * @notify: dmub notification structure
621  *
622  * Dmub AUX or SET_CONFIG command completion processing callback
623  * Copies dmub notification to DM which is to be read by AUX command.
624  * issuing thread and also signals the event to wake up the thread.
625  */
626 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
627                                         struct dmub_notification *notify)
628 {
629         if (adev->dm.dmub_notify)
630                 memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
631         if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
632                 complete(&adev->dm.dmub_aux_transfer_done);
633 }
634
635 /**
636  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
637  * @adev: amdgpu_device pointer
638  * @notify: dmub notification structure
639  *
640  * Dmub Hpd interrupt processing callback. Gets displayindex through the
641  * ink index and calls helper to do the processing.
642  */
643 static void dmub_hpd_callback(struct amdgpu_device *adev,
644                               struct dmub_notification *notify)
645 {
646         struct amdgpu_dm_connector *aconnector;
647         struct amdgpu_dm_connector *hpd_aconnector = NULL;
648         struct drm_connector *connector;
649         struct drm_connector_list_iter iter;
650         struct dc_link *link;
651         u8 link_index = 0;
652         struct drm_device *dev;
653
654         if (adev == NULL)
655                 return;
656
657         if (notify == NULL) {
658                 DRM_ERROR("DMUB HPD callback notification was NULL");
659                 return;
660         }
661
662         if (notify->link_index > adev->dm.dc->link_count) {
663                 DRM_ERROR("DMUB HPD index (%u)is abnormal", notify->link_index);
664                 return;
665         }
666
667         link_index = notify->link_index;
668         link = adev->dm.dc->links[link_index];
669         dev = adev->dm.ddev;
670
671         drm_connector_list_iter_begin(dev, &iter);
672         drm_for_each_connector_iter(connector, &iter) {
673                 aconnector = to_amdgpu_dm_connector(connector);
674                 if (link && aconnector->dc_link == link) {
675                         DRM_INFO("DMUB HPD callback: link_index=%u\n", link_index);
676                         hpd_aconnector = aconnector;
677                         break;
678                 }
679         }
680         drm_connector_list_iter_end(&iter);
681
682         if (hpd_aconnector) {
683                 if (notify->type == DMUB_NOTIFICATION_HPD)
684                         handle_hpd_irq_helper(hpd_aconnector);
685                 else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
686                         handle_hpd_rx_irq(hpd_aconnector);
687         }
688 }
689
690 /**
691  * register_dmub_notify_callback - Sets callback for DMUB notify
692  * @adev: amdgpu_device pointer
693  * @type: Type of dmub notification
694  * @callback: Dmub interrupt callback function
695  * @dmub_int_thread_offload: offload indicator
696  *
697  * API to register a dmub callback handler for a dmub notification
698  * Also sets indicator whether callback processing to be offloaded.
699  * to dmub interrupt handling thread
700  * Return: true if successfully registered, false if there is existing registration
701  */
702 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
703                                           enum dmub_notification_type type,
704                                           dmub_notify_interrupt_callback_t callback,
705                                           bool dmub_int_thread_offload)
706 {
707         if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
708                 adev->dm.dmub_callback[type] = callback;
709                 adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
710         } else
711                 return false;
712
713         return true;
714 }
715
716 static void dm_handle_hpd_work(struct work_struct *work)
717 {
718         struct dmub_hpd_work *dmub_hpd_wrk;
719
720         dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
721
722         if (!dmub_hpd_wrk->dmub_notify) {
723                 DRM_ERROR("dmub_hpd_wrk dmub_notify is NULL");
724                 return;
725         }
726
727         if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
728                 dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
729                 dmub_hpd_wrk->dmub_notify);
730         }
731
732         kfree(dmub_hpd_wrk->dmub_notify);
733         kfree(dmub_hpd_wrk);
734
735 }
736
737 #define DMUB_TRACE_MAX_READ 64
738 /**
739  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
740  * @interrupt_params: used for determining the Outbox instance
741  *
742  * Handles the Outbox Interrupt
743  * event handler.
744  */
745 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
746 {
747         struct dmub_notification notify;
748         struct common_irq_params *irq_params = interrupt_params;
749         struct amdgpu_device *adev = irq_params->adev;
750         struct amdgpu_display_manager *dm = &adev->dm;
751         struct dmcub_trace_buf_entry entry = { 0 };
752         u32 count = 0;
753         struct dmub_hpd_work *dmub_hpd_wrk;
754         struct dc_link *plink = NULL;
755
756         if (dc_enable_dmub_notifications(adev->dm.dc) &&
757                 irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
758
759                 do {
760                         dc_stat_get_dmub_notification(adev->dm.dc, &notify);
761                         if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
762                                 DRM_ERROR("DM: notify type %d invalid!", notify.type);
763                                 continue;
764                         }
765                         if (!dm->dmub_callback[notify.type]) {
766                                 DRM_DEBUG_DRIVER("DMUB notification skipped, no handler: type=%d\n", notify.type);
767                                 continue;
768                         }
769                         if (dm->dmub_thread_offload[notify.type] == true) {
770                                 dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
771                                 if (!dmub_hpd_wrk) {
772                                         DRM_ERROR("Failed to allocate dmub_hpd_wrk");
773                                         return;
774                                 }
775                                 dmub_hpd_wrk->dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_ATOMIC);
776                                 if (!dmub_hpd_wrk->dmub_notify) {
777                                         kfree(dmub_hpd_wrk);
778                                         DRM_ERROR("Failed to allocate dmub_hpd_wrk->dmub_notify");
779                                         return;
780                                 }
781                                 INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
782                                 if (dmub_hpd_wrk->dmub_notify)
783                                         memcpy(dmub_hpd_wrk->dmub_notify, &notify, sizeof(struct dmub_notification));
784                                 dmub_hpd_wrk->adev = adev;
785                                 if (notify.type == DMUB_NOTIFICATION_HPD) {
786                                         plink = adev->dm.dc->links[notify.link_index];
787                                         if (plink) {
788                                                 plink->hpd_status =
789                                                         notify.hpd_status == DP_HPD_PLUG;
790                                         }
791                                 }
792                                 queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
793                         } else {
794                                 dm->dmub_callback[notify.type](adev, &notify);
795                         }
796                 } while (notify.pending_notification);
797         }
798
799
800         do {
801                 if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
802                         trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
803                                                         entry.param0, entry.param1);
804
805                         DRM_DEBUG_DRIVER("trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
806                                  entry.trace_code, entry.tick_count, entry.param0, entry.param1);
807                 } else
808                         break;
809
810                 count++;
811
812         } while (count <= DMUB_TRACE_MAX_READ);
813
814         if (count > DMUB_TRACE_MAX_READ)
815                 DRM_DEBUG_DRIVER("Warning : count > DMUB_TRACE_MAX_READ");
816 }
817
818 static int dm_set_clockgating_state(void *handle,
819                   enum amd_clockgating_state state)
820 {
821         return 0;
822 }
823
824 static int dm_set_powergating_state(void *handle,
825                   enum amd_powergating_state state)
826 {
827         return 0;
828 }
829
830 /* Prototypes of private functions */
831 static int dm_early_init(void* handle);
832
833 /* Allocate memory for FBC compressed data  */
834 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
835 {
836         struct drm_device *dev = connector->dev;
837         struct amdgpu_device *adev = drm_to_adev(dev);
838         struct dm_compressor_info *compressor = &adev->dm.compressor;
839         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
840         struct drm_display_mode *mode;
841         unsigned long max_size = 0;
842
843         if (adev->dm.dc->fbc_compressor == NULL)
844                 return;
845
846         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
847                 return;
848
849         if (compressor->bo_ptr)
850                 return;
851
852
853         list_for_each_entry(mode, &connector->modes, head) {
854                 if (max_size < mode->htotal * mode->vtotal)
855                         max_size = mode->htotal * mode->vtotal;
856         }
857
858         if (max_size) {
859                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
860                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
861                             &compressor->gpu_addr, &compressor->cpu_addr);
862
863                 if (r)
864                         DRM_ERROR("DM: Failed to initialize FBC\n");
865                 else {
866                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
867                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
868                 }
869
870         }
871
872 }
873
874 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
875                                           int pipe, bool *enabled,
876                                           unsigned char *buf, int max_bytes)
877 {
878         struct drm_device *dev = dev_get_drvdata(kdev);
879         struct amdgpu_device *adev = drm_to_adev(dev);
880         struct drm_connector *connector;
881         struct drm_connector_list_iter conn_iter;
882         struct amdgpu_dm_connector *aconnector;
883         int ret = 0;
884
885         *enabled = false;
886
887         mutex_lock(&adev->dm.audio_lock);
888
889         drm_connector_list_iter_begin(dev, &conn_iter);
890         drm_for_each_connector_iter(connector, &conn_iter) {
891                 aconnector = to_amdgpu_dm_connector(connector);
892                 if (aconnector->audio_inst != port)
893                         continue;
894
895                 *enabled = true;
896                 ret = drm_eld_size(connector->eld);
897                 memcpy(buf, connector->eld, min(max_bytes, ret));
898
899                 break;
900         }
901         drm_connector_list_iter_end(&conn_iter);
902
903         mutex_unlock(&adev->dm.audio_lock);
904
905         DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
906
907         return ret;
908 }
909
910 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
911         .get_eld = amdgpu_dm_audio_component_get_eld,
912 };
913
914 static int amdgpu_dm_audio_component_bind(struct device *kdev,
915                                        struct device *hda_kdev, void *data)
916 {
917         struct drm_device *dev = dev_get_drvdata(kdev);
918         struct amdgpu_device *adev = drm_to_adev(dev);
919         struct drm_audio_component *acomp = data;
920
921         acomp->ops = &amdgpu_dm_audio_component_ops;
922         acomp->dev = kdev;
923         adev->dm.audio_component = acomp;
924
925         return 0;
926 }
927
928 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
929                                           struct device *hda_kdev, void *data)
930 {
931         struct drm_device *dev = dev_get_drvdata(kdev);
932         struct amdgpu_device *adev = drm_to_adev(dev);
933         struct drm_audio_component *acomp = data;
934
935         acomp->ops = NULL;
936         acomp->dev = NULL;
937         adev->dm.audio_component = NULL;
938 }
939
940 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
941         .bind   = amdgpu_dm_audio_component_bind,
942         .unbind = amdgpu_dm_audio_component_unbind,
943 };
944
945 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
946 {
947         int i, ret;
948
949         if (!amdgpu_audio)
950                 return 0;
951
952         adev->mode_info.audio.enabled = true;
953
954         adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
955
956         for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
957                 adev->mode_info.audio.pin[i].channels = -1;
958                 adev->mode_info.audio.pin[i].rate = -1;
959                 adev->mode_info.audio.pin[i].bits_per_sample = -1;
960                 adev->mode_info.audio.pin[i].status_bits = 0;
961                 adev->mode_info.audio.pin[i].category_code = 0;
962                 adev->mode_info.audio.pin[i].connected = false;
963                 adev->mode_info.audio.pin[i].id =
964                         adev->dm.dc->res_pool->audios[i]->inst;
965                 adev->mode_info.audio.pin[i].offset = 0;
966         }
967
968         ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
969         if (ret < 0)
970                 return ret;
971
972         adev->dm.audio_registered = true;
973
974         return 0;
975 }
976
977 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
978 {
979         if (!amdgpu_audio)
980                 return;
981
982         if (!adev->mode_info.audio.enabled)
983                 return;
984
985         if (adev->dm.audio_registered) {
986                 component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
987                 adev->dm.audio_registered = false;
988         }
989
990         /* TODO: Disable audio? */
991
992         adev->mode_info.audio.enabled = false;
993 }
994
995 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
996 {
997         struct drm_audio_component *acomp = adev->dm.audio_component;
998
999         if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1000                 DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
1001
1002                 acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1003                                                  pin, -1);
1004         }
1005 }
1006
1007 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1008 {
1009         const struct dmcub_firmware_header_v1_0 *hdr;
1010         struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1011         struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1012         const struct firmware *dmub_fw = adev->dm.dmub_fw;
1013         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1014         struct abm *abm = adev->dm.dc->res_pool->abm;
1015         struct dmub_srv_hw_params hw_params;
1016         enum dmub_status status;
1017         const unsigned char *fw_inst_const, *fw_bss_data;
1018         u32 i, fw_inst_const_size, fw_bss_data_size;
1019         bool has_hw_support;
1020
1021         if (!dmub_srv)
1022                 /* DMUB isn't supported on the ASIC. */
1023                 return 0;
1024
1025         if (!fb_info) {
1026                 DRM_ERROR("No framebuffer info for DMUB service.\n");
1027                 return -EINVAL;
1028         }
1029
1030         if (!dmub_fw) {
1031                 /* Firmware required for DMUB support. */
1032                 DRM_ERROR("No firmware provided for DMUB.\n");
1033                 return -EINVAL;
1034         }
1035
1036         status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1037         if (status != DMUB_STATUS_OK) {
1038                 DRM_ERROR("Error checking HW support for DMUB: %d\n", status);
1039                 return -EINVAL;
1040         }
1041
1042         if (!has_hw_support) {
1043                 DRM_INFO("DMUB unsupported on ASIC\n");
1044                 return 0;
1045         }
1046
1047         /* Reset DMCUB if it was previously running - before we overwrite its memory. */
1048         status = dmub_srv_hw_reset(dmub_srv);
1049         if (status != DMUB_STATUS_OK)
1050                 DRM_WARN("Error resetting DMUB HW: %d\n", status);
1051
1052         hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1053
1054         fw_inst_const = dmub_fw->data +
1055                         le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1056                         PSP_HEADER_BYTES;
1057
1058         fw_bss_data = dmub_fw->data +
1059                       le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1060                       le32_to_cpu(hdr->inst_const_bytes);
1061
1062         /* Copy firmware and bios info into FB memory. */
1063         fw_inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
1064                              PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
1065
1066         fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1067
1068         /* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1069          * amdgpu_ucode_init_single_fw will load dmub firmware
1070          * fw_inst_const part to cw0; otherwise, the firmware back door load
1071          * will be done by dm_dmub_hw_init
1072          */
1073         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1074                 memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1075                                 fw_inst_const_size);
1076         }
1077
1078         if (fw_bss_data_size)
1079                 memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1080                        fw_bss_data, fw_bss_data_size);
1081
1082         /* Copy firmware bios info into FB memory. */
1083         memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1084                adev->bios_size);
1085
1086         /* Reset regions that need to be reset. */
1087         memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1088         fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1089
1090         memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1091                fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1092
1093         memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1094                fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1095
1096         /* Initialize hardware. */
1097         memset(&hw_params, 0, sizeof(hw_params));
1098         hw_params.fb_base = adev->gmc.fb_start;
1099         hw_params.fb_offset = adev->vm_manager.vram_base_offset;
1100
1101         /* backdoor load firmware and trigger dmub running */
1102         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1103                 hw_params.load_inst_const = true;
1104
1105         if (dmcu)
1106                 hw_params.psp_version = dmcu->psp_version;
1107
1108         for (i = 0; i < fb_info->num_fb; ++i)
1109                 hw_params.fb[i] = &fb_info->fb[i];
1110
1111         switch (adev->ip_versions[DCE_HWIP][0]) {
1112         case IP_VERSION(3, 1, 3):
1113         case IP_VERSION(3, 1, 4):
1114                 hw_params.dpia_supported = true;
1115                 hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
1116                 break;
1117         default:
1118                 break;
1119         }
1120
1121         status = dmub_srv_hw_init(dmub_srv, &hw_params);
1122         if (status != DMUB_STATUS_OK) {
1123                 DRM_ERROR("Error initializing DMUB HW: %d\n", status);
1124                 return -EINVAL;
1125         }
1126
1127         /* Wait for firmware load to finish. */
1128         status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1129         if (status != DMUB_STATUS_OK)
1130                 DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1131
1132         /* Init DMCU and ABM if available. */
1133         if (dmcu && abm) {
1134                 dmcu->funcs->dmcu_init(dmcu);
1135                 abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1136         }
1137
1138         if (!adev->dm.dc->ctx->dmub_srv)
1139                 adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1140         if (!adev->dm.dc->ctx->dmub_srv) {
1141                 DRM_ERROR("Couldn't allocate DC DMUB server!\n");
1142                 return -ENOMEM;
1143         }
1144
1145         DRM_INFO("DMUB hardware initialized: version=0x%08X\n",
1146                  adev->dm.dmcub_fw_version);
1147
1148         return 0;
1149 }
1150
1151 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1152 {
1153         struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1154         enum dmub_status status;
1155         bool init;
1156
1157         if (!dmub_srv) {
1158                 /* DMUB isn't supported on the ASIC. */
1159                 return;
1160         }
1161
1162         status = dmub_srv_is_hw_init(dmub_srv, &init);
1163         if (status != DMUB_STATUS_OK)
1164                 DRM_WARN("DMUB hardware init check failed: %d\n", status);
1165
1166         if (status == DMUB_STATUS_OK && init) {
1167                 /* Wait for firmware load to finish. */
1168                 status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1169                 if (status != DMUB_STATUS_OK)
1170                         DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1171         } else {
1172                 /* Perform the full hardware initialization. */
1173                 dm_dmub_hw_init(adev);
1174         }
1175 }
1176
1177 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1178 {
1179         u64 pt_base;
1180         u32 logical_addr_low;
1181         u32 logical_addr_high;
1182         u32 agp_base, agp_bot, agp_top;
1183         PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1184
1185         memset(pa_config, 0, sizeof(*pa_config));
1186
1187         logical_addr_low  = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1188         pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1189
1190         if (adev->apu_flags & AMD_APU_IS_RAVEN2)
1191                 /*
1192                  * Raven2 has a HW issue that it is unable to use the vram which
1193                  * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1194                  * workaround that increase system aperture high address (add 1)
1195                  * to get rid of the VM fault and hardware hang.
1196                  */
1197                 logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1198         else
1199                 logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1200
1201         agp_base = 0;
1202         agp_bot = adev->gmc.agp_start >> 24;
1203         agp_top = adev->gmc.agp_end >> 24;
1204
1205
1206         page_table_start.high_part = (u32)(adev->gmc.gart_start >> 44) & 0xF;
1207         page_table_start.low_part = (u32)(adev->gmc.gart_start >> 12);
1208         page_table_end.high_part = (u32)(adev->gmc.gart_end >> 44) & 0xF;
1209         page_table_end.low_part = (u32)(adev->gmc.gart_end >> 12);
1210         page_table_base.high_part = upper_32_bits(pt_base) & 0xF;
1211         page_table_base.low_part = lower_32_bits(pt_base);
1212
1213         pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1214         pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1215
1216         pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24 ;
1217         pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1218         pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1219
1220         pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1221         pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1222         pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1223
1224         pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1225         pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1226         pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1227
1228         pa_config->is_hvm_enabled = 0;
1229
1230 }
1231
1232 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1233 {
1234         struct hpd_rx_irq_offload_work *offload_work;
1235         struct amdgpu_dm_connector *aconnector;
1236         struct dc_link *dc_link;
1237         struct amdgpu_device *adev;
1238         enum dc_connection_type new_connection_type = dc_connection_none;
1239         unsigned long flags;
1240
1241         offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1242         aconnector = offload_work->offload_wq->aconnector;
1243
1244         if (!aconnector) {
1245                 DRM_ERROR("Can't retrieve aconnector in hpd_rx_irq_offload_work");
1246                 goto skip;
1247         }
1248
1249         adev = drm_to_adev(aconnector->base.dev);
1250         dc_link = aconnector->dc_link;
1251
1252         mutex_lock(&aconnector->hpd_lock);
1253         if (!dc_link_detect_sink(dc_link, &new_connection_type))
1254                 DRM_ERROR("KMS: Failed to detect connector\n");
1255         mutex_unlock(&aconnector->hpd_lock);
1256
1257         if (new_connection_type == dc_connection_none)
1258                 goto skip;
1259
1260         if (amdgpu_in_reset(adev))
1261                 goto skip;
1262
1263         mutex_lock(&adev->dm.dc_lock);
1264         if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST)
1265                 dc_link_dp_handle_automated_test(dc_link);
1266         else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1267                         hpd_rx_irq_check_link_loss_status(dc_link, &offload_work->data) &&
1268                         dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1269                 dc_link_dp_handle_link_loss(dc_link);
1270                 spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1271                 offload_work->offload_wq->is_handling_link_loss = false;
1272                 spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1273         }
1274         mutex_unlock(&adev->dm.dc_lock);
1275
1276 skip:
1277         kfree(offload_work);
1278
1279 }
1280
1281 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct dc *dc)
1282 {
1283         int max_caps = dc->caps.max_links;
1284         int i = 0;
1285         struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1286
1287         hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
1288
1289         if (!hpd_rx_offload_wq)
1290                 return NULL;
1291
1292
1293         for (i = 0; i < max_caps; i++) {
1294                 hpd_rx_offload_wq[i].wq =
1295                                     create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1296
1297                 if (hpd_rx_offload_wq[i].wq == NULL) {
1298                         DRM_ERROR("create amdgpu_dm_hpd_rx_offload_wq fail!");
1299                         goto out_err;
1300                 }
1301
1302                 spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1303         }
1304
1305         return hpd_rx_offload_wq;
1306
1307 out_err:
1308         for (i = 0; i < max_caps; i++) {
1309                 if (hpd_rx_offload_wq[i].wq)
1310                         destroy_workqueue(hpd_rx_offload_wq[i].wq);
1311         }
1312         kfree(hpd_rx_offload_wq);
1313         return NULL;
1314 }
1315
1316 struct amdgpu_stutter_quirk {
1317         u16 chip_vendor;
1318         u16 chip_device;
1319         u16 subsys_vendor;
1320         u16 subsys_device;
1321         u8 revision;
1322 };
1323
1324 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1325         /* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1326         { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1327         { 0, 0, 0, 0, 0 },
1328 };
1329
1330 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1331 {
1332         const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1333
1334         while (p && p->chip_device != 0) {
1335                 if (pdev->vendor == p->chip_vendor &&
1336                     pdev->device == p->chip_device &&
1337                     pdev->subsystem_vendor == p->subsys_vendor &&
1338                     pdev->subsystem_device == p->subsys_device &&
1339                     pdev->revision == p->revision) {
1340                         return true;
1341                 }
1342                 ++p;
1343         }
1344         return false;
1345 }
1346
1347 static const struct dmi_system_id hpd_disconnect_quirk_table[] = {
1348         {
1349                 .matches = {
1350                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1351                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3660"),
1352                 },
1353         },
1354         {
1355                 .matches = {
1356                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1357                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3260"),
1358                 },
1359         },
1360         {
1361                 .matches = {
1362                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1363                         DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3460"),
1364                 },
1365         },
1366         {
1367                 .matches = {
1368                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1369                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower Plus 7010"),
1370                 },
1371         },
1372         {
1373                 .matches = {
1374                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1375                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower 7010"),
1376                 },
1377         },
1378         {
1379                 .matches = {
1380                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1381                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF Plus 7010"),
1382                 },
1383         },
1384         {
1385                 .matches = {
1386                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1387                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF 7010"),
1388                 },
1389         },
1390         {
1391                 .matches = {
1392                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1393                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro Plus 7010"),
1394                 },
1395         },
1396         {
1397                 .matches = {
1398                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1399                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro 7010"),
1400                 },
1401         },
1402         {}
1403         /* TODO: refactor this from a fixed table to a dynamic option */
1404 };
1405
1406 static void retrieve_dmi_info(struct amdgpu_display_manager *dm)
1407 {
1408         const struct dmi_system_id *dmi_id;
1409
1410         dm->aux_hpd_discon_quirk = false;
1411
1412         dmi_id = dmi_first_match(hpd_disconnect_quirk_table);
1413         if (dmi_id) {
1414                 dm->aux_hpd_discon_quirk = true;
1415                 DRM_INFO("aux_hpd_discon_quirk attached\n");
1416         }
1417 }
1418
1419 static int amdgpu_dm_init(struct amdgpu_device *adev)
1420 {
1421         struct dc_init_data init_data;
1422 #ifdef CONFIG_DRM_AMD_DC_HDCP
1423         struct dc_callback_init init_params;
1424 #endif
1425         int r;
1426
1427         adev->dm.ddev = adev_to_drm(adev);
1428         adev->dm.adev = adev;
1429
1430         /* Zero all the fields */
1431         memset(&init_data, 0, sizeof(init_data));
1432 #ifdef CONFIG_DRM_AMD_DC_HDCP
1433         memset(&init_params, 0, sizeof(init_params));
1434 #endif
1435
1436         mutex_init(&adev->dm.dpia_aux_lock);
1437         mutex_init(&adev->dm.dc_lock);
1438         mutex_init(&adev->dm.audio_lock);
1439
1440         if(amdgpu_dm_irq_init(adev)) {
1441                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
1442                 goto error;
1443         }
1444
1445         init_data.asic_id.chip_family = adev->family;
1446
1447         init_data.asic_id.pci_revision_id = adev->pdev->revision;
1448         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1449         init_data.asic_id.chip_id = adev->pdev->device;
1450
1451         init_data.asic_id.vram_width = adev->gmc.vram_width;
1452         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
1453         init_data.asic_id.atombios_base_address =
1454                 adev->mode_info.atom_context->bios;
1455
1456         init_data.driver = adev;
1457
1458         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
1459
1460         if (!adev->dm.cgs_device) {
1461                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
1462                 goto error;
1463         }
1464
1465         init_data.cgs_device = adev->dm.cgs_device;
1466
1467         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1468
1469         switch (adev->ip_versions[DCE_HWIP][0]) {
1470         case IP_VERSION(2, 1, 0):
1471                 switch (adev->dm.dmcub_fw_version) {
1472                 case 0: /* development */
1473                 case 0x1: /* linux-firmware.git hash 6d9f399 */
1474                 case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1475                         init_data.flags.disable_dmcu = false;
1476                         break;
1477                 default:
1478                         init_data.flags.disable_dmcu = true;
1479                 }
1480                 break;
1481         case IP_VERSION(2, 0, 3):
1482                 init_data.flags.disable_dmcu = true;
1483                 break;
1484         default:
1485                 break;
1486         }
1487
1488         switch (adev->asic_type) {
1489         case CHIP_CARRIZO:
1490         case CHIP_STONEY:
1491                 init_data.flags.gpu_vm_support = true;
1492                 break;
1493         default:
1494                 switch (adev->ip_versions[DCE_HWIP][0]) {
1495                 case IP_VERSION(1, 0, 0):
1496                 case IP_VERSION(1, 0, 1):
1497                         /* enable S/G on PCO and RV2 */
1498                         if ((adev->apu_flags & AMD_APU_IS_RAVEN2) ||
1499                             (adev->apu_flags & AMD_APU_IS_PICASSO))
1500                                 init_data.flags.gpu_vm_support = true;
1501                         break;
1502                 case IP_VERSION(2, 1, 0):
1503                 case IP_VERSION(3, 0, 1):
1504                 case IP_VERSION(3, 1, 2):
1505                 case IP_VERSION(3, 1, 3):
1506                 case IP_VERSION(3, 1, 6):
1507                         init_data.flags.gpu_vm_support = true;
1508                         break;
1509                 default:
1510                         break;
1511                 }
1512                 break;
1513         }
1514
1515         if (init_data.flags.gpu_vm_support)
1516                 adev->mode_info.gpu_vm_support = true;
1517
1518         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1519                 init_data.flags.fbc_support = true;
1520
1521         if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1522                 init_data.flags.multi_mon_pp_mclk_switch = true;
1523
1524         if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1525                 init_data.flags.disable_fractional_pwm = true;
1526
1527         if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1528                 init_data.flags.edp_no_power_sequencing = true;
1529
1530         if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1531                 init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1532         if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1533                 init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1534
1535         init_data.flags.seamless_boot_edp_requested = false;
1536
1537         if (check_seamless_boot_capability(adev)) {
1538                 init_data.flags.seamless_boot_edp_requested = true;
1539                 init_data.flags.allow_seamless_boot_optimization = true;
1540                 DRM_INFO("Seamless boot condition check passed\n");
1541         }
1542
1543         init_data.flags.enable_mipi_converter_optimization = true;
1544
1545         init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1546         init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1547
1548         INIT_LIST_HEAD(&adev->dm.da_list);
1549
1550         retrieve_dmi_info(&adev->dm);
1551
1552         /* Display Core create. */
1553         adev->dm.dc = dc_create(&init_data);
1554
1555         if (adev->dm.dc) {
1556                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
1557         } else {
1558                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
1559                 goto error;
1560         }
1561
1562         if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
1563                 adev->dm.dc->debug.force_single_disp_pipe_split = false;
1564                 adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
1565         }
1566
1567         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
1568                 adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
1569         if (dm_should_disable_stutter(adev->pdev))
1570                 adev->dm.dc->debug.disable_stutter = true;
1571
1572         if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
1573                 adev->dm.dc->debug.disable_stutter = true;
1574
1575         if (amdgpu_dc_debug_mask & DC_DISABLE_DSC) {
1576                 adev->dm.dc->debug.disable_dsc = true;
1577         }
1578
1579         if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
1580                 adev->dm.dc->debug.disable_clock_gate = true;
1581
1582         if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
1583                 adev->dm.dc->debug.force_subvp_mclk_switch = true;
1584
1585         adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
1586
1587         /* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
1588         adev->dm.dc->debug.ignore_cable_id = true;
1589
1590         r = dm_dmub_hw_init(adev);
1591         if (r) {
1592                 DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
1593                 goto error;
1594         }
1595
1596         dc_hardware_init(adev->dm.dc);
1597
1598         adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev->dm.dc);
1599         if (!adev->dm.hpd_rx_offload_wq) {
1600                 DRM_ERROR("amdgpu: failed to create hpd rx offload workqueue.\n");
1601                 goto error;
1602         }
1603
1604         if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
1605                 struct dc_phy_addr_space_config pa_config;
1606
1607                 mmhub_read_system_context(adev, &pa_config);
1608
1609                 // Call the DC init_memory func
1610                 dc_setup_system_context(adev->dm.dc, &pa_config);
1611         }
1612
1613         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
1614         if (!adev->dm.freesync_module) {
1615                 DRM_ERROR(
1616                 "amdgpu: failed to initialize freesync_module.\n");
1617         } else
1618                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
1619                                 adev->dm.freesync_module);
1620
1621         amdgpu_dm_init_color_mod();
1622
1623         if (adev->dm.dc->caps.max_links > 0) {
1624                 adev->dm.vblank_control_workqueue =
1625                         create_singlethread_workqueue("dm_vblank_control_workqueue");
1626                 if (!adev->dm.vblank_control_workqueue)
1627                         DRM_ERROR("amdgpu: failed to initialize vblank_workqueue.\n");
1628         }
1629
1630 #ifdef CONFIG_DRM_AMD_DC_HDCP
1631         if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
1632                 adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
1633
1634                 if (!adev->dm.hdcp_workqueue)
1635                         DRM_ERROR("amdgpu: failed to initialize hdcp_workqueue.\n");
1636                 else
1637                         DRM_DEBUG_DRIVER("amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
1638
1639                 dc_init_callbacks(adev->dm.dc, &init_params);
1640         }
1641 #endif
1642 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1643         adev->dm.secure_display_ctxs = amdgpu_dm_crtc_secure_display_create_contexts(adev);
1644         if (!adev->dm.secure_display_ctxs) {
1645                 DRM_ERROR("amdgpu: failed to initialize secure_display_ctxs.\n");
1646         }
1647 #endif
1648         if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1649                 init_completion(&adev->dm.dmub_aux_transfer_done);
1650                 adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
1651                 if (!adev->dm.dmub_notify) {
1652                         DRM_INFO("amdgpu: fail to allocate adev->dm.dmub_notify");
1653                         goto error;
1654                 }
1655
1656                 adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
1657                 if (!adev->dm.delayed_hpd_wq) {
1658                         DRM_ERROR("amdgpu: failed to create hpd offload workqueue.\n");
1659                         goto error;
1660                 }
1661
1662                 amdgpu_dm_outbox_init(adev);
1663                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
1664                         dmub_aux_setconfig_callback, false)) {
1665                         DRM_ERROR("amdgpu: fail to register dmub aux callback");
1666                         goto error;
1667                 }
1668                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD, dmub_hpd_callback, true)) {
1669                         DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1670                         goto error;
1671                 }
1672                 if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ, dmub_hpd_callback, true)) {
1673                         DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1674                         goto error;
1675                 }
1676         }
1677
1678         /* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
1679          * It is expected that DMUB will resend any pending notifications at this point, for
1680          * example HPD from DPIA.
1681          */
1682         if (dc_is_dmub_outbox_supported(adev->dm.dc))
1683                 dc_enable_dmub_outbox(adev->dm.dc);
1684
1685         if (amdgpu_dm_initialize_drm_device(adev)) {
1686                 DRM_ERROR(
1687                 "amdgpu: failed to initialize sw for display support.\n");
1688                 goto error;
1689         }
1690
1691         /* create fake encoders for MST */
1692         dm_dp_create_fake_mst_encoders(adev);
1693
1694         /* TODO: Add_display_info? */
1695
1696         /* TODO use dynamic cursor width */
1697         adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
1698         adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
1699
1700         if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
1701                 DRM_ERROR(
1702                 "amdgpu: failed to initialize sw for display support.\n");
1703                 goto error;
1704         }
1705
1706
1707         DRM_DEBUG_DRIVER("KMS initialized.\n");
1708
1709         return 0;
1710 error:
1711         amdgpu_dm_fini(adev);
1712
1713         return -EINVAL;
1714 }
1715
1716 static int amdgpu_dm_early_fini(void *handle)
1717 {
1718         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1719
1720         amdgpu_dm_audio_fini(adev);
1721
1722         return 0;
1723 }
1724
1725 static void amdgpu_dm_fini(struct amdgpu_device *adev)
1726 {
1727         int i;
1728
1729         if (adev->dm.vblank_control_workqueue) {
1730                 destroy_workqueue(adev->dm.vblank_control_workqueue);
1731                 adev->dm.vblank_control_workqueue = NULL;
1732         }
1733
1734         amdgpu_dm_destroy_drm_device(&adev->dm);
1735
1736 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1737         if (adev->dm.secure_display_ctxs) {
1738                 for (i = 0; i < adev->mode_info.num_crtc; i++) {
1739                         if (adev->dm.secure_display_ctxs[i].crtc) {
1740                                 flush_work(&adev->dm.secure_display_ctxs[i].notify_ta_work);
1741                                 flush_work(&adev->dm.secure_display_ctxs[i].forward_roi_work);
1742                         }
1743                 }
1744                 kfree(adev->dm.secure_display_ctxs);
1745                 adev->dm.secure_display_ctxs = NULL;
1746         }
1747 #endif
1748 #ifdef CONFIG_DRM_AMD_DC_HDCP
1749         if (adev->dm.hdcp_workqueue) {
1750                 hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
1751                 adev->dm.hdcp_workqueue = NULL;
1752         }
1753
1754         if (adev->dm.dc)
1755                 dc_deinit_callbacks(adev->dm.dc);
1756 #endif
1757
1758         dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
1759
1760         if (dc_enable_dmub_notifications(adev->dm.dc)) {
1761                 kfree(adev->dm.dmub_notify);
1762                 adev->dm.dmub_notify = NULL;
1763                 destroy_workqueue(adev->dm.delayed_hpd_wq);
1764                 adev->dm.delayed_hpd_wq = NULL;
1765         }
1766
1767         if (adev->dm.dmub_bo)
1768                 amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
1769                                       &adev->dm.dmub_bo_gpu_addr,
1770                                       &adev->dm.dmub_bo_cpu_addr);
1771
1772         if (adev->dm.hpd_rx_offload_wq) {
1773                 for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
1774                         if (adev->dm.hpd_rx_offload_wq[i].wq) {
1775                                 destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
1776                                 adev->dm.hpd_rx_offload_wq[i].wq = NULL;
1777                         }
1778                 }
1779
1780                 kfree(adev->dm.hpd_rx_offload_wq);
1781                 adev->dm.hpd_rx_offload_wq = NULL;
1782         }
1783
1784         /* DC Destroy TODO: Replace destroy DAL */
1785         if (adev->dm.dc)
1786                 dc_destroy(&adev->dm.dc);
1787         /*
1788          * TODO: pageflip, vlank interrupt
1789          *
1790          * amdgpu_dm_irq_fini(adev);
1791          */
1792
1793         if (adev->dm.cgs_device) {
1794                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
1795                 adev->dm.cgs_device = NULL;
1796         }
1797         if (adev->dm.freesync_module) {
1798                 mod_freesync_destroy(adev->dm.freesync_module);
1799                 adev->dm.freesync_module = NULL;
1800         }
1801
1802         mutex_destroy(&adev->dm.audio_lock);
1803         mutex_destroy(&adev->dm.dc_lock);
1804         mutex_destroy(&adev->dm.dpia_aux_lock);
1805
1806         return;
1807 }
1808
1809 static int load_dmcu_fw(struct amdgpu_device *adev)
1810 {
1811         const char *fw_name_dmcu = NULL;
1812         int r;
1813         const struct dmcu_firmware_header_v1_0 *hdr;
1814
1815         switch(adev->asic_type) {
1816 #if defined(CONFIG_DRM_AMD_DC_SI)
1817         case CHIP_TAHITI:
1818         case CHIP_PITCAIRN:
1819         case CHIP_VERDE:
1820         case CHIP_OLAND:
1821 #endif
1822         case CHIP_BONAIRE:
1823         case CHIP_HAWAII:
1824         case CHIP_KAVERI:
1825         case CHIP_KABINI:
1826         case CHIP_MULLINS:
1827         case CHIP_TONGA:
1828         case CHIP_FIJI:
1829         case CHIP_CARRIZO:
1830         case CHIP_STONEY:
1831         case CHIP_POLARIS11:
1832         case CHIP_POLARIS10:
1833         case CHIP_POLARIS12:
1834         case CHIP_VEGAM:
1835         case CHIP_VEGA10:
1836         case CHIP_VEGA12:
1837         case CHIP_VEGA20:
1838                 return 0;
1839         case CHIP_NAVI12:
1840                 fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
1841                 break;
1842         case CHIP_RAVEN:
1843                 if (ASICREV_IS_PICASSO(adev->external_rev_id))
1844                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1845                 else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
1846                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1847                 else
1848                         return 0;
1849                 break;
1850         default:
1851                 switch (adev->ip_versions[DCE_HWIP][0]) {
1852                 case IP_VERSION(2, 0, 2):
1853                 case IP_VERSION(2, 0, 3):
1854                 case IP_VERSION(2, 0, 0):
1855                 case IP_VERSION(2, 1, 0):
1856                 case IP_VERSION(3, 0, 0):
1857                 case IP_VERSION(3, 0, 2):
1858                 case IP_VERSION(3, 0, 3):
1859                 case IP_VERSION(3, 0, 1):
1860                 case IP_VERSION(3, 1, 2):
1861                 case IP_VERSION(3, 1, 3):
1862                 case IP_VERSION(3, 1, 4):
1863                 case IP_VERSION(3, 1, 5):
1864                 case IP_VERSION(3, 1, 6):
1865                 case IP_VERSION(3, 2, 0):
1866                 case IP_VERSION(3, 2, 1):
1867                         return 0;
1868                 default:
1869                         break;
1870                 }
1871                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1872                 return -EINVAL;
1873         }
1874
1875         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1876                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
1877                 return 0;
1878         }
1879
1880         r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, fw_name_dmcu);
1881         if (r == -ENODEV) {
1882                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
1883                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
1884                 adev->dm.fw_dmcu = NULL;
1885                 return 0;
1886         }
1887         if (r) {
1888                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
1889                         fw_name_dmcu);
1890                 amdgpu_ucode_release(&adev->dm.fw_dmcu);
1891                 return r;
1892         }
1893
1894         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
1895         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
1896         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
1897         adev->firmware.fw_size +=
1898                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1899
1900         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
1901         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
1902         adev->firmware.fw_size +=
1903                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1904
1905         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
1906
1907         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
1908
1909         return 0;
1910 }
1911
1912 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
1913 {
1914         struct amdgpu_device *adev = ctx;
1915
1916         return dm_read_reg(adev->dm.dc->ctx, address);
1917 }
1918
1919 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
1920                                      uint32_t value)
1921 {
1922         struct amdgpu_device *adev = ctx;
1923
1924         return dm_write_reg(adev->dm.dc->ctx, address, value);
1925 }
1926
1927 static int dm_dmub_sw_init(struct amdgpu_device *adev)
1928 {
1929         struct dmub_srv_create_params create_params;
1930         struct dmub_srv_region_params region_params;
1931         struct dmub_srv_region_info region_info;
1932         struct dmub_srv_fb_params fb_params;
1933         struct dmub_srv_fb_info *fb_info;
1934         struct dmub_srv *dmub_srv;
1935         const struct dmcub_firmware_header_v1_0 *hdr;
1936         enum dmub_asic dmub_asic;
1937         enum dmub_status status;
1938         int r;
1939
1940         switch (adev->ip_versions[DCE_HWIP][0]) {
1941         case IP_VERSION(2, 1, 0):
1942                 dmub_asic = DMUB_ASIC_DCN21;
1943                 break;
1944         case IP_VERSION(3, 0, 0):
1945                 dmub_asic = DMUB_ASIC_DCN30;
1946                 break;
1947         case IP_VERSION(3, 0, 1):
1948                 dmub_asic = DMUB_ASIC_DCN301;
1949                 break;
1950         case IP_VERSION(3, 0, 2):
1951                 dmub_asic = DMUB_ASIC_DCN302;
1952                 break;
1953         case IP_VERSION(3, 0, 3):
1954                 dmub_asic = DMUB_ASIC_DCN303;
1955                 break;
1956         case IP_VERSION(3, 1, 2):
1957         case IP_VERSION(3, 1, 3):
1958                 dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
1959                 break;
1960         case IP_VERSION(3, 1, 4):
1961                 dmub_asic = DMUB_ASIC_DCN314;
1962                 break;
1963         case IP_VERSION(3, 1, 5):
1964                 dmub_asic = DMUB_ASIC_DCN315;
1965                 break;
1966         case IP_VERSION(3, 1, 6):
1967                 dmub_asic = DMUB_ASIC_DCN316;
1968                 break;
1969         case IP_VERSION(3, 2, 0):
1970                 dmub_asic = DMUB_ASIC_DCN32;
1971                 break;
1972         case IP_VERSION(3, 2, 1):
1973                 dmub_asic = DMUB_ASIC_DCN321;
1974                 break;
1975         default:
1976                 /* ASIC doesn't support DMUB. */
1977                 return 0;
1978         }
1979
1980         hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
1981         adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
1982
1983         if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
1984                 adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
1985                         AMDGPU_UCODE_ID_DMCUB;
1986                 adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
1987                         adev->dm.dmub_fw;
1988                 adev->firmware.fw_size +=
1989                         ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
1990
1991                 DRM_INFO("Loading DMUB firmware via PSP: version=0x%08X\n",
1992                          adev->dm.dmcub_fw_version);
1993         }
1994
1995
1996         adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
1997         dmub_srv = adev->dm.dmub_srv;
1998
1999         if (!dmub_srv) {
2000                 DRM_ERROR("Failed to allocate DMUB service!\n");
2001                 return -ENOMEM;
2002         }
2003
2004         memset(&create_params, 0, sizeof(create_params));
2005         create_params.user_ctx = adev;
2006         create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2007         create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2008         create_params.asic = dmub_asic;
2009
2010         /* Create the DMUB service. */
2011         status = dmub_srv_create(dmub_srv, &create_params);
2012         if (status != DMUB_STATUS_OK) {
2013                 DRM_ERROR("Error creating DMUB service: %d\n", status);
2014                 return -EINVAL;
2015         }
2016
2017         /* Calculate the size of all the regions for the DMUB service. */
2018         memset(&region_params, 0, sizeof(region_params));
2019
2020         region_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2021                                         PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
2022         region_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2023         region_params.vbios_size = adev->bios_size;
2024         region_params.fw_bss_data = region_params.bss_data_size ?
2025                 adev->dm.dmub_fw->data +
2026                 le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2027                 le32_to_cpu(hdr->inst_const_bytes) : NULL;
2028         region_params.fw_inst_const =
2029                 adev->dm.dmub_fw->data +
2030                 le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2031                 PSP_HEADER_BYTES;
2032
2033         status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2034                                            &region_info);
2035
2036         if (status != DMUB_STATUS_OK) {
2037                 DRM_ERROR("Error calculating DMUB region info: %d\n", status);
2038                 return -EINVAL;
2039         }
2040
2041         /*
2042          * Allocate a framebuffer based on the total size of all the regions.
2043          * TODO: Move this into GART.
2044          */
2045         r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2046                                     AMDGPU_GEM_DOMAIN_VRAM |
2047                                     AMDGPU_GEM_DOMAIN_GTT,
2048                                     &adev->dm.dmub_bo,
2049                                     &adev->dm.dmub_bo_gpu_addr,
2050                                     &adev->dm.dmub_bo_cpu_addr);
2051         if (r)
2052                 return r;
2053
2054         /* Rebase the regions on the framebuffer address. */
2055         memset(&fb_params, 0, sizeof(fb_params));
2056         fb_params.cpu_addr = adev->dm.dmub_bo_cpu_addr;
2057         fb_params.gpu_addr = adev->dm.dmub_bo_gpu_addr;
2058         fb_params.region_info = &region_info;
2059
2060         adev->dm.dmub_fb_info =
2061                 kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2062         fb_info = adev->dm.dmub_fb_info;
2063
2064         if (!fb_info) {
2065                 DRM_ERROR(
2066                         "Failed to allocate framebuffer info for DMUB service!\n");
2067                 return -ENOMEM;
2068         }
2069
2070         status = dmub_srv_calc_fb_info(dmub_srv, &fb_params, fb_info);
2071         if (status != DMUB_STATUS_OK) {
2072                 DRM_ERROR("Error calculating DMUB FB info: %d\n", status);
2073                 return -EINVAL;
2074         }
2075
2076         return 0;
2077 }
2078
2079 static int dm_sw_init(void *handle)
2080 {
2081         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2082         int r;
2083
2084         r = dm_dmub_sw_init(adev);
2085         if (r)
2086                 return r;
2087
2088         return load_dmcu_fw(adev);
2089 }
2090
2091 static int dm_sw_fini(void *handle)
2092 {
2093         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2094
2095         kfree(adev->dm.dmub_fb_info);
2096         adev->dm.dmub_fb_info = NULL;
2097
2098         if (adev->dm.dmub_srv) {
2099                 dmub_srv_destroy(adev->dm.dmub_srv);
2100                 adev->dm.dmub_srv = NULL;
2101         }
2102
2103         amdgpu_ucode_release(&adev->dm.dmub_fw);
2104         amdgpu_ucode_release(&adev->dm.fw_dmcu);
2105
2106         return 0;
2107 }
2108
2109 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2110 {
2111         struct amdgpu_dm_connector *aconnector;
2112         struct drm_connector *connector;
2113         struct drm_connector_list_iter iter;
2114         int ret = 0;
2115
2116         drm_connector_list_iter_begin(dev, &iter);
2117         drm_for_each_connector_iter(connector, &iter) {
2118                 aconnector = to_amdgpu_dm_connector(connector);
2119                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
2120                     aconnector->mst_mgr.aux) {
2121                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
2122                                          aconnector,
2123                                          aconnector->base.base.id);
2124
2125                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2126                         if (ret < 0) {
2127                                 DRM_ERROR("DM_MST: Failed to start MST\n");
2128                                 aconnector->dc_link->type =
2129                                         dc_connection_single;
2130                                 ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2131                                                                      aconnector->dc_link);
2132                                 break;
2133                         }
2134                 }
2135         }
2136         drm_connector_list_iter_end(&iter);
2137
2138         return ret;
2139 }
2140
2141 static int dm_late_init(void *handle)
2142 {
2143         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2144
2145         struct dmcu_iram_parameters params;
2146         unsigned int linear_lut[16];
2147         int i;
2148         struct dmcu *dmcu = NULL;
2149
2150         dmcu = adev->dm.dc->res_pool->dmcu;
2151
2152         for (i = 0; i < 16; i++)
2153                 linear_lut[i] = 0xFFFF * i / 15;
2154
2155         params.set = 0;
2156         params.backlight_ramping_override = false;
2157         params.backlight_ramping_start = 0xCCCC;
2158         params.backlight_ramping_reduction = 0xCCCCCCCC;
2159         params.backlight_lut_array_size = 16;
2160         params.backlight_lut_array = linear_lut;
2161
2162         /* Min backlight level after ABM reduction,  Don't allow below 1%
2163          * 0xFFFF x 0.01 = 0x28F
2164          */
2165         params.min_abm_backlight = 0x28F;
2166         /* In the case where abm is implemented on dmcub,
2167         * dmcu object will be null.
2168         * ABM 2.4 and up are implemented on dmcub.
2169         */
2170         if (dmcu) {
2171                 if (!dmcu_load_iram(dmcu, params))
2172                         return -EINVAL;
2173         } else if (adev->dm.dc->ctx->dmub_srv) {
2174                 struct dc_link *edp_links[MAX_NUM_EDP];
2175                 int edp_num;
2176
2177                 get_edp_links(adev->dm.dc, edp_links, &edp_num);
2178                 for (i = 0; i < edp_num; i++) {
2179                         if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2180                                 return -EINVAL;
2181                 }
2182         }
2183
2184         return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2185 }
2186
2187 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2188 {
2189         struct amdgpu_dm_connector *aconnector;
2190         struct drm_connector *connector;
2191         struct drm_connector_list_iter iter;
2192         struct drm_dp_mst_topology_mgr *mgr;
2193         int ret;
2194         bool need_hotplug = false;
2195
2196         drm_connector_list_iter_begin(dev, &iter);
2197         drm_for_each_connector_iter(connector, &iter) {
2198                 aconnector = to_amdgpu_dm_connector(connector);
2199                 if (aconnector->dc_link->type != dc_connection_mst_branch ||
2200                     aconnector->mst_port)
2201                         continue;
2202
2203                 mgr = &aconnector->mst_mgr;
2204
2205                 if (suspend) {
2206                         drm_dp_mst_topology_mgr_suspend(mgr);
2207                 } else {
2208                         ret = drm_dp_mst_topology_mgr_resume(mgr, true);
2209                         if (ret < 0) {
2210                                 dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2211                                         aconnector->dc_link);
2212                                 need_hotplug = true;
2213                         }
2214                 }
2215         }
2216         drm_connector_list_iter_end(&iter);
2217
2218         if (need_hotplug)
2219                 drm_kms_helper_hotplug_event(dev);
2220 }
2221
2222 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2223 {
2224         int ret = 0;
2225
2226         /* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2227          * on window driver dc implementation.
2228          * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2229          * should be passed to smu during boot up and resume from s3.
2230          * boot up: dc calculate dcn watermark clock settings within dc_create,
2231          * dcn20_resource_construct
2232          * then call pplib functions below to pass the settings to smu:
2233          * smu_set_watermarks_for_clock_ranges
2234          * smu_set_watermarks_table
2235          * navi10_set_watermarks_table
2236          * smu_write_watermarks_table
2237          *
2238          * For Renoir, clock settings of dcn watermark are also fixed values.
2239          * dc has implemented different flow for window driver:
2240          * dc_hardware_init / dc_set_power_state
2241          * dcn10_init_hw
2242          * notify_wm_ranges
2243          * set_wm_ranges
2244          * -- Linux
2245          * smu_set_watermarks_for_clock_ranges
2246          * renoir_set_watermarks_table
2247          * smu_write_watermarks_table
2248          *
2249          * For Linux,
2250          * dc_hardware_init -> amdgpu_dm_init
2251          * dc_set_power_state --> dm_resume
2252          *
2253          * therefore, this function apply to navi10/12/14 but not Renoir
2254          * *
2255          */
2256         switch (adev->ip_versions[DCE_HWIP][0]) {
2257         case IP_VERSION(2, 0, 2):
2258         case IP_VERSION(2, 0, 0):
2259                 break;
2260         default:
2261                 return 0;
2262         }
2263
2264         ret = amdgpu_dpm_write_watermarks_table(adev);
2265         if (ret) {
2266                 DRM_ERROR("Failed to update WMTABLE!\n");
2267                 return ret;
2268         }
2269
2270         return 0;
2271 }
2272
2273 /**
2274  * dm_hw_init() - Initialize DC device
2275  * @handle: The base driver device containing the amdgpu_dm device.
2276  *
2277  * Initialize the &struct amdgpu_display_manager device. This involves calling
2278  * the initializers of each DM component, then populating the struct with them.
2279  *
2280  * Although the function implies hardware initialization, both hardware and
2281  * software are initialized here. Splitting them out to their relevant init
2282  * hooks is a future TODO item.
2283  *
2284  * Some notable things that are initialized here:
2285  *
2286  * - Display Core, both software and hardware
2287  * - DC modules that we need (freesync and color management)
2288  * - DRM software states
2289  * - Interrupt sources and handlers
2290  * - Vblank support
2291  * - Debug FS entries, if enabled
2292  */
2293 static int dm_hw_init(void *handle)
2294 {
2295         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2296         /* Create DAL display manager */
2297         amdgpu_dm_init(adev);
2298         amdgpu_dm_hpd_init(adev);
2299
2300         return 0;
2301 }
2302
2303 /**
2304  * dm_hw_fini() - Teardown DC device
2305  * @handle: The base driver device containing the amdgpu_dm device.
2306  *
2307  * Teardown components within &struct amdgpu_display_manager that require
2308  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
2309  * were loaded. Also flush IRQ workqueues and disable them.
2310  */
2311 static int dm_hw_fini(void *handle)
2312 {
2313         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2314
2315         amdgpu_dm_hpd_fini(adev);
2316
2317         amdgpu_dm_irq_fini(adev);
2318         amdgpu_dm_fini(adev);
2319         return 0;
2320 }
2321
2322
2323 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
2324                                  struct dc_state *state, bool enable)
2325 {
2326         enum dc_irq_source irq_source;
2327         struct amdgpu_crtc *acrtc;
2328         int rc = -EBUSY;
2329         int i = 0;
2330
2331         for (i = 0; i < state->stream_count; i++) {
2332                 acrtc = get_crtc_by_otg_inst(
2333                                 adev, state->stream_status[i].primary_otg_inst);
2334
2335                 if (acrtc && state->stream_status[i].plane_count != 0) {
2336                         irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
2337                         rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2338                         DRM_DEBUG_VBL("crtc %d - vupdate irq %sabling: r=%d\n",
2339                                       acrtc->crtc_id, enable ? "en" : "dis", rc);
2340                         if (rc)
2341                                 DRM_WARN("Failed to %s pflip interrupts\n",
2342                                          enable ? "enable" : "disable");
2343
2344                         if (enable) {
2345                                 rc = dm_enable_vblank(&acrtc->base);
2346                                 if (rc)
2347                                         DRM_WARN("Failed to enable vblank interrupts\n");
2348                         } else {
2349                                 dm_disable_vblank(&acrtc->base);
2350                         }
2351
2352                 }
2353         }
2354
2355 }
2356
2357 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
2358 {
2359         struct dc_state *context = NULL;
2360         enum dc_status res = DC_ERROR_UNEXPECTED;
2361         int i;
2362         struct dc_stream_state *del_streams[MAX_PIPES];
2363         int del_streams_count = 0;
2364
2365         memset(del_streams, 0, sizeof(del_streams));
2366
2367         context = dc_create_state(dc);
2368         if (context == NULL)
2369                 goto context_alloc_fail;
2370
2371         dc_resource_state_copy_construct_current(dc, context);
2372
2373         /* First remove from context all streams */
2374         for (i = 0; i < context->stream_count; i++) {
2375                 struct dc_stream_state *stream = context->streams[i];
2376
2377                 del_streams[del_streams_count++] = stream;
2378         }
2379
2380         /* Remove all planes for removed streams and then remove the streams */
2381         for (i = 0; i < del_streams_count; i++) {
2382                 if (!dc_rem_all_planes_for_stream(dc, del_streams[i], context)) {
2383                         res = DC_FAIL_DETACH_SURFACES;
2384                         goto fail;
2385                 }
2386
2387                 res = dc_remove_stream_from_ctx(dc, context, del_streams[i]);
2388                 if (res != DC_OK)
2389                         goto fail;
2390         }
2391
2392         res = dc_commit_state(dc, context);
2393
2394 fail:
2395         dc_release_state(context);
2396
2397 context_alloc_fail:
2398         return res;
2399 }
2400
2401 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
2402 {
2403         int i;
2404
2405         if (dm->hpd_rx_offload_wq) {
2406                 for (i = 0; i < dm->dc->caps.max_links; i++)
2407                         flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
2408         }
2409 }
2410
2411 static int dm_suspend(void *handle)
2412 {
2413         struct amdgpu_device *adev = handle;
2414         struct amdgpu_display_manager *dm = &adev->dm;
2415         int ret = 0;
2416
2417         if (amdgpu_in_reset(adev)) {
2418                 mutex_lock(&dm->dc_lock);
2419
2420                 dc_allow_idle_optimizations(adev->dm.dc, false);
2421
2422                 dm->cached_dc_state = dc_copy_state(dm->dc->current_state);
2423
2424                 dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
2425
2426                 amdgpu_dm_commit_zero_streams(dm->dc);
2427
2428                 amdgpu_dm_irq_suspend(adev);
2429
2430                 hpd_rx_irq_work_suspend(dm);
2431
2432                 return ret;
2433         }
2434
2435         WARN_ON(adev->dm.cached_state);
2436         adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
2437
2438         s3_handle_mst(adev_to_drm(adev), true);
2439
2440         amdgpu_dm_irq_suspend(adev);
2441
2442         hpd_rx_irq_work_suspend(dm);
2443
2444         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
2445
2446         return 0;
2447 }
2448
2449 struct amdgpu_dm_connector *
2450 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
2451                                              struct drm_crtc *crtc)
2452 {
2453         u32 i;
2454         struct drm_connector_state *new_con_state;
2455         struct drm_connector *connector;
2456         struct drm_crtc *crtc_from_state;
2457
2458         for_each_new_connector_in_state(state, connector, new_con_state, i) {
2459                 crtc_from_state = new_con_state->crtc;
2460
2461                 if (crtc_from_state == crtc)
2462                         return to_amdgpu_dm_connector(connector);
2463         }
2464
2465         return NULL;
2466 }
2467
2468 static void emulated_link_detect(struct dc_link *link)
2469 {
2470         struct dc_sink_init_data sink_init_data = { 0 };
2471         struct display_sink_capability sink_caps = { 0 };
2472         enum dc_edid_status edid_status;
2473         struct dc_context *dc_ctx = link->ctx;
2474         struct dc_sink *sink = NULL;
2475         struct dc_sink *prev_sink = NULL;
2476
2477         link->type = dc_connection_none;
2478         prev_sink = link->local_sink;
2479
2480         if (prev_sink)
2481                 dc_sink_release(prev_sink);
2482
2483         switch (link->connector_signal) {
2484         case SIGNAL_TYPE_HDMI_TYPE_A: {
2485                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2486                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
2487                 break;
2488         }
2489
2490         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
2491                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2492                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
2493                 break;
2494         }
2495
2496         case SIGNAL_TYPE_DVI_DUAL_LINK: {
2497                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2498                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
2499                 break;
2500         }
2501
2502         case SIGNAL_TYPE_LVDS: {
2503                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2504                 sink_caps.signal = SIGNAL_TYPE_LVDS;
2505                 break;
2506         }
2507
2508         case SIGNAL_TYPE_EDP: {
2509                 sink_caps.transaction_type =
2510                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2511                 sink_caps.signal = SIGNAL_TYPE_EDP;
2512                 break;
2513         }
2514
2515         case SIGNAL_TYPE_DISPLAY_PORT: {
2516                 sink_caps.transaction_type =
2517                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2518                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
2519                 break;
2520         }
2521
2522         default:
2523                 DC_ERROR("Invalid connector type! signal:%d\n",
2524                         link->connector_signal);
2525                 return;
2526         }
2527
2528         sink_init_data.link = link;
2529         sink_init_data.sink_signal = sink_caps.signal;
2530
2531         sink = dc_sink_create(&sink_init_data);
2532         if (!sink) {
2533                 DC_ERROR("Failed to create sink!\n");
2534                 return;
2535         }
2536
2537         /* dc_sink_create returns a new reference */
2538         link->local_sink = sink;
2539
2540         edid_status = dm_helpers_read_local_edid(
2541                         link->ctx,
2542                         link,
2543                         sink);
2544
2545         if (edid_status != EDID_OK)
2546                 DC_ERROR("Failed to read EDID");
2547
2548 }
2549
2550 static void dm_gpureset_commit_state(struct dc_state *dc_state,
2551                                      struct amdgpu_display_manager *dm)
2552 {
2553         struct {
2554                 struct dc_surface_update surface_updates[MAX_SURFACES];
2555                 struct dc_plane_info plane_infos[MAX_SURFACES];
2556                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
2557                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
2558                 struct dc_stream_update stream_update;
2559         } * bundle;
2560         int k, m;
2561
2562         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
2563
2564         if (!bundle) {
2565                 dm_error("Failed to allocate update bundle\n");
2566                 goto cleanup;
2567         }
2568
2569         for (k = 0; k < dc_state->stream_count; k++) {
2570                 bundle->stream_update.stream = dc_state->streams[k];
2571
2572                 for (m = 0; m < dc_state->stream_status->plane_count; m++) {
2573                         bundle->surface_updates[m].surface =
2574                                 dc_state->stream_status->plane_states[m];
2575                         bundle->surface_updates[m].surface->force_full_update =
2576                                 true;
2577                 }
2578                 dc_commit_updates_for_stream(
2579                         dm->dc, bundle->surface_updates,
2580                         dc_state->stream_status->plane_count,
2581                         dc_state->streams[k], &bundle->stream_update, dc_state);
2582         }
2583
2584 cleanup:
2585         kfree(bundle);
2586
2587         return;
2588 }
2589
2590 static int dm_resume(void *handle)
2591 {
2592         struct amdgpu_device *adev = handle;
2593         struct drm_device *ddev = adev_to_drm(adev);
2594         struct amdgpu_display_manager *dm = &adev->dm;
2595         struct amdgpu_dm_connector *aconnector;
2596         struct drm_connector *connector;
2597         struct drm_connector_list_iter iter;
2598         struct drm_crtc *crtc;
2599         struct drm_crtc_state *new_crtc_state;
2600         struct dm_crtc_state *dm_new_crtc_state;
2601         struct drm_plane *plane;
2602         struct drm_plane_state *new_plane_state;
2603         struct dm_plane_state *dm_new_plane_state;
2604         struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
2605         enum dc_connection_type new_connection_type = dc_connection_none;
2606         struct dc_state *dc_state;
2607         int i, r, j;
2608
2609         if (amdgpu_in_reset(adev)) {
2610                 dc_state = dm->cached_dc_state;
2611
2612                 /*
2613                  * The dc->current_state is backed up into dm->cached_dc_state
2614                  * before we commit 0 streams.
2615                  *
2616                  * DC will clear link encoder assignments on the real state
2617                  * but the changes won't propagate over to the copy we made
2618                  * before the 0 streams commit.
2619                  *
2620                  * DC expects that link encoder assignments are *not* valid
2621                  * when committing a state, so as a workaround we can copy
2622                  * off of the current state.
2623                  *
2624                  * We lose the previous assignments, but we had already
2625                  * commit 0 streams anyway.
2626                  */
2627                 link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
2628
2629                 r = dm_dmub_hw_init(adev);
2630                 if (r)
2631                         DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
2632
2633                 dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2634                 dc_resume(dm->dc);
2635
2636                 amdgpu_dm_irq_resume_early(adev);
2637
2638                 for (i = 0; i < dc_state->stream_count; i++) {
2639                         dc_state->streams[i]->mode_changed = true;
2640                         for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
2641                                 dc_state->stream_status[i].plane_states[j]->update_flags.raw
2642                                         = 0xffffffff;
2643                         }
2644                 }
2645
2646                 if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2647                         amdgpu_dm_outbox_init(adev);
2648                         dc_enable_dmub_outbox(adev->dm.dc);
2649                 }
2650
2651                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
2652
2653                 dm_gpureset_commit_state(dm->cached_dc_state, dm);
2654
2655                 dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
2656
2657                 dc_release_state(dm->cached_dc_state);
2658                 dm->cached_dc_state = NULL;
2659
2660                 amdgpu_dm_irq_resume_late(adev);
2661
2662                 mutex_unlock(&dm->dc_lock);
2663
2664                 return 0;
2665         }
2666         /* Recreate dc_state - DC invalidates it when setting power state to S3. */
2667         dc_release_state(dm_state->context);
2668         dm_state->context = dc_create_state(dm->dc);
2669         /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
2670         dc_resource_state_construct(dm->dc, dm_state->context);
2671
2672         /* Before powering on DC we need to re-initialize DMUB. */
2673         dm_dmub_hw_resume(adev);
2674
2675         /* Re-enable outbox interrupts for DPIA. */
2676         if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2677                 amdgpu_dm_outbox_init(adev);
2678                 dc_enable_dmub_outbox(adev->dm.dc);
2679         }
2680
2681         /* power on hardware */
2682         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2683
2684         /* program HPD filter */
2685         dc_resume(dm->dc);
2686
2687         /*
2688          * early enable HPD Rx IRQ, should be done before set mode as short
2689          * pulse interrupts are used for MST
2690          */
2691         amdgpu_dm_irq_resume_early(adev);
2692
2693         /* On resume we need to rewrite the MSTM control bits to enable MST*/
2694         s3_handle_mst(ddev, false);
2695
2696         /* Do detection*/
2697         drm_connector_list_iter_begin(ddev, &iter);
2698         drm_for_each_connector_iter(connector, &iter) {
2699                 aconnector = to_amdgpu_dm_connector(connector);
2700
2701                 if (!aconnector->dc_link)
2702                         continue;
2703
2704                 /*
2705                  * this is the case when traversing through already created
2706                  * MST connectors, should be skipped
2707                  */
2708                 if (aconnector->dc_link->type == dc_connection_mst_branch)
2709                         continue;
2710
2711                 mutex_lock(&aconnector->hpd_lock);
2712                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
2713                         DRM_ERROR("KMS: Failed to detect connector\n");
2714
2715                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
2716                         emulated_link_detect(aconnector->dc_link);
2717                 } else {
2718                         mutex_lock(&dm->dc_lock);
2719                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
2720                         mutex_unlock(&dm->dc_lock);
2721                 }
2722
2723                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2724                         aconnector->fake_enable = false;
2725
2726                 if (aconnector->dc_sink)
2727                         dc_sink_release(aconnector->dc_sink);
2728                 aconnector->dc_sink = NULL;
2729                 amdgpu_dm_update_connector_after_detect(aconnector);
2730                 mutex_unlock(&aconnector->hpd_lock);
2731         }
2732         drm_connector_list_iter_end(&iter);
2733
2734         /* Force mode set in atomic commit */
2735         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
2736                 new_crtc_state->active_changed = true;
2737
2738         /*
2739          * atomic_check is expected to create the dc states. We need to release
2740          * them here, since they were duplicated as part of the suspend
2741          * procedure.
2742          */
2743         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
2744                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
2745                 if (dm_new_crtc_state->stream) {
2746                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
2747                         dc_stream_release(dm_new_crtc_state->stream);
2748                         dm_new_crtc_state->stream = NULL;
2749                 }
2750         }
2751
2752         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
2753                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
2754                 if (dm_new_plane_state->dc_state) {
2755                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
2756                         dc_plane_state_release(dm_new_plane_state->dc_state);
2757                         dm_new_plane_state->dc_state = NULL;
2758                 }
2759         }
2760
2761         drm_atomic_helper_resume(ddev, dm->cached_state);
2762
2763         dm->cached_state = NULL;
2764
2765         amdgpu_dm_irq_resume_late(adev);
2766
2767         amdgpu_dm_smu_write_watermarks_table(adev);
2768
2769         return 0;
2770 }
2771
2772 /**
2773  * DOC: DM Lifecycle
2774  *
2775  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
2776  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
2777  * the base driver's device list to be initialized and torn down accordingly.
2778  *
2779  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
2780  */
2781
2782 static const struct amd_ip_funcs amdgpu_dm_funcs = {
2783         .name = "dm",
2784         .early_init = dm_early_init,
2785         .late_init = dm_late_init,
2786         .sw_init = dm_sw_init,
2787         .sw_fini = dm_sw_fini,
2788         .early_fini = amdgpu_dm_early_fini,
2789         .hw_init = dm_hw_init,
2790         .hw_fini = dm_hw_fini,
2791         .suspend = dm_suspend,
2792         .resume = dm_resume,
2793         .is_idle = dm_is_idle,
2794         .wait_for_idle = dm_wait_for_idle,
2795         .check_soft_reset = dm_check_soft_reset,
2796         .soft_reset = dm_soft_reset,
2797         .set_clockgating_state = dm_set_clockgating_state,
2798         .set_powergating_state = dm_set_powergating_state,
2799 };
2800
2801 const struct amdgpu_ip_block_version dm_ip_block =
2802 {
2803         .type = AMD_IP_BLOCK_TYPE_DCE,
2804         .major = 1,
2805         .minor = 0,
2806         .rev = 0,
2807         .funcs = &amdgpu_dm_funcs,
2808 };
2809
2810
2811 /**
2812  * DOC: atomic
2813  *
2814  * *WIP*
2815  */
2816
2817 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
2818         .fb_create = amdgpu_display_user_framebuffer_create,
2819         .get_format_info = amd_get_format_info,
2820         .atomic_check = amdgpu_dm_atomic_check,
2821         .atomic_commit = drm_atomic_helper_commit,
2822 };
2823
2824 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2825         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2826         .atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
2827 };
2828
2829 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
2830 {
2831         struct amdgpu_dm_backlight_caps *caps;
2832         struct amdgpu_display_manager *dm;
2833         struct drm_connector *conn_base;
2834         struct amdgpu_device *adev;
2835         struct dc_link *link = NULL;
2836         struct drm_luminance_range_info *luminance_range;
2837         int i;
2838
2839         if (!aconnector || !aconnector->dc_link)
2840                 return;
2841
2842         link = aconnector->dc_link;
2843         if (link->connector_signal != SIGNAL_TYPE_EDP)
2844                 return;
2845
2846         conn_base = &aconnector->base;
2847         adev = drm_to_adev(conn_base->dev);
2848         dm = &adev->dm;
2849         for (i = 0; i < dm->num_of_edps; i++) {
2850                 if (link == dm->backlight_link[i])
2851                         break;
2852         }
2853         if (i >= dm->num_of_edps)
2854                 return;
2855         caps = &dm->backlight_caps[i];
2856         caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
2857         caps->aux_support = false;
2858
2859         if (caps->ext_caps->bits.oled == 1 /*||
2860             caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
2861             caps->ext_caps->bits.hdr_aux_backlight_control == 1*/)
2862                 caps->aux_support = true;
2863
2864         if (amdgpu_backlight == 0)
2865                 caps->aux_support = false;
2866         else if (amdgpu_backlight == 1)
2867                 caps->aux_support = true;
2868
2869         luminance_range = &conn_base->display_info.luminance_range;
2870         caps->aux_min_input_signal = luminance_range->min_luminance;
2871         caps->aux_max_input_signal = luminance_range->max_luminance;
2872 }
2873
2874 void amdgpu_dm_update_connector_after_detect(
2875                 struct amdgpu_dm_connector *aconnector)
2876 {
2877         struct drm_connector *connector = &aconnector->base;
2878         struct drm_device *dev = connector->dev;
2879         struct dc_sink *sink;
2880
2881         /* MST handled by drm_mst framework */
2882         if (aconnector->mst_mgr.mst_state == true)
2883                 return;
2884
2885         sink = aconnector->dc_link->local_sink;
2886         if (sink)
2887                 dc_sink_retain(sink);
2888
2889         /*
2890          * Edid mgmt connector gets first update only in mode_valid hook and then
2891          * the connector sink is set to either fake or physical sink depends on link status.
2892          * Skip if already done during boot.
2893          */
2894         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
2895                         && aconnector->dc_em_sink) {
2896
2897                 /*
2898                  * For S3 resume with headless use eml_sink to fake stream
2899                  * because on resume connector->sink is set to NULL
2900                  */
2901                 mutex_lock(&dev->mode_config.mutex);
2902
2903                 if (sink) {
2904                         if (aconnector->dc_sink) {
2905                                 amdgpu_dm_update_freesync_caps(connector, NULL);
2906                                 /*
2907                                  * retain and release below are used to
2908                                  * bump up refcount for sink because the link doesn't point
2909                                  * to it anymore after disconnect, so on next crtc to connector
2910                                  * reshuffle by UMD we will get into unwanted dc_sink release
2911                                  */
2912                                 dc_sink_release(aconnector->dc_sink);
2913                         }
2914                         aconnector->dc_sink = sink;
2915                         dc_sink_retain(aconnector->dc_sink);
2916                         amdgpu_dm_update_freesync_caps(connector,
2917                                         aconnector->edid);
2918                 } else {
2919                         amdgpu_dm_update_freesync_caps(connector, NULL);
2920                         if (!aconnector->dc_sink) {
2921                                 aconnector->dc_sink = aconnector->dc_em_sink;
2922                                 dc_sink_retain(aconnector->dc_sink);
2923                         }
2924                 }
2925
2926                 mutex_unlock(&dev->mode_config.mutex);
2927
2928                 if (sink)
2929                         dc_sink_release(sink);
2930                 return;
2931         }
2932
2933         /*
2934          * TODO: temporary guard to look for proper fix
2935          * if this sink is MST sink, we should not do anything
2936          */
2937         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
2938                 dc_sink_release(sink);
2939                 return;
2940         }
2941
2942         if (aconnector->dc_sink == sink) {
2943                 /*
2944                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
2945                  * Do nothing!!
2946                  */
2947                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
2948                                 aconnector->connector_id);
2949                 if (sink)
2950                         dc_sink_release(sink);
2951                 return;
2952         }
2953
2954         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
2955                 aconnector->connector_id, aconnector->dc_sink, sink);
2956
2957         mutex_lock(&dev->mode_config.mutex);
2958
2959         /*
2960          * 1. Update status of the drm connector
2961          * 2. Send an event and let userspace tell us what to do
2962          */
2963         if (sink) {
2964                 /*
2965                  * TODO: check if we still need the S3 mode update workaround.
2966                  * If yes, put it here.
2967                  */
2968                 if (aconnector->dc_sink) {
2969                         amdgpu_dm_update_freesync_caps(connector, NULL);
2970                         dc_sink_release(aconnector->dc_sink);
2971                 }
2972
2973                 aconnector->dc_sink = sink;
2974                 dc_sink_retain(aconnector->dc_sink);
2975                 if (sink->dc_edid.length == 0) {
2976                         aconnector->edid = NULL;
2977                         if (aconnector->dc_link->aux_mode) {
2978                                 drm_dp_cec_unset_edid(
2979                                         &aconnector->dm_dp_aux.aux);
2980                         }
2981                 } else {
2982                         aconnector->edid =
2983                                 (struct edid *)sink->dc_edid.raw_edid;
2984
2985                         if (aconnector->dc_link->aux_mode)
2986                                 drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
2987                                                     aconnector->edid);
2988                 }
2989
2990                 drm_connector_update_edid_property(connector, aconnector->edid);
2991                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
2992                 update_connector_ext_caps(aconnector);
2993         } else {
2994                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
2995                 amdgpu_dm_update_freesync_caps(connector, NULL);
2996                 drm_connector_update_edid_property(connector, NULL);
2997                 aconnector->num_modes = 0;
2998                 dc_sink_release(aconnector->dc_sink);
2999                 aconnector->dc_sink = NULL;
3000                 aconnector->edid = NULL;
3001 #ifdef CONFIG_DRM_AMD_DC_HDCP
3002                 /* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3003                 if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3004                         connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3005 #endif
3006         }
3007
3008         mutex_unlock(&dev->mode_config.mutex);
3009
3010         update_subconnector_property(aconnector);
3011
3012         if (sink)
3013                 dc_sink_release(sink);
3014 }
3015
3016 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3017 {
3018         struct drm_connector *connector = &aconnector->base;
3019         struct drm_device *dev = connector->dev;
3020         enum dc_connection_type new_connection_type = dc_connection_none;
3021         struct amdgpu_device *adev = drm_to_adev(dev);
3022 #ifdef CONFIG_DRM_AMD_DC_HDCP
3023         struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3024 #endif
3025         bool ret = false;
3026
3027         if (adev->dm.disable_hpd_irq)
3028                 return;
3029
3030         /*
3031          * In case of failure or MST no need to update connector status or notify the OS
3032          * since (for MST case) MST does this in its own context.
3033          */
3034         mutex_lock(&aconnector->hpd_lock);
3035
3036 #ifdef CONFIG_DRM_AMD_DC_HDCP
3037         if (adev->dm.hdcp_workqueue) {
3038                 hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3039                 dm_con_state->update_hdcp = true;
3040         }
3041 #endif
3042         if (aconnector->fake_enable)
3043                 aconnector->fake_enable = false;
3044
3045         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
3046                 DRM_ERROR("KMS: Failed to detect connector\n");
3047
3048         if (aconnector->base.force && new_connection_type == dc_connection_none) {
3049                 emulated_link_detect(aconnector->dc_link);
3050
3051                 drm_modeset_lock_all(dev);
3052                 dm_restore_drm_connector_state(dev, connector);
3053                 drm_modeset_unlock_all(dev);
3054
3055                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3056                         drm_kms_helper_connector_hotplug_event(connector);
3057         } else {
3058                 mutex_lock(&adev->dm.dc_lock);
3059                 ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3060                 mutex_unlock(&adev->dm.dc_lock);
3061                 if (ret) {
3062                         amdgpu_dm_update_connector_after_detect(aconnector);
3063
3064                         drm_modeset_lock_all(dev);
3065                         dm_restore_drm_connector_state(dev, connector);
3066                         drm_modeset_unlock_all(dev);
3067
3068                         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3069                                 drm_kms_helper_connector_hotplug_event(connector);
3070                 }
3071         }
3072         mutex_unlock(&aconnector->hpd_lock);
3073
3074 }
3075
3076 static void handle_hpd_irq(void *param)
3077 {
3078         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3079
3080         handle_hpd_irq_helper(aconnector);
3081
3082 }
3083
3084 static void dm_handle_mst_sideband_msg(struct amdgpu_dm_connector *aconnector)
3085 {
3086         u8 esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
3087         u8 dret;
3088         bool new_irq_handled = false;
3089         int dpcd_addr;
3090         int dpcd_bytes_to_read;
3091
3092         const int max_process_count = 30;
3093         int process_count = 0;
3094
3095         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
3096
3097         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
3098                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
3099                 /* DPCD 0x200 - 0x201 for downstream IRQ */
3100                 dpcd_addr = DP_SINK_COUNT;
3101         } else {
3102                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
3103                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
3104                 dpcd_addr = DP_SINK_COUNT_ESI;
3105         }
3106
3107         dret = drm_dp_dpcd_read(
3108                 &aconnector->dm_dp_aux.aux,
3109                 dpcd_addr,
3110                 esi,
3111                 dpcd_bytes_to_read);
3112
3113         while (dret == dpcd_bytes_to_read &&
3114                 process_count < max_process_count) {
3115                 u8 retry;
3116                 dret = 0;
3117
3118                 process_count++;
3119
3120                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
3121                 /* handle HPD short pulse irq */
3122                 if (aconnector->mst_mgr.mst_state)
3123                         drm_dp_mst_hpd_irq(
3124                                 &aconnector->mst_mgr,
3125                                 esi,
3126                                 &new_irq_handled);
3127
3128                 if (new_irq_handled) {
3129                         /* ACK at DPCD to notify down stream */
3130                         const int ack_dpcd_bytes_to_write =
3131                                 dpcd_bytes_to_read - 1;
3132
3133                         for (retry = 0; retry < 3; retry++) {
3134                                 u8 wret;
3135
3136                                 wret = drm_dp_dpcd_write(
3137                                         &aconnector->dm_dp_aux.aux,
3138                                         dpcd_addr + 1,
3139                                         &esi[1],
3140                                         ack_dpcd_bytes_to_write);
3141                                 if (wret == ack_dpcd_bytes_to_write)
3142                                         break;
3143                         }
3144
3145                         /* check if there is new irq to be handled */
3146                         dret = drm_dp_dpcd_read(
3147                                 &aconnector->dm_dp_aux.aux,
3148                                 dpcd_addr,
3149                                 esi,
3150                                 dpcd_bytes_to_read);
3151
3152                         new_irq_handled = false;
3153                 } else {
3154                         break;
3155                 }
3156         }
3157
3158         if (process_count == max_process_count)
3159                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
3160 }
3161
3162 static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
3163                                                         union hpd_irq_data hpd_irq_data)
3164 {
3165         struct hpd_rx_irq_offload_work *offload_work =
3166                                 kzalloc(sizeof(*offload_work), GFP_KERNEL);
3167
3168         if (!offload_work) {
3169                 DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
3170                 return;
3171         }
3172
3173         INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3174         offload_work->data = hpd_irq_data;
3175         offload_work->offload_wq = offload_wq;
3176
3177         queue_work(offload_wq->wq, &offload_work->work);
3178         DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3179 }
3180
3181 static void handle_hpd_rx_irq(void *param)
3182 {
3183         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3184         struct drm_connector *connector = &aconnector->base;
3185         struct drm_device *dev = connector->dev;
3186         struct dc_link *dc_link = aconnector->dc_link;
3187         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3188         bool result = false;
3189         enum dc_connection_type new_connection_type = dc_connection_none;
3190         struct amdgpu_device *adev = drm_to_adev(dev);
3191         union hpd_irq_data hpd_irq_data;
3192         bool link_loss = false;
3193         bool has_left_work = false;
3194         int idx = aconnector->base.index;
3195         struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3196
3197         memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3198
3199         if (adev->dm.disable_hpd_irq)
3200                 return;
3201
3202         /*
3203          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3204          * conflict, after implement i2c helper, this mutex should be
3205          * retired.
3206          */
3207         mutex_lock(&aconnector->hpd_lock);
3208
3209         result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3210                                                 &link_loss, true, &has_left_work);
3211
3212         if (!has_left_work)
3213                 goto out;
3214
3215         if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3216                 schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3217                 goto out;
3218         }
3219
3220         if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3221                 if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3222                         hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3223                         dm_handle_mst_sideband_msg(aconnector);
3224                         goto out;
3225                 }
3226
3227                 if (link_loss) {
3228                         bool skip = false;
3229
3230                         spin_lock(&offload_wq->offload_lock);
3231                         skip = offload_wq->is_handling_link_loss;
3232
3233                         if (!skip)
3234                                 offload_wq->is_handling_link_loss = true;
3235
3236                         spin_unlock(&offload_wq->offload_lock);
3237
3238                         if (!skip)
3239                                 schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3240
3241                         goto out;
3242                 }
3243         }
3244
3245 out:
3246         if (result && !is_mst_root_connector) {
3247                 /* Downstream Port status changed. */
3248                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
3249                         DRM_ERROR("KMS: Failed to detect connector\n");
3250
3251                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
3252                         emulated_link_detect(dc_link);
3253
3254                         if (aconnector->fake_enable)
3255                                 aconnector->fake_enable = false;
3256
3257                         amdgpu_dm_update_connector_after_detect(aconnector);
3258
3259
3260                         drm_modeset_lock_all(dev);
3261                         dm_restore_drm_connector_state(dev, connector);
3262                         drm_modeset_unlock_all(dev);
3263
3264                         drm_kms_helper_connector_hotplug_event(connector);
3265                 } else {
3266                         bool ret = false;
3267
3268                         mutex_lock(&adev->dm.dc_lock);
3269                         ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
3270                         mutex_unlock(&adev->dm.dc_lock);
3271
3272                         if (ret) {
3273                                 if (aconnector->fake_enable)
3274                                         aconnector->fake_enable = false;
3275
3276                                 amdgpu_dm_update_connector_after_detect(aconnector);
3277
3278                                 drm_modeset_lock_all(dev);
3279                                 dm_restore_drm_connector_state(dev, connector);
3280                                 drm_modeset_unlock_all(dev);
3281
3282                                 drm_kms_helper_connector_hotplug_event(connector);
3283                         }
3284                 }
3285         }
3286 #ifdef CONFIG_DRM_AMD_DC_HDCP
3287         if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
3288                 if (adev->dm.hdcp_workqueue)
3289                         hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
3290         }
3291 #endif
3292
3293         if (dc_link->type != dc_connection_mst_branch)
3294                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
3295
3296         mutex_unlock(&aconnector->hpd_lock);
3297 }
3298
3299 static void register_hpd_handlers(struct amdgpu_device *adev)
3300 {
3301         struct drm_device *dev = adev_to_drm(adev);
3302         struct drm_connector *connector;
3303         struct amdgpu_dm_connector *aconnector;
3304         const struct dc_link *dc_link;
3305         struct dc_interrupt_params int_params = {0};
3306
3307         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3308         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3309
3310         list_for_each_entry(connector,
3311                         &dev->mode_config.connector_list, head) {
3312
3313                 aconnector = to_amdgpu_dm_connector(connector);
3314                 dc_link = aconnector->dc_link;
3315
3316                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
3317                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3318                         int_params.irq_source = dc_link->irq_source_hpd;
3319
3320                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
3321                                         handle_hpd_irq,
3322                                         (void *) aconnector);
3323                 }
3324
3325                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
3326
3327                         /* Also register for DP short pulse (hpd_rx). */
3328                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3329                         int_params.irq_source = dc_link->irq_source_hpd_rx;
3330
3331                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
3332                                         handle_hpd_rx_irq,
3333                                         (void *) aconnector);
3334
3335                         if (adev->dm.hpd_rx_offload_wq)
3336                                 adev->dm.hpd_rx_offload_wq[connector->index].aconnector =
3337                                         aconnector;
3338                 }
3339         }
3340 }
3341
3342 #if defined(CONFIG_DRM_AMD_DC_SI)
3343 /* Register IRQ sources and initialize IRQ callbacks */
3344 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
3345 {
3346         struct dc *dc = adev->dm.dc;
3347         struct common_irq_params *c_irq_params;
3348         struct dc_interrupt_params int_params = {0};
3349         int r;
3350         int i;
3351         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3352
3353         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3354         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3355
3356         /*
3357          * Actions of amdgpu_irq_add_id():
3358          * 1. Register a set() function with base driver.
3359          *    Base driver will call set() function to enable/disable an
3360          *    interrupt in DC hardware.
3361          * 2. Register amdgpu_dm_irq_handler().
3362          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3363          *    coming from DC hardware.
3364          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3365          *    for acknowledging and handling. */
3366
3367         /* Use VBLANK interrupt */
3368         for (i = 0; i < adev->mode_info.num_crtc; i++) {
3369                 r = amdgpu_irq_add_id(adev, client_id, i+1 , &adev->crtc_irq);
3370                 if (r) {
3371                         DRM_ERROR("Failed to add crtc irq id!\n");
3372                         return r;
3373                 }
3374
3375                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3376                 int_params.irq_source =
3377                         dc_interrupt_to_irq_source(dc, i+1 , 0);
3378
3379                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3380
3381                 c_irq_params->adev = adev;
3382                 c_irq_params->irq_src = int_params.irq_source;
3383
3384                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3385                                 dm_crtc_high_irq, c_irq_params);
3386         }
3387
3388         /* Use GRPH_PFLIP interrupt */
3389         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3390                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3391                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3392                 if (r) {
3393                         DRM_ERROR("Failed to add page flip irq id!\n");
3394                         return r;
3395                 }
3396
3397                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3398                 int_params.irq_source =
3399                         dc_interrupt_to_irq_source(dc, i, 0);
3400
3401                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3402
3403                 c_irq_params->adev = adev;
3404                 c_irq_params->irq_src = int_params.irq_source;
3405
3406                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3407                                 dm_pflip_high_irq, c_irq_params);
3408
3409         }
3410
3411         /* HPD */
3412         r = amdgpu_irq_add_id(adev, client_id,
3413                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3414         if (r) {
3415                 DRM_ERROR("Failed to add hpd irq id!\n");
3416                 return r;
3417         }
3418
3419         register_hpd_handlers(adev);
3420
3421         return 0;
3422 }
3423 #endif
3424
3425 /* Register IRQ sources and initialize IRQ callbacks */
3426 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
3427 {
3428         struct dc *dc = adev->dm.dc;
3429         struct common_irq_params *c_irq_params;
3430         struct dc_interrupt_params int_params = {0};
3431         int r;
3432         int i;
3433         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3434
3435         if (adev->family >= AMDGPU_FAMILY_AI)
3436                 client_id = SOC15_IH_CLIENTID_DCE;
3437
3438         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3439         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3440
3441         /*
3442          * Actions of amdgpu_irq_add_id():
3443          * 1. Register a set() function with base driver.
3444          *    Base driver will call set() function to enable/disable an
3445          *    interrupt in DC hardware.
3446          * 2. Register amdgpu_dm_irq_handler().
3447          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3448          *    coming from DC hardware.
3449          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3450          *    for acknowledging and handling. */
3451
3452         /* Use VBLANK interrupt */
3453         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
3454                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
3455                 if (r) {
3456                         DRM_ERROR("Failed to add crtc irq id!\n");
3457                         return r;
3458                 }
3459
3460                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3461                 int_params.irq_source =
3462                         dc_interrupt_to_irq_source(dc, i, 0);
3463
3464                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3465
3466                 c_irq_params->adev = adev;
3467                 c_irq_params->irq_src = int_params.irq_source;
3468
3469                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3470                                 dm_crtc_high_irq, c_irq_params);
3471         }
3472
3473         /* Use VUPDATE interrupt */
3474         for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
3475                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
3476                 if (r) {
3477                         DRM_ERROR("Failed to add vupdate irq id!\n");
3478                         return r;
3479                 }
3480
3481                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3482                 int_params.irq_source =
3483                         dc_interrupt_to_irq_source(dc, i, 0);
3484
3485                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3486
3487                 c_irq_params->adev = adev;
3488                 c_irq_params->irq_src = int_params.irq_source;
3489
3490                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3491                                 dm_vupdate_high_irq, c_irq_params);
3492         }
3493
3494         /* Use GRPH_PFLIP interrupt */
3495         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3496                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3497                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3498                 if (r) {
3499                         DRM_ERROR("Failed to add page flip irq id!\n");
3500                         return r;
3501                 }
3502
3503                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3504                 int_params.irq_source =
3505                         dc_interrupt_to_irq_source(dc, i, 0);
3506
3507                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3508
3509                 c_irq_params->adev = adev;
3510                 c_irq_params->irq_src = int_params.irq_source;
3511
3512                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3513                                 dm_pflip_high_irq, c_irq_params);
3514
3515         }
3516
3517         /* HPD */
3518         r = amdgpu_irq_add_id(adev, client_id,
3519                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3520         if (r) {
3521                 DRM_ERROR("Failed to add hpd irq id!\n");
3522                 return r;
3523         }
3524
3525         register_hpd_handlers(adev);
3526
3527         return 0;
3528 }
3529
3530 /* Register IRQ sources and initialize IRQ callbacks */
3531 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
3532 {
3533         struct dc *dc = adev->dm.dc;
3534         struct common_irq_params *c_irq_params;
3535         struct dc_interrupt_params int_params = {0};
3536         int r;
3537         int i;
3538 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3539         static const unsigned int vrtl_int_srcid[] = {
3540                 DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
3541                 DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
3542                 DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
3543                 DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
3544                 DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
3545                 DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
3546         };
3547 #endif
3548
3549         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3550         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3551
3552         /*
3553          * Actions of amdgpu_irq_add_id():
3554          * 1. Register a set() function with base driver.
3555          *    Base driver will call set() function to enable/disable an
3556          *    interrupt in DC hardware.
3557          * 2. Register amdgpu_dm_irq_handler().
3558          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3559          *    coming from DC hardware.
3560          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3561          *    for acknowledging and handling.
3562          */
3563
3564         /* Use VSTARTUP interrupt */
3565         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
3566                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
3567                         i++) {
3568                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
3569
3570                 if (r) {
3571                         DRM_ERROR("Failed to add crtc irq id!\n");
3572                         return r;
3573                 }
3574
3575                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3576                 int_params.irq_source =
3577                         dc_interrupt_to_irq_source(dc, i, 0);
3578
3579                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3580
3581                 c_irq_params->adev = adev;
3582                 c_irq_params->irq_src = int_params.irq_source;
3583
3584                 amdgpu_dm_irq_register_interrupt(
3585                         adev, &int_params, dm_crtc_high_irq, c_irq_params);
3586         }
3587
3588         /* Use otg vertical line interrupt */
3589 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3590         for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
3591                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
3592                                 vrtl_int_srcid[i], &adev->vline0_irq);
3593
3594                 if (r) {
3595                         DRM_ERROR("Failed to add vline0 irq id!\n");
3596                         return r;
3597                 }
3598
3599                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3600                 int_params.irq_source =
3601                         dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
3602
3603                 if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
3604                         DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
3605                         break;
3606                 }
3607
3608                 c_irq_params = &adev->dm.vline0_params[int_params.irq_source
3609                                         - DC_IRQ_SOURCE_DC1_VLINE0];
3610
3611                 c_irq_params->adev = adev;
3612                 c_irq_params->irq_src = int_params.irq_source;
3613
3614                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3615                                 dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
3616         }
3617 #endif
3618
3619         /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
3620          * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
3621          * to trigger at end of each vblank, regardless of state of the lock,
3622          * matching DCE behaviour.
3623          */
3624         for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
3625              i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
3626              i++) {
3627                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
3628
3629                 if (r) {
3630                         DRM_ERROR("Failed to add vupdate irq id!\n");
3631                         return r;
3632                 }
3633
3634                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3635                 int_params.irq_source =
3636                         dc_interrupt_to_irq_source(dc, i, 0);
3637
3638                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3639
3640                 c_irq_params->adev = adev;
3641                 c_irq_params->irq_src = int_params.irq_source;
3642
3643                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3644                                 dm_vupdate_high_irq, c_irq_params);
3645         }
3646
3647         /* Use GRPH_PFLIP interrupt */
3648         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
3649                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
3650                         i++) {
3651                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
3652                 if (r) {
3653                         DRM_ERROR("Failed to add page flip irq id!\n");
3654                         return r;
3655                 }
3656
3657                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3658                 int_params.irq_source =
3659                         dc_interrupt_to_irq_source(dc, i, 0);
3660
3661                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3662
3663                 c_irq_params->adev = adev;
3664                 c_irq_params->irq_src = int_params.irq_source;
3665
3666                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3667                                 dm_pflip_high_irq, c_irq_params);
3668
3669         }
3670
3671         /* HPD */
3672         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
3673                         &adev->hpd_irq);
3674         if (r) {
3675                 DRM_ERROR("Failed to add hpd irq id!\n");
3676                 return r;
3677         }
3678
3679         register_hpd_handlers(adev);
3680
3681         return 0;
3682 }
3683 /* Register Outbox IRQ sources and initialize IRQ callbacks */
3684 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
3685 {
3686         struct dc *dc = adev->dm.dc;
3687         struct common_irq_params *c_irq_params;
3688         struct dc_interrupt_params int_params = {0};
3689         int r, i;
3690
3691         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3692         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3693
3694         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
3695                         &adev->dmub_outbox_irq);
3696         if (r) {
3697                 DRM_ERROR("Failed to add outbox irq id!\n");
3698                 return r;
3699         }
3700
3701         if (dc->ctx->dmub_srv) {
3702                 i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
3703                 int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3704                 int_params.irq_source =
3705                 dc_interrupt_to_irq_source(dc, i, 0);
3706
3707                 c_irq_params = &adev->dm.dmub_outbox_params[0];
3708
3709                 c_irq_params->adev = adev;
3710                 c_irq_params->irq_src = int_params.irq_source;
3711
3712                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
3713                                 dm_dmub_outbox1_low_irq, c_irq_params);
3714         }
3715
3716         return 0;
3717 }
3718
3719 /*
3720  * Acquires the lock for the atomic state object and returns
3721  * the new atomic state.
3722  *
3723  * This should only be called during atomic check.
3724  */
3725 int dm_atomic_get_state(struct drm_atomic_state *state,
3726                         struct dm_atomic_state **dm_state)
3727 {
3728         struct drm_device *dev = state->dev;
3729         struct amdgpu_device *adev = drm_to_adev(dev);
3730         struct amdgpu_display_manager *dm = &adev->dm;
3731         struct drm_private_state *priv_state;
3732
3733         if (*dm_state)
3734                 return 0;
3735
3736         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
3737         if (IS_ERR(priv_state))
3738                 return PTR_ERR(priv_state);
3739
3740         *dm_state = to_dm_atomic_state(priv_state);
3741
3742         return 0;
3743 }
3744
3745 static struct dm_atomic_state *
3746 dm_atomic_get_new_state(struct drm_atomic_state *state)
3747 {
3748         struct drm_device *dev = state->dev;
3749         struct amdgpu_device *adev = drm_to_adev(dev);
3750         struct amdgpu_display_manager *dm = &adev->dm;
3751         struct drm_private_obj *obj;
3752         struct drm_private_state *new_obj_state;
3753         int i;
3754
3755         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
3756                 if (obj->funcs == dm->atomic_obj.funcs)
3757                         return to_dm_atomic_state(new_obj_state);
3758         }
3759
3760         return NULL;
3761 }
3762
3763 static struct drm_private_state *
3764 dm_atomic_duplicate_state(struct drm_private_obj *obj)
3765 {
3766         struct dm_atomic_state *old_state, *new_state;
3767
3768         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
3769         if (!new_state)
3770                 return NULL;
3771
3772         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
3773
3774         old_state = to_dm_atomic_state(obj->state);
3775
3776         if (old_state && old_state->context)
3777                 new_state->context = dc_copy_state(old_state->context);
3778
3779         if (!new_state->context) {
3780                 kfree(new_state);
3781                 return NULL;
3782         }
3783
3784         return &new_state->base;
3785 }
3786
3787 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
3788                                     struct drm_private_state *state)
3789 {
3790         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3791
3792         if (dm_state && dm_state->context)
3793                 dc_release_state(dm_state->context);
3794
3795         kfree(dm_state);
3796 }
3797
3798 static struct drm_private_state_funcs dm_atomic_state_funcs = {
3799         .atomic_duplicate_state = dm_atomic_duplicate_state,
3800         .atomic_destroy_state = dm_atomic_destroy_state,
3801 };
3802
3803 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
3804 {
3805         struct dm_atomic_state *state;
3806         int r;
3807
3808         adev->mode_info.mode_config_initialized = true;
3809
3810         adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
3811         adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
3812
3813         adev_to_drm(adev)->mode_config.max_width = 16384;
3814         adev_to_drm(adev)->mode_config.max_height = 16384;
3815
3816         adev_to_drm(adev)->mode_config.preferred_depth = 24;
3817         if (adev->asic_type == CHIP_HAWAII)
3818                 /* disable prefer shadow for now due to hibernation issues */
3819                 adev_to_drm(adev)->mode_config.prefer_shadow = 0;
3820         else
3821                 adev_to_drm(adev)->mode_config.prefer_shadow = 1;
3822         /* indicates support for immediate flip */
3823         adev_to_drm(adev)->mode_config.async_page_flip = true;
3824
3825         state = kzalloc(sizeof(*state), GFP_KERNEL);
3826         if (!state)
3827                 return -ENOMEM;
3828
3829         state->context = dc_create_state(adev->dm.dc);
3830         if (!state->context) {
3831                 kfree(state);
3832                 return -ENOMEM;
3833         }
3834
3835         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
3836
3837         drm_atomic_private_obj_init(adev_to_drm(adev),
3838                                     &adev->dm.atomic_obj,
3839                                     &state->base,
3840                                     &dm_atomic_state_funcs);
3841
3842         r = amdgpu_display_modeset_create_props(adev);
3843         if (r) {
3844                 dc_release_state(state->context);
3845                 kfree(state);
3846                 return r;
3847         }
3848
3849         r = amdgpu_dm_audio_init(adev);
3850         if (r) {
3851                 dc_release_state(state->context);
3852                 kfree(state);
3853                 return r;
3854         }
3855
3856         return 0;
3857 }
3858
3859 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
3860 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
3861 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
3862
3863 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
3864                                             int bl_idx)
3865 {
3866 #if defined(CONFIG_ACPI)
3867         struct amdgpu_dm_backlight_caps caps;
3868
3869         memset(&caps, 0, sizeof(caps));
3870
3871         if (dm->backlight_caps[bl_idx].caps_valid)
3872                 return;
3873
3874         amdgpu_acpi_get_backlight_caps(&caps);
3875         if (caps.caps_valid) {
3876                 dm->backlight_caps[bl_idx].caps_valid = true;
3877                 if (caps.aux_support)
3878                         return;
3879                 dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
3880                 dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
3881         } else {
3882                 dm->backlight_caps[bl_idx].min_input_signal =
3883                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3884                 dm->backlight_caps[bl_idx].max_input_signal =
3885                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3886         }
3887 #else
3888         if (dm->backlight_caps[bl_idx].aux_support)
3889                 return;
3890
3891         dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3892         dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3893 #endif
3894 }
3895
3896 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
3897                                 unsigned *min, unsigned *max)
3898 {
3899         if (!caps)
3900                 return 0;
3901
3902         if (caps->aux_support) {
3903                 // Firmware limits are in nits, DC API wants millinits.
3904                 *max = 1000 * caps->aux_max_input_signal;
3905                 *min = 1000 * caps->aux_min_input_signal;
3906         } else {
3907                 // Firmware limits are 8-bit, PWM control is 16-bit.
3908                 *max = 0x101 * caps->max_input_signal;
3909                 *min = 0x101 * caps->min_input_signal;
3910         }
3911         return 1;
3912 }
3913
3914 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
3915                                         uint32_t brightness)
3916 {
3917         unsigned min, max;
3918
3919         if (!get_brightness_range(caps, &min, &max))
3920                 return brightness;
3921
3922         // Rescale 0..255 to min..max
3923         return min + DIV_ROUND_CLOSEST((max - min) * brightness,
3924                                        AMDGPU_MAX_BL_LEVEL);
3925 }
3926
3927 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
3928                                       uint32_t brightness)
3929 {
3930         unsigned min, max;
3931
3932         if (!get_brightness_range(caps, &min, &max))
3933                 return brightness;
3934
3935         if (brightness < min)
3936                 return 0;
3937         // Rescale min..max to 0..255
3938         return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
3939                                  max - min);
3940 }
3941
3942 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
3943                                          int bl_idx,
3944                                          u32 user_brightness)
3945 {
3946         struct amdgpu_dm_backlight_caps caps;
3947         struct dc_link *link;
3948         u32 brightness;
3949         bool rc;
3950
3951         amdgpu_dm_update_backlight_caps(dm, bl_idx);
3952         caps = dm->backlight_caps[bl_idx];
3953
3954         dm->brightness[bl_idx] = user_brightness;
3955         /* update scratch register */
3956         if (bl_idx == 0)
3957                 amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
3958         brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
3959         link = (struct dc_link *)dm->backlight_link[bl_idx];
3960
3961         /* Change brightness based on AUX property */
3962         if (caps.aux_support) {
3963                 rc = dc_link_set_backlight_level_nits(link, true, brightness,
3964                                                       AUX_BL_DEFAULT_TRANSITION_TIME_MS);
3965                 if (!rc)
3966                         DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
3967         } else {
3968                 rc = dc_link_set_backlight_level(link, brightness, 0);
3969                 if (!rc)
3970                         DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
3971         }
3972
3973         if (rc)
3974                 dm->actual_brightness[bl_idx] = user_brightness;
3975 }
3976
3977 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
3978 {
3979         struct amdgpu_display_manager *dm = bl_get_data(bd);
3980         int i;
3981
3982         for (i = 0; i < dm->num_of_edps; i++) {
3983                 if (bd == dm->backlight_dev[i])
3984                         break;
3985         }
3986         if (i >= AMDGPU_DM_MAX_NUM_EDP)
3987                 i = 0;
3988         amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
3989
3990         return 0;
3991 }
3992
3993 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
3994                                          int bl_idx)
3995 {
3996         struct amdgpu_dm_backlight_caps caps;
3997         struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
3998
3999         amdgpu_dm_update_backlight_caps(dm, bl_idx);
4000         caps = dm->backlight_caps[bl_idx];
4001
4002         if (caps.aux_support) {
4003                 u32 avg, peak;
4004                 bool rc;
4005
4006                 rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
4007                 if (!rc)
4008                         return dm->brightness[bl_idx];
4009                 return convert_brightness_to_user(&caps, avg);
4010         } else {
4011                 int ret = dc_link_get_backlight_level(link);
4012
4013                 if (ret == DC_ERROR_UNEXPECTED)
4014                         return dm->brightness[bl_idx];
4015                 return convert_brightness_to_user(&caps, ret);
4016         }
4017 }
4018
4019 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
4020 {
4021         struct amdgpu_display_manager *dm = bl_get_data(bd);
4022         int i;
4023
4024         for (i = 0; i < dm->num_of_edps; i++) {
4025                 if (bd == dm->backlight_dev[i])
4026                         break;
4027         }
4028         if (i >= AMDGPU_DM_MAX_NUM_EDP)
4029                 i = 0;
4030         return amdgpu_dm_backlight_get_level(dm, i);
4031 }
4032
4033 static const struct backlight_ops amdgpu_dm_backlight_ops = {
4034         .options = BL_CORE_SUSPENDRESUME,
4035         .get_brightness = amdgpu_dm_backlight_get_brightness,
4036         .update_status  = amdgpu_dm_backlight_update_status,
4037 };
4038
4039 static void
4040 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
4041 {
4042         char bl_name[16];
4043         struct backlight_properties props = { 0 };
4044
4045         amdgpu_dm_update_backlight_caps(dm, dm->num_of_edps);
4046         dm->brightness[dm->num_of_edps] = AMDGPU_MAX_BL_LEVEL;
4047
4048         if (!acpi_video_backlight_use_native()) {
4049                 drm_info(adev_to_drm(dm->adev), "Skipping amdgpu DM backlight registration\n");
4050                 /* Try registering an ACPI video backlight device instead. */
4051                 acpi_video_register_backlight();
4052                 return;
4053         }
4054
4055         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
4056         props.brightness = AMDGPU_MAX_BL_LEVEL;
4057         props.type = BACKLIGHT_RAW;
4058
4059         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
4060                  adev_to_drm(dm->adev)->primary->index + dm->num_of_edps);
4061
4062         dm->backlight_dev[dm->num_of_edps] = backlight_device_register(bl_name,
4063                                                                        adev_to_drm(dm->adev)->dev,
4064                                                                        dm,
4065                                                                        &amdgpu_dm_backlight_ops,
4066                                                                        &props);
4067
4068         if (IS_ERR(dm->backlight_dev[dm->num_of_edps]))
4069                 DRM_ERROR("DM: Backlight registration failed!\n");
4070         else
4071                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
4072 }
4073
4074 static int initialize_plane(struct amdgpu_display_manager *dm,
4075                             struct amdgpu_mode_info *mode_info, int plane_id,
4076                             enum drm_plane_type plane_type,
4077                             const struct dc_plane_cap *plane_cap)
4078 {
4079         struct drm_plane *plane;
4080         unsigned long possible_crtcs;
4081         int ret = 0;
4082
4083         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
4084         if (!plane) {
4085                 DRM_ERROR("KMS: Failed to allocate plane\n");
4086                 return -ENOMEM;
4087         }
4088         plane->type = plane_type;
4089
4090         /*
4091          * HACK: IGT tests expect that the primary plane for a CRTC
4092          * can only have one possible CRTC. Only expose support for
4093          * any CRTC if they're not going to be used as a primary plane
4094          * for a CRTC - like overlay or underlay planes.
4095          */
4096         possible_crtcs = 1 << plane_id;
4097         if (plane_id >= dm->dc->caps.max_streams)
4098                 possible_crtcs = 0xff;
4099
4100         ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
4101
4102         if (ret) {
4103                 DRM_ERROR("KMS: Failed to initialize plane\n");
4104                 kfree(plane);
4105                 return ret;
4106         }
4107
4108         if (mode_info)
4109                 mode_info->planes[plane_id] = plane;
4110
4111         return ret;
4112 }
4113
4114
4115 static void register_backlight_device(struct amdgpu_display_manager *dm,
4116                                       struct dc_link *link)
4117 {
4118         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4119             link->type != dc_connection_none) {
4120                 /*
4121                  * Event if registration failed, we should continue with
4122                  * DM initialization because not having a backlight control
4123                  * is better then a black screen.
4124                  */
4125                 if (!dm->backlight_dev[dm->num_of_edps])
4126                         amdgpu_dm_register_backlight_device(dm);
4127
4128                 if (dm->backlight_dev[dm->num_of_edps]) {
4129                         dm->backlight_link[dm->num_of_edps] = link;
4130                         dm->num_of_edps++;
4131                 }
4132         }
4133 }
4134
4135 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
4136
4137 /*
4138  * In this architecture, the association
4139  * connector -> encoder -> crtc
4140  * id not really requried. The crtc and connector will hold the
4141  * display_index as an abstraction to use with DAL component
4142  *
4143  * Returns 0 on success
4144  */
4145 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
4146 {
4147         struct amdgpu_display_manager *dm = &adev->dm;
4148         s32 i;
4149         struct amdgpu_dm_connector *aconnector = NULL;
4150         struct amdgpu_encoder *aencoder = NULL;
4151         struct amdgpu_mode_info *mode_info = &adev->mode_info;
4152         u32 link_cnt;
4153         s32 primary_planes;
4154         enum dc_connection_type new_connection_type = dc_connection_none;
4155         const struct dc_plane_cap *plane;
4156         bool psr_feature_enabled = false;
4157
4158         dm->display_indexes_num = dm->dc->caps.max_streams;
4159         /* Update the actual used number of crtc */
4160         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
4161
4162         link_cnt = dm->dc->caps.max_links;
4163         if (amdgpu_dm_mode_config_init(dm->adev)) {
4164                 DRM_ERROR("DM: Failed to initialize mode config\n");
4165                 return -EINVAL;
4166         }
4167
4168         /* There is one primary plane per CRTC */
4169         primary_planes = dm->dc->caps.max_streams;
4170         ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
4171
4172         /*
4173          * Initialize primary planes, implicit planes for legacy IOCTLS.
4174          * Order is reversed to match iteration order in atomic check.
4175          */
4176         for (i = (primary_planes - 1); i >= 0; i--) {
4177                 plane = &dm->dc->caps.planes[i];
4178
4179                 if (initialize_plane(dm, mode_info, i,
4180                                      DRM_PLANE_TYPE_PRIMARY, plane)) {
4181                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
4182                         goto fail;
4183                 }
4184         }
4185
4186         /*
4187          * Initialize overlay planes, index starting after primary planes.
4188          * These planes have a higher DRM index than the primary planes since
4189          * they should be considered as having a higher z-order.
4190          * Order is reversed to match iteration order in atomic check.
4191          *
4192          * Only support DCN for now, and only expose one so we don't encourage
4193          * userspace to use up all the pipes.
4194          */
4195         for (i = 0; i < dm->dc->caps.max_planes; ++i) {
4196                 struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
4197
4198                 /* Do not create overlay if MPO disabled */
4199                 if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
4200                         break;
4201
4202                 if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
4203                         continue;
4204
4205                 if (!plane->blends_with_above || !plane->blends_with_below)
4206                         continue;
4207
4208                 if (!plane->pixel_format_support.argb8888)
4209                         continue;
4210
4211                 if (initialize_plane(dm, NULL, primary_planes + i,
4212                                      DRM_PLANE_TYPE_OVERLAY, plane)) {
4213                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
4214                         goto fail;
4215                 }
4216
4217                 /* Only create one overlay plane. */
4218                 break;
4219         }
4220
4221         for (i = 0; i < dm->dc->caps.max_streams; i++)
4222                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
4223                         DRM_ERROR("KMS: Failed to initialize crtc\n");
4224                         goto fail;
4225                 }
4226
4227         /* Use Outbox interrupt */
4228         switch (adev->ip_versions[DCE_HWIP][0]) {
4229         case IP_VERSION(3, 0, 0):
4230         case IP_VERSION(3, 1, 2):
4231         case IP_VERSION(3, 1, 3):
4232         case IP_VERSION(3, 1, 4):
4233         case IP_VERSION(3, 1, 5):
4234         case IP_VERSION(3, 1, 6):
4235         case IP_VERSION(3, 2, 0):
4236         case IP_VERSION(3, 2, 1):
4237         case IP_VERSION(2, 1, 0):
4238                 if (register_outbox_irq_handlers(dm->adev)) {
4239                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4240                         goto fail;
4241                 }
4242                 break;
4243         default:
4244                 DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
4245                               adev->ip_versions[DCE_HWIP][0]);
4246         }
4247
4248         /* Determine whether to enable PSR support by default. */
4249         if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
4250                 switch (adev->ip_versions[DCE_HWIP][0]) {
4251                 case IP_VERSION(3, 1, 2):
4252                 case IP_VERSION(3, 1, 3):
4253                 case IP_VERSION(3, 1, 4):
4254                 case IP_VERSION(3, 1, 5):
4255                 case IP_VERSION(3, 1, 6):
4256                 case IP_VERSION(3, 2, 0):
4257                 case IP_VERSION(3, 2, 1):
4258                         psr_feature_enabled = true;
4259                         break;
4260                 default:
4261                         psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
4262                         break;
4263                 }
4264         }
4265
4266         /* loops over all connectors on the board */
4267         for (i = 0; i < link_cnt; i++) {
4268                 struct dc_link *link = NULL;
4269
4270                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
4271                         DRM_ERROR(
4272                                 "KMS: Cannot support more than %d display indexes\n",
4273                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
4274                         continue;
4275                 }
4276
4277                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
4278                 if (!aconnector)
4279                         goto fail;
4280
4281                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
4282                 if (!aencoder)
4283                         goto fail;
4284
4285                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
4286                         DRM_ERROR("KMS: Failed to initialize encoder\n");
4287                         goto fail;
4288                 }
4289
4290                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
4291                         DRM_ERROR("KMS: Failed to initialize connector\n");
4292                         goto fail;
4293                 }
4294
4295                 link = dc_get_link_at_index(dm->dc, i);
4296
4297                 if (!dc_link_detect_sink(link, &new_connection_type))
4298                         DRM_ERROR("KMS: Failed to detect connector\n");
4299
4300                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
4301                         emulated_link_detect(link);
4302                         amdgpu_dm_update_connector_after_detect(aconnector);
4303                 } else {
4304                         bool ret = false;
4305
4306                         mutex_lock(&dm->dc_lock);
4307                         ret = dc_link_detect(link, DETECT_REASON_BOOT);
4308                         mutex_unlock(&dm->dc_lock);
4309
4310                         if (ret) {
4311                                 amdgpu_dm_update_connector_after_detect(aconnector);
4312                                 register_backlight_device(dm, link);
4313
4314                                 if (dm->num_of_edps)
4315                                         update_connector_ext_caps(aconnector);
4316
4317                                 if (psr_feature_enabled)
4318                                         amdgpu_dm_set_psr_caps(link);
4319
4320                                 /* TODO: Fix vblank control helpers to delay PSR entry to allow this when
4321                                  * PSR is also supported.
4322                                  */
4323                                 if (link->psr_settings.psr_feature_enabled)
4324                                         adev_to_drm(adev)->vblank_disable_immediate = false;
4325                         }
4326                 }
4327                 amdgpu_set_panel_orientation(&aconnector->base);
4328         }
4329
4330         /* If we didn't find a panel, notify the acpi video detection */
4331         if (dm->adev->flags & AMD_IS_APU && dm->num_of_edps == 0)
4332                 acpi_video_report_nolcd();
4333
4334         /* Software is initialized. Now we can register interrupt handlers. */
4335         switch (adev->asic_type) {
4336 #if defined(CONFIG_DRM_AMD_DC_SI)
4337         case CHIP_TAHITI:
4338         case CHIP_PITCAIRN:
4339         case CHIP_VERDE:
4340         case CHIP_OLAND:
4341                 if (dce60_register_irq_handlers(dm->adev)) {
4342                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4343                         goto fail;
4344                 }
4345                 break;
4346 #endif
4347         case CHIP_BONAIRE:
4348         case CHIP_HAWAII:
4349         case CHIP_KAVERI:
4350         case CHIP_KABINI:
4351         case CHIP_MULLINS:
4352         case CHIP_TONGA:
4353         case CHIP_FIJI:
4354         case CHIP_CARRIZO:
4355         case CHIP_STONEY:
4356         case CHIP_POLARIS11:
4357         case CHIP_POLARIS10:
4358         case CHIP_POLARIS12:
4359         case CHIP_VEGAM:
4360         case CHIP_VEGA10:
4361         case CHIP_VEGA12:
4362         case CHIP_VEGA20:
4363                 if (dce110_register_irq_handlers(dm->adev)) {
4364                         DRM_ERROR("DM: Failed to initialize IRQ\n");
4365                         goto fail;
4366                 }
4367                 break;
4368         default:
4369                 switch (adev->ip_versions[DCE_HWIP][0]) {
4370                 case IP_VERSION(1, 0, 0):
4371                 case IP_VERSION(1, 0, 1):
4372                 case IP_VERSION(2, 0, 2):
4373                 case IP_VERSION(2, 0, 3):
4374                 case IP_VERSION(2, 0, 0):
4375                 case IP_VERSION(2, 1, 0):
4376                 case IP_VERSION(3, 0, 0):
4377                 case IP_VERSION(3, 0, 2):
4378                 case IP_VERSION(3, 0, 3):
4379                 case IP_VERSION(3, 0, 1):
4380                 case IP_VERSION(3, 1, 2):
4381                 case IP_VERSION(3, 1, 3):
4382                 case IP_VERSION(3, 1, 4):
4383                 case IP_VERSION(3, 1, 5):
4384                 case IP_VERSION(3, 1, 6):
4385                 case IP_VERSION(3, 2, 0):
4386                 case IP_VERSION(3, 2, 1):
4387                         if (dcn10_register_irq_handlers(dm->adev)) {
4388                                 DRM_ERROR("DM: Failed to initialize IRQ\n");
4389                                 goto fail;
4390                         }
4391                         break;
4392                 default:
4393                         DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4394                                         adev->ip_versions[DCE_HWIP][0]);
4395                         goto fail;
4396                 }
4397                 break;
4398         }
4399
4400         return 0;
4401 fail:
4402         kfree(aencoder);
4403         kfree(aconnector);
4404
4405         return -EINVAL;
4406 }
4407
4408 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4409 {
4410         drm_atomic_private_obj_fini(&dm->atomic_obj);
4411         return;
4412 }
4413
4414 /******************************************************************************
4415  * amdgpu_display_funcs functions
4416  *****************************************************************************/
4417
4418 /*
4419  * dm_bandwidth_update - program display watermarks
4420  *
4421  * @adev: amdgpu_device pointer
4422  *
4423  * Calculate and program the display watermarks and line buffer allocation.
4424  */
4425 static void dm_bandwidth_update(struct amdgpu_device *adev)
4426 {
4427         /* TODO: implement later */
4428 }
4429
4430 static const struct amdgpu_display_funcs dm_display_funcs = {
4431         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4432         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4433         .backlight_set_level = NULL, /* never called for DC */
4434         .backlight_get_level = NULL, /* never called for DC */
4435         .hpd_sense = NULL,/* called unconditionally */
4436         .hpd_set_polarity = NULL, /* called unconditionally */
4437         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4438         .page_flip_get_scanoutpos =
4439                 dm_crtc_get_scanoutpos,/* called unconditionally */
4440         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4441         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
4442 };
4443
4444 #if defined(CONFIG_DEBUG_KERNEL_DC)
4445
4446 static ssize_t s3_debug_store(struct device *device,
4447                               struct device_attribute *attr,
4448                               const char *buf,
4449                               size_t count)
4450 {
4451         int ret;
4452         int s3_state;
4453         struct drm_device *drm_dev = dev_get_drvdata(device);
4454         struct amdgpu_device *adev = drm_to_adev(drm_dev);
4455
4456         ret = kstrtoint(buf, 0, &s3_state);
4457
4458         if (ret == 0) {
4459                 if (s3_state) {
4460                         dm_resume(adev);
4461                         drm_kms_helper_hotplug_event(adev_to_drm(adev));
4462                 } else
4463                         dm_suspend(adev);
4464         }
4465
4466         return ret == 0 ? count : 0;
4467 }
4468
4469 DEVICE_ATTR_WO(s3_debug);
4470
4471 #endif
4472
4473 static int dm_init_microcode(struct amdgpu_device *adev)
4474 {
4475         char *fw_name_dmub;
4476         int r;
4477
4478         switch (adev->ip_versions[DCE_HWIP][0]) {
4479         case IP_VERSION(2, 1, 0):
4480                 fw_name_dmub = FIRMWARE_RENOIR_DMUB;
4481                 if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
4482                         fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
4483                 break;
4484         case IP_VERSION(3, 0, 0):
4485                 if (adev->ip_versions[GC_HWIP][0] == IP_VERSION(10, 3, 0))
4486                         fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
4487                 else
4488                         fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
4489                 break;
4490         case IP_VERSION(3, 0, 1):
4491                 fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
4492                 break;
4493         case IP_VERSION(3, 0, 2):
4494                 fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
4495                 break;
4496         case IP_VERSION(3, 0, 3):
4497                 fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
4498                 break;
4499         case IP_VERSION(3, 1, 2):
4500         case IP_VERSION(3, 1, 3):
4501                 fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
4502                 break;
4503         case IP_VERSION(3, 1, 4):
4504                 fw_name_dmub = FIRMWARE_DCN_314_DMUB;
4505                 break;
4506         case IP_VERSION(3, 1, 5):
4507                 fw_name_dmub = FIRMWARE_DCN_315_DMUB;
4508                 break;
4509         case IP_VERSION(3, 1, 6):
4510                 fw_name_dmub = FIRMWARE_DCN316_DMUB;
4511                 break;
4512         case IP_VERSION(3, 2, 0):
4513                 fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
4514                 break;
4515         case IP_VERSION(3, 2, 1):
4516                 fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
4517                 break;
4518         default:
4519                 /* ASIC doesn't support DMUB. */
4520                 return 0;
4521         }
4522         r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, fw_name_dmub);
4523         if (r)
4524                 DRM_ERROR("DMUB firmware loading failed: %d\n", r);
4525         return r;
4526 }
4527
4528 static int dm_early_init(void *handle)
4529 {
4530         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4531
4532         switch (adev->asic_type) {
4533 #if defined(CONFIG_DRM_AMD_DC_SI)
4534         case CHIP_TAHITI:
4535         case CHIP_PITCAIRN:
4536         case CHIP_VERDE:
4537                 adev->mode_info.num_crtc = 6;
4538                 adev->mode_info.num_hpd = 6;
4539                 adev->mode_info.num_dig = 6;
4540                 break;
4541         case CHIP_OLAND:
4542                 adev->mode_info.num_crtc = 2;
4543                 adev->mode_info.num_hpd = 2;
4544                 adev->mode_info.num_dig = 2;
4545                 break;
4546 #endif
4547         case CHIP_BONAIRE:
4548         case CHIP_HAWAII:
4549                 adev->mode_info.num_crtc = 6;
4550                 adev->mode_info.num_hpd = 6;
4551                 adev->mode_info.num_dig = 6;
4552                 break;
4553         case CHIP_KAVERI:
4554                 adev->mode_info.num_crtc = 4;
4555                 adev->mode_info.num_hpd = 6;
4556                 adev->mode_info.num_dig = 7;
4557                 break;
4558         case CHIP_KABINI:
4559         case CHIP_MULLINS:
4560                 adev->mode_info.num_crtc = 2;
4561                 adev->mode_info.num_hpd = 6;
4562                 adev->mode_info.num_dig = 6;
4563                 break;
4564         case CHIP_FIJI:
4565         case CHIP_TONGA:
4566                 adev->mode_info.num_crtc = 6;
4567                 adev->mode_info.num_hpd = 6;
4568                 adev->mode_info.num_dig = 7;
4569                 break;
4570         case CHIP_CARRIZO:
4571                 adev->mode_info.num_crtc = 3;
4572                 adev->mode_info.num_hpd = 6;
4573                 adev->mode_info.num_dig = 9;
4574                 break;
4575         case CHIP_STONEY:
4576                 adev->mode_info.num_crtc = 2;
4577                 adev->mode_info.num_hpd = 6;
4578                 adev->mode_info.num_dig = 9;
4579                 break;
4580         case CHIP_POLARIS11:
4581         case CHIP_POLARIS12:
4582                 adev->mode_info.num_crtc = 5;
4583                 adev->mode_info.num_hpd = 5;
4584                 adev->mode_info.num_dig = 5;
4585                 break;
4586         case CHIP_POLARIS10:
4587         case CHIP_VEGAM:
4588                 adev->mode_info.num_crtc = 6;
4589                 adev->mode_info.num_hpd = 6;
4590                 adev->mode_info.num_dig = 6;
4591                 break;
4592         case CHIP_VEGA10:
4593         case CHIP_VEGA12:
4594         case CHIP_VEGA20:
4595                 adev->mode_info.num_crtc = 6;
4596                 adev->mode_info.num_hpd = 6;
4597                 adev->mode_info.num_dig = 6;
4598                 break;
4599         default:
4600
4601                 switch (adev->ip_versions[DCE_HWIP][0]) {
4602                 case IP_VERSION(2, 0, 2):
4603                 case IP_VERSION(3, 0, 0):
4604                         adev->mode_info.num_crtc = 6;
4605                         adev->mode_info.num_hpd = 6;
4606                         adev->mode_info.num_dig = 6;
4607                         break;
4608                 case IP_VERSION(2, 0, 0):
4609                 case IP_VERSION(3, 0, 2):
4610                         adev->mode_info.num_crtc = 5;
4611                         adev->mode_info.num_hpd = 5;
4612                         adev->mode_info.num_dig = 5;
4613                         break;
4614                 case IP_VERSION(2, 0, 3):
4615                 case IP_VERSION(3, 0, 3):
4616                         adev->mode_info.num_crtc = 2;
4617                         adev->mode_info.num_hpd = 2;
4618                         adev->mode_info.num_dig = 2;
4619                         break;
4620                 case IP_VERSION(1, 0, 0):
4621                 case IP_VERSION(1, 0, 1):
4622                 case IP_VERSION(3, 0, 1):
4623                 case IP_VERSION(2, 1, 0):
4624                 case IP_VERSION(3, 1, 2):
4625                 case IP_VERSION(3, 1, 3):
4626                 case IP_VERSION(3, 1, 4):
4627                 case IP_VERSION(3, 1, 5):
4628                 case IP_VERSION(3, 1, 6):
4629                 case IP_VERSION(3, 2, 0):
4630                 case IP_VERSION(3, 2, 1):
4631                         adev->mode_info.num_crtc = 4;
4632                         adev->mode_info.num_hpd = 4;
4633                         adev->mode_info.num_dig = 4;
4634                         break;
4635                 default:
4636                         DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4637                                         adev->ip_versions[DCE_HWIP][0]);
4638                         return -EINVAL;
4639                 }
4640                 break;
4641         }
4642
4643         amdgpu_dm_set_irq_funcs(adev);
4644
4645         if (adev->mode_info.funcs == NULL)
4646                 adev->mode_info.funcs = &dm_display_funcs;
4647
4648         /*
4649          * Note: Do NOT change adev->audio_endpt_rreg and
4650          * adev->audio_endpt_wreg because they are initialised in
4651          * amdgpu_device_init()
4652          */
4653 #if defined(CONFIG_DEBUG_KERNEL_DC)
4654         device_create_file(
4655                 adev_to_drm(adev)->dev,
4656                 &dev_attr_s3_debug);
4657 #endif
4658         adev->dc_enabled = true;
4659
4660         return dm_init_microcode(adev);
4661 }
4662
4663 static bool modereset_required(struct drm_crtc_state *crtc_state)
4664 {
4665         return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4666 }
4667
4668 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4669 {
4670         drm_encoder_cleanup(encoder);
4671         kfree(encoder);
4672 }
4673
4674 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4675         .destroy = amdgpu_dm_encoder_destroy,
4676 };
4677
4678 static int
4679 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4680                             const enum surface_pixel_format format,
4681                             enum dc_color_space *color_space)
4682 {
4683         bool full_range;
4684
4685         *color_space = COLOR_SPACE_SRGB;
4686
4687         /* DRM color properties only affect non-RGB formats. */
4688         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4689                 return 0;
4690
4691         full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4692
4693         switch (plane_state->color_encoding) {
4694         case DRM_COLOR_YCBCR_BT601:
4695                 if (full_range)
4696                         *color_space = COLOR_SPACE_YCBCR601;
4697                 else
4698                         *color_space = COLOR_SPACE_YCBCR601_LIMITED;
4699                 break;
4700
4701         case DRM_COLOR_YCBCR_BT709:
4702                 if (full_range)
4703                         *color_space = COLOR_SPACE_YCBCR709;
4704                 else
4705                         *color_space = COLOR_SPACE_YCBCR709_LIMITED;
4706                 break;
4707
4708         case DRM_COLOR_YCBCR_BT2020:
4709                 if (full_range)
4710                         *color_space = COLOR_SPACE_2020_YCBCR;
4711                 else
4712                         return -EINVAL;
4713                 break;
4714
4715         default:
4716                 return -EINVAL;
4717         }
4718
4719         return 0;
4720 }
4721
4722 static int
4723 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4724                             const struct drm_plane_state *plane_state,
4725                             const u64 tiling_flags,
4726                             struct dc_plane_info *plane_info,
4727                             struct dc_plane_address *address,
4728                             bool tmz_surface,
4729                             bool force_disable_dcc)
4730 {
4731         const struct drm_framebuffer *fb = plane_state->fb;
4732         const struct amdgpu_framebuffer *afb =
4733                 to_amdgpu_framebuffer(plane_state->fb);
4734         int ret;
4735
4736         memset(plane_info, 0, sizeof(*plane_info));
4737
4738         switch (fb->format->format) {
4739         case DRM_FORMAT_C8:
4740                 plane_info->format =
4741                         SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4742                 break;
4743         case DRM_FORMAT_RGB565:
4744                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4745                 break;
4746         case DRM_FORMAT_XRGB8888:
4747         case DRM_FORMAT_ARGB8888:
4748                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4749                 break;
4750         case DRM_FORMAT_XRGB2101010:
4751         case DRM_FORMAT_ARGB2101010:
4752                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4753                 break;
4754         case DRM_FORMAT_XBGR2101010:
4755         case DRM_FORMAT_ABGR2101010:
4756                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4757                 break;
4758         case DRM_FORMAT_XBGR8888:
4759         case DRM_FORMAT_ABGR8888:
4760                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4761                 break;
4762         case DRM_FORMAT_NV21:
4763                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4764                 break;
4765         case DRM_FORMAT_NV12:
4766                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4767                 break;
4768         case DRM_FORMAT_P010:
4769                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4770                 break;
4771         case DRM_FORMAT_XRGB16161616F:
4772         case DRM_FORMAT_ARGB16161616F:
4773                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4774                 break;
4775         case DRM_FORMAT_XBGR16161616F:
4776         case DRM_FORMAT_ABGR16161616F:
4777                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4778                 break;
4779         case DRM_FORMAT_XRGB16161616:
4780         case DRM_FORMAT_ARGB16161616:
4781                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4782                 break;
4783         case DRM_FORMAT_XBGR16161616:
4784         case DRM_FORMAT_ABGR16161616:
4785                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4786                 break;
4787         default:
4788                 DRM_ERROR(
4789                         "Unsupported screen format %p4cc\n",
4790                         &fb->format->format);
4791                 return -EINVAL;
4792         }
4793
4794         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4795         case DRM_MODE_ROTATE_0:
4796                 plane_info->rotation = ROTATION_ANGLE_0;
4797                 break;
4798         case DRM_MODE_ROTATE_90:
4799                 plane_info->rotation = ROTATION_ANGLE_90;
4800                 break;
4801         case DRM_MODE_ROTATE_180:
4802                 plane_info->rotation = ROTATION_ANGLE_180;
4803                 break;
4804         case DRM_MODE_ROTATE_270:
4805                 plane_info->rotation = ROTATION_ANGLE_270;
4806                 break;
4807         default:
4808                 plane_info->rotation = ROTATION_ANGLE_0;
4809                 break;
4810         }
4811
4812
4813         plane_info->visible = true;
4814         plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4815
4816         plane_info->layer_index = plane_state->normalized_zpos;
4817
4818         ret = fill_plane_color_attributes(plane_state, plane_info->format,
4819                                           &plane_info->color_space);
4820         if (ret)
4821                 return ret;
4822
4823         ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4824                                            plane_info->rotation, tiling_flags,
4825                                            &plane_info->tiling_info,
4826                                            &plane_info->plane_size,
4827                                            &plane_info->dcc, address,
4828                                            tmz_surface, force_disable_dcc);
4829         if (ret)
4830                 return ret;
4831
4832         fill_blending_from_plane_state(
4833                 plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4834                 &plane_info->global_alpha, &plane_info->global_alpha_value);
4835
4836         return 0;
4837 }
4838
4839 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4840                                     struct dc_plane_state *dc_plane_state,
4841                                     struct drm_plane_state *plane_state,
4842                                     struct drm_crtc_state *crtc_state)
4843 {
4844         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4845         struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4846         struct dc_scaling_info scaling_info;
4847         struct dc_plane_info plane_info;
4848         int ret;
4849         bool force_disable_dcc = false;
4850
4851         ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4852         if (ret)
4853                 return ret;
4854
4855         dc_plane_state->src_rect = scaling_info.src_rect;
4856         dc_plane_state->dst_rect = scaling_info.dst_rect;
4857         dc_plane_state->clip_rect = scaling_info.clip_rect;
4858         dc_plane_state->scaling_quality = scaling_info.scaling_quality;
4859
4860         force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
4861         ret = fill_dc_plane_info_and_addr(adev, plane_state,
4862                                           afb->tiling_flags,
4863                                           &plane_info,
4864                                           &dc_plane_state->address,
4865                                           afb->tmz_surface,
4866                                           force_disable_dcc);
4867         if (ret)
4868                 return ret;
4869
4870         dc_plane_state->format = plane_info.format;
4871         dc_plane_state->color_space = plane_info.color_space;
4872         dc_plane_state->format = plane_info.format;
4873         dc_plane_state->plane_size = plane_info.plane_size;
4874         dc_plane_state->rotation = plane_info.rotation;
4875         dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
4876         dc_plane_state->stereo_format = plane_info.stereo_format;
4877         dc_plane_state->tiling_info = plane_info.tiling_info;
4878         dc_plane_state->visible = plane_info.visible;
4879         dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
4880         dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
4881         dc_plane_state->global_alpha = plane_info.global_alpha;
4882         dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
4883         dc_plane_state->dcc = plane_info.dcc;
4884         dc_plane_state->layer_index = plane_info.layer_index;
4885         dc_plane_state->flip_int_enabled = true;
4886
4887         /*
4888          * Always set input transfer function, since plane state is refreshed
4889          * every time.
4890          */
4891         ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
4892         if (ret)
4893                 return ret;
4894
4895         return 0;
4896 }
4897
4898 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
4899                                       struct rect *dirty_rect, int32_t x,
4900                                       s32 y, s32 width, s32 height,
4901                                       int *i, bool ffu)
4902 {
4903         if (*i > DC_MAX_DIRTY_RECTS)
4904                 return;
4905
4906         if (*i == DC_MAX_DIRTY_RECTS)
4907                 goto out;
4908
4909         dirty_rect->x = x;
4910         dirty_rect->y = y;
4911         dirty_rect->width = width;
4912         dirty_rect->height = height;
4913
4914         if (ffu)
4915                 drm_dbg(plane->dev,
4916                         "[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
4917                         plane->base.id, width, height);
4918         else
4919                 drm_dbg(plane->dev,
4920                         "[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
4921                         plane->base.id, x, y, width, height);
4922
4923 out:
4924         (*i)++;
4925 }
4926
4927 /**
4928  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
4929  *
4930  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
4931  *         remote fb
4932  * @old_plane_state: Old state of @plane
4933  * @new_plane_state: New state of @plane
4934  * @crtc_state: New state of CRTC connected to the @plane
4935  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
4936  *
4937  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
4938  * (referred to as "damage clips" in DRM nomenclature) that require updating on
4939  * the eDP remote buffer. The responsibility of specifying the dirty regions is
4940  * amdgpu_dm's.
4941  *
4942  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
4943  * plane with regions that require flushing to the eDP remote buffer. In
4944  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
4945  * implicitly provide damage clips without any client support via the plane
4946  * bounds.
4947  */
4948 static void fill_dc_dirty_rects(struct drm_plane *plane,
4949                                 struct drm_plane_state *old_plane_state,
4950                                 struct drm_plane_state *new_plane_state,
4951                                 struct drm_crtc_state *crtc_state,
4952                                 struct dc_flip_addrs *flip_addrs)
4953 {
4954         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4955         struct rect *dirty_rects = flip_addrs->dirty_rects;
4956         u32 num_clips;
4957         struct drm_mode_rect *clips;
4958         bool bb_changed;
4959         bool fb_changed;
4960         u32 i = 0;
4961
4962         /*
4963          * Cursor plane has it's own dirty rect update interface. See
4964          * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
4965          */
4966         if (plane->type == DRM_PLANE_TYPE_CURSOR)
4967                 return;
4968
4969         num_clips = drm_plane_get_damage_clips_count(new_plane_state);
4970         clips = drm_plane_get_damage_clips(new_plane_state);
4971
4972         if (!dm_crtc_state->mpo_requested) {
4973                 if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
4974                         goto ffu;
4975
4976                 for (; flip_addrs->dirty_rect_count < num_clips; clips++)
4977                         fill_dc_dirty_rect(new_plane_state->plane,
4978                                            &dirty_rects[i], clips->x1,
4979                                            clips->y1, clips->x2 - clips->x1,
4980                                            clips->y2 - clips->y1,
4981                                            &flip_addrs->dirty_rect_count,
4982                                            false);
4983                 return;
4984         }
4985
4986         /*
4987          * MPO is requested. Add entire plane bounding box to dirty rects if
4988          * flipped to or damaged.
4989          *
4990          * If plane is moved or resized, also add old bounding box to dirty
4991          * rects.
4992          */
4993         fb_changed = old_plane_state->fb->base.id !=
4994                      new_plane_state->fb->base.id;
4995         bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
4996                       old_plane_state->crtc_y != new_plane_state->crtc_y ||
4997                       old_plane_state->crtc_w != new_plane_state->crtc_w ||
4998                       old_plane_state->crtc_h != new_plane_state->crtc_h);
4999
5000         drm_dbg(plane->dev,
5001                 "[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
5002                 new_plane_state->plane->base.id,
5003                 bb_changed, fb_changed, num_clips);
5004
5005         if (bb_changed) {
5006                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5007                                    new_plane_state->crtc_x,
5008                                    new_plane_state->crtc_y,
5009                                    new_plane_state->crtc_w,
5010                                    new_plane_state->crtc_h, &i, false);
5011
5012                 /* Add old plane bounding-box if plane is moved or resized */
5013                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5014                                    old_plane_state->crtc_x,
5015                                    old_plane_state->crtc_y,
5016                                    old_plane_state->crtc_w,
5017                                    old_plane_state->crtc_h, &i, false);
5018         }
5019
5020         if (num_clips) {
5021                 for (; i < num_clips; clips++)
5022                         fill_dc_dirty_rect(new_plane_state->plane,
5023                                            &dirty_rects[i], clips->x1,
5024                                            clips->y1, clips->x2 - clips->x1,
5025                                            clips->y2 - clips->y1, &i, false);
5026         } else if (fb_changed && !bb_changed) {
5027                 fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
5028                                    new_plane_state->crtc_x,
5029                                    new_plane_state->crtc_y,
5030                                    new_plane_state->crtc_w,
5031                                    new_plane_state->crtc_h, &i, false);
5032         }
5033
5034         if (i > DC_MAX_DIRTY_RECTS)
5035                 goto ffu;
5036
5037         flip_addrs->dirty_rect_count = i;
5038         return;
5039
5040 ffu:
5041         fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
5042                            dm_crtc_state->base.mode.crtc_hdisplay,
5043                            dm_crtc_state->base.mode.crtc_vdisplay,
5044                            &flip_addrs->dirty_rect_count, true);
5045 }
5046
5047 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
5048                                            const struct dm_connector_state *dm_state,
5049                                            struct dc_stream_state *stream)
5050 {
5051         enum amdgpu_rmx_type rmx_type;
5052
5053         struct rect src = { 0 }; /* viewport in composition space*/
5054         struct rect dst = { 0 }; /* stream addressable area */
5055
5056         /* no mode. nothing to be done */
5057         if (!mode)
5058                 return;
5059
5060         /* Full screen scaling by default */
5061         src.width = mode->hdisplay;
5062         src.height = mode->vdisplay;
5063         dst.width = stream->timing.h_addressable;
5064         dst.height = stream->timing.v_addressable;
5065
5066         if (dm_state) {
5067                 rmx_type = dm_state->scaling;
5068                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5069                         if (src.width * dst.height <
5070                                         src.height * dst.width) {
5071                                 /* height needs less upscaling/more downscaling */
5072                                 dst.width = src.width *
5073                                                 dst.height / src.height;
5074                         } else {
5075                                 /* width needs less upscaling/more downscaling */
5076                                 dst.height = src.height *
5077                                                 dst.width / src.width;
5078                         }
5079                 } else if (rmx_type == RMX_CENTER) {
5080                         dst = src;
5081                 }
5082
5083                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
5084                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
5085
5086                 if (dm_state->underscan_enable) {
5087                         dst.x += dm_state->underscan_hborder / 2;
5088                         dst.y += dm_state->underscan_vborder / 2;
5089                         dst.width -= dm_state->underscan_hborder;
5090                         dst.height -= dm_state->underscan_vborder;
5091                 }
5092         }
5093
5094         stream->src = src;
5095         stream->dst = dst;
5096
5097         DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5098                       dst.x, dst.y, dst.width, dst.height);
5099
5100 }
5101
5102 static enum dc_color_depth
5103 convert_color_depth_from_display_info(const struct drm_connector *connector,
5104                                       bool is_y420, int requested_bpc)
5105 {
5106         u8 bpc;
5107
5108         if (is_y420) {
5109                 bpc = 8;
5110
5111                 /* Cap display bpc based on HDMI 2.0 HF-VSDB */
5112                 if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5113                         bpc = 16;
5114                 else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5115                         bpc = 12;
5116                 else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5117                         bpc = 10;
5118         } else {
5119                 bpc = (uint8_t)connector->display_info.bpc;
5120                 /* Assume 8 bpc by default if no bpc is specified. */
5121                 bpc = bpc ? bpc : 8;
5122         }
5123
5124         if (requested_bpc > 0) {
5125                 /*
5126                  * Cap display bpc based on the user requested value.
5127                  *
5128                  * The value for state->max_bpc may not correctly updated
5129                  * depending on when the connector gets added to the state
5130                  * or if this was called outside of atomic check, so it
5131                  * can't be used directly.
5132                  */
5133                 bpc = min_t(u8, bpc, requested_bpc);
5134
5135                 /* Round down to the nearest even number. */
5136                 bpc = bpc - (bpc & 1);
5137         }
5138
5139         switch (bpc) {
5140         case 0:
5141                 /*
5142                  * Temporary Work around, DRM doesn't parse color depth for
5143                  * EDID revision before 1.4
5144                  * TODO: Fix edid parsing
5145                  */
5146                 return COLOR_DEPTH_888;
5147         case 6:
5148                 return COLOR_DEPTH_666;
5149         case 8:
5150                 return COLOR_DEPTH_888;
5151         case 10:
5152                 return COLOR_DEPTH_101010;
5153         case 12:
5154                 return COLOR_DEPTH_121212;
5155         case 14:
5156                 return COLOR_DEPTH_141414;
5157         case 16:
5158                 return COLOR_DEPTH_161616;
5159         default:
5160                 return COLOR_DEPTH_UNDEFINED;
5161         }
5162 }
5163
5164 static enum dc_aspect_ratio
5165 get_aspect_ratio(const struct drm_display_mode *mode_in)
5166 {
5167         /* 1-1 mapping, since both enums follow the HDMI spec. */
5168         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5169 }
5170
5171 static enum dc_color_space
5172 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5173 {
5174         enum dc_color_space color_space = COLOR_SPACE_SRGB;
5175
5176         switch (dc_crtc_timing->pixel_encoding) {
5177         case PIXEL_ENCODING_YCBCR422:
5178         case PIXEL_ENCODING_YCBCR444:
5179         case PIXEL_ENCODING_YCBCR420:
5180         {
5181                 /*
5182                  * 27030khz is the separation point between HDTV and SDTV
5183                  * according to HDMI spec, we use YCbCr709 and YCbCr601
5184                  * respectively
5185                  */
5186                 if (dc_crtc_timing->pix_clk_100hz > 270300) {
5187                         if (dc_crtc_timing->flags.Y_ONLY)
5188                                 color_space =
5189                                         COLOR_SPACE_YCBCR709_LIMITED;
5190                         else
5191                                 color_space = COLOR_SPACE_YCBCR709;
5192                 } else {
5193                         if (dc_crtc_timing->flags.Y_ONLY)
5194                                 color_space =
5195                                         COLOR_SPACE_YCBCR601_LIMITED;
5196                         else
5197                                 color_space = COLOR_SPACE_YCBCR601;
5198                 }
5199
5200         }
5201         break;
5202         case PIXEL_ENCODING_RGB:
5203                 color_space = COLOR_SPACE_SRGB;
5204                 break;
5205
5206         default:
5207                 WARN_ON(1);
5208                 break;
5209         }
5210
5211         return color_space;
5212 }
5213
5214 static bool adjust_colour_depth_from_display_info(
5215         struct dc_crtc_timing *timing_out,
5216         const struct drm_display_info *info)
5217 {
5218         enum dc_color_depth depth = timing_out->display_color_depth;
5219         int normalized_clk;
5220         do {
5221                 normalized_clk = timing_out->pix_clk_100hz / 10;
5222                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5223                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5224                         normalized_clk /= 2;
5225                 /* Adjusting pix clock following on HDMI spec based on colour depth */
5226                 switch (depth) {
5227                 case COLOR_DEPTH_888:
5228                         break;
5229                 case COLOR_DEPTH_101010:
5230                         normalized_clk = (normalized_clk * 30) / 24;
5231                         break;
5232                 case COLOR_DEPTH_121212:
5233                         normalized_clk = (normalized_clk * 36) / 24;
5234                         break;
5235                 case COLOR_DEPTH_161616:
5236                         normalized_clk = (normalized_clk * 48) / 24;
5237                         break;
5238                 default:
5239                         /* The above depths are the only ones valid for HDMI. */
5240                         return false;
5241                 }
5242                 if (normalized_clk <= info->max_tmds_clock) {
5243                         timing_out->display_color_depth = depth;
5244                         return true;
5245                 }
5246         } while (--depth > COLOR_DEPTH_666);
5247         return false;
5248 }
5249
5250 static void fill_stream_properties_from_drm_display_mode(
5251         struct dc_stream_state *stream,
5252         const struct drm_display_mode *mode_in,
5253         const struct drm_connector *connector,
5254         const struct drm_connector_state *connector_state,
5255         const struct dc_stream_state *old_stream,
5256         int requested_bpc)
5257 {
5258         struct dc_crtc_timing *timing_out = &stream->timing;
5259         const struct drm_display_info *info = &connector->display_info;
5260         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5261         struct hdmi_vendor_infoframe hv_frame;
5262         struct hdmi_avi_infoframe avi_frame;
5263
5264         memset(&hv_frame, 0, sizeof(hv_frame));
5265         memset(&avi_frame, 0, sizeof(avi_frame));
5266
5267         timing_out->h_border_left = 0;
5268         timing_out->h_border_right = 0;
5269         timing_out->v_border_top = 0;
5270         timing_out->v_border_bottom = 0;
5271         /* TODO: un-hardcode */
5272         if (drm_mode_is_420_only(info, mode_in)
5273                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5274                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5275         else if (drm_mode_is_420_also(info, mode_in)
5276                         && aconnector->force_yuv420_output)
5277                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5278         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5279                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5280                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5281         else
5282                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5283
5284         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5285         timing_out->display_color_depth = convert_color_depth_from_display_info(
5286                 connector,
5287                 (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5288                 requested_bpc);
5289         timing_out->scan_type = SCANNING_TYPE_NODATA;
5290         timing_out->hdmi_vic = 0;
5291
5292         if (old_stream) {
5293                 timing_out->vic = old_stream->timing.vic;
5294                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5295                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5296         } else {
5297                 timing_out->vic = drm_match_cea_mode(mode_in);
5298                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5299                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5300                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5301                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5302         }
5303
5304         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5305                 drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5306                 timing_out->vic = avi_frame.video_code;
5307                 drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5308                 timing_out->hdmi_vic = hv_frame.vic;
5309         }
5310
5311         if (is_freesync_video_mode(mode_in, aconnector)) {
5312                 timing_out->h_addressable = mode_in->hdisplay;
5313                 timing_out->h_total = mode_in->htotal;
5314                 timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5315                 timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5316                 timing_out->v_total = mode_in->vtotal;
5317                 timing_out->v_addressable = mode_in->vdisplay;
5318                 timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5319                 timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5320                 timing_out->pix_clk_100hz = mode_in->clock * 10;
5321         } else {
5322                 timing_out->h_addressable = mode_in->crtc_hdisplay;
5323                 timing_out->h_total = mode_in->crtc_htotal;
5324                 timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5325                 timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5326                 timing_out->v_total = mode_in->crtc_vtotal;
5327                 timing_out->v_addressable = mode_in->crtc_vdisplay;
5328                 timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5329                 timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5330                 timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5331         }
5332
5333         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5334
5335         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5336         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5337         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5338                 if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5339                     drm_mode_is_420_also(info, mode_in) &&
5340                     timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5341                         timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5342                         adjust_colour_depth_from_display_info(timing_out, info);
5343                 }
5344         }
5345
5346         stream->output_color_space = get_output_color_space(timing_out);
5347 }
5348
5349 static void fill_audio_info(struct audio_info *audio_info,
5350                             const struct drm_connector *drm_connector,
5351                             const struct dc_sink *dc_sink)
5352 {
5353         int i = 0;
5354         int cea_revision = 0;
5355         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5356
5357         audio_info->manufacture_id = edid_caps->manufacturer_id;
5358         audio_info->product_id = edid_caps->product_id;
5359
5360         cea_revision = drm_connector->display_info.cea_rev;
5361
5362         strscpy(audio_info->display_name,
5363                 edid_caps->display_name,
5364                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5365
5366         if (cea_revision >= 3) {
5367                 audio_info->mode_count = edid_caps->audio_mode_count;
5368
5369                 for (i = 0; i < audio_info->mode_count; ++i) {
5370                         audio_info->modes[i].format_code =
5371                                         (enum audio_format_code)
5372                                         (edid_caps->audio_modes[i].format_code);
5373                         audio_info->modes[i].channel_count =
5374                                         edid_caps->audio_modes[i].channel_count;
5375                         audio_info->modes[i].sample_rates.all =
5376                                         edid_caps->audio_modes[i].sample_rate;
5377                         audio_info->modes[i].sample_size =
5378                                         edid_caps->audio_modes[i].sample_size;
5379                 }
5380         }
5381
5382         audio_info->flags.all = edid_caps->speaker_flags;
5383
5384         /* TODO: We only check for the progressive mode, check for interlace mode too */
5385         if (drm_connector->latency_present[0]) {
5386                 audio_info->video_latency = drm_connector->video_latency[0];
5387                 audio_info->audio_latency = drm_connector->audio_latency[0];
5388         }
5389
5390         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5391
5392 }
5393
5394 static void
5395 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5396                                       struct drm_display_mode *dst_mode)
5397 {
5398         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5399         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5400         dst_mode->crtc_clock = src_mode->crtc_clock;
5401         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5402         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5403         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5404         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5405         dst_mode->crtc_htotal = src_mode->crtc_htotal;
5406         dst_mode->crtc_hskew = src_mode->crtc_hskew;
5407         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5408         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5409         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5410         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5411         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5412 }
5413
5414 static void
5415 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5416                                         const struct drm_display_mode *native_mode,
5417                                         bool scale_enabled)
5418 {
5419         if (scale_enabled) {
5420                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5421         } else if (native_mode->clock == drm_mode->clock &&
5422                         native_mode->htotal == drm_mode->htotal &&
5423                         native_mode->vtotal == drm_mode->vtotal) {
5424                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5425         } else {
5426                 /* no scaling nor amdgpu inserted, no need to patch */
5427         }
5428 }
5429
5430 static struct dc_sink *
5431 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5432 {
5433         struct dc_sink_init_data sink_init_data = { 0 };
5434         struct dc_sink *sink = NULL;
5435         sink_init_data.link = aconnector->dc_link;
5436         sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5437
5438         sink = dc_sink_create(&sink_init_data);
5439         if (!sink) {
5440                 DRM_ERROR("Failed to create sink!\n");
5441                 return NULL;
5442         }
5443         sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5444
5445         return sink;
5446 }
5447
5448 static void set_multisync_trigger_params(
5449                 struct dc_stream_state *stream)
5450 {
5451         struct dc_stream_state *master = NULL;
5452
5453         if (stream->triggered_crtc_reset.enabled) {
5454                 master = stream->triggered_crtc_reset.event_source;
5455                 stream->triggered_crtc_reset.event =
5456                         master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5457                         CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5458                 stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5459         }
5460 }
5461
5462 static void set_master_stream(struct dc_stream_state *stream_set[],
5463                               int stream_count)
5464 {
5465         int j, highest_rfr = 0, master_stream = 0;
5466
5467         for (j = 0;  j < stream_count; j++) {
5468                 if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5469                         int refresh_rate = 0;
5470
5471                         refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5472                                 (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5473                         if (refresh_rate > highest_rfr) {
5474                                 highest_rfr = refresh_rate;
5475                                 master_stream = j;
5476                         }
5477                 }
5478         }
5479         for (j = 0;  j < stream_count; j++) {
5480                 if (stream_set[j])
5481                         stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5482         }
5483 }
5484
5485 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5486 {
5487         int i = 0;
5488         struct dc_stream_state *stream;
5489
5490         if (context->stream_count < 2)
5491                 return;
5492         for (i = 0; i < context->stream_count ; i++) {
5493                 if (!context->streams[i])
5494                         continue;
5495                 /*
5496                  * TODO: add a function to read AMD VSDB bits and set
5497                  * crtc_sync_master.multi_sync_enabled flag
5498                  * For now it's set to false
5499                  */
5500         }
5501
5502         set_master_stream(context->streams, context->stream_count);
5503
5504         for (i = 0; i < context->stream_count ; i++) {
5505                 stream = context->streams[i];
5506
5507                 if (!stream)
5508                         continue;
5509
5510                 set_multisync_trigger_params(stream);
5511         }
5512 }
5513
5514 /**
5515  * DOC: FreeSync Video
5516  *
5517  * When a userspace application wants to play a video, the content follows a
5518  * standard format definition that usually specifies the FPS for that format.
5519  * The below list illustrates some video format and the expected FPS,
5520  * respectively:
5521  *
5522  * - TV/NTSC (23.976 FPS)
5523  * - Cinema (24 FPS)
5524  * - TV/PAL (25 FPS)
5525  * - TV/NTSC (29.97 FPS)
5526  * - TV/NTSC (30 FPS)
5527  * - Cinema HFR (48 FPS)
5528  * - TV/PAL (50 FPS)
5529  * - Commonly used (60 FPS)
5530  * - Multiples of 24 (48,72,96 FPS)
5531  *
5532  * The list of standards video format is not huge and can be added to the
5533  * connector modeset list beforehand. With that, userspace can leverage
5534  * FreeSync to extends the front porch in order to attain the target refresh
5535  * rate. Such a switch will happen seamlessly, without screen blanking or
5536  * reprogramming of the output in any other way. If the userspace requests a
5537  * modesetting change compatible with FreeSync modes that only differ in the
5538  * refresh rate, DC will skip the full update and avoid blink during the
5539  * transition. For example, the video player can change the modesetting from
5540  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5541  * causing any display blink. This same concept can be applied to a mode
5542  * setting change.
5543  */
5544 static struct drm_display_mode *
5545 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5546                 bool use_probed_modes)
5547 {
5548         struct drm_display_mode *m, *m_pref = NULL;
5549         u16 current_refresh, highest_refresh;
5550         struct list_head *list_head = use_probed_modes ?
5551                 &aconnector->base.probed_modes :
5552                 &aconnector->base.modes;
5553
5554         if (aconnector->freesync_vid_base.clock != 0)
5555                 return &aconnector->freesync_vid_base;
5556
5557         /* Find the preferred mode */
5558         list_for_each_entry (m, list_head, head) {
5559                 if (m->type & DRM_MODE_TYPE_PREFERRED) {
5560                         m_pref = m;
5561                         break;
5562                 }
5563         }
5564
5565         if (!m_pref) {
5566                 /* Probably an EDID with no preferred mode. Fallback to first entry */
5567                 m_pref = list_first_entry_or_null(
5568                                 &aconnector->base.modes, struct drm_display_mode, head);
5569                 if (!m_pref) {
5570                         DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5571                         return NULL;
5572                 }
5573         }
5574
5575         highest_refresh = drm_mode_vrefresh(m_pref);
5576
5577         /*
5578          * Find the mode with highest refresh rate with same resolution.
5579          * For some monitors, preferred mode is not the mode with highest
5580          * supported refresh rate.
5581          */
5582         list_for_each_entry (m, list_head, head) {
5583                 current_refresh  = drm_mode_vrefresh(m);
5584
5585                 if (m->hdisplay == m_pref->hdisplay &&
5586                     m->vdisplay == m_pref->vdisplay &&
5587                     highest_refresh < current_refresh) {
5588                         highest_refresh = current_refresh;
5589                         m_pref = m;
5590                 }
5591         }
5592
5593         drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5594         return m_pref;
5595 }
5596
5597 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5598                 struct amdgpu_dm_connector *aconnector)
5599 {
5600         struct drm_display_mode *high_mode;
5601         int timing_diff;
5602
5603         high_mode = get_highest_refresh_rate_mode(aconnector, false);
5604         if (!high_mode || !mode)
5605                 return false;
5606
5607         timing_diff = high_mode->vtotal - mode->vtotal;
5608
5609         if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5610             high_mode->hdisplay != mode->hdisplay ||
5611             high_mode->vdisplay != mode->vdisplay ||
5612             high_mode->hsync_start != mode->hsync_start ||
5613             high_mode->hsync_end != mode->hsync_end ||
5614             high_mode->htotal != mode->htotal ||
5615             high_mode->hskew != mode->hskew ||
5616             high_mode->vscan != mode->vscan ||
5617             high_mode->vsync_start - mode->vsync_start != timing_diff ||
5618             high_mode->vsync_end - mode->vsync_end != timing_diff)
5619                 return false;
5620         else
5621                 return true;
5622 }
5623
5624 #if defined(CONFIG_DRM_AMD_DC_DCN)
5625 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5626                             struct dc_sink *sink, struct dc_stream_state *stream,
5627                             struct dsc_dec_dpcd_caps *dsc_caps)
5628 {
5629         stream->timing.flags.DSC = 0;
5630         dsc_caps->is_dsc_supported = false;
5631
5632         if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5633             sink->sink_signal == SIGNAL_TYPE_EDP)) {
5634                 if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5635                         sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5636                         dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5637                                 aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5638                                 aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5639                                 dsc_caps);
5640         }
5641 }
5642
5643
5644 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5645                                     struct dc_sink *sink, struct dc_stream_state *stream,
5646                                     struct dsc_dec_dpcd_caps *dsc_caps,
5647                                     uint32_t max_dsc_target_bpp_limit_override)
5648 {
5649         const struct dc_link_settings *verified_link_cap = NULL;
5650         u32 link_bw_in_kbps;
5651         u32 edp_min_bpp_x16, edp_max_bpp_x16;
5652         struct dc *dc = sink->ctx->dc;
5653         struct dc_dsc_bw_range bw_range = {0};
5654         struct dc_dsc_config dsc_cfg = {0};
5655
5656         verified_link_cap = dc_link_get_link_cap(stream->link);
5657         link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5658         edp_min_bpp_x16 = 8 * 16;
5659         edp_max_bpp_x16 = 8 * 16;
5660
5661         if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5662                 edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5663
5664         if (edp_max_bpp_x16 < edp_min_bpp_x16)
5665                 edp_min_bpp_x16 = edp_max_bpp_x16;
5666
5667         if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5668                                 dc->debug.dsc_min_slice_height_override,
5669                                 edp_min_bpp_x16, edp_max_bpp_x16,
5670                                 dsc_caps,
5671                                 &stream->timing,
5672                                 &bw_range)) {
5673
5674                 if (bw_range.max_kbps < link_bw_in_kbps) {
5675                         if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5676                                         dsc_caps,
5677                                         dc->debug.dsc_min_slice_height_override,
5678                                         max_dsc_target_bpp_limit_override,
5679                                         0,
5680                                         &stream->timing,
5681                                         &dsc_cfg)) {
5682                                 stream->timing.dsc_cfg = dsc_cfg;
5683                                 stream->timing.flags.DSC = 1;
5684                                 stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5685                         }
5686                         return;
5687                 }
5688         }
5689
5690         if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5691                                 dsc_caps,
5692                                 dc->debug.dsc_min_slice_height_override,
5693                                 max_dsc_target_bpp_limit_override,
5694                                 link_bw_in_kbps,
5695                                 &stream->timing,
5696                                 &dsc_cfg)) {
5697                 stream->timing.dsc_cfg = dsc_cfg;
5698                 stream->timing.flags.DSC = 1;
5699         }
5700 }
5701
5702
5703 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5704                                         struct dc_sink *sink, struct dc_stream_state *stream,
5705                                         struct dsc_dec_dpcd_caps *dsc_caps)
5706 {
5707         struct drm_connector *drm_connector = &aconnector->base;
5708         u32 link_bandwidth_kbps;
5709         struct dc *dc = sink->ctx->dc;
5710         u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
5711         u32 dsc_max_supported_bw_in_kbps;
5712         u32 max_dsc_target_bpp_limit_override =
5713                 drm_connector->display_info.max_dsc_bpp;
5714
5715         link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5716                                                         dc_link_get_link_cap(aconnector->dc_link));
5717
5718         /* Set DSC policy according to dsc_clock_en */
5719         dc_dsc_policy_set_enable_dsc_when_not_needed(
5720                 aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5721
5722         if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5723             !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5724             dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5725
5726                 apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5727
5728         } else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5729                 if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5730                         if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5731                                                 dsc_caps,
5732                                                 aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5733                                                 max_dsc_target_bpp_limit_override,
5734                                                 link_bandwidth_kbps,
5735                                                 &stream->timing,
5736                                                 &stream->timing.dsc_cfg)) {
5737                                 stream->timing.flags.DSC = 1;
5738                                 DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5739                         }
5740                 } else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5741                         timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5742                         max_supported_bw_in_kbps = link_bandwidth_kbps;
5743                         dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5744
5745                         if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5746                                         max_supported_bw_in_kbps > 0 &&
5747                                         dsc_max_supported_bw_in_kbps > 0)
5748                                 if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5749                                                 dsc_caps,
5750                                                 aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5751                                                 max_dsc_target_bpp_limit_override,
5752                                                 dsc_max_supported_bw_in_kbps,
5753                                                 &stream->timing,
5754                                                 &stream->timing.dsc_cfg)) {
5755                                         stream->timing.flags.DSC = 1;
5756                                         DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5757                                                                          __func__, drm_connector->name);
5758                                 }
5759                 }
5760         }
5761
5762         /* Overwrite the stream flag if DSC is enabled through debugfs */
5763         if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5764                 stream->timing.flags.DSC = 1;
5765
5766         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5767                 stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5768
5769         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5770                 stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5771
5772         if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5773                 stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5774 }
5775 #endif /* CONFIG_DRM_AMD_DC_DCN */
5776
5777 static struct dc_stream_state *
5778 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5779                        const struct drm_display_mode *drm_mode,
5780                        const struct dm_connector_state *dm_state,
5781                        const struct dc_stream_state *old_stream,
5782                        int requested_bpc)
5783 {
5784         struct drm_display_mode *preferred_mode = NULL;
5785         struct drm_connector *drm_connector;
5786         const struct drm_connector_state *con_state =
5787                 dm_state ? &dm_state->base : NULL;
5788         struct dc_stream_state *stream = NULL;
5789         struct drm_display_mode mode;
5790         struct drm_display_mode saved_mode;
5791         struct drm_display_mode *freesync_mode = NULL;
5792         bool native_mode_found = false;
5793         bool recalculate_timing = false;
5794         bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5795         int mode_refresh;
5796         int preferred_refresh = 0;
5797         enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
5798 #if defined(CONFIG_DRM_AMD_DC_DCN)
5799         struct dsc_dec_dpcd_caps dsc_caps;
5800 #endif
5801
5802         struct dc_sink *sink = NULL;
5803
5804         drm_mode_init(&mode, drm_mode);
5805         memset(&saved_mode, 0, sizeof(saved_mode));
5806
5807         if (aconnector == NULL) {
5808                 DRM_ERROR("aconnector is NULL!\n");
5809                 return stream;
5810         }
5811
5812         drm_connector = &aconnector->base;
5813
5814         if (!aconnector->dc_sink) {
5815                 sink = create_fake_sink(aconnector);
5816                 if (!sink)
5817                         return stream;
5818         } else {
5819                 sink = aconnector->dc_sink;
5820                 dc_sink_retain(sink);
5821         }
5822
5823         stream = dc_create_stream_for_sink(sink);
5824
5825         if (stream == NULL) {
5826                 DRM_ERROR("Failed to create stream for sink!\n");
5827                 goto finish;
5828         }
5829
5830         stream->dm_stream_context = aconnector;
5831
5832         stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5833                 drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5834
5835         list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5836                 /* Search for preferred mode */
5837                 if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5838                         native_mode_found = true;
5839                         break;
5840                 }
5841         }
5842         if (!native_mode_found)
5843                 preferred_mode = list_first_entry_or_null(
5844                                 &aconnector->base.modes,
5845                                 struct drm_display_mode,
5846                                 head);
5847
5848         mode_refresh = drm_mode_vrefresh(&mode);
5849
5850         if (preferred_mode == NULL) {
5851                 /*
5852                  * This may not be an error, the use case is when we have no
5853                  * usermode calls to reset and set mode upon hotplug. In this
5854                  * case, we call set mode ourselves to restore the previous mode
5855                  * and the modelist may not be filled in in time.
5856                  */
5857                 DRM_DEBUG_DRIVER("No preferred mode found\n");
5858         } else {
5859                 recalculate_timing = amdgpu_freesync_vid_mode &&
5860                                  is_freesync_video_mode(&mode, aconnector);
5861                 if (recalculate_timing) {
5862                         freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5863                         drm_mode_copy(&saved_mode, &mode);
5864                         drm_mode_copy(&mode, freesync_mode);
5865                 } else {
5866                         decide_crtc_timing_for_drm_display_mode(
5867                                         &mode, preferred_mode, scale);
5868
5869                         preferred_refresh = drm_mode_vrefresh(preferred_mode);
5870                 }
5871         }
5872
5873         if (recalculate_timing)
5874                 drm_mode_set_crtcinfo(&saved_mode, 0);
5875         else if (!dm_state)
5876                 drm_mode_set_crtcinfo(&mode, 0);
5877
5878         /*
5879         * If scaling is enabled and refresh rate didn't change
5880         * we copy the vic and polarities of the old timings
5881         */
5882         if (!scale || mode_refresh != preferred_refresh)
5883                 fill_stream_properties_from_drm_display_mode(
5884                         stream, &mode, &aconnector->base, con_state, NULL,
5885                         requested_bpc);
5886         else
5887                 fill_stream_properties_from_drm_display_mode(
5888                         stream, &mode, &aconnector->base, con_state, old_stream,
5889                         requested_bpc);
5890
5891 #if defined(CONFIG_DRM_AMD_DC_DCN)
5892         /* SST DSC determination policy */
5893         update_dsc_caps(aconnector, sink, stream, &dsc_caps);
5894         if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
5895                 apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
5896 #endif
5897
5898         update_stream_scaling_settings(&mode, dm_state, stream);
5899
5900         fill_audio_info(
5901                 &stream->audio_info,
5902                 drm_connector,
5903                 sink);
5904
5905         update_stream_signal(stream, sink);
5906
5907         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5908                 mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
5909
5910         if (stream->link->psr_settings.psr_feature_enabled) {
5911                 //
5912                 // should decide stream support vsc sdp colorimetry capability
5913                 // before building vsc info packet
5914                 //
5915                 stream->use_vsc_sdp_for_colorimetry = false;
5916                 if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
5917                         stream->use_vsc_sdp_for_colorimetry =
5918                                 aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
5919                 } else {
5920                         if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
5921                                 stream->use_vsc_sdp_for_colorimetry = true;
5922                 }
5923                 if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
5924                         tf = TRANSFER_FUNC_GAMMA_22;
5925                 mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
5926                 aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
5927
5928         }
5929 finish:
5930         dc_sink_release(sink);
5931
5932         return stream;
5933 }
5934
5935 static enum drm_connector_status
5936 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
5937 {
5938         bool connected;
5939         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5940
5941         /*
5942          * Notes:
5943          * 1. This interface is NOT called in context of HPD irq.
5944          * 2. This interface *is called* in context of user-mode ioctl. Which
5945          * makes it a bad place for *any* MST-related activity.
5946          */
5947
5948         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
5949             !aconnector->fake_enable)
5950                 connected = (aconnector->dc_sink != NULL);
5951         else
5952                 connected = (aconnector->base.force == DRM_FORCE_ON ||
5953                                 aconnector->base.force == DRM_FORCE_ON_DIGITAL);
5954
5955         update_subconnector_property(aconnector);
5956
5957         return (connected ? connector_status_connected :
5958                         connector_status_disconnected);
5959 }
5960
5961 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
5962                                             struct drm_connector_state *connector_state,
5963                                             struct drm_property *property,
5964                                             uint64_t val)
5965 {
5966         struct drm_device *dev = connector->dev;
5967         struct amdgpu_device *adev = drm_to_adev(dev);
5968         struct dm_connector_state *dm_old_state =
5969                 to_dm_connector_state(connector->state);
5970         struct dm_connector_state *dm_new_state =
5971                 to_dm_connector_state(connector_state);
5972
5973         int ret = -EINVAL;
5974
5975         if (property == dev->mode_config.scaling_mode_property) {
5976                 enum amdgpu_rmx_type rmx_type;
5977
5978                 switch (val) {
5979                 case DRM_MODE_SCALE_CENTER:
5980                         rmx_type = RMX_CENTER;
5981                         break;
5982                 case DRM_MODE_SCALE_ASPECT:
5983                         rmx_type = RMX_ASPECT;
5984                         break;
5985                 case DRM_MODE_SCALE_FULLSCREEN:
5986                         rmx_type = RMX_FULL;
5987                         break;
5988                 case DRM_MODE_SCALE_NONE:
5989                 default:
5990                         rmx_type = RMX_OFF;
5991                         break;
5992                 }
5993
5994                 if (dm_old_state->scaling == rmx_type)
5995                         return 0;
5996
5997                 dm_new_state->scaling = rmx_type;
5998                 ret = 0;
5999         } else if (property == adev->mode_info.underscan_hborder_property) {
6000                 dm_new_state->underscan_hborder = val;
6001                 ret = 0;
6002         } else if (property == adev->mode_info.underscan_vborder_property) {
6003                 dm_new_state->underscan_vborder = val;
6004                 ret = 0;
6005         } else if (property == adev->mode_info.underscan_property) {
6006                 dm_new_state->underscan_enable = val;
6007                 ret = 0;
6008         } else if (property == adev->mode_info.abm_level_property) {
6009                 dm_new_state->abm_level = val;
6010                 ret = 0;
6011         }
6012
6013         return ret;
6014 }
6015
6016 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
6017                                             const struct drm_connector_state *state,
6018                                             struct drm_property *property,
6019                                             uint64_t *val)
6020 {
6021         struct drm_device *dev = connector->dev;
6022         struct amdgpu_device *adev = drm_to_adev(dev);
6023         struct dm_connector_state *dm_state =
6024                 to_dm_connector_state(state);
6025         int ret = -EINVAL;
6026
6027         if (property == dev->mode_config.scaling_mode_property) {
6028                 switch (dm_state->scaling) {
6029                 case RMX_CENTER:
6030                         *val = DRM_MODE_SCALE_CENTER;
6031                         break;
6032                 case RMX_ASPECT:
6033                         *val = DRM_MODE_SCALE_ASPECT;
6034                         break;
6035                 case RMX_FULL:
6036                         *val = DRM_MODE_SCALE_FULLSCREEN;
6037                         break;
6038                 case RMX_OFF:
6039                 default:
6040                         *val = DRM_MODE_SCALE_NONE;
6041                         break;
6042                 }
6043                 ret = 0;
6044         } else if (property == adev->mode_info.underscan_hborder_property) {
6045                 *val = dm_state->underscan_hborder;
6046                 ret = 0;
6047         } else if (property == adev->mode_info.underscan_vborder_property) {
6048                 *val = dm_state->underscan_vborder;
6049                 ret = 0;
6050         } else if (property == adev->mode_info.underscan_property) {
6051                 *val = dm_state->underscan_enable;
6052                 ret = 0;
6053         } else if (property == adev->mode_info.abm_level_property) {
6054                 *val = dm_state->abm_level;
6055                 ret = 0;
6056         }
6057
6058         return ret;
6059 }
6060
6061 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6062 {
6063         struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6064
6065         drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6066 }
6067
6068 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6069 {
6070         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6071         const struct dc_link *link = aconnector->dc_link;
6072         struct amdgpu_device *adev = drm_to_adev(connector->dev);
6073         struct amdgpu_display_manager *dm = &adev->dm;
6074         int i;
6075
6076         /*
6077          * Call only if mst_mgr was initialized before since it's not done
6078          * for all connector types.
6079          */
6080         if (aconnector->mst_mgr.dev)
6081                 drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6082
6083 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
6084         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
6085         for (i = 0; i < dm->num_of_edps; i++) {
6086                 if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6087                         backlight_device_unregister(dm->backlight_dev[i]);
6088                         dm->backlight_dev[i] = NULL;
6089                 }
6090         }
6091 #endif
6092
6093         if (aconnector->dc_em_sink)
6094                 dc_sink_release(aconnector->dc_em_sink);
6095         aconnector->dc_em_sink = NULL;
6096         if (aconnector->dc_sink)
6097                 dc_sink_release(aconnector->dc_sink);
6098         aconnector->dc_sink = NULL;
6099
6100         drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6101         drm_connector_unregister(connector);
6102         drm_connector_cleanup(connector);
6103         if (aconnector->i2c) {
6104                 i2c_del_adapter(&aconnector->i2c->base);
6105                 kfree(aconnector->i2c);
6106         }
6107         kfree(aconnector->dm_dp_aux.aux.name);
6108
6109         kfree(connector);
6110 }
6111
6112 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6113 {
6114         struct dm_connector_state *state =
6115                 to_dm_connector_state(connector->state);
6116
6117         if (connector->state)
6118                 __drm_atomic_helper_connector_destroy_state(connector->state);
6119
6120         kfree(state);
6121
6122         state = kzalloc(sizeof(*state), GFP_KERNEL);
6123
6124         if (state) {
6125                 state->scaling = RMX_OFF;
6126                 state->underscan_enable = false;
6127                 state->underscan_hborder = 0;
6128                 state->underscan_vborder = 0;
6129                 state->base.max_requested_bpc = 8;
6130                 state->vcpi_slots = 0;
6131                 state->pbn = 0;
6132
6133                 if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6134                         state->abm_level = amdgpu_dm_abm_level;
6135
6136                 __drm_atomic_helper_connector_reset(connector, &state->base);
6137         }
6138 }
6139
6140 struct drm_connector_state *
6141 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6142 {
6143         struct dm_connector_state *state =
6144                 to_dm_connector_state(connector->state);
6145
6146         struct dm_connector_state *new_state =
6147                         kmemdup(state, sizeof(*state), GFP_KERNEL);
6148
6149         if (!new_state)
6150                 return NULL;
6151
6152         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6153
6154         new_state->freesync_capable = state->freesync_capable;
6155         new_state->abm_level = state->abm_level;
6156         new_state->scaling = state->scaling;
6157         new_state->underscan_enable = state->underscan_enable;
6158         new_state->underscan_hborder = state->underscan_hborder;
6159         new_state->underscan_vborder = state->underscan_vborder;
6160         new_state->vcpi_slots = state->vcpi_slots;
6161         new_state->pbn = state->pbn;
6162         return &new_state->base;
6163 }
6164
6165 static int
6166 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6167 {
6168         struct amdgpu_dm_connector *amdgpu_dm_connector =
6169                 to_amdgpu_dm_connector(connector);
6170         int r;
6171
6172         if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6173             (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6174                 amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6175                 r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6176                 if (r)
6177                         return r;
6178         }
6179
6180 #if defined(CONFIG_DEBUG_FS)
6181         connector_debugfs_init(amdgpu_dm_connector);
6182 #endif
6183
6184         return 0;
6185 }
6186
6187 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6188         .reset = amdgpu_dm_connector_funcs_reset,
6189         .detect = amdgpu_dm_connector_detect,
6190         .fill_modes = drm_helper_probe_single_connector_modes,
6191         .destroy = amdgpu_dm_connector_destroy,
6192         .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6193         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6194         .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6195         .atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6196         .late_register = amdgpu_dm_connector_late_register,
6197         .early_unregister = amdgpu_dm_connector_unregister
6198 };
6199
6200 static int get_modes(struct drm_connector *connector)
6201 {
6202         return amdgpu_dm_connector_get_modes(connector);
6203 }
6204
6205 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6206 {
6207         struct dc_sink_init_data init_params = {
6208                         .link = aconnector->dc_link,
6209                         .sink_signal = SIGNAL_TYPE_VIRTUAL
6210         };
6211         struct edid *edid;
6212
6213         if (!aconnector->base.edid_blob_ptr) {
6214                 DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6215                                 aconnector->base.name);
6216
6217                 aconnector->base.force = DRM_FORCE_OFF;
6218                 return;
6219         }
6220
6221         edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6222
6223         aconnector->edid = edid;
6224
6225         aconnector->dc_em_sink = dc_link_add_remote_sink(
6226                 aconnector->dc_link,
6227                 (uint8_t *)edid,
6228                 (edid->extensions + 1) * EDID_LENGTH,
6229                 &init_params);
6230
6231         if (aconnector->base.force == DRM_FORCE_ON) {
6232                 aconnector->dc_sink = aconnector->dc_link->local_sink ?
6233                 aconnector->dc_link->local_sink :
6234                 aconnector->dc_em_sink;
6235                 dc_sink_retain(aconnector->dc_sink);
6236         }
6237 }
6238
6239 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6240 {
6241         struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6242
6243         /*
6244          * In case of headless boot with force on for DP managed connector
6245          * Those settings have to be != 0 to get initial modeset
6246          */
6247         if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6248                 link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6249                 link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6250         }
6251
6252         create_eml_sink(aconnector);
6253 }
6254
6255 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
6256                                                 struct dc_stream_state *stream)
6257 {
6258         enum dc_status dc_result = DC_ERROR_UNEXPECTED;
6259         struct dc_plane_state *dc_plane_state = NULL;
6260         struct dc_state *dc_state = NULL;
6261
6262         if (!stream)
6263                 goto cleanup;
6264
6265         dc_plane_state = dc_create_plane_state(dc);
6266         if (!dc_plane_state)
6267                 goto cleanup;
6268
6269         dc_state = dc_create_state(dc);
6270         if (!dc_state)
6271                 goto cleanup;
6272
6273         /* populate stream to plane */
6274         dc_plane_state->src_rect.height  = stream->src.height;
6275         dc_plane_state->src_rect.width   = stream->src.width;
6276         dc_plane_state->dst_rect.height  = stream->src.height;
6277         dc_plane_state->dst_rect.width   = stream->src.width;
6278         dc_plane_state->clip_rect.height = stream->src.height;
6279         dc_plane_state->clip_rect.width  = stream->src.width;
6280         dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
6281         dc_plane_state->plane_size.surface_size.height = stream->src.height;
6282         dc_plane_state->plane_size.surface_size.width  = stream->src.width;
6283         dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
6284         dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
6285         dc_plane_state->tiling_info.gfx9.swizzle =  DC_SW_UNKNOWN;
6286         dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6287         dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
6288         dc_plane_state->rotation = ROTATION_ANGLE_0;
6289         dc_plane_state->is_tiling_rotated = false;
6290         dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
6291
6292         dc_result = dc_validate_stream(dc, stream);
6293         if (dc_result == DC_OK)
6294                 dc_result = dc_validate_plane(dc, dc_plane_state);
6295
6296         if (dc_result == DC_OK)
6297                 dc_result = dc_add_stream_to_ctx(dc, dc_state, stream);
6298
6299         if (dc_result == DC_OK && !dc_add_plane_to_context(
6300                                                 dc,
6301                                                 stream,
6302                                                 dc_plane_state,
6303                                                 dc_state))
6304                 dc_result = DC_FAIL_ATTACH_SURFACES;
6305
6306         if (dc_result == DC_OK)
6307                 dc_result = dc_validate_global_state(dc, dc_state, true);
6308
6309 cleanup:
6310         if (dc_state)
6311                 dc_release_state(dc_state);
6312
6313         if (dc_plane_state)
6314                 dc_plane_state_release(dc_plane_state);
6315
6316         return dc_result;
6317 }
6318
6319 struct dc_stream_state *
6320 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6321                                 const struct drm_display_mode *drm_mode,
6322                                 const struct dm_connector_state *dm_state,
6323                                 const struct dc_stream_state *old_stream)
6324 {
6325         struct drm_connector *connector = &aconnector->base;
6326         struct amdgpu_device *adev = drm_to_adev(connector->dev);
6327         struct dc_stream_state *stream;
6328         const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6329         int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6330         enum dc_status dc_result = DC_OK;
6331
6332         do {
6333                 stream = create_stream_for_sink(aconnector, drm_mode,
6334                                                 dm_state, old_stream,
6335                                                 requested_bpc);
6336                 if (stream == NULL) {
6337                         DRM_ERROR("Failed to create stream for sink!\n");
6338                         break;
6339                 }
6340
6341                 dc_result = dc_validate_stream(adev->dm.dc, stream);
6342                 if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6343                         dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6344
6345                 if (dc_result == DC_OK)
6346                         dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
6347
6348                 if (dc_result != DC_OK) {
6349                         DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6350                                       drm_mode->hdisplay,
6351                                       drm_mode->vdisplay,
6352                                       drm_mode->clock,
6353                                       dc_result,
6354                                       dc_status_to_str(dc_result));
6355
6356                         dc_stream_release(stream);
6357                         stream = NULL;
6358                         requested_bpc -= 2; /* lower bpc to retry validation */
6359                 }
6360
6361         } while (stream == NULL && requested_bpc >= 6);
6362
6363         if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6364                 DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6365
6366                 aconnector->force_yuv420_output = true;
6367                 stream = create_validate_stream_for_sink(aconnector, drm_mode,
6368                                                 dm_state, old_stream);
6369                 aconnector->force_yuv420_output = false;
6370         }
6371
6372         return stream;
6373 }
6374
6375 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6376                                    struct drm_display_mode *mode)
6377 {
6378         int result = MODE_ERROR;
6379         struct dc_sink *dc_sink;
6380         /* TODO: Unhardcode stream count */
6381         struct dc_stream_state *stream;
6382         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6383
6384         if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6385                         (mode->flags & DRM_MODE_FLAG_DBLSCAN))
6386                 return result;
6387
6388         /*
6389          * Only run this the first time mode_valid is called to initilialize
6390          * EDID mgmt
6391          */
6392         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6393                 !aconnector->dc_em_sink)
6394                 handle_edid_mgmt(aconnector);
6395
6396         dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6397
6398         if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6399                                 aconnector->base.force != DRM_FORCE_ON) {
6400                 DRM_ERROR("dc_sink is NULL!\n");
6401                 goto fail;
6402         }
6403
6404         stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6405         if (stream) {
6406                 dc_stream_release(stream);
6407                 result = MODE_OK;
6408         }
6409
6410 fail:
6411         /* TODO: error handling*/
6412         return result;
6413 }
6414
6415 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6416                                 struct dc_info_packet *out)
6417 {
6418         struct hdmi_drm_infoframe frame;
6419         unsigned char buf[30]; /* 26 + 4 */
6420         ssize_t len;
6421         int ret, i;
6422
6423         memset(out, 0, sizeof(*out));
6424
6425         if (!state->hdr_output_metadata)
6426                 return 0;
6427
6428         ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6429         if (ret)
6430                 return ret;
6431
6432         len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6433         if (len < 0)
6434                 return (int)len;
6435
6436         /* Static metadata is a fixed 26 bytes + 4 byte header. */
6437         if (len != 30)
6438                 return -EINVAL;
6439
6440         /* Prepare the infopacket for DC. */
6441         switch (state->connector->connector_type) {
6442         case DRM_MODE_CONNECTOR_HDMIA:
6443                 out->hb0 = 0x87; /* type */
6444                 out->hb1 = 0x01; /* version */
6445                 out->hb2 = 0x1A; /* length */
6446                 out->sb[0] = buf[3]; /* checksum */
6447                 i = 1;
6448                 break;
6449
6450         case DRM_MODE_CONNECTOR_DisplayPort:
6451         case DRM_MODE_CONNECTOR_eDP:
6452                 out->hb0 = 0x00; /* sdp id, zero */
6453                 out->hb1 = 0x87; /* type */
6454                 out->hb2 = 0x1D; /* payload len - 1 */
6455                 out->hb3 = (0x13 << 2); /* sdp version */
6456                 out->sb[0] = 0x01; /* version */
6457                 out->sb[1] = 0x1A; /* length */
6458                 i = 2;
6459                 break;
6460
6461         default:
6462                 return -EINVAL;
6463         }
6464
6465         memcpy(&out->sb[i], &buf[4], 26);
6466         out->valid = true;
6467
6468         print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6469                        sizeof(out->sb), false);
6470
6471         return 0;
6472 }
6473
6474 static int
6475 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6476                                  struct drm_atomic_state *state)
6477 {
6478         struct drm_connector_state *new_con_state =
6479                 drm_atomic_get_new_connector_state(state, conn);
6480         struct drm_connector_state *old_con_state =
6481                 drm_atomic_get_old_connector_state(state, conn);
6482         struct drm_crtc *crtc = new_con_state->crtc;
6483         struct drm_crtc_state *new_crtc_state;
6484         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6485         int ret;
6486
6487         trace_amdgpu_dm_connector_atomic_check(new_con_state);
6488
6489         if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6490                 ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6491                 if (ret < 0)
6492                         return ret;
6493         }
6494
6495         if (!crtc)
6496                 return 0;
6497
6498         if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6499                 struct dc_info_packet hdr_infopacket;
6500
6501                 ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6502                 if (ret)
6503                         return ret;
6504
6505                 new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6506                 if (IS_ERR(new_crtc_state))
6507                         return PTR_ERR(new_crtc_state);
6508
6509                 /*
6510                  * DC considers the stream backends changed if the
6511                  * static metadata changes. Forcing the modeset also
6512                  * gives a simple way for userspace to switch from
6513                  * 8bpc to 10bpc when setting the metadata to enter
6514                  * or exit HDR.
6515                  *
6516                  * Changing the static metadata after it's been
6517                  * set is permissible, however. So only force a
6518                  * modeset if we're entering or exiting HDR.
6519                  */
6520                 new_crtc_state->mode_changed =
6521                         !old_con_state->hdr_output_metadata ||
6522                         !new_con_state->hdr_output_metadata;
6523         }
6524
6525         return 0;
6526 }
6527
6528 static const struct drm_connector_helper_funcs
6529 amdgpu_dm_connector_helper_funcs = {
6530         /*
6531          * If hotplugging a second bigger display in FB Con mode, bigger resolution
6532          * modes will be filtered by drm_mode_validate_size(), and those modes
6533          * are missing after user start lightdm. So we need to renew modes list.
6534          * in get_modes call back, not just return the modes count
6535          */
6536         .get_modes = get_modes,
6537         .mode_valid = amdgpu_dm_connector_mode_valid,
6538         .atomic_check = amdgpu_dm_connector_atomic_check,
6539 };
6540
6541 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6542 {
6543
6544 }
6545
6546 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6547 {
6548         switch (display_color_depth) {
6549         case COLOR_DEPTH_666:
6550                 return 6;
6551         case COLOR_DEPTH_888:
6552                 return 8;
6553         case COLOR_DEPTH_101010:
6554                 return 10;
6555         case COLOR_DEPTH_121212:
6556                 return 12;
6557         case COLOR_DEPTH_141414:
6558                 return 14;
6559         case COLOR_DEPTH_161616:
6560                 return 16;
6561         default:
6562                 break;
6563         }
6564         return 0;
6565 }
6566
6567 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6568                                           struct drm_crtc_state *crtc_state,
6569                                           struct drm_connector_state *conn_state)
6570 {
6571         struct drm_atomic_state *state = crtc_state->state;
6572         struct drm_connector *connector = conn_state->connector;
6573         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6574         struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6575         const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6576         struct drm_dp_mst_topology_mgr *mst_mgr;
6577         struct drm_dp_mst_port *mst_port;
6578         struct drm_dp_mst_topology_state *mst_state;
6579         enum dc_color_depth color_depth;
6580         int clock, bpp = 0;
6581         bool is_y420 = false;
6582
6583         if (!aconnector->port || !aconnector->dc_sink)
6584                 return 0;
6585
6586         mst_port = aconnector->port;
6587         mst_mgr = &aconnector->mst_port->mst_mgr;
6588
6589         if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6590                 return 0;
6591
6592         mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6593         if (IS_ERR(mst_state))
6594                 return PTR_ERR(mst_state);
6595
6596         if (!mst_state->pbn_div)
6597                 mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_port->dc_link);
6598
6599         if (!state->duplicated) {
6600                 int max_bpc = conn_state->max_requested_bpc;
6601                 is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6602                           aconnector->force_yuv420_output;
6603                 color_depth = convert_color_depth_from_display_info(connector,
6604                                                                     is_y420,
6605                                                                     max_bpc);
6606                 bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6607                 clock = adjusted_mode->clock;
6608                 dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6609         }
6610
6611         dm_new_connector_state->vcpi_slots =
6612                 drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6613                                               dm_new_connector_state->pbn);
6614         if (dm_new_connector_state->vcpi_slots < 0) {
6615                 DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6616                 return dm_new_connector_state->vcpi_slots;
6617         }
6618         return 0;
6619 }
6620
6621 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6622         .disable = dm_encoder_helper_disable,
6623         .atomic_check = dm_encoder_helper_atomic_check
6624 };
6625
6626 #if defined(CONFIG_DRM_AMD_DC_DCN)
6627 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6628                                             struct dc_state *dc_state,
6629                                             struct dsc_mst_fairness_vars *vars)
6630 {
6631         struct dc_stream_state *stream = NULL;
6632         struct drm_connector *connector;
6633         struct drm_connector_state *new_con_state;
6634         struct amdgpu_dm_connector *aconnector;
6635         struct dm_connector_state *dm_conn_state;
6636         int i, j, ret;
6637         int vcpi, pbn_div, pbn, slot_num = 0;
6638
6639         for_each_new_connector_in_state(state, connector, new_con_state, i) {
6640
6641                 aconnector = to_amdgpu_dm_connector(connector);
6642
6643                 if (!aconnector->port)
6644                         continue;
6645
6646                 if (!new_con_state || !new_con_state->crtc)
6647                         continue;
6648
6649                 dm_conn_state = to_dm_connector_state(new_con_state);
6650
6651                 for (j = 0; j < dc_state->stream_count; j++) {
6652                         stream = dc_state->streams[j];
6653                         if (!stream)
6654                                 continue;
6655
6656                         if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6657                                 break;
6658
6659                         stream = NULL;
6660                 }
6661
6662                 if (!stream)
6663                         continue;
6664
6665                 pbn_div = dm_mst_get_pbn_divider(stream->link);
6666                 /* pbn is calculated by compute_mst_dsc_configs_for_state*/
6667                 for (j = 0; j < dc_state->stream_count; j++) {
6668                         if (vars[j].aconnector == aconnector) {
6669                                 pbn = vars[j].pbn;
6670                                 break;
6671                         }
6672                 }
6673
6674                 if (j == dc_state->stream_count)
6675                         continue;
6676
6677                 slot_num = DIV_ROUND_UP(pbn, pbn_div);
6678
6679                 if (stream->timing.flags.DSC != 1) {
6680                         dm_conn_state->pbn = pbn;
6681                         dm_conn_state->vcpi_slots = slot_num;
6682
6683                         ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->port,
6684                                                            dm_conn_state->pbn, false);
6685                         if (ret < 0)
6686                                 return ret;
6687
6688                         continue;
6689                 }
6690
6691                 vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->port, pbn, true);
6692                 if (vcpi < 0)
6693                         return vcpi;
6694
6695                 dm_conn_state->pbn = pbn;
6696                 dm_conn_state->vcpi_slots = vcpi;
6697         }
6698         return 0;
6699 }
6700 #endif
6701
6702 static int to_drm_connector_type(enum signal_type st)
6703 {
6704         switch (st) {
6705         case SIGNAL_TYPE_HDMI_TYPE_A:
6706                 return DRM_MODE_CONNECTOR_HDMIA;
6707         case SIGNAL_TYPE_EDP:
6708                 return DRM_MODE_CONNECTOR_eDP;
6709         case SIGNAL_TYPE_LVDS:
6710                 return DRM_MODE_CONNECTOR_LVDS;
6711         case SIGNAL_TYPE_RGB:
6712                 return DRM_MODE_CONNECTOR_VGA;
6713         case SIGNAL_TYPE_DISPLAY_PORT:
6714         case SIGNAL_TYPE_DISPLAY_PORT_MST:
6715                 return DRM_MODE_CONNECTOR_DisplayPort;
6716         case SIGNAL_TYPE_DVI_DUAL_LINK:
6717         case SIGNAL_TYPE_DVI_SINGLE_LINK:
6718                 return DRM_MODE_CONNECTOR_DVID;
6719         case SIGNAL_TYPE_VIRTUAL:
6720                 return DRM_MODE_CONNECTOR_VIRTUAL;
6721
6722         default:
6723                 return DRM_MODE_CONNECTOR_Unknown;
6724         }
6725 }
6726
6727 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6728 {
6729         struct drm_encoder *encoder;
6730
6731         /* There is only one encoder per connector */
6732         drm_connector_for_each_possible_encoder(connector, encoder)
6733                 return encoder;
6734
6735         return NULL;
6736 }
6737
6738 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6739 {
6740         struct drm_encoder *encoder;
6741         struct amdgpu_encoder *amdgpu_encoder;
6742
6743         encoder = amdgpu_dm_connector_to_encoder(connector);
6744
6745         if (encoder == NULL)
6746                 return;
6747
6748         amdgpu_encoder = to_amdgpu_encoder(encoder);
6749
6750         amdgpu_encoder->native_mode.clock = 0;
6751
6752         if (!list_empty(&connector->probed_modes)) {
6753                 struct drm_display_mode *preferred_mode = NULL;
6754
6755                 list_for_each_entry(preferred_mode,
6756                                     &connector->probed_modes,
6757                                     head) {
6758                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6759                                 amdgpu_encoder->native_mode = *preferred_mode;
6760
6761                         break;
6762                 }
6763
6764         }
6765 }
6766
6767 static struct drm_display_mode *
6768 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6769                              char *name,
6770                              int hdisplay, int vdisplay)
6771 {
6772         struct drm_device *dev = encoder->dev;
6773         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6774         struct drm_display_mode *mode = NULL;
6775         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6776
6777         mode = drm_mode_duplicate(dev, native_mode);
6778
6779         if (mode == NULL)
6780                 return NULL;
6781
6782         mode->hdisplay = hdisplay;
6783         mode->vdisplay = vdisplay;
6784         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6785         strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6786
6787         return mode;
6788
6789 }
6790
6791 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6792                                                  struct drm_connector *connector)
6793 {
6794         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6795         struct drm_display_mode *mode = NULL;
6796         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6797         struct amdgpu_dm_connector *amdgpu_dm_connector =
6798                                 to_amdgpu_dm_connector(connector);
6799         int i;
6800         int n;
6801         struct mode_size {
6802                 char name[DRM_DISPLAY_MODE_LEN];
6803                 int w;
6804                 int h;
6805         } common_modes[] = {
6806                 {  "640x480",  640,  480},
6807                 {  "800x600",  800,  600},
6808                 { "1024x768", 1024,  768},
6809                 { "1280x720", 1280,  720},
6810                 { "1280x800", 1280,  800},
6811                 {"1280x1024", 1280, 1024},
6812                 { "1440x900", 1440,  900},
6813                 {"1680x1050", 1680, 1050},
6814                 {"1600x1200", 1600, 1200},
6815                 {"1920x1080", 1920, 1080},
6816                 {"1920x1200", 1920, 1200}
6817         };
6818
6819         n = ARRAY_SIZE(common_modes);
6820
6821         for (i = 0; i < n; i++) {
6822                 struct drm_display_mode *curmode = NULL;
6823                 bool mode_existed = false;
6824
6825                 if (common_modes[i].w > native_mode->hdisplay ||
6826                     common_modes[i].h > native_mode->vdisplay ||
6827                    (common_modes[i].w == native_mode->hdisplay &&
6828                     common_modes[i].h == native_mode->vdisplay))
6829                         continue;
6830
6831                 list_for_each_entry(curmode, &connector->probed_modes, head) {
6832                         if (common_modes[i].w == curmode->hdisplay &&
6833                             common_modes[i].h == curmode->vdisplay) {
6834                                 mode_existed = true;
6835                                 break;
6836                         }
6837                 }
6838
6839                 if (mode_existed)
6840                         continue;
6841
6842                 mode = amdgpu_dm_create_common_mode(encoder,
6843                                 common_modes[i].name, common_modes[i].w,
6844                                 common_modes[i].h);
6845                 if (!mode)
6846                         continue;
6847
6848                 drm_mode_probed_add(connector, mode);
6849                 amdgpu_dm_connector->num_modes++;
6850         }
6851 }
6852
6853 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6854 {
6855         struct drm_encoder *encoder;
6856         struct amdgpu_encoder *amdgpu_encoder;
6857         const struct drm_display_mode *native_mode;
6858
6859         if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6860             connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6861                 return;
6862
6863         mutex_lock(&connector->dev->mode_config.mutex);
6864         amdgpu_dm_connector_get_modes(connector);
6865         mutex_unlock(&connector->dev->mode_config.mutex);
6866
6867         encoder = amdgpu_dm_connector_to_encoder(connector);
6868         if (!encoder)
6869                 return;
6870
6871         amdgpu_encoder = to_amdgpu_encoder(encoder);
6872
6873         native_mode = &amdgpu_encoder->native_mode;
6874         if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6875                 return;
6876
6877         drm_connector_set_panel_orientation_with_quirk(connector,
6878                                                        DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6879                                                        native_mode->hdisplay,
6880                                                        native_mode->vdisplay);
6881 }
6882
6883 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6884                                               struct edid *edid)
6885 {
6886         struct amdgpu_dm_connector *amdgpu_dm_connector =
6887                         to_amdgpu_dm_connector(connector);
6888
6889         if (edid) {
6890                 /* empty probed_modes */
6891                 INIT_LIST_HEAD(&connector->probed_modes);
6892                 amdgpu_dm_connector->num_modes =
6893                                 drm_add_edid_modes(connector, edid);
6894
6895                 /* sorting the probed modes before calling function
6896                  * amdgpu_dm_get_native_mode() since EDID can have
6897                  * more than one preferred mode. The modes that are
6898                  * later in the probed mode list could be of higher
6899                  * and preferred resolution. For example, 3840x2160
6900                  * resolution in base EDID preferred timing and 4096x2160
6901                  * preferred resolution in DID extension block later.
6902                  */
6903                 drm_mode_sort(&connector->probed_modes);
6904                 amdgpu_dm_get_native_mode(connector);
6905
6906                 /* Freesync capabilities are reset by calling
6907                  * drm_add_edid_modes() and need to be
6908                  * restored here.
6909                  */
6910                 amdgpu_dm_update_freesync_caps(connector, edid);
6911         } else {
6912                 amdgpu_dm_connector->num_modes = 0;
6913         }
6914 }
6915
6916 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
6917                               struct drm_display_mode *mode)
6918 {
6919         struct drm_display_mode *m;
6920
6921         list_for_each_entry (m, &aconnector->base.probed_modes, head) {
6922                 if (drm_mode_equal(m, mode))
6923                         return true;
6924         }
6925
6926         return false;
6927 }
6928
6929 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
6930 {
6931         const struct drm_display_mode *m;
6932         struct drm_display_mode *new_mode;
6933         uint i;
6934         u32 new_modes_count = 0;
6935
6936         /* Standard FPS values
6937          *
6938          * 23.976       - TV/NTSC
6939          * 24           - Cinema
6940          * 25           - TV/PAL
6941          * 29.97        - TV/NTSC
6942          * 30           - TV/NTSC
6943          * 48           - Cinema HFR
6944          * 50           - TV/PAL
6945          * 60           - Commonly used
6946          * 48,72,96,120 - Multiples of 24
6947          */
6948         static const u32 common_rates[] = {
6949                 23976, 24000, 25000, 29970, 30000,
6950                 48000, 50000, 60000, 72000, 96000, 120000
6951         };
6952
6953         /*
6954          * Find mode with highest refresh rate with the same resolution
6955          * as the preferred mode. Some monitors report a preferred mode
6956          * with lower resolution than the highest refresh rate supported.
6957          */
6958
6959         m = get_highest_refresh_rate_mode(aconnector, true);
6960         if (!m)
6961                 return 0;
6962
6963         for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
6964                 u64 target_vtotal, target_vtotal_diff;
6965                 u64 num, den;
6966
6967                 if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
6968                         continue;
6969
6970                 if (common_rates[i] < aconnector->min_vfreq * 1000 ||
6971                     common_rates[i] > aconnector->max_vfreq * 1000)
6972                         continue;
6973
6974                 num = (unsigned long long)m->clock * 1000 * 1000;
6975                 den = common_rates[i] * (unsigned long long)m->htotal;
6976                 target_vtotal = div_u64(num, den);
6977                 target_vtotal_diff = target_vtotal - m->vtotal;
6978
6979                 /* Check for illegal modes */
6980                 if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
6981                     m->vsync_end + target_vtotal_diff < m->vsync_start ||
6982                     m->vtotal + target_vtotal_diff < m->vsync_end)
6983                         continue;
6984
6985                 new_mode = drm_mode_duplicate(aconnector->base.dev, m);
6986                 if (!new_mode)
6987                         goto out;
6988
6989                 new_mode->vtotal += (u16)target_vtotal_diff;
6990                 new_mode->vsync_start += (u16)target_vtotal_diff;
6991                 new_mode->vsync_end += (u16)target_vtotal_diff;
6992                 new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6993                 new_mode->type |= DRM_MODE_TYPE_DRIVER;
6994
6995                 if (!is_duplicate_mode(aconnector, new_mode)) {
6996                         drm_mode_probed_add(&aconnector->base, new_mode);
6997                         new_modes_count += 1;
6998                 } else
6999                         drm_mode_destroy(aconnector->base.dev, new_mode);
7000         }
7001  out:
7002         return new_modes_count;
7003 }
7004
7005 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
7006                                                    struct edid *edid)
7007 {
7008         struct amdgpu_dm_connector *amdgpu_dm_connector =
7009                 to_amdgpu_dm_connector(connector);
7010
7011         if (!(amdgpu_freesync_vid_mode && edid))
7012                 return;
7013
7014         if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
7015                 amdgpu_dm_connector->num_modes +=
7016                         add_fs_modes(amdgpu_dm_connector);
7017 }
7018
7019 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
7020 {
7021         struct amdgpu_dm_connector *amdgpu_dm_connector =
7022                         to_amdgpu_dm_connector(connector);
7023         struct drm_encoder *encoder;
7024         struct edid *edid = amdgpu_dm_connector->edid;
7025
7026         encoder = amdgpu_dm_connector_to_encoder(connector);
7027
7028         if (!drm_edid_is_valid(edid)) {
7029                 amdgpu_dm_connector->num_modes =
7030                                 drm_add_modes_noedid(connector, 640, 480);
7031         } else {
7032                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
7033                 amdgpu_dm_connector_add_common_modes(encoder, connector);
7034                 amdgpu_dm_connector_add_freesync_modes(connector, edid);
7035         }
7036         amdgpu_dm_fbc_init(connector);
7037
7038         return amdgpu_dm_connector->num_modes;
7039 }
7040
7041 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
7042                                      struct amdgpu_dm_connector *aconnector,
7043                                      int connector_type,
7044                                      struct dc_link *link,
7045                                      int link_index)
7046 {
7047         struct amdgpu_device *adev = drm_to_adev(dm->ddev);
7048
7049         /*
7050          * Some of the properties below require access to state, like bpc.
7051          * Allocate some default initial connector state with our reset helper.
7052          */
7053         if (aconnector->base.funcs->reset)
7054                 aconnector->base.funcs->reset(&aconnector->base);
7055
7056         aconnector->connector_id = link_index;
7057         aconnector->dc_link = link;
7058         aconnector->base.interlace_allowed = false;
7059         aconnector->base.doublescan_allowed = false;
7060         aconnector->base.stereo_allowed = false;
7061         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
7062         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
7063         aconnector->audio_inst = -1;
7064         mutex_init(&aconnector->hpd_lock);
7065
7066         /*
7067          * configure support HPD hot plug connector_>polled default value is 0
7068          * which means HPD hot plug not supported
7069          */
7070         switch (connector_type) {
7071         case DRM_MODE_CONNECTOR_HDMIA:
7072                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7073                 aconnector->base.ycbcr_420_allowed =
7074                         link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
7075                 break;
7076         case DRM_MODE_CONNECTOR_DisplayPort:
7077                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7078                 link->link_enc = link_enc_cfg_get_link_enc(link);
7079                 ASSERT(link->link_enc);
7080                 if (link->link_enc)
7081                         aconnector->base.ycbcr_420_allowed =
7082                         link->link_enc->features.dp_ycbcr420_supported ? true : false;
7083                 break;
7084         case DRM_MODE_CONNECTOR_DVID:
7085                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
7086                 break;
7087         default:
7088                 break;
7089         }
7090
7091         drm_object_attach_property(&aconnector->base.base,
7092                                 dm->ddev->mode_config.scaling_mode_property,
7093                                 DRM_MODE_SCALE_NONE);
7094
7095         drm_object_attach_property(&aconnector->base.base,
7096                                 adev->mode_info.underscan_property,
7097                                 UNDERSCAN_OFF);
7098         drm_object_attach_property(&aconnector->base.base,
7099                                 adev->mode_info.underscan_hborder_property,
7100                                 0);
7101         drm_object_attach_property(&aconnector->base.base,
7102                                 adev->mode_info.underscan_vborder_property,
7103                                 0);
7104
7105         if (!aconnector->mst_port)
7106                 drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
7107
7108         /* This defaults to the max in the range, but we want 8bpc for non-edp. */
7109         aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7110         aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7111
7112         if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7113             (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7114                 drm_object_attach_property(&aconnector->base.base,
7115                                 adev->mode_info.abm_level_property, 0);
7116         }
7117
7118         if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7119             connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7120             connector_type == DRM_MODE_CONNECTOR_eDP) {
7121                 drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7122
7123                 if (!aconnector->mst_port)
7124                         drm_connector_attach_vrr_capable_property(&aconnector->base);
7125
7126 #ifdef CONFIG_DRM_AMD_DC_HDCP
7127                 if (adev->dm.hdcp_workqueue)
7128                         drm_connector_attach_content_protection_property(&aconnector->base, true);
7129 #endif
7130         }
7131 }
7132
7133 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7134                               struct i2c_msg *msgs, int num)
7135 {
7136         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7137         struct ddc_service *ddc_service = i2c->ddc_service;
7138         struct i2c_command cmd;
7139         int i;
7140         int result = -EIO;
7141
7142         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7143
7144         if (!cmd.payloads)
7145                 return result;
7146
7147         cmd.number_of_payloads = num;
7148         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7149         cmd.speed = 100;
7150
7151         for (i = 0; i < num; i++) {
7152                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7153                 cmd.payloads[i].address = msgs[i].addr;
7154                 cmd.payloads[i].length = msgs[i].len;
7155                 cmd.payloads[i].data = msgs[i].buf;
7156         }
7157
7158         if (dc_submit_i2c(
7159                         ddc_service->ctx->dc,
7160                         ddc_service->link->link_index,
7161                         &cmd))
7162                 result = num;
7163
7164         kfree(cmd.payloads);
7165         return result;
7166 }
7167
7168 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7169 {
7170         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7171 }
7172
7173 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7174         .master_xfer = amdgpu_dm_i2c_xfer,
7175         .functionality = amdgpu_dm_i2c_func,
7176 };
7177
7178 static struct amdgpu_i2c_adapter *
7179 create_i2c(struct ddc_service *ddc_service,
7180            int link_index,
7181            int *res)
7182 {
7183         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7184         struct amdgpu_i2c_adapter *i2c;
7185
7186         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7187         if (!i2c)
7188                 return NULL;
7189         i2c->base.owner = THIS_MODULE;
7190         i2c->base.class = I2C_CLASS_DDC;
7191         i2c->base.dev.parent = &adev->pdev->dev;
7192         i2c->base.algo = &amdgpu_dm_i2c_algo;
7193         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7194         i2c_set_adapdata(&i2c->base, i2c);
7195         i2c->ddc_service = ddc_service;
7196
7197         return i2c;
7198 }
7199
7200
7201 /*
7202  * Note: this function assumes that dc_link_detect() was called for the
7203  * dc_link which will be represented by this aconnector.
7204  */
7205 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7206                                     struct amdgpu_dm_connector *aconnector,
7207                                     u32 link_index,
7208                                     struct amdgpu_encoder *aencoder)
7209 {
7210         int res = 0;
7211         int connector_type;
7212         struct dc *dc = dm->dc;
7213         struct dc_link *link = dc_get_link_at_index(dc, link_index);
7214         struct amdgpu_i2c_adapter *i2c;
7215
7216         link->priv = aconnector;
7217
7218         DRM_DEBUG_DRIVER("%s()\n", __func__);
7219
7220         i2c = create_i2c(link->ddc, link->link_index, &res);
7221         if (!i2c) {
7222                 DRM_ERROR("Failed to create i2c adapter data\n");
7223                 return -ENOMEM;
7224         }
7225
7226         aconnector->i2c = i2c;
7227         res = i2c_add_adapter(&i2c->base);
7228
7229         if (res) {
7230                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7231                 goto out_free;
7232         }
7233
7234         connector_type = to_drm_connector_type(link->connector_signal);
7235
7236         res = drm_connector_init_with_ddc(
7237                         dm->ddev,
7238                         &aconnector->base,
7239                         &amdgpu_dm_connector_funcs,
7240                         connector_type,
7241                         &i2c->base);
7242
7243         if (res) {
7244                 DRM_ERROR("connector_init failed\n");
7245                 aconnector->connector_id = -1;
7246                 goto out_free;
7247         }
7248
7249         drm_connector_helper_add(
7250                         &aconnector->base,
7251                         &amdgpu_dm_connector_helper_funcs);
7252
7253         amdgpu_dm_connector_init_helper(
7254                 dm,
7255                 aconnector,
7256                 connector_type,
7257                 link,
7258                 link_index);
7259
7260         drm_connector_attach_encoder(
7261                 &aconnector->base, &aencoder->base);
7262
7263         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7264                 || connector_type == DRM_MODE_CONNECTOR_eDP)
7265                 amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7266
7267 out_free:
7268         if (res) {
7269                 kfree(i2c);
7270                 aconnector->i2c = NULL;
7271         }
7272         return res;
7273 }
7274
7275 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7276 {
7277         switch (adev->mode_info.num_crtc) {
7278         case 1:
7279                 return 0x1;
7280         case 2:
7281                 return 0x3;
7282         case 3:
7283                 return 0x7;
7284         case 4:
7285                 return 0xf;
7286         case 5:
7287                 return 0x1f;
7288         case 6:
7289         default:
7290                 return 0x3f;
7291         }
7292 }
7293
7294 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7295                                   struct amdgpu_encoder *aencoder,
7296                                   uint32_t link_index)
7297 {
7298         struct amdgpu_device *adev = drm_to_adev(dev);
7299
7300         int res = drm_encoder_init(dev,
7301                                    &aencoder->base,
7302                                    &amdgpu_dm_encoder_funcs,
7303                                    DRM_MODE_ENCODER_TMDS,
7304                                    NULL);
7305
7306         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7307
7308         if (!res)
7309                 aencoder->encoder_id = link_index;
7310         else
7311                 aencoder->encoder_id = -1;
7312
7313         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7314
7315         return res;
7316 }
7317
7318 static void manage_dm_interrupts(struct amdgpu_device *adev,
7319                                  struct amdgpu_crtc *acrtc,
7320                                  bool enable)
7321 {
7322         /*
7323          * We have no guarantee that the frontend index maps to the same
7324          * backend index - some even map to more than one.
7325          *
7326          * TODO: Use a different interrupt or check DC itself for the mapping.
7327          */
7328         int irq_type =
7329                 amdgpu_display_crtc_idx_to_irq_type(
7330                         adev,
7331                         acrtc->crtc_id);
7332
7333         if (enable) {
7334                 drm_crtc_vblank_on(&acrtc->base);
7335                 amdgpu_irq_get(
7336                         adev,
7337                         &adev->pageflip_irq,
7338                         irq_type);
7339 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7340                 amdgpu_irq_get(
7341                         adev,
7342                         &adev->vline0_irq,
7343                         irq_type);
7344 #endif
7345         } else {
7346 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7347                 amdgpu_irq_put(
7348                         adev,
7349                         &adev->vline0_irq,
7350                         irq_type);
7351 #endif
7352                 amdgpu_irq_put(
7353                         adev,
7354                         &adev->pageflip_irq,
7355                         irq_type);
7356                 drm_crtc_vblank_off(&acrtc->base);
7357         }
7358 }
7359
7360 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7361                                       struct amdgpu_crtc *acrtc)
7362 {
7363         int irq_type =
7364                 amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7365
7366         /**
7367          * This reads the current state for the IRQ and force reapplies
7368          * the setting to hardware.
7369          */
7370         amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7371 }
7372
7373 static bool
7374 is_scaling_state_different(const struct dm_connector_state *dm_state,
7375                            const struct dm_connector_state *old_dm_state)
7376 {
7377         if (dm_state->scaling != old_dm_state->scaling)
7378                 return true;
7379         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7380                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7381                         return true;
7382         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7383                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7384                         return true;
7385         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7386                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7387                 return true;
7388         return false;
7389 }
7390
7391 #ifdef CONFIG_DRM_AMD_DC_HDCP
7392 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
7393                                             struct drm_crtc_state *old_crtc_state,
7394                                             struct drm_connector_state *new_conn_state,
7395                                             struct drm_connector_state *old_conn_state,
7396                                             const struct drm_connector *connector,
7397                                             struct hdcp_workqueue *hdcp_w)
7398 {
7399         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7400         struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7401
7402         pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
7403                 connector->index, connector->status, connector->dpms);
7404         pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
7405                 old_conn_state->content_protection, new_conn_state->content_protection);
7406
7407         if (old_crtc_state)
7408                 pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7409                 old_crtc_state->enable,
7410                 old_crtc_state->active,
7411                 old_crtc_state->mode_changed,
7412                 old_crtc_state->active_changed,
7413                 old_crtc_state->connectors_changed);
7414
7415         if (new_crtc_state)
7416                 pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
7417                 new_crtc_state->enable,
7418                 new_crtc_state->active,
7419                 new_crtc_state->mode_changed,
7420                 new_crtc_state->active_changed,
7421                 new_crtc_state->connectors_changed);
7422
7423         /* hdcp content type change */
7424         if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
7425             new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7426                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7427                 pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
7428                 return true;
7429         }
7430
7431         /* CP is being re enabled, ignore this */
7432         if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7433             new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7434                 if (new_crtc_state && new_crtc_state->mode_changed) {
7435                         new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7436                         pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
7437                         return true;
7438                 }
7439                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7440                 pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
7441                 return false;
7442         }
7443
7444         /* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7445          *
7446          * Handles:     UNDESIRED -> ENABLED
7447          */
7448         if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7449             new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7450                 new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7451
7452         /* Stream removed and re-enabled
7453          *
7454          * Can sometimes overlap with the HPD case,
7455          * thus set update_hdcp to false to avoid
7456          * setting HDCP multiple times.
7457          *
7458          * Handles:     DESIRED -> DESIRED (Special case)
7459          */
7460         if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
7461                 new_conn_state->crtc && new_conn_state->crtc->enabled &&
7462                 connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7463                 dm_con_state->update_hdcp = false;
7464                 pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
7465                         __func__);
7466                 return true;
7467         }
7468
7469         /* Hot-plug, headless s3, dpms
7470          *
7471          * Only start HDCP if the display is connected/enabled.
7472          * update_hdcp flag will be set to false until the next
7473          * HPD comes in.
7474          *
7475          * Handles:     DESIRED -> DESIRED (Special case)
7476          */
7477         if (dm_con_state->update_hdcp &&
7478         new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7479         connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7480                 dm_con_state->update_hdcp = false;
7481                 pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
7482                         __func__);
7483                 return true;
7484         }
7485
7486         if (old_conn_state->content_protection == new_conn_state->content_protection) {
7487                 if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7488                         if (new_crtc_state && new_crtc_state->mode_changed) {
7489                                 pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
7490                                         __func__);
7491                                 return true;
7492                         }
7493                         pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
7494                                 __func__);
7495                         return false;
7496                 }
7497
7498                 pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
7499                 return false;
7500         }
7501
7502         if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
7503                 pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
7504                         __func__);
7505                 return true;
7506         }
7507
7508         pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
7509         return false;
7510 }
7511 #endif
7512
7513 static void remove_stream(struct amdgpu_device *adev,
7514                           struct amdgpu_crtc *acrtc,
7515                           struct dc_stream_state *stream)
7516 {
7517         /* this is the update mode case */
7518
7519         acrtc->otg_inst = -1;
7520         acrtc->enabled = false;
7521 }
7522
7523 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7524 {
7525
7526         assert_spin_locked(&acrtc->base.dev->event_lock);
7527         WARN_ON(acrtc->event);
7528
7529         acrtc->event = acrtc->base.state->event;
7530
7531         /* Set the flip status */
7532         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7533
7534         /* Mark this event as consumed */
7535         acrtc->base.state->event = NULL;
7536
7537         DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7538                      acrtc->crtc_id);
7539 }
7540
7541 static void update_freesync_state_on_stream(
7542         struct amdgpu_display_manager *dm,
7543         struct dm_crtc_state *new_crtc_state,
7544         struct dc_stream_state *new_stream,
7545         struct dc_plane_state *surface,
7546         u32 flip_timestamp_in_us)
7547 {
7548         struct mod_vrr_params vrr_params;
7549         struct dc_info_packet vrr_infopacket = {0};
7550         struct amdgpu_device *adev = dm->adev;
7551         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7552         unsigned long flags;
7553         bool pack_sdp_v1_3 = false;
7554
7555         if (!new_stream)
7556                 return;
7557
7558         /*
7559          * TODO: Determine why min/max totals and vrefresh can be 0 here.
7560          * For now it's sufficient to just guard against these conditions.
7561          */
7562
7563         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7564                 return;
7565
7566         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7567         vrr_params = acrtc->dm_irq_params.vrr_params;
7568
7569         if (surface) {
7570                 mod_freesync_handle_preflip(
7571                         dm->freesync_module,
7572                         surface,
7573                         new_stream,
7574                         flip_timestamp_in_us,
7575                         &vrr_params);
7576
7577                 if (adev->family < AMDGPU_FAMILY_AI &&
7578                     amdgpu_dm_vrr_active(new_crtc_state)) {
7579                         mod_freesync_handle_v_update(dm->freesync_module,
7580                                                      new_stream, &vrr_params);
7581
7582                         /* Need to call this before the frame ends. */
7583                         dc_stream_adjust_vmin_vmax(dm->dc,
7584                                                    new_crtc_state->stream,
7585                                                    &vrr_params.adjust);
7586                 }
7587         }
7588
7589         mod_freesync_build_vrr_infopacket(
7590                 dm->freesync_module,
7591                 new_stream,
7592                 &vrr_params,
7593                 PACKET_TYPE_VRR,
7594                 TRANSFER_FUNC_UNKNOWN,
7595                 &vrr_infopacket,
7596                 pack_sdp_v1_3);
7597
7598         new_crtc_state->freesync_vrr_info_changed |=
7599                 (memcmp(&new_crtc_state->vrr_infopacket,
7600                         &vrr_infopacket,
7601                         sizeof(vrr_infopacket)) != 0);
7602
7603         acrtc->dm_irq_params.vrr_params = vrr_params;
7604         new_crtc_state->vrr_infopacket = vrr_infopacket;
7605
7606         new_stream->vrr_infopacket = vrr_infopacket;
7607
7608         if (new_crtc_state->freesync_vrr_info_changed)
7609                 DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7610                               new_crtc_state->base.crtc->base.id,
7611                               (int)new_crtc_state->base.vrr_enabled,
7612                               (int)vrr_params.state);
7613
7614         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7615 }
7616
7617 static void update_stream_irq_parameters(
7618         struct amdgpu_display_manager *dm,
7619         struct dm_crtc_state *new_crtc_state)
7620 {
7621         struct dc_stream_state *new_stream = new_crtc_state->stream;
7622         struct mod_vrr_params vrr_params;
7623         struct mod_freesync_config config = new_crtc_state->freesync_config;
7624         struct amdgpu_device *adev = dm->adev;
7625         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7626         unsigned long flags;
7627
7628         if (!new_stream)
7629                 return;
7630
7631         /*
7632          * TODO: Determine why min/max totals and vrefresh can be 0 here.
7633          * For now it's sufficient to just guard against these conditions.
7634          */
7635         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7636                 return;
7637
7638         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7639         vrr_params = acrtc->dm_irq_params.vrr_params;
7640
7641         if (new_crtc_state->vrr_supported &&
7642             config.min_refresh_in_uhz &&
7643             config.max_refresh_in_uhz) {
7644                 /*
7645                  * if freesync compatible mode was set, config.state will be set
7646                  * in atomic check
7647                  */
7648                 if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7649                     (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7650                      new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7651                         vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7652                         vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7653                         vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7654                         vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7655                 } else {
7656                         config.state = new_crtc_state->base.vrr_enabled ?
7657                                                      VRR_STATE_ACTIVE_VARIABLE :
7658                                                      VRR_STATE_INACTIVE;
7659                 }
7660         } else {
7661                 config.state = VRR_STATE_UNSUPPORTED;
7662         }
7663
7664         mod_freesync_build_vrr_params(dm->freesync_module,
7665                                       new_stream,
7666                                       &config, &vrr_params);
7667
7668         new_crtc_state->freesync_config = config;
7669         /* Copy state for access from DM IRQ handler */
7670         acrtc->dm_irq_params.freesync_config = config;
7671         acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7672         acrtc->dm_irq_params.vrr_params = vrr_params;
7673         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7674 }
7675
7676 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7677                                             struct dm_crtc_state *new_state)
7678 {
7679         bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7680         bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7681
7682         if (!old_vrr_active && new_vrr_active) {
7683                 /* Transition VRR inactive -> active:
7684                  * While VRR is active, we must not disable vblank irq, as a
7685                  * reenable after disable would compute bogus vblank/pflip
7686                  * timestamps if it likely happened inside display front-porch.
7687                  *
7688                  * We also need vupdate irq for the actual core vblank handling
7689                  * at end of vblank.
7690                  */
7691                 WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7692                 WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7693                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7694                                  __func__, new_state->base.crtc->base.id);
7695         } else if (old_vrr_active && !new_vrr_active) {
7696                 /* Transition VRR active -> inactive:
7697                  * Allow vblank irq disable again for fixed refresh rate.
7698                  */
7699                 WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7700                 drm_crtc_vblank_put(new_state->base.crtc);
7701                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7702                                  __func__, new_state->base.crtc->base.id);
7703         }
7704 }
7705
7706 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7707 {
7708         struct drm_plane *plane;
7709         struct drm_plane_state *old_plane_state;
7710         int i;
7711
7712         /*
7713          * TODO: Make this per-stream so we don't issue redundant updates for
7714          * commits with multiple streams.
7715          */
7716         for_each_old_plane_in_state(state, plane, old_plane_state, i)
7717                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
7718                         handle_cursor_update(plane, old_plane_state);
7719 }
7720
7721 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7722                                     struct dc_state *dc_state,
7723                                     struct drm_device *dev,
7724                                     struct amdgpu_display_manager *dm,
7725                                     struct drm_crtc *pcrtc,
7726                                     bool wait_for_vblank)
7727 {
7728         u32 i;
7729         u64 timestamp_ns;
7730         struct drm_plane *plane;
7731         struct drm_plane_state *old_plane_state, *new_plane_state;
7732         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7733         struct drm_crtc_state *new_pcrtc_state =
7734                         drm_atomic_get_new_crtc_state(state, pcrtc);
7735         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7736         struct dm_crtc_state *dm_old_crtc_state =
7737                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7738         int planes_count = 0, vpos, hpos;
7739         unsigned long flags;
7740         u32 target_vblank, last_flip_vblank;
7741         bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7742         bool cursor_update = false;
7743         bool pflip_present = false;
7744         struct {
7745                 struct dc_surface_update surface_updates[MAX_SURFACES];
7746                 struct dc_plane_info plane_infos[MAX_SURFACES];
7747                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
7748                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7749                 struct dc_stream_update stream_update;
7750         } *bundle;
7751
7752         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7753
7754         if (!bundle) {
7755                 dm_error("Failed to allocate update bundle\n");
7756                 goto cleanup;
7757         }
7758
7759         /*
7760          * Disable the cursor first if we're disabling all the planes.
7761          * It'll remain on the screen after the planes are re-enabled
7762          * if we don't.
7763          */
7764         if (acrtc_state->active_planes == 0)
7765                 amdgpu_dm_commit_cursors(state);
7766
7767         /* update planes when needed */
7768         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7769                 struct drm_crtc *crtc = new_plane_state->crtc;
7770                 struct drm_crtc_state *new_crtc_state;
7771                 struct drm_framebuffer *fb = new_plane_state->fb;
7772                 struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7773                 bool plane_needs_flip;
7774                 struct dc_plane_state *dc_plane;
7775                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7776
7777                 /* Cursor plane is handled after stream updates */
7778                 if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7779                         if ((fb && crtc == pcrtc) ||
7780                             (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7781                                 cursor_update = true;
7782
7783                         continue;
7784                 }
7785
7786                 if (!fb || !crtc || pcrtc != crtc)
7787                         continue;
7788
7789                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7790                 if (!new_crtc_state->active)
7791                         continue;
7792
7793                 dc_plane = dm_new_plane_state->dc_state;
7794
7795                 bundle->surface_updates[planes_count].surface = dc_plane;
7796                 if (new_pcrtc_state->color_mgmt_changed) {
7797                         bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7798                         bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7799                         bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7800                 }
7801
7802                 fill_dc_scaling_info(dm->adev, new_plane_state,
7803                                      &bundle->scaling_infos[planes_count]);
7804
7805                 bundle->surface_updates[planes_count].scaling_info =
7806                         &bundle->scaling_infos[planes_count];
7807
7808                 plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7809
7810                 pflip_present = pflip_present || plane_needs_flip;
7811
7812                 if (!plane_needs_flip) {
7813                         planes_count += 1;
7814                         continue;
7815                 }
7816
7817                 fill_dc_plane_info_and_addr(
7818                         dm->adev, new_plane_state,
7819                         afb->tiling_flags,
7820                         &bundle->plane_infos[planes_count],
7821                         &bundle->flip_addrs[planes_count].address,
7822                         afb->tmz_surface, false);
7823
7824                 drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7825                                  new_plane_state->plane->index,
7826                                  bundle->plane_infos[planes_count].dcc.enable);
7827
7828                 bundle->surface_updates[planes_count].plane_info =
7829                         &bundle->plane_infos[planes_count];
7830
7831                 if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7832                         fill_dc_dirty_rects(plane, old_plane_state,
7833                                             new_plane_state, new_crtc_state,
7834                                             &bundle->flip_addrs[planes_count]);
7835
7836                 /*
7837                  * Only allow immediate flips for fast updates that don't
7838                  * change FB pitch, DCC state, rotation or mirroing.
7839                  */
7840                 bundle->flip_addrs[planes_count].flip_immediate =
7841                         crtc->state->async_flip &&
7842                         acrtc_state->update_type == UPDATE_TYPE_FAST;
7843
7844                 timestamp_ns = ktime_get_ns();
7845                 bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7846                 bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7847                 bundle->surface_updates[planes_count].surface = dc_plane;
7848
7849                 if (!bundle->surface_updates[planes_count].surface) {
7850                         DRM_ERROR("No surface for CRTC: id=%d\n",
7851                                         acrtc_attach->crtc_id);
7852                         continue;
7853                 }
7854
7855                 if (plane == pcrtc->primary)
7856                         update_freesync_state_on_stream(
7857                                 dm,
7858                                 acrtc_state,
7859                                 acrtc_state->stream,
7860                                 dc_plane,
7861                                 bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7862
7863                 drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7864                                  __func__,
7865                                  bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7866                                  bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7867
7868                 planes_count += 1;
7869
7870         }
7871
7872         if (pflip_present) {
7873                 if (!vrr_active) {
7874                         /* Use old throttling in non-vrr fixed refresh rate mode
7875                          * to keep flip scheduling based on target vblank counts
7876                          * working in a backwards compatible way, e.g., for
7877                          * clients using the GLX_OML_sync_control extension or
7878                          * DRI3/Present extension with defined target_msc.
7879                          */
7880                         last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7881                 }
7882                 else {
7883                         /* For variable refresh rate mode only:
7884                          * Get vblank of last completed flip to avoid > 1 vrr
7885                          * flips per video frame by use of throttling, but allow
7886                          * flip programming anywhere in the possibly large
7887                          * variable vrr vblank interval for fine-grained flip
7888                          * timing control and more opportunity to avoid stutter
7889                          * on late submission of flips.
7890                          */
7891                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7892                         last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
7893                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7894                 }
7895
7896                 target_vblank = last_flip_vblank + wait_for_vblank;
7897
7898                 /*
7899                  * Wait until we're out of the vertical blank period before the one
7900                  * targeted by the flip
7901                  */
7902                 while ((acrtc_attach->enabled &&
7903                         (amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
7904                                                             0, &vpos, &hpos, NULL,
7905                                                             NULL, &pcrtc->hwmode)
7906                          & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
7907                         (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
7908                         (int)(target_vblank -
7909                           amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
7910                         usleep_range(1000, 1100);
7911                 }
7912
7913                 /**
7914                  * Prepare the flip event for the pageflip interrupt to handle.
7915                  *
7916                  * This only works in the case where we've already turned on the
7917                  * appropriate hardware blocks (eg. HUBP) so in the transition case
7918                  * from 0 -> n planes we have to skip a hardware generated event
7919                  * and rely on sending it from software.
7920                  */
7921                 if (acrtc_attach->base.state->event &&
7922                     acrtc_state->active_planes > 0) {
7923                         drm_crtc_vblank_get(pcrtc);
7924
7925                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7926
7927                         WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
7928                         prepare_flip_isr(acrtc_attach);
7929
7930                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7931                 }
7932
7933                 if (acrtc_state->stream) {
7934                         if (acrtc_state->freesync_vrr_info_changed)
7935                                 bundle->stream_update.vrr_infopacket =
7936                                         &acrtc_state->stream->vrr_infopacket;
7937                 }
7938         } else if (cursor_update && acrtc_state->active_planes > 0 &&
7939                    acrtc_attach->base.state->event) {
7940                 drm_crtc_vblank_get(pcrtc);
7941
7942                 spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7943
7944                 acrtc_attach->event = acrtc_attach->base.state->event;
7945                 acrtc_attach->base.state->event = NULL;
7946
7947                 spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7948         }
7949
7950         /* Update the planes if changed or disable if we don't have any. */
7951         if ((planes_count || acrtc_state->active_planes == 0) &&
7952                 acrtc_state->stream) {
7953                 /*
7954                  * If PSR or idle optimizations are enabled then flush out
7955                  * any pending work before hardware programming.
7956                  */
7957                 if (dm->vblank_control_workqueue)
7958                         flush_workqueue(dm->vblank_control_workqueue);
7959
7960                 bundle->stream_update.stream = acrtc_state->stream;
7961                 if (new_pcrtc_state->mode_changed) {
7962                         bundle->stream_update.src = acrtc_state->stream->src;
7963                         bundle->stream_update.dst = acrtc_state->stream->dst;
7964                 }
7965
7966                 if (new_pcrtc_state->color_mgmt_changed) {
7967                         /*
7968                          * TODO: This isn't fully correct since we've actually
7969                          * already modified the stream in place.
7970                          */
7971                         bundle->stream_update.gamut_remap =
7972                                 &acrtc_state->stream->gamut_remap_matrix;
7973                         bundle->stream_update.output_csc_transform =
7974                                 &acrtc_state->stream->csc_color_matrix;
7975                         bundle->stream_update.out_transfer_func =
7976                                 acrtc_state->stream->out_transfer_func;
7977                 }
7978
7979                 acrtc_state->stream->abm_level = acrtc_state->abm_level;
7980                 if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
7981                         bundle->stream_update.abm_level = &acrtc_state->abm_level;
7982
7983                 /*
7984                  * If FreeSync state on the stream has changed then we need to
7985                  * re-adjust the min/max bounds now that DC doesn't handle this
7986                  * as part of commit.
7987                  */
7988                 if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
7989                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7990                         dc_stream_adjust_vmin_vmax(
7991                                 dm->dc, acrtc_state->stream,
7992                                 &acrtc_attach->dm_irq_params.vrr_params.adjust);
7993                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7994                 }
7995                 mutex_lock(&dm->dc_lock);
7996                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7997                                 acrtc_state->stream->link->psr_settings.psr_allow_active)
7998                         amdgpu_dm_psr_disable(acrtc_state->stream);
7999
8000                 dc_commit_updates_for_stream(dm->dc,
8001                                                      bundle->surface_updates,
8002                                                      planes_count,
8003                                                      acrtc_state->stream,
8004                                                      &bundle->stream_update,
8005                                                      dc_state);
8006
8007                 /**
8008                  * Enable or disable the interrupts on the backend.
8009                  *
8010                  * Most pipes are put into power gating when unused.
8011                  *
8012                  * When power gating is enabled on a pipe we lose the
8013                  * interrupt enablement state when power gating is disabled.
8014                  *
8015                  * So we need to update the IRQ control state in hardware
8016                  * whenever the pipe turns on (since it could be previously
8017                  * power gated) or off (since some pipes can't be power gated
8018                  * on some ASICs).
8019                  */
8020                 if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
8021                         dm_update_pflip_irq_state(drm_to_adev(dev),
8022                                                   acrtc_attach);
8023
8024                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
8025                                 acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
8026                                 !acrtc_state->stream->link->psr_settings.psr_feature_enabled)
8027                         amdgpu_dm_link_setup_psr(acrtc_state->stream);
8028
8029                 /* Decrement skip count when PSR is enabled and we're doing fast updates. */
8030                 if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
8031                     acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
8032                         struct amdgpu_dm_connector *aconn =
8033                                 (struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
8034
8035                         if (aconn->psr_skip_count > 0)
8036                                 aconn->psr_skip_count--;
8037
8038                         /* Allow PSR when skip count is 0. */
8039                         acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
8040
8041                         /*
8042                          * If sink supports PSR SU, there is no need to rely on
8043                          * a vblank event disable request to enable PSR. PSR SU
8044                          * can be enabled immediately once OS demonstrates an
8045                          * adequate number of fast atomic commits to notify KMD
8046                          * of update events. See `vblank_control_worker()`.
8047                          */
8048                         if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
8049                             acrtc_attach->dm_irq_params.allow_psr_entry &&
8050 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
8051                             !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
8052 #endif
8053                             !acrtc_state->stream->link->psr_settings.psr_allow_active)
8054                                 amdgpu_dm_psr_enable(acrtc_state->stream);
8055                 } else {
8056                         acrtc_attach->dm_irq_params.allow_psr_entry = false;
8057                 }
8058
8059                 mutex_unlock(&dm->dc_lock);
8060         }
8061
8062         /*
8063          * Update cursor state *after* programming all the planes.
8064          * This avoids redundant programming in the case where we're going
8065          * to be disabling a single plane - those pipes are being disabled.
8066          */
8067         if (acrtc_state->active_planes)
8068                 amdgpu_dm_commit_cursors(state);
8069
8070 cleanup:
8071         kfree(bundle);
8072 }
8073
8074 static void amdgpu_dm_commit_audio(struct drm_device *dev,
8075                                    struct drm_atomic_state *state)
8076 {
8077         struct amdgpu_device *adev = drm_to_adev(dev);
8078         struct amdgpu_dm_connector *aconnector;
8079         struct drm_connector *connector;
8080         struct drm_connector_state *old_con_state, *new_con_state;
8081         struct drm_crtc_state *new_crtc_state;
8082         struct dm_crtc_state *new_dm_crtc_state;
8083         const struct dc_stream_status *status;
8084         int i, inst;
8085
8086         /* Notify device removals. */
8087         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8088                 if (old_con_state->crtc != new_con_state->crtc) {
8089                         /* CRTC changes require notification. */
8090                         goto notify;
8091                 }
8092
8093                 if (!new_con_state->crtc)
8094                         continue;
8095
8096                 new_crtc_state = drm_atomic_get_new_crtc_state(
8097                         state, new_con_state->crtc);
8098
8099                 if (!new_crtc_state)
8100                         continue;
8101
8102                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8103                         continue;
8104
8105         notify:
8106                 aconnector = to_amdgpu_dm_connector(connector);
8107
8108                 mutex_lock(&adev->dm.audio_lock);
8109                 inst = aconnector->audio_inst;
8110                 aconnector->audio_inst = -1;
8111                 mutex_unlock(&adev->dm.audio_lock);
8112
8113                 amdgpu_dm_audio_eld_notify(adev, inst);
8114         }
8115
8116         /* Notify audio device additions. */
8117         for_each_new_connector_in_state(state, connector, new_con_state, i) {
8118                 if (!new_con_state->crtc)
8119                         continue;
8120
8121                 new_crtc_state = drm_atomic_get_new_crtc_state(
8122                         state, new_con_state->crtc);
8123
8124                 if (!new_crtc_state)
8125                         continue;
8126
8127                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8128                         continue;
8129
8130                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
8131                 if (!new_dm_crtc_state->stream)
8132                         continue;
8133
8134                 status = dc_stream_get_status(new_dm_crtc_state->stream);
8135                 if (!status)
8136                         continue;
8137
8138                 aconnector = to_amdgpu_dm_connector(connector);
8139
8140                 mutex_lock(&adev->dm.audio_lock);
8141                 inst = status->audio_inst;
8142                 aconnector->audio_inst = inst;
8143                 mutex_unlock(&adev->dm.audio_lock);
8144
8145                 amdgpu_dm_audio_eld_notify(adev, inst);
8146         }
8147 }
8148
8149 /*
8150  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8151  * @crtc_state: the DRM CRTC state
8152  * @stream_state: the DC stream state.
8153  *
8154  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8155  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8156  */
8157 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8158                                                 struct dc_stream_state *stream_state)
8159 {
8160         stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8161 }
8162
8163 /**
8164  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8165  * @state: The atomic state to commit
8166  *
8167  * This will tell DC to commit the constructed DC state from atomic_check,
8168  * programming the hardware. Any failures here implies a hardware failure, since
8169  * atomic check should have filtered anything non-kosher.
8170  */
8171 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8172 {
8173         struct drm_device *dev = state->dev;
8174         struct amdgpu_device *adev = drm_to_adev(dev);
8175         struct amdgpu_display_manager *dm = &adev->dm;
8176         struct dm_atomic_state *dm_state;
8177         struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8178         u32 i, j;
8179         struct drm_crtc *crtc;
8180         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8181         unsigned long flags;
8182         bool wait_for_vblank = true;
8183         struct drm_connector *connector;
8184         struct drm_connector_state *old_con_state, *new_con_state;
8185         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8186         int crtc_disable_count = 0;
8187         bool mode_set_reset_required = false;
8188         int r;
8189
8190         trace_amdgpu_dm_atomic_commit_tail_begin(state);
8191
8192         r = drm_atomic_helper_wait_for_fences(dev, state, false);
8193         if (unlikely(r))
8194                 DRM_ERROR("Waiting for fences timed out!");
8195
8196         drm_atomic_helper_update_legacy_modeset_state(dev, state);
8197         drm_dp_mst_atomic_wait_for_dependencies(state);
8198
8199         dm_state = dm_atomic_get_new_state(state);
8200         if (dm_state && dm_state->context) {
8201                 dc_state = dm_state->context;
8202         } else {
8203                 /* No state changes, retain current state. */
8204                 dc_state_temp = dc_create_state(dm->dc);
8205                 ASSERT(dc_state_temp);
8206                 dc_state = dc_state_temp;
8207                 dc_resource_state_copy_construct_current(dm->dc, dc_state);
8208         }
8209
8210         for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8211                                        new_crtc_state, i) {
8212                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8213
8214                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8215
8216                 if (old_crtc_state->active &&
8217                     (!new_crtc_state->active ||
8218                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8219                         manage_dm_interrupts(adev, acrtc, false);
8220                         dc_stream_release(dm_old_crtc_state->stream);
8221                 }
8222         }
8223
8224         drm_atomic_helper_calc_timestamping_constants(state);
8225
8226         /* update changed items */
8227         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8228                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8229
8230                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8231                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8232
8233                 drm_dbg_state(state->dev,
8234                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8235                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
8236                         "connectors_changed:%d\n",
8237                         acrtc->crtc_id,
8238                         new_crtc_state->enable,
8239                         new_crtc_state->active,
8240                         new_crtc_state->planes_changed,
8241                         new_crtc_state->mode_changed,
8242                         new_crtc_state->active_changed,
8243                         new_crtc_state->connectors_changed);
8244
8245                 /* Disable cursor if disabling crtc */
8246                 if (old_crtc_state->active && !new_crtc_state->active) {
8247                         struct dc_cursor_position position;
8248
8249                         memset(&position, 0, sizeof(position));
8250                         mutex_lock(&dm->dc_lock);
8251                         dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8252                         mutex_unlock(&dm->dc_lock);
8253                 }
8254
8255                 /* Copy all transient state flags into dc state */
8256                 if (dm_new_crtc_state->stream) {
8257                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8258                                                             dm_new_crtc_state->stream);
8259                 }
8260
8261                 /* handles headless hotplug case, updating new_state and
8262                  * aconnector as needed
8263                  */
8264
8265                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8266
8267                         DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8268
8269                         if (!dm_new_crtc_state->stream) {
8270                                 /*
8271                                  * this could happen because of issues with
8272                                  * userspace notifications delivery.
8273                                  * In this case userspace tries to set mode on
8274                                  * display which is disconnected in fact.
8275                                  * dc_sink is NULL in this case on aconnector.
8276                                  * We expect reset mode will come soon.
8277                                  *
8278                                  * This can also happen when unplug is done
8279                                  * during resume sequence ended
8280                                  *
8281                                  * In this case, we want to pretend we still
8282                                  * have a sink to keep the pipe running so that
8283                                  * hw state is consistent with the sw state
8284                                  */
8285                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8286                                                 __func__, acrtc->base.base.id);
8287                                 continue;
8288                         }
8289
8290                         if (dm_old_crtc_state->stream)
8291                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8292
8293                         pm_runtime_get_noresume(dev->dev);
8294
8295                         acrtc->enabled = true;
8296                         acrtc->hw_mode = new_crtc_state->mode;
8297                         crtc->hwmode = new_crtc_state->mode;
8298                         mode_set_reset_required = true;
8299                 } else if (modereset_required(new_crtc_state)) {
8300                         DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8301                         /* i.e. reset mode */
8302                         if (dm_old_crtc_state->stream)
8303                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8304
8305                         mode_set_reset_required = true;
8306                 }
8307         } /* for_each_crtc_in_state() */
8308
8309         if (dc_state) {
8310                 /* if there mode set or reset, disable eDP PSR */
8311                 if (mode_set_reset_required) {
8312                         if (dm->vblank_control_workqueue)
8313                                 flush_workqueue(dm->vblank_control_workqueue);
8314
8315                         amdgpu_dm_psr_disable_all(dm);
8316                 }
8317
8318                 dm_enable_per_frame_crtc_master_sync(dc_state);
8319                 mutex_lock(&dm->dc_lock);
8320                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
8321
8322                 /* Allow idle optimization when vblank count is 0 for display off */
8323                 if (dm->active_vblank_irq_count == 0)
8324                         dc_allow_idle_optimizations(dm->dc, true);
8325                 mutex_unlock(&dm->dc_lock);
8326         }
8327
8328         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8329                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8330
8331                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8332
8333                 if (dm_new_crtc_state->stream != NULL) {
8334                         const struct dc_stream_status *status =
8335                                         dc_stream_get_status(dm_new_crtc_state->stream);
8336
8337                         if (!status)
8338                                 status = dc_stream_get_status_from_state(dc_state,
8339                                                                          dm_new_crtc_state->stream);
8340                         if (!status)
8341                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8342                         else
8343                                 acrtc->otg_inst = status->primary_otg_inst;
8344                 }
8345         }
8346 #ifdef CONFIG_DRM_AMD_DC_HDCP
8347         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8348                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8349                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8350                 struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8351
8352                 pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
8353
8354                 if (!connector)
8355                         continue;
8356
8357                 pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
8358                         connector->index, connector->status, connector->dpms);
8359                 pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
8360                         old_con_state->content_protection, new_con_state->content_protection);
8361
8362                 if (aconnector->dc_sink) {
8363                         if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
8364                                 aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
8365                                 pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
8366                                 aconnector->dc_sink->edid_caps.display_name);
8367                         }
8368                 }
8369
8370                 new_crtc_state = NULL;
8371                 old_crtc_state = NULL;
8372
8373                 if (acrtc) {
8374                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8375                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8376                 }
8377
8378                 if (old_crtc_state)
8379                         pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8380                         old_crtc_state->enable,
8381                         old_crtc_state->active,
8382                         old_crtc_state->mode_changed,
8383                         old_crtc_state->active_changed,
8384                         old_crtc_state->connectors_changed);
8385
8386                 if (new_crtc_state)
8387                         pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
8388                         new_crtc_state->enable,
8389                         new_crtc_state->active,
8390                         new_crtc_state->mode_changed,
8391                         new_crtc_state->active_changed,
8392                         new_crtc_state->connectors_changed);
8393         }
8394
8395         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8396                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8397                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8398                 struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8399
8400                 new_crtc_state = NULL;
8401                 old_crtc_state = NULL;
8402
8403                 if (acrtc) {
8404                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8405                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8406                 }
8407
8408                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8409
8410                 if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8411                     connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8412                         hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8413                         new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8414                         dm_new_con_state->update_hdcp = true;
8415                         continue;
8416                 }
8417
8418                 if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
8419                                                                                         old_con_state, connector, adev->dm.hdcp_workqueue)) {
8420                         /* when display is unplugged from mst hub, connctor will
8421                          * be destroyed within dm_dp_mst_connector_destroy. connector
8422                          * hdcp perperties, like type, undesired, desired, enabled,
8423                          * will be lost. So, save hdcp properties into hdcp_work within
8424                          * amdgpu_dm_atomic_commit_tail. if the same display is
8425                          * plugged back with same display index, its hdcp properties
8426                          * will be retrieved from hdcp_work within dm_dp_mst_get_modes
8427                          */
8428
8429                         bool enable_encryption = false;
8430
8431                         if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
8432                                 enable_encryption = true;
8433
8434                         if (aconnector->dc_link && aconnector->dc_sink &&
8435                                 aconnector->dc_link->type == dc_connection_mst_branch) {
8436                                 struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
8437                                 struct hdcp_workqueue *hdcp_w =
8438                                         &hdcp_work[aconnector->dc_link->link_index];
8439
8440                                 hdcp_w->hdcp_content_type[connector->index] =
8441                                         new_con_state->hdcp_content_type;
8442                                 hdcp_w->content_protection[connector->index] =
8443                                         new_con_state->content_protection;
8444                         }
8445
8446                         if (new_crtc_state && new_crtc_state->mode_changed &&
8447                                 new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
8448                                 enable_encryption = true;
8449
8450                         DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
8451
8452                         hdcp_update_display(
8453                                 adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8454                                 new_con_state->hdcp_content_type, enable_encryption);
8455                 }
8456         }
8457 #endif
8458
8459         /* Handle connector state changes */
8460         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8461                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8462                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8463                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8464                 struct dc_surface_update dummy_updates[MAX_SURFACES];
8465                 struct dc_stream_update stream_update;
8466                 struct dc_info_packet hdr_packet;
8467                 struct dc_stream_status *status = NULL;
8468                 bool abm_changed, hdr_changed, scaling_changed;
8469
8470                 memset(&dummy_updates, 0, sizeof(dummy_updates));
8471                 memset(&stream_update, 0, sizeof(stream_update));
8472
8473                 if (acrtc) {
8474                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8475                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8476                 }
8477
8478                 /* Skip any modesets/resets */
8479                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8480                         continue;
8481
8482                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8483                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8484
8485                 scaling_changed = is_scaling_state_different(dm_new_con_state,
8486                                                              dm_old_con_state);
8487
8488                 abm_changed = dm_new_crtc_state->abm_level !=
8489                               dm_old_crtc_state->abm_level;
8490
8491                 hdr_changed =
8492                         !drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8493
8494                 if (!scaling_changed && !abm_changed && !hdr_changed)
8495                         continue;
8496
8497                 stream_update.stream = dm_new_crtc_state->stream;
8498                 if (scaling_changed) {
8499                         update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8500                                         dm_new_con_state, dm_new_crtc_state->stream);
8501
8502                         stream_update.src = dm_new_crtc_state->stream->src;
8503                         stream_update.dst = dm_new_crtc_state->stream->dst;
8504                 }
8505
8506                 if (abm_changed) {
8507                         dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8508
8509                         stream_update.abm_level = &dm_new_crtc_state->abm_level;
8510                 }
8511
8512                 if (hdr_changed) {
8513                         fill_hdr_info_packet(new_con_state, &hdr_packet);
8514                         stream_update.hdr_static_metadata = &hdr_packet;
8515                 }
8516
8517                 status = dc_stream_get_status(dm_new_crtc_state->stream);
8518
8519                 if (WARN_ON(!status))
8520                         continue;
8521
8522                 WARN_ON(!status->plane_count);
8523
8524                 /*
8525                  * TODO: DC refuses to perform stream updates without a dc_surface_update.
8526                  * Here we create an empty update on each plane.
8527                  * To fix this, DC should permit updating only stream properties.
8528                  */
8529                 for (j = 0; j < status->plane_count; j++)
8530                         dummy_updates[j].surface = status->plane_states[0];
8531
8532
8533                 mutex_lock(&dm->dc_lock);
8534                 dc_commit_updates_for_stream(dm->dc,
8535                                                      dummy_updates,
8536                                                      status->plane_count,
8537                                                      dm_new_crtc_state->stream,
8538                                                      &stream_update,
8539                                                      dc_state);
8540                 mutex_unlock(&dm->dc_lock);
8541         }
8542
8543         /**
8544          * Enable interrupts for CRTCs that are newly enabled or went through
8545          * a modeset. It was intentionally deferred until after the front end
8546          * state was modified to wait until the OTG was on and so the IRQ
8547          * handlers didn't access stale or invalid state.
8548          */
8549         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8550                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8551 #ifdef CONFIG_DEBUG_FS
8552                 enum amdgpu_dm_pipe_crc_source cur_crc_src;
8553 #endif
8554                 /* Count number of newly disabled CRTCs for dropping PM refs later. */
8555                 if (old_crtc_state->active && !new_crtc_state->active)
8556                         crtc_disable_count++;
8557
8558                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8559                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8560
8561                 /* For freesync config update on crtc state and params for irq */
8562                 update_stream_irq_parameters(dm, dm_new_crtc_state);
8563
8564 #ifdef CONFIG_DEBUG_FS
8565                 spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8566                 cur_crc_src = acrtc->dm_irq_params.crc_src;
8567                 spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8568 #endif
8569
8570                 if (new_crtc_state->active &&
8571                     (!old_crtc_state->active ||
8572                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8573                         dc_stream_retain(dm_new_crtc_state->stream);
8574                         acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8575                         manage_dm_interrupts(adev, acrtc, true);
8576                 }
8577                 /* Handle vrr on->off / off->on transitions */
8578                 amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8579
8580 #ifdef CONFIG_DEBUG_FS
8581                 if (new_crtc_state->active &&
8582                     (!old_crtc_state->active ||
8583                      drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8584                         /**
8585                          * Frontend may have changed so reapply the CRC capture
8586                          * settings for the stream.
8587                          */
8588                         if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8589 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8590                                 if (amdgpu_dm_crc_window_is_activated(crtc)) {
8591                                         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8592                                         acrtc->dm_irq_params.window_param.update_win = true;
8593
8594                                         /**
8595                                          * It takes 2 frames for HW to stably generate CRC when
8596                                          * resuming from suspend, so we set skip_frame_cnt 2.
8597                                          */
8598                                         acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
8599                                         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8600                                 }
8601 #endif
8602                                 if (amdgpu_dm_crtc_configure_crc_source(
8603                                         crtc, dm_new_crtc_state, cur_crc_src))
8604                                         DRM_DEBUG_DRIVER("Failed to configure crc source");
8605                         }
8606                 }
8607 #endif
8608         }
8609
8610         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8611                 if (new_crtc_state->async_flip)
8612                         wait_for_vblank = false;
8613
8614         /* update planes when needed per crtc*/
8615         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8616                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8617
8618                 if (dm_new_crtc_state->stream)
8619                         amdgpu_dm_commit_planes(state, dc_state, dev,
8620                                                 dm, crtc, wait_for_vblank);
8621         }
8622
8623         /* Update audio instances for each connector. */
8624         amdgpu_dm_commit_audio(dev, state);
8625
8626         /* restore the backlight level */
8627         for (i = 0; i < dm->num_of_edps; i++) {
8628                 if (dm->backlight_dev[i] &&
8629                     (dm->actual_brightness[i] != dm->brightness[i]))
8630                         amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8631         }
8632
8633         /*
8634          * send vblank event on all events not handled in flip and
8635          * mark consumed event for drm_atomic_helper_commit_hw_done
8636          */
8637         spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8638         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8639
8640                 if (new_crtc_state->event)
8641                         drm_send_event_locked(dev, &new_crtc_state->event->base);
8642
8643                 new_crtc_state->event = NULL;
8644         }
8645         spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8646
8647         /* Signal HW programming completion */
8648         drm_atomic_helper_commit_hw_done(state);
8649
8650         if (wait_for_vblank)
8651                 drm_atomic_helper_wait_for_flip_done(dev, state);
8652
8653         drm_atomic_helper_cleanup_planes(dev, state);
8654
8655         /* return the stolen vga memory back to VRAM */
8656         if (!adev->mman.keep_stolen_vga_memory)
8657                 amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8658         amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8659
8660         /*
8661          * Finally, drop a runtime PM reference for each newly disabled CRTC,
8662          * so we can put the GPU into runtime suspend if we're not driving any
8663          * displays anymore
8664          */
8665         for (i = 0; i < crtc_disable_count; i++)
8666                 pm_runtime_put_autosuspend(dev->dev);
8667         pm_runtime_mark_last_busy(dev->dev);
8668
8669         if (dc_state_temp)
8670                 dc_release_state(dc_state_temp);
8671 }
8672
8673 static int dm_force_atomic_commit(struct drm_connector *connector)
8674 {
8675         int ret = 0;
8676         struct drm_device *ddev = connector->dev;
8677         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8678         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8679         struct drm_plane *plane = disconnected_acrtc->base.primary;
8680         struct drm_connector_state *conn_state;
8681         struct drm_crtc_state *crtc_state;
8682         struct drm_plane_state *plane_state;
8683
8684         if (!state)
8685                 return -ENOMEM;
8686
8687         state->acquire_ctx = ddev->mode_config.acquire_ctx;
8688
8689         /* Construct an atomic state to restore previous display setting */
8690
8691         /*
8692          * Attach connectors to drm_atomic_state
8693          */
8694         conn_state = drm_atomic_get_connector_state(state, connector);
8695
8696         ret = PTR_ERR_OR_ZERO(conn_state);
8697         if (ret)
8698                 goto out;
8699
8700         /* Attach crtc to drm_atomic_state*/
8701         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8702
8703         ret = PTR_ERR_OR_ZERO(crtc_state);
8704         if (ret)
8705                 goto out;
8706
8707         /* force a restore */
8708         crtc_state->mode_changed = true;
8709
8710         /* Attach plane to drm_atomic_state */
8711         plane_state = drm_atomic_get_plane_state(state, plane);
8712
8713         ret = PTR_ERR_OR_ZERO(plane_state);
8714         if (ret)
8715                 goto out;
8716
8717         /* Call commit internally with the state we just constructed */
8718         ret = drm_atomic_commit(state);
8719
8720 out:
8721         drm_atomic_state_put(state);
8722         if (ret)
8723                 DRM_ERROR("Restoring old state failed with %i\n", ret);
8724
8725         return ret;
8726 }
8727
8728 /*
8729  * This function handles all cases when set mode does not come upon hotplug.
8730  * This includes when a display is unplugged then plugged back into the
8731  * same port and when running without usermode desktop manager supprot
8732  */
8733 void dm_restore_drm_connector_state(struct drm_device *dev,
8734                                     struct drm_connector *connector)
8735 {
8736         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8737         struct amdgpu_crtc *disconnected_acrtc;
8738         struct dm_crtc_state *acrtc_state;
8739
8740         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8741                 return;
8742
8743         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8744         if (!disconnected_acrtc)
8745                 return;
8746
8747         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8748         if (!acrtc_state->stream)
8749                 return;
8750
8751         /*
8752          * If the previous sink is not released and different from the current,
8753          * we deduce we are in a state where we can not rely on usermode call
8754          * to turn on the display, so we do it here
8755          */
8756         if (acrtc_state->stream->sink != aconnector->dc_sink)
8757                 dm_force_atomic_commit(&aconnector->base);
8758 }
8759
8760 /*
8761  * Grabs all modesetting locks to serialize against any blocking commits,
8762  * Waits for completion of all non blocking commits.
8763  */
8764 static int do_aquire_global_lock(struct drm_device *dev,
8765                                  struct drm_atomic_state *state)
8766 {
8767         struct drm_crtc *crtc;
8768         struct drm_crtc_commit *commit;
8769         long ret;
8770
8771         /*
8772          * Adding all modeset locks to aquire_ctx will
8773          * ensure that when the framework release it the
8774          * extra locks we are locking here will get released to
8775          */
8776         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8777         if (ret)
8778                 return ret;
8779
8780         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8781                 spin_lock(&crtc->commit_lock);
8782                 commit = list_first_entry_or_null(&crtc->commit_list,
8783                                 struct drm_crtc_commit, commit_entry);
8784                 if (commit)
8785                         drm_crtc_commit_get(commit);
8786                 spin_unlock(&crtc->commit_lock);
8787
8788                 if (!commit)
8789                         continue;
8790
8791                 /*
8792                  * Make sure all pending HW programming completed and
8793                  * page flips done
8794                  */
8795                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8796
8797                 if (ret > 0)
8798                         ret = wait_for_completion_interruptible_timeout(
8799                                         &commit->flip_done, 10*HZ);
8800
8801                 if (ret == 0)
8802                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8803                                   "timed out\n", crtc->base.id, crtc->name);
8804
8805                 drm_crtc_commit_put(commit);
8806         }
8807
8808         return ret < 0 ? ret : 0;
8809 }
8810
8811 static void get_freesync_config_for_crtc(
8812         struct dm_crtc_state *new_crtc_state,
8813         struct dm_connector_state *new_con_state)
8814 {
8815         struct mod_freesync_config config = {0};
8816         struct amdgpu_dm_connector *aconnector =
8817                         to_amdgpu_dm_connector(new_con_state->base.connector);
8818         struct drm_display_mode *mode = &new_crtc_state->base.mode;
8819         int vrefresh = drm_mode_vrefresh(mode);
8820         bool fs_vid_mode = false;
8821         bool drr_active = false;
8822
8823         new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8824                                         vrefresh >= aconnector->min_vfreq &&
8825                                         vrefresh <= aconnector->max_vfreq;
8826
8827         drr_active = new_crtc_state->vrr_supported &&
8828                 new_crtc_state->freesync_config.state != VRR_STATE_DISABLED &&
8829                 new_crtc_state->freesync_config.state != VRR_STATE_INACTIVE &&
8830                 new_crtc_state->freesync_config.state != VRR_STATE_UNSUPPORTED;
8831
8832         if (drr_active)
8833                 new_crtc_state->stream->ignore_msa_timing_param = true;
8834
8835         if (new_crtc_state->vrr_supported) {
8836                 fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8837                 config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8838                 config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8839                 config.vsif_supported = true;
8840                 config.btr = true;
8841
8842                 if (fs_vid_mode) {
8843                         config.state = VRR_STATE_ACTIVE_FIXED;
8844                         config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8845                         goto out;
8846                 } else if (new_crtc_state->base.vrr_enabled) {
8847                         config.state = VRR_STATE_ACTIVE_VARIABLE;
8848                 } else {
8849                         config.state = VRR_STATE_INACTIVE;
8850                 }
8851         }
8852 out:
8853         new_crtc_state->freesync_config = config;
8854 }
8855
8856 static void reset_freesync_config_for_crtc(
8857         struct dm_crtc_state *new_crtc_state)
8858 {
8859         new_crtc_state->vrr_supported = false;
8860
8861         memset(&new_crtc_state->vrr_infopacket, 0,
8862                sizeof(new_crtc_state->vrr_infopacket));
8863 }
8864
8865 static bool
8866 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8867                                  struct drm_crtc_state *new_crtc_state)
8868 {
8869         const struct drm_display_mode *old_mode, *new_mode;
8870
8871         if (!old_crtc_state || !new_crtc_state)
8872                 return false;
8873
8874         old_mode = &old_crtc_state->mode;
8875         new_mode = &new_crtc_state->mode;
8876
8877         if (old_mode->clock       == new_mode->clock &&
8878             old_mode->hdisplay    == new_mode->hdisplay &&
8879             old_mode->vdisplay    == new_mode->vdisplay &&
8880             old_mode->htotal      == new_mode->htotal &&
8881             old_mode->vtotal      != new_mode->vtotal &&
8882             old_mode->hsync_start == new_mode->hsync_start &&
8883             old_mode->vsync_start != new_mode->vsync_start &&
8884             old_mode->hsync_end   == new_mode->hsync_end &&
8885             old_mode->vsync_end   != new_mode->vsync_end &&
8886             old_mode->hskew       == new_mode->hskew &&
8887             old_mode->vscan       == new_mode->vscan &&
8888             (old_mode->vsync_end - old_mode->vsync_start) ==
8889             (new_mode->vsync_end - new_mode->vsync_start))
8890                 return true;
8891
8892         return false;
8893 }
8894
8895 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
8896         u64 num, den, res;
8897         struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
8898
8899         dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
8900
8901         num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
8902         den = (unsigned long long)new_crtc_state->mode.htotal *
8903               (unsigned long long)new_crtc_state->mode.vtotal;
8904
8905         res = div_u64(num, den);
8906         dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
8907 }
8908
8909 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
8910                          struct drm_atomic_state *state,
8911                          struct drm_crtc *crtc,
8912                          struct drm_crtc_state *old_crtc_state,
8913                          struct drm_crtc_state *new_crtc_state,
8914                          bool enable,
8915                          bool *lock_and_validation_needed)
8916 {
8917         struct dm_atomic_state *dm_state = NULL;
8918         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8919         struct dc_stream_state *new_stream;
8920         int ret = 0;
8921
8922         /*
8923          * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
8924          * update changed items
8925          */
8926         struct amdgpu_crtc *acrtc = NULL;
8927         struct amdgpu_dm_connector *aconnector = NULL;
8928         struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
8929         struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
8930
8931         new_stream = NULL;
8932
8933         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8934         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8935         acrtc = to_amdgpu_crtc(crtc);
8936         aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
8937
8938         /* TODO This hack should go away */
8939         if (aconnector && enable) {
8940                 /* Make sure fake sink is created in plug-in scenario */
8941                 drm_new_conn_state = drm_atomic_get_new_connector_state(state,
8942                                                             &aconnector->base);
8943                 drm_old_conn_state = drm_atomic_get_old_connector_state(state,
8944                                                             &aconnector->base);
8945
8946                 if (IS_ERR(drm_new_conn_state)) {
8947                         ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
8948                         goto fail;
8949                 }
8950
8951                 dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
8952                 dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
8953
8954                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8955                         goto skip_modeset;
8956
8957                 new_stream = create_validate_stream_for_sink(aconnector,
8958                                                              &new_crtc_state->mode,
8959                                                              dm_new_conn_state,
8960                                                              dm_old_crtc_state->stream);
8961
8962                 /*
8963                  * we can have no stream on ACTION_SET if a display
8964                  * was disconnected during S3, in this case it is not an
8965                  * error, the OS will be updated after detection, and
8966                  * will do the right thing on next atomic commit
8967                  */
8968
8969                 if (!new_stream) {
8970                         DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8971                                         __func__, acrtc->base.base.id);
8972                         ret = -ENOMEM;
8973                         goto fail;
8974                 }
8975
8976                 /*
8977                  * TODO: Check VSDB bits to decide whether this should
8978                  * be enabled or not.
8979                  */
8980                 new_stream->triggered_crtc_reset.enabled =
8981                         dm->force_timing_sync;
8982
8983                 dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8984
8985                 ret = fill_hdr_info_packet(drm_new_conn_state,
8986                                            &new_stream->hdr_static_metadata);
8987                 if (ret)
8988                         goto fail;
8989
8990                 /*
8991                  * If we already removed the old stream from the context
8992                  * (and set the new stream to NULL) then we can't reuse
8993                  * the old stream even if the stream and scaling are unchanged.
8994                  * We'll hit the BUG_ON and black screen.
8995                  *
8996                  * TODO: Refactor this function to allow this check to work
8997                  * in all conditions.
8998                  */
8999                 if (amdgpu_freesync_vid_mode &&
9000                     dm_new_crtc_state->stream &&
9001                     is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
9002                         goto skip_modeset;
9003
9004                 if (dm_new_crtc_state->stream &&
9005                     dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
9006                     dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
9007                         new_crtc_state->mode_changed = false;
9008                         DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
9009                                          new_crtc_state->mode_changed);
9010                 }
9011         }
9012
9013         /* mode_changed flag may get updated above, need to check again */
9014         if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
9015                 goto skip_modeset;
9016
9017         drm_dbg_state(state->dev,
9018                 "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
9019                 "planes_changed:%d, mode_changed:%d,active_changed:%d,"
9020                 "connectors_changed:%d\n",
9021                 acrtc->crtc_id,
9022                 new_crtc_state->enable,
9023                 new_crtc_state->active,
9024                 new_crtc_state->planes_changed,
9025                 new_crtc_state->mode_changed,
9026                 new_crtc_state->active_changed,
9027                 new_crtc_state->connectors_changed);
9028
9029         /* Remove stream for any changed/disabled CRTC */
9030         if (!enable) {
9031
9032                 if (!dm_old_crtc_state->stream)
9033                         goto skip_modeset;
9034
9035                 if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
9036                     is_timing_unchanged_for_freesync(new_crtc_state,
9037                                                      old_crtc_state)) {
9038                         new_crtc_state->mode_changed = false;
9039                         DRM_DEBUG_DRIVER(
9040                                 "Mode change not required for front porch change, "
9041                                 "setting mode_changed to %d",
9042                                 new_crtc_state->mode_changed);
9043
9044                         set_freesync_fixed_config(dm_new_crtc_state);
9045
9046                         goto skip_modeset;
9047                 } else if (amdgpu_freesync_vid_mode && aconnector &&
9048                            is_freesync_video_mode(&new_crtc_state->mode,
9049                                                   aconnector)) {
9050                         struct drm_display_mode *high_mode;
9051
9052                         high_mode = get_highest_refresh_rate_mode(aconnector, false);
9053                         if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
9054                                 set_freesync_fixed_config(dm_new_crtc_state);
9055                         }
9056                 }
9057
9058                 ret = dm_atomic_get_state(state, &dm_state);
9059                 if (ret)
9060                         goto fail;
9061
9062                 DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
9063                                 crtc->base.id);
9064
9065                 /* i.e. reset mode */
9066                 if (dc_remove_stream_from_ctx(
9067                                 dm->dc,
9068                                 dm_state->context,
9069                                 dm_old_crtc_state->stream) != DC_OK) {
9070                         ret = -EINVAL;
9071                         goto fail;
9072                 }
9073
9074                 dc_stream_release(dm_old_crtc_state->stream);
9075                 dm_new_crtc_state->stream = NULL;
9076
9077                 reset_freesync_config_for_crtc(dm_new_crtc_state);
9078
9079                 *lock_and_validation_needed = true;
9080
9081         } else {/* Add stream for any updated/enabled CRTC */
9082                 /*
9083                  * Quick fix to prevent NULL pointer on new_stream when
9084                  * added MST connectors not found in existing crtc_state in the chained mode
9085                  * TODO: need to dig out the root cause of that
9086                  */
9087                 if (!aconnector)
9088                         goto skip_modeset;
9089
9090                 if (modereset_required(new_crtc_state))
9091                         goto skip_modeset;
9092
9093                 if (modeset_required(new_crtc_state, new_stream,
9094                                      dm_old_crtc_state->stream)) {
9095
9096                         WARN_ON(dm_new_crtc_state->stream);
9097
9098                         ret = dm_atomic_get_state(state, &dm_state);
9099                         if (ret)
9100                                 goto fail;
9101
9102                         dm_new_crtc_state->stream = new_stream;
9103
9104                         dc_stream_retain(new_stream);
9105
9106                         DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
9107                                          crtc->base.id);
9108
9109                         if (dc_add_stream_to_ctx(
9110                                         dm->dc,
9111                                         dm_state->context,
9112                                         dm_new_crtc_state->stream) != DC_OK) {
9113                                 ret = -EINVAL;
9114                                 goto fail;
9115                         }
9116
9117                         *lock_and_validation_needed = true;
9118                 }
9119         }
9120
9121 skip_modeset:
9122         /* Release extra reference */
9123         if (new_stream)
9124                  dc_stream_release(new_stream);
9125
9126         /*
9127          * We want to do dc stream updates that do not require a
9128          * full modeset below.
9129          */
9130         if (!(enable && aconnector && new_crtc_state->active))
9131                 return 0;
9132         /*
9133          * Given above conditions, the dc state cannot be NULL because:
9134          * 1. We're in the process of enabling CRTCs (just been added
9135          *    to the dc context, or already is on the context)
9136          * 2. Has a valid connector attached, and
9137          * 3. Is currently active and enabled.
9138          * => The dc stream state currently exists.
9139          */
9140         BUG_ON(dm_new_crtc_state->stream == NULL);
9141
9142         /* Scaling or underscan settings */
9143         if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
9144                                 drm_atomic_crtc_needs_modeset(new_crtc_state))
9145                 update_stream_scaling_settings(
9146                         &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
9147
9148         /* ABM settings */
9149         dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
9150
9151         /*
9152          * Color management settings. We also update color properties
9153          * when a modeset is needed, to ensure it gets reprogrammed.
9154          */
9155         if (dm_new_crtc_state->base.color_mgmt_changed ||
9156             drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9157                 ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
9158                 if (ret)
9159                         goto fail;
9160         }
9161
9162         /* Update Freesync settings. */
9163         get_freesync_config_for_crtc(dm_new_crtc_state,
9164                                      dm_new_conn_state);
9165
9166         return ret;
9167
9168 fail:
9169         if (new_stream)
9170                 dc_stream_release(new_stream);
9171         return ret;
9172 }
9173
9174 static bool should_reset_plane(struct drm_atomic_state *state,
9175                                struct drm_plane *plane,
9176                                struct drm_plane_state *old_plane_state,
9177                                struct drm_plane_state *new_plane_state)
9178 {
9179         struct drm_plane *other;
9180         struct drm_plane_state *old_other_state, *new_other_state;
9181         struct drm_crtc_state *new_crtc_state;
9182         int i;
9183
9184         /*
9185          * TODO: Remove this hack once the checks below are sufficient
9186          * enough to determine when we need to reset all the planes on
9187          * the stream.
9188          */
9189         if (state->allow_modeset)
9190                 return true;
9191
9192         /* Exit early if we know that we're adding or removing the plane. */
9193         if (old_plane_state->crtc != new_plane_state->crtc)
9194                 return true;
9195
9196         /* old crtc == new_crtc == NULL, plane not in context. */
9197         if (!new_plane_state->crtc)
9198                 return false;
9199
9200         new_crtc_state =
9201                 drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
9202
9203         if (!new_crtc_state)
9204                 return true;
9205
9206         /* CRTC Degamma changes currently require us to recreate planes. */
9207         if (new_crtc_state->color_mgmt_changed)
9208                 return true;
9209
9210         if (drm_atomic_crtc_needs_modeset(new_crtc_state))
9211                 return true;
9212
9213         /*
9214          * If there are any new primary or overlay planes being added or
9215          * removed then the z-order can potentially change. To ensure
9216          * correct z-order and pipe acquisition the current DC architecture
9217          * requires us to remove and recreate all existing planes.
9218          *
9219          * TODO: Come up with a more elegant solution for this.
9220          */
9221         for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
9222                 struct amdgpu_framebuffer *old_afb, *new_afb;
9223                 if (other->type == DRM_PLANE_TYPE_CURSOR)
9224                         continue;
9225
9226                 if (old_other_state->crtc != new_plane_state->crtc &&
9227                     new_other_state->crtc != new_plane_state->crtc)
9228                         continue;
9229
9230                 if (old_other_state->crtc != new_other_state->crtc)
9231                         return true;
9232
9233                 /* Src/dst size and scaling updates. */
9234                 if (old_other_state->src_w != new_other_state->src_w ||
9235                     old_other_state->src_h != new_other_state->src_h ||
9236                     old_other_state->crtc_w != new_other_state->crtc_w ||
9237                     old_other_state->crtc_h != new_other_state->crtc_h)
9238                         return true;
9239
9240                 /* Rotation / mirroring updates. */
9241                 if (old_other_state->rotation != new_other_state->rotation)
9242                         return true;
9243
9244                 /* Blending updates. */
9245                 if (old_other_state->pixel_blend_mode !=
9246                     new_other_state->pixel_blend_mode)
9247                         return true;
9248
9249                 /* Alpha updates. */
9250                 if (old_other_state->alpha != new_other_state->alpha)
9251                         return true;
9252
9253                 /* Colorspace changes. */
9254                 if (old_other_state->color_range != new_other_state->color_range ||
9255                     old_other_state->color_encoding != new_other_state->color_encoding)
9256                         return true;
9257
9258                 /* Framebuffer checks fall at the end. */
9259                 if (!old_other_state->fb || !new_other_state->fb)
9260                         continue;
9261
9262                 /* Pixel format changes can require bandwidth updates. */
9263                 if (old_other_state->fb->format != new_other_state->fb->format)
9264                         return true;
9265
9266                 old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9267                 new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9268
9269                 /* Tiling and DCC changes also require bandwidth updates. */
9270                 if (old_afb->tiling_flags != new_afb->tiling_flags ||
9271                     old_afb->base.modifier != new_afb->base.modifier)
9272                         return true;
9273         }
9274
9275         return false;
9276 }
9277
9278 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9279                               struct drm_plane_state *new_plane_state,
9280                               struct drm_framebuffer *fb)
9281 {
9282         struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9283         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9284         unsigned int pitch;
9285         bool linear;
9286
9287         if (fb->width > new_acrtc->max_cursor_width ||
9288             fb->height > new_acrtc->max_cursor_height) {
9289                 DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9290                                  new_plane_state->fb->width,
9291                                  new_plane_state->fb->height);
9292                 return -EINVAL;
9293         }
9294         if (new_plane_state->src_w != fb->width << 16 ||
9295             new_plane_state->src_h != fb->height << 16) {
9296                 DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9297                 return -EINVAL;
9298         }
9299
9300         /* Pitch in pixels */
9301         pitch = fb->pitches[0] / fb->format->cpp[0];
9302
9303         if (fb->width != pitch) {
9304                 DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9305                                  fb->width, pitch);
9306                 return -EINVAL;
9307         }
9308
9309         switch (pitch) {
9310         case 64:
9311         case 128:
9312         case 256:
9313                 /* FB pitch is supported by cursor plane */
9314                 break;
9315         default:
9316                 DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9317                 return -EINVAL;
9318         }
9319
9320         /* Core DRM takes care of checking FB modifiers, so we only need to
9321          * check tiling flags when the FB doesn't have a modifier. */
9322         if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9323                 if (adev->family < AMDGPU_FAMILY_AI) {
9324                         linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9325                                  AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9326                                  AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9327                 } else {
9328                         linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9329                 }
9330                 if (!linear) {
9331                         DRM_DEBUG_ATOMIC("Cursor FB not linear");
9332                         return -EINVAL;
9333                 }
9334         }
9335
9336         return 0;
9337 }
9338
9339 static int dm_update_plane_state(struct dc *dc,
9340                                  struct drm_atomic_state *state,
9341                                  struct drm_plane *plane,
9342                                  struct drm_plane_state *old_plane_state,
9343                                  struct drm_plane_state *new_plane_state,
9344                                  bool enable,
9345                                  bool *lock_and_validation_needed)
9346 {
9347
9348         struct dm_atomic_state *dm_state = NULL;
9349         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9350         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9351         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9352         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9353         struct amdgpu_crtc *new_acrtc;
9354         bool needs_reset;
9355         int ret = 0;
9356
9357
9358         new_plane_crtc = new_plane_state->crtc;
9359         old_plane_crtc = old_plane_state->crtc;
9360         dm_new_plane_state = to_dm_plane_state(new_plane_state);
9361         dm_old_plane_state = to_dm_plane_state(old_plane_state);
9362
9363         if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9364                 if (!enable || !new_plane_crtc ||
9365                         drm_atomic_plane_disabling(plane->state, new_plane_state))
9366                         return 0;
9367
9368                 new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9369
9370                 if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9371                         DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9372                         return -EINVAL;
9373                 }
9374
9375                 if (new_plane_state->fb) {
9376                         ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9377                                                  new_plane_state->fb);
9378                         if (ret)
9379                                 return ret;
9380                 }
9381
9382                 return 0;
9383         }
9384
9385         needs_reset = should_reset_plane(state, plane, old_plane_state,
9386                                          new_plane_state);
9387
9388         /* Remove any changed/removed planes */
9389         if (!enable) {
9390                 if (!needs_reset)
9391                         return 0;
9392
9393                 if (!old_plane_crtc)
9394                         return 0;
9395
9396                 old_crtc_state = drm_atomic_get_old_crtc_state(
9397                                 state, old_plane_crtc);
9398                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9399
9400                 if (!dm_old_crtc_state->stream)
9401                         return 0;
9402
9403                 DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9404                                 plane->base.id, old_plane_crtc->base.id);
9405
9406                 ret = dm_atomic_get_state(state, &dm_state);
9407                 if (ret)
9408                         return ret;
9409
9410                 if (!dc_remove_plane_from_context(
9411                                 dc,
9412                                 dm_old_crtc_state->stream,
9413                                 dm_old_plane_state->dc_state,
9414                                 dm_state->context)) {
9415
9416                         return -EINVAL;
9417                 }
9418
9419
9420                 dc_plane_state_release(dm_old_plane_state->dc_state);
9421                 dm_new_plane_state->dc_state = NULL;
9422
9423                 *lock_and_validation_needed = true;
9424
9425         } else { /* Add new planes */
9426                 struct dc_plane_state *dc_new_plane_state;
9427
9428                 if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9429                         return 0;
9430
9431                 if (!new_plane_crtc)
9432                         return 0;
9433
9434                 new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9435                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9436
9437                 if (!dm_new_crtc_state->stream)
9438                         return 0;
9439
9440                 if (!needs_reset)
9441                         return 0;
9442
9443                 ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9444                 if (ret)
9445                         return ret;
9446
9447                 WARN_ON(dm_new_plane_state->dc_state);
9448
9449                 dc_new_plane_state = dc_create_plane_state(dc);
9450                 if (!dc_new_plane_state)
9451                         return -ENOMEM;
9452
9453                 DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9454                                  plane->base.id, new_plane_crtc->base.id);
9455
9456                 ret = fill_dc_plane_attributes(
9457                         drm_to_adev(new_plane_crtc->dev),
9458                         dc_new_plane_state,
9459                         new_plane_state,
9460                         new_crtc_state);
9461                 if (ret) {
9462                         dc_plane_state_release(dc_new_plane_state);
9463                         return ret;
9464                 }
9465
9466                 ret = dm_atomic_get_state(state, &dm_state);
9467                 if (ret) {
9468                         dc_plane_state_release(dc_new_plane_state);
9469                         return ret;
9470                 }
9471
9472                 /*
9473                  * Any atomic check errors that occur after this will
9474                  * not need a release. The plane state will be attached
9475                  * to the stream, and therefore part of the atomic
9476                  * state. It'll be released when the atomic state is
9477                  * cleaned.
9478                  */
9479                 if (!dc_add_plane_to_context(
9480                                 dc,
9481                                 dm_new_crtc_state->stream,
9482                                 dc_new_plane_state,
9483                                 dm_state->context)) {
9484
9485                         dc_plane_state_release(dc_new_plane_state);
9486                         return -EINVAL;
9487                 }
9488
9489                 dm_new_plane_state->dc_state = dc_new_plane_state;
9490
9491                 dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9492
9493                 /* Tell DC to do a full surface update every time there
9494                  * is a plane change. Inefficient, but works for now.
9495                  */
9496                 dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9497
9498                 *lock_and_validation_needed = true;
9499         }
9500
9501
9502         return ret;
9503 }
9504
9505 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9506                                        int *src_w, int *src_h)
9507 {
9508         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9509         case DRM_MODE_ROTATE_90:
9510         case DRM_MODE_ROTATE_270:
9511                 *src_w = plane_state->src_h >> 16;
9512                 *src_h = plane_state->src_w >> 16;
9513                 break;
9514         case DRM_MODE_ROTATE_0:
9515         case DRM_MODE_ROTATE_180:
9516         default:
9517                 *src_w = plane_state->src_w >> 16;
9518                 *src_h = plane_state->src_h >> 16;
9519                 break;
9520         }
9521 }
9522
9523 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9524                                 struct drm_crtc *crtc,
9525                                 struct drm_crtc_state *new_crtc_state)
9526 {
9527         struct drm_plane *cursor = crtc->cursor, *underlying;
9528         struct drm_plane_state *new_cursor_state, *new_underlying_state;
9529         int i;
9530         int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9531         int cursor_src_w, cursor_src_h;
9532         int underlying_src_w, underlying_src_h;
9533
9534         /* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9535          * cursor per pipe but it's going to inherit the scaling and
9536          * positioning from the underlying pipe. Check the cursor plane's
9537          * blending properties match the underlying planes'. */
9538
9539         new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9540         if (!new_cursor_state || !new_cursor_state->fb) {
9541                 return 0;
9542         }
9543
9544         dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9545         cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9546         cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9547
9548         for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9549                 /* Narrow down to non-cursor planes on the same CRTC as the cursor */
9550                 if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9551                         continue;
9552
9553                 /* Ignore disabled planes */
9554                 if (!new_underlying_state->fb)
9555                         continue;
9556
9557                 dm_get_oriented_plane_size(new_underlying_state,
9558                                            &underlying_src_w, &underlying_src_h);
9559                 underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9560                 underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9561
9562                 if (cursor_scale_w != underlying_scale_w ||
9563                     cursor_scale_h != underlying_scale_h) {
9564                         drm_dbg_atomic(crtc->dev,
9565                                        "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9566                                        cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9567                         return -EINVAL;
9568                 }
9569
9570                 /* If this plane covers the whole CRTC, no need to check planes underneath */
9571                 if (new_underlying_state->crtc_x <= 0 &&
9572                     new_underlying_state->crtc_y <= 0 &&
9573                     new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9574                     new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9575                         break;
9576         }
9577
9578         return 0;
9579 }
9580
9581 #if defined(CONFIG_DRM_AMD_DC_DCN)
9582 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9583 {
9584         struct drm_connector *connector;
9585         struct drm_connector_state *conn_state, *old_conn_state;
9586         struct amdgpu_dm_connector *aconnector = NULL;
9587         int i;
9588         for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9589                 if (!conn_state->crtc)
9590                         conn_state = old_conn_state;
9591
9592                 if (conn_state->crtc != crtc)
9593                         continue;
9594
9595                 aconnector = to_amdgpu_dm_connector(connector);
9596                 if (!aconnector->port || !aconnector->mst_port)
9597                         aconnector = NULL;
9598                 else
9599                         break;
9600         }
9601
9602         if (!aconnector)
9603                 return 0;
9604
9605         return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_port->mst_mgr);
9606 }
9607 #endif
9608
9609 /**
9610  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9611  *
9612  * @dev: The DRM device
9613  * @state: The atomic state to commit
9614  *
9615  * Validate that the given atomic state is programmable by DC into hardware.
9616  * This involves constructing a &struct dc_state reflecting the new hardware
9617  * state we wish to commit, then querying DC to see if it is programmable. It's
9618  * important not to modify the existing DC state. Otherwise, atomic_check
9619  * may unexpectedly commit hardware changes.
9620  *
9621  * When validating the DC state, it's important that the right locks are
9622  * acquired. For full updates case which removes/adds/updates streams on one
9623  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9624  * that any such full update commit will wait for completion of any outstanding
9625  * flip using DRMs synchronization events.
9626  *
9627  * Note that DM adds the affected connectors for all CRTCs in state, when that
9628  * might not seem necessary. This is because DC stream creation requires the
9629  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9630  * be possible but non-trivial - a possible TODO item.
9631  *
9632  * Return: -Error code if validation failed.
9633  */
9634 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9635                                   struct drm_atomic_state *state)
9636 {
9637         struct amdgpu_device *adev = drm_to_adev(dev);
9638         struct dm_atomic_state *dm_state = NULL;
9639         struct dc *dc = adev->dm.dc;
9640         struct drm_connector *connector;
9641         struct drm_connector_state *old_con_state, *new_con_state;
9642         struct drm_crtc *crtc;
9643         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9644         struct drm_plane *plane;
9645         struct drm_plane_state *old_plane_state, *new_plane_state;
9646         enum dc_status status;
9647         int ret, i;
9648         bool lock_and_validation_needed = false;
9649         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9650 #if defined(CONFIG_DRM_AMD_DC_DCN)
9651         struct dsc_mst_fairness_vars vars[MAX_PIPES];
9652 #endif
9653
9654         trace_amdgpu_dm_atomic_check_begin(state);
9655
9656         ret = drm_atomic_helper_check_modeset(dev, state);
9657         if (ret) {
9658                 DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9659                 goto fail;
9660         }
9661
9662         /* Check connector changes */
9663         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9664                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9665                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9666
9667                 /* Skip connectors that are disabled or part of modeset already. */
9668                 if (!new_con_state->crtc)
9669                         continue;
9670
9671                 new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9672                 if (IS_ERR(new_crtc_state)) {
9673                         DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9674                         ret = PTR_ERR(new_crtc_state);
9675                         goto fail;
9676                 }
9677
9678                 if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
9679                     dm_old_con_state->scaling != dm_new_con_state->scaling)
9680                         new_crtc_state->connectors_changed = true;
9681         }
9682
9683 #if defined(CONFIG_DRM_AMD_DC_DCN)
9684         if (dc_resource_is_dsc_encoding_supported(dc)) {
9685                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9686                         if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9687                                 ret = add_affected_mst_dsc_crtcs(state, crtc);
9688                                 if (ret) {
9689                                         DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9690                                         goto fail;
9691                                 }
9692                         }
9693                 }
9694         }
9695 #endif
9696         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9697                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9698
9699                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9700                     !new_crtc_state->color_mgmt_changed &&
9701                     old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9702                         dm_old_crtc_state->dsc_force_changed == false)
9703                         continue;
9704
9705                 ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9706                 if (ret) {
9707                         DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9708                         goto fail;
9709                 }
9710
9711                 if (!new_crtc_state->enable)
9712                         continue;
9713
9714                 ret = drm_atomic_add_affected_connectors(state, crtc);
9715                 if (ret) {
9716                         DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9717                         goto fail;
9718                 }
9719
9720                 ret = drm_atomic_add_affected_planes(state, crtc);
9721                 if (ret) {
9722                         DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9723                         goto fail;
9724                 }
9725
9726                 if (dm_old_crtc_state->dsc_force_changed)
9727                         new_crtc_state->mode_changed = true;
9728         }
9729
9730         /*
9731          * Add all primary and overlay planes on the CRTC to the state
9732          * whenever a plane is enabled to maintain correct z-ordering
9733          * and to enable fast surface updates.
9734          */
9735         drm_for_each_crtc(crtc, dev) {
9736                 bool modified = false;
9737
9738                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9739                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
9740                                 continue;
9741
9742                         if (new_plane_state->crtc == crtc ||
9743                             old_plane_state->crtc == crtc) {
9744                                 modified = true;
9745                                 break;
9746                         }
9747                 }
9748
9749                 if (!modified)
9750                         continue;
9751
9752                 drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9753                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
9754                                 continue;
9755
9756                         new_plane_state =
9757                                 drm_atomic_get_plane_state(state, plane);
9758
9759                         if (IS_ERR(new_plane_state)) {
9760                                 ret = PTR_ERR(new_plane_state);
9761                                 DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9762                                 goto fail;
9763                         }
9764                 }
9765         }
9766
9767         /*
9768          * DC consults the zpos (layer_index in DC terminology) to determine the
9769          * hw plane on which to enable the hw cursor (see
9770          * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9771          * atomic state, so call drm helper to normalize zpos.
9772          */
9773         drm_atomic_normalize_zpos(dev, state);
9774
9775         /* Remove exiting planes if they are modified */
9776         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9777                 ret = dm_update_plane_state(dc, state, plane,
9778                                             old_plane_state,
9779                                             new_plane_state,
9780                                             false,
9781                                             &lock_and_validation_needed);
9782                 if (ret) {
9783                         DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9784                         goto fail;
9785                 }
9786         }
9787
9788         /* Disable all crtcs which require disable */
9789         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9790                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
9791                                            old_crtc_state,
9792                                            new_crtc_state,
9793                                            false,
9794                                            &lock_and_validation_needed);
9795                 if (ret) {
9796                         DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9797                         goto fail;
9798                 }
9799         }
9800
9801         /* Enable all crtcs which require enable */
9802         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9803                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
9804                                            old_crtc_state,
9805                                            new_crtc_state,
9806                                            true,
9807                                            &lock_and_validation_needed);
9808                 if (ret) {
9809                         DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9810                         goto fail;
9811                 }
9812         }
9813
9814         /* Add new/modified planes */
9815         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9816                 ret = dm_update_plane_state(dc, state, plane,
9817                                             old_plane_state,
9818                                             new_plane_state,
9819                                             true,
9820                                             &lock_and_validation_needed);
9821                 if (ret) {
9822                         DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9823                         goto fail;
9824                 }
9825         }
9826
9827 #if defined(CONFIG_DRM_AMD_DC_DCN)
9828         if (dc_resource_is_dsc_encoding_supported(dc)) {
9829                 ret = pre_validate_dsc(state, &dm_state, vars);
9830                 if (ret != 0)
9831                         goto fail;
9832         }
9833 #endif
9834
9835         /* Run this here since we want to validate the streams we created */
9836         ret = drm_atomic_helper_check_planes(dev, state);
9837         if (ret) {
9838                 DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
9839                 goto fail;
9840         }
9841
9842         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9843                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9844                 if (dm_new_crtc_state->mpo_requested)
9845                         DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
9846         }
9847
9848         /* Check cursor planes scaling */
9849         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9850                 ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
9851                 if (ret) {
9852                         DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
9853                         goto fail;
9854                 }
9855         }
9856
9857         if (state->legacy_cursor_update) {
9858                 /*
9859                  * This is a fast cursor update coming from the plane update
9860                  * helper, check if it can be done asynchronously for better
9861                  * performance.
9862                  */
9863                 state->async_update =
9864                         !drm_atomic_helper_async_check(dev, state);
9865
9866                 /*
9867                  * Skip the remaining global validation if this is an async
9868                  * update. Cursor updates can be done without affecting
9869                  * state or bandwidth calcs and this avoids the performance
9870                  * penalty of locking the private state object and
9871                  * allocating a new dc_state.
9872                  */
9873                 if (state->async_update)
9874                         return 0;
9875         }
9876
9877         /* Check scaling and underscan changes*/
9878         /* TODO Removed scaling changes validation due to inability to commit
9879          * new stream into context w\o causing full reset. Need to
9880          * decide how to handle.
9881          */
9882         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9883                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9884                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9885                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9886
9887                 /* Skip any modesets/resets */
9888                 if (!acrtc || drm_atomic_crtc_needs_modeset(
9889                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
9890                         continue;
9891
9892                 /* Skip any thing not scale or underscan changes */
9893                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
9894                         continue;
9895
9896                 lock_and_validation_needed = true;
9897         }
9898
9899         /**
9900          * Streams and planes are reset when there are changes that affect
9901          * bandwidth. Anything that affects bandwidth needs to go through
9902          * DC global validation to ensure that the configuration can be applied
9903          * to hardware.
9904          *
9905          * We have to currently stall out here in atomic_check for outstanding
9906          * commits to finish in this case because our IRQ handlers reference
9907          * DRM state directly - we can end up disabling interrupts too early
9908          * if we don't.
9909          *
9910          * TODO: Remove this stall and drop DM state private objects.
9911          */
9912         if (lock_and_validation_needed) {
9913                 ret = dm_atomic_get_state(state, &dm_state);
9914                 if (ret) {
9915                         DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
9916                         goto fail;
9917                 }
9918
9919                 ret = do_aquire_global_lock(dev, state);
9920                 if (ret) {
9921                         DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
9922                         goto fail;
9923                 }
9924
9925 #if defined(CONFIG_DRM_AMD_DC_DCN)
9926                 ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
9927                 if (ret) {
9928                         DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
9929                         goto fail;
9930                 }
9931
9932                 ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
9933                 if (ret) {
9934                         DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
9935                         goto fail;
9936                 }
9937 #endif
9938
9939                 /*
9940                  * Perform validation of MST topology in the state:
9941                  * We need to perform MST atomic check before calling
9942                  * dc_validate_global_state(), or there is a chance
9943                  * to get stuck in an infinite loop and hang eventually.
9944                  */
9945                 ret = drm_dp_mst_atomic_check(state);
9946                 if (ret) {
9947                         DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
9948                         goto fail;
9949                 }
9950                 status = dc_validate_global_state(dc, dm_state->context, true);
9951                 if (status != DC_OK) {
9952                         DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
9953                                        dc_status_to_str(status), status);
9954                         ret = -EINVAL;
9955                         goto fail;
9956                 }
9957         } else {
9958                 /*
9959                  * The commit is a fast update. Fast updates shouldn't change
9960                  * the DC context, affect global validation, and can have their
9961                  * commit work done in parallel with other commits not touching
9962                  * the same resource. If we have a new DC context as part of
9963                  * the DM atomic state from validation we need to free it and
9964                  * retain the existing one instead.
9965                  *
9966                  * Furthermore, since the DM atomic state only contains the DC
9967                  * context and can safely be annulled, we can free the state
9968                  * and clear the associated private object now to free
9969                  * some memory and avoid a possible use-after-free later.
9970                  */
9971
9972                 for (i = 0; i < state->num_private_objs; i++) {
9973                         struct drm_private_obj *obj = state->private_objs[i].ptr;
9974
9975                         if (obj->funcs == adev->dm.atomic_obj.funcs) {
9976                                 int j = state->num_private_objs-1;
9977
9978                                 dm_atomic_destroy_state(obj,
9979                                                 state->private_objs[i].state);
9980
9981                                 /* If i is not at the end of the array then the
9982                                  * last element needs to be moved to where i was
9983                                  * before the array can safely be truncated.
9984                                  */
9985                                 if (i != j)
9986                                         state->private_objs[i] =
9987                                                 state->private_objs[j];
9988
9989                                 state->private_objs[j].ptr = NULL;
9990                                 state->private_objs[j].state = NULL;
9991                                 state->private_objs[j].old_state = NULL;
9992                                 state->private_objs[j].new_state = NULL;
9993
9994                                 state->num_private_objs = j;
9995                                 break;
9996                         }
9997                 }
9998         }
9999
10000         /* Store the overall update type for use later in atomic check. */
10001         for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
10002                 struct dm_crtc_state *dm_new_crtc_state =
10003                         to_dm_crtc_state(new_crtc_state);
10004
10005                 dm_new_crtc_state->update_type = lock_and_validation_needed ?
10006                                                          UPDATE_TYPE_FULL :
10007                                                          UPDATE_TYPE_FAST;
10008         }
10009
10010         /* Must be success */
10011         WARN_ON(ret);
10012
10013         trace_amdgpu_dm_atomic_check_finish(state, ret);
10014
10015         return ret;
10016
10017 fail:
10018         if (ret == -EDEADLK)
10019                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10020         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10021                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10022         else
10023                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
10024
10025         trace_amdgpu_dm_atomic_check_finish(state, ret);
10026
10027         return ret;
10028 }
10029
10030 static bool is_dp_capable_without_timing_msa(struct dc *dc,
10031                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
10032 {
10033         u8 dpcd_data;
10034         bool capable = false;
10035
10036         if (amdgpu_dm_connector->dc_link &&
10037                 dm_helpers_dp_read_dpcd(
10038                                 NULL,
10039                                 amdgpu_dm_connector->dc_link,
10040                                 DP_DOWN_STREAM_PORT_COUNT,
10041                                 &dpcd_data,
10042                                 sizeof(dpcd_data))) {
10043                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10044         }
10045
10046         return capable;
10047 }
10048
10049 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10050                 unsigned int offset,
10051                 unsigned int total_length,
10052                 u8 *data,
10053                 unsigned int length,
10054                 struct amdgpu_hdmi_vsdb_info *vsdb)
10055 {
10056         bool res;
10057         union dmub_rb_cmd cmd;
10058         struct dmub_cmd_send_edid_cea *input;
10059         struct dmub_cmd_edid_cea_output *output;
10060
10061         if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10062                 return false;
10063
10064         memset(&cmd, 0, sizeof(cmd));
10065
10066         input = &cmd.edid_cea.data.input;
10067
10068         cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10069         cmd.edid_cea.header.sub_type = 0;
10070         cmd.edid_cea.header.payload_bytes =
10071                 sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10072         input->offset = offset;
10073         input->length = length;
10074         input->cea_total_length = total_length;
10075         memcpy(input->payload, data, length);
10076
10077         res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
10078         if (!res) {
10079                 DRM_ERROR("EDID CEA parser failed\n");
10080                 return false;
10081         }
10082
10083         output = &cmd.edid_cea.data.output;
10084
10085         if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10086                 if (!output->ack.success) {
10087                         DRM_ERROR("EDID CEA ack failed at offset %d\n",
10088                                         output->ack.offset);
10089                 }
10090         } else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10091                 if (!output->amd_vsdb.vsdb_found)
10092                         return false;
10093
10094                 vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10095                 vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10096                 vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10097                 vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10098         } else {
10099                 DRM_WARN("Unknown EDID CEA parser results\n");
10100                 return false;
10101         }
10102
10103         return true;
10104 }
10105
10106 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10107                 u8 *edid_ext, int len,
10108                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10109 {
10110         int i;
10111
10112         /* send extension block to DMCU for parsing */
10113         for (i = 0; i < len; i += 8) {
10114                 bool res;
10115                 int offset;
10116
10117                 /* send 8 bytes a time */
10118                 if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10119                         return false;
10120
10121                 if (i+8 == len) {
10122                         /* EDID block sent completed, expect result */
10123                         int version, min_rate, max_rate;
10124
10125                         res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10126                         if (res) {
10127                                 /* amd vsdb found */
10128                                 vsdb_info->freesync_supported = 1;
10129                                 vsdb_info->amd_vsdb_version = version;
10130                                 vsdb_info->min_refresh_rate_hz = min_rate;
10131                                 vsdb_info->max_refresh_rate_hz = max_rate;
10132                                 return true;
10133                         }
10134                         /* not amd vsdb */
10135                         return false;
10136                 }
10137
10138                 /* check for ack*/
10139                 res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10140                 if (!res)
10141                         return false;
10142         }
10143
10144         return false;
10145 }
10146
10147 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10148                 u8 *edid_ext, int len,
10149                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10150 {
10151         int i;
10152
10153         /* send extension block to DMCU for parsing */
10154         for (i = 0; i < len; i += 8) {
10155                 /* send 8 bytes a time */
10156                 if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10157                         return false;
10158         }
10159
10160         return vsdb_info->freesync_supported;
10161 }
10162
10163 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
10164                 u8 *edid_ext, int len,
10165                 struct amdgpu_hdmi_vsdb_info *vsdb_info)
10166 {
10167         struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
10168
10169         if (adev->dm.dmub_srv)
10170                 return parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
10171         else
10172                 return parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
10173 }
10174
10175 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
10176                 struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
10177 {
10178         u8 *edid_ext = NULL;
10179         int i;
10180         bool valid_vsdb_found = false;
10181
10182         /*----- drm_find_cea_extension() -----*/
10183         /* No EDID or EDID extensions */
10184         if (edid == NULL || edid->extensions == 0)
10185                 return -ENODEV;
10186
10187         /* Find CEA extension */
10188         for (i = 0; i < edid->extensions; i++) {
10189                 edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
10190                 if (edid_ext[0] == CEA_EXT)
10191                         break;
10192         }
10193
10194         if (i == edid->extensions)
10195                 return -ENODEV;
10196
10197         /*----- cea_db_offsets() -----*/
10198         if (edid_ext[0] != CEA_EXT)
10199                 return -ENODEV;
10200
10201         valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
10202
10203         return valid_vsdb_found ? i : -ENODEV;
10204 }
10205
10206 /**
10207  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
10208  *
10209  * @connector: Connector to query.
10210  * @edid: EDID from monitor
10211  *
10212  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
10213  * track of some of the display information in the internal data struct used by
10214  * amdgpu_dm. This function checks which type of connector we need to set the
10215  * FreeSync parameters.
10216  */
10217 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
10218                                     struct edid *edid)
10219 {
10220         int i = 0;
10221         struct detailed_timing *timing;
10222         struct detailed_non_pixel *data;
10223         struct detailed_data_monitor_range *range;
10224         struct amdgpu_dm_connector *amdgpu_dm_connector =
10225                         to_amdgpu_dm_connector(connector);
10226         struct dm_connector_state *dm_con_state = NULL;
10227         struct dc_sink *sink;
10228
10229         struct drm_device *dev = connector->dev;
10230         struct amdgpu_device *adev = drm_to_adev(dev);
10231         struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
10232         bool freesync_capable = false;
10233
10234         if (!connector->state) {
10235                 DRM_ERROR("%s - Connector has no state", __func__);
10236                 goto update;
10237         }
10238
10239         sink = amdgpu_dm_connector->dc_sink ?
10240                 amdgpu_dm_connector->dc_sink :
10241                 amdgpu_dm_connector->dc_em_sink;
10242
10243         if (!edid || !sink) {
10244                 dm_con_state = to_dm_connector_state(connector->state);
10245
10246                 amdgpu_dm_connector->min_vfreq = 0;
10247                 amdgpu_dm_connector->max_vfreq = 0;
10248                 amdgpu_dm_connector->pixel_clock_mhz = 0;
10249                 connector->display_info.monitor_range.min_vfreq = 0;
10250                 connector->display_info.monitor_range.max_vfreq = 0;
10251                 freesync_capable = false;
10252
10253                 goto update;
10254         }
10255
10256         dm_con_state = to_dm_connector_state(connector->state);
10257
10258         if (!adev->dm.freesync_module)
10259                 goto update;
10260
10261         if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10262                 || sink->sink_signal == SIGNAL_TYPE_EDP) {
10263                 bool edid_check_required = false;
10264
10265                 if (edid) {
10266                         edid_check_required = is_dp_capable_without_timing_msa(
10267                                                 adev->dm.dc,
10268                                                 amdgpu_dm_connector);
10269                 }
10270
10271                 if (edid_check_required == true && (edid->version > 1 ||
10272                    (edid->version == 1 && edid->revision > 1))) {
10273                         for (i = 0; i < 4; i++) {
10274
10275                                 timing  = &edid->detailed_timings[i];
10276                                 data    = &timing->data.other_data;
10277                                 range   = &data->data.range;
10278                                 /*
10279                                  * Check if monitor has continuous frequency mode
10280                                  */
10281                                 if (data->type != EDID_DETAIL_MONITOR_RANGE)
10282                                         continue;
10283                                 /*
10284                                  * Check for flag range limits only. If flag == 1 then
10285                                  * no additional timing information provided.
10286                                  * Default GTF, GTF Secondary curve and CVT are not
10287                                  * supported
10288                                  */
10289                                 if (range->flags != 1)
10290                                         continue;
10291
10292                                 amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10293                                 amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10294                                 amdgpu_dm_connector->pixel_clock_mhz =
10295                                         range->pixel_clock_mhz * 10;
10296
10297                                 connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10298                                 connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10299
10300                                 break;
10301                         }
10302
10303                         if (amdgpu_dm_connector->max_vfreq -
10304                             amdgpu_dm_connector->min_vfreq > 10) {
10305
10306                                 freesync_capable = true;
10307                         }
10308                 }
10309         } else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10310                 i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10311                 if (i >= 0 && vsdb_info.freesync_supported) {
10312                         timing  = &edid->detailed_timings[i];
10313                         data    = &timing->data.other_data;
10314
10315                         amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10316                         amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10317                         if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10318                                 freesync_capable = true;
10319
10320                         connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10321                         connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10322                 }
10323         }
10324
10325 update:
10326         if (dm_con_state)
10327                 dm_con_state->freesync_capable = freesync_capable;
10328
10329         if (connector->vrr_capable_property)
10330                 drm_connector_set_vrr_capable_property(connector,
10331                                                        freesync_capable);
10332 }
10333
10334 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10335 {
10336         struct amdgpu_device *adev = drm_to_adev(dev);
10337         struct dc *dc = adev->dm.dc;
10338         int i;
10339
10340         mutex_lock(&adev->dm.dc_lock);
10341         if (dc->current_state) {
10342                 for (i = 0; i < dc->current_state->stream_count; ++i)
10343                         dc->current_state->streams[i]
10344                                 ->triggered_crtc_reset.enabled =
10345                                 adev->dm.force_timing_sync;
10346
10347                 dm_enable_per_frame_crtc_master_sync(dc->current_state);
10348                 dc_trigger_sync(dc, dc->current_state);
10349         }
10350         mutex_unlock(&adev->dm.dc_lock);
10351 }
10352
10353 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10354                        u32 value, const char *func_name)
10355 {
10356 #ifdef DM_CHECK_ADDR_0
10357         if (address == 0) {
10358                 DC_ERR("invalid register write. address = 0");
10359                 return;
10360         }
10361 #endif
10362         cgs_write_register(ctx->cgs_device, address, value);
10363         trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10364 }
10365
10366 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10367                           const char *func_name)
10368 {
10369         u32 value;
10370 #ifdef DM_CHECK_ADDR_0
10371         if (address == 0) {
10372                 DC_ERR("invalid register read; address = 0\n");
10373                 return 0;
10374         }
10375 #endif
10376
10377         if (ctx->dmub_srv &&
10378             ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10379             !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10380                 ASSERT(false);
10381                 return 0;
10382         }
10383
10384         value = cgs_read_register(ctx->cgs_device, address);
10385
10386         trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10387
10388         return value;
10389 }
10390
10391 int amdgpu_dm_process_dmub_aux_transfer_sync(
10392                 struct dc_context *ctx,
10393                 unsigned int link_index,
10394                 struct aux_payload *payload,
10395                 enum aux_return_code_type *operation_result)
10396 {
10397         struct amdgpu_device *adev = ctx->driver_context;
10398         struct dmub_notification *p_notify = adev->dm.dmub_notify;
10399         int ret = -1;
10400
10401         mutex_lock(&adev->dm.dpia_aux_lock);
10402         if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
10403                 *operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10404                 goto out;
10405         }
10406
10407         if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10408                 DRM_ERROR("wait_for_completion_timeout timeout!");
10409                 *operation_result = AUX_RET_ERROR_TIMEOUT;
10410                 goto out;
10411         }
10412
10413         if (p_notify->result != AUX_RET_SUCCESS) {
10414                 /*
10415                  * Transient states before tunneling is enabled could
10416                  * lead to this error. We can ignore this for now.
10417                  */
10418                 if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
10419                         DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
10420                                         payload->address, payload->length,
10421                                         p_notify->result);
10422                 }
10423                 *operation_result = AUX_RET_ERROR_INVALID_REPLY;
10424                 goto out;
10425         }
10426
10427
10428         payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10429         if (!payload->write && p_notify->aux_reply.length &&
10430                         (payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
10431
10432                 if (payload->length != p_notify->aux_reply.length) {
10433                         DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
10434                                 p_notify->aux_reply.length,
10435                                         payload->address, payload->length);
10436                         *operation_result = AUX_RET_ERROR_INVALID_REPLY;
10437                         goto out;
10438                 }
10439
10440                 memcpy(payload->data, p_notify->aux_reply.data,
10441                                 p_notify->aux_reply.length);
10442         }
10443
10444         /* success */
10445         ret = p_notify->aux_reply.length;
10446         *operation_result = p_notify->result;
10447 out:
10448         mutex_unlock(&adev->dm.dpia_aux_lock);
10449         return ret;
10450 }
10451
10452 int amdgpu_dm_process_dmub_set_config_sync(
10453                 struct dc_context *ctx,
10454                 unsigned int link_index,
10455                 struct set_config_cmd_payload *payload,
10456                 enum set_config_status *operation_result)
10457 {
10458         struct amdgpu_device *adev = ctx->driver_context;
10459         bool is_cmd_complete;
10460         int ret;
10461
10462         mutex_lock(&adev->dm.dpia_aux_lock);
10463         is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
10464                         link_index, payload, adev->dm.dmub_notify);
10465
10466         if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
10467                 ret = 0;
10468                 *operation_result = adev->dm.dmub_notify->sc_status;
10469         } else {
10470                 DRM_ERROR("wait_for_completion_timeout timeout!");
10471                 ret = -1;
10472                 *operation_result = SET_CONFIG_UNKNOWN_ERROR;
10473         }
10474
10475         mutex_unlock(&adev->dm.dpia_aux_lock);
10476         return ret;
10477 }
10478
10479 /*
10480  * Check whether seamless boot is supported.
10481  *
10482  * So far we only support seamless boot on CHIP_VANGOGH.
10483  * If everything goes well, we may consider expanding
10484  * seamless boot to other ASICs.
10485  */
10486 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10487 {
10488         switch (adev->ip_versions[DCE_HWIP][0]) {
10489         case IP_VERSION(3, 0, 1):
10490                 if (!adev->mman.keep_stolen_vga_memory)
10491                         return true;
10492                 break;
10493         default:
10494                 break;
10495         }
10496
10497         return false;
10498 }