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