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