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