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