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