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