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