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