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