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