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