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