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