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