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