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