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