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