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