linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c
<<
>>
Prefs
   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 "dc/inc/core_types.h"
  32#include "dal_asic_id.h"
  33
  34#include "vid.h"
  35#include "amdgpu.h"
  36#include "amdgpu_display.h"
  37#include "amdgpu_ucode.h"
  38#include "atom.h"
  39#include "amdgpu_dm.h"
  40#include "amdgpu_pm.h"
  41
  42#include "amd_shared.h"
  43#include "amdgpu_dm_irq.h"
  44#include "dm_helpers.h"
  45#include "amdgpu_dm_mst_types.h"
  46#if defined(CONFIG_DEBUG_FS)
  47#include "amdgpu_dm_debugfs.h"
  48#endif
  49
  50#include "ivsrcid/ivsrcid_vislands30.h"
  51
  52#include <linux/module.h>
  53#include <linux/moduleparam.h>
  54#include <linux/version.h>
  55#include <linux/types.h>
  56#include <linux/pm_runtime.h>
  57#include <linux/pci.h>
  58#include <linux/firmware.h>
  59#include <linux/component.h>
  60
  61#include <drm/drm_atomic.h>
  62#include <drm/drm_atomic_uapi.h>
  63#include <drm/drm_atomic_helper.h>
  64#include <drm/drm_dp_mst_helper.h>
  65#include <drm/drm_fb_helper.h>
  66#include <drm/drm_fourcc.h>
  67#include <drm/drm_edid.h>
  68#include <drm/drm_vblank.h>
  69#include <drm/drm_audio_component.h>
  70
  71#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
  72#include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
  73
  74#include "dcn/dcn_1_0_offset.h"
  75#include "dcn/dcn_1_0_sh_mask.h"
  76#include "soc15_hw_ip.h"
  77#include "vega10_ip_offset.h"
  78
  79#include "soc15_common.h"
  80#endif
  81
  82#include "modules/inc/mod_freesync.h"
  83#include "modules/power/power_helpers.h"
  84#include "modules/inc/mod_info_packet.h"
  85
  86#define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
  87MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
  88
  89/**
  90 * DOC: overview
  91 *
  92 * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
  93 * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
  94 * requests into DC requests, and DC responses into DRM responses.
  95 *
  96 * The root control structure is &struct amdgpu_display_manager.
  97 */
  98
  99/* basic init/fini API */
 100static int amdgpu_dm_init(struct amdgpu_device *adev);
 101static void amdgpu_dm_fini(struct amdgpu_device *adev);
 102
 103/*
 104 * initializes drm_device display related structures, based on the information
 105 * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
 106 * drm_encoder, drm_mode_config
 107 *
 108 * Returns 0 on success
 109 */
 110static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
 111/* removes and deallocates the drm structures, created by the above function */
 112static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
 113
 114static void
 115amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
 116
 117static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
 118                                struct drm_plane *plane,
 119                                unsigned long possible_crtcs,
 120                                const struct dc_plane_cap *plane_cap);
 121static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
 122                               struct drm_plane *plane,
 123                               uint32_t link_index);
 124static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
 125                                    struct amdgpu_dm_connector *amdgpu_dm_connector,
 126                                    uint32_t link_index,
 127                                    struct amdgpu_encoder *amdgpu_encoder);
 128static int amdgpu_dm_encoder_init(struct drm_device *dev,
 129                                  struct amdgpu_encoder *aencoder,
 130                                  uint32_t link_index);
 131
 132static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
 133
 134static int amdgpu_dm_atomic_commit(struct drm_device *dev,
 135                                   struct drm_atomic_state *state,
 136                                   bool nonblock);
 137
 138static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
 139
 140static int amdgpu_dm_atomic_check(struct drm_device *dev,
 141                                  struct drm_atomic_state *state);
 142
 143static void handle_cursor_update(struct drm_plane *plane,
 144                                 struct drm_plane_state *old_plane_state);
 145
 146/*
 147 * dm_vblank_get_counter
 148 *
 149 * @brief
 150 * Get counter for number of vertical blanks
 151 *
 152 * @param
 153 * struct amdgpu_device *adev - [in] desired amdgpu device
 154 * int disp_idx - [in] which CRTC to get the counter from
 155 *
 156 * @return
 157 * Counter for vertical blanks
 158 */
 159static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
 160{
 161        if (crtc >= adev->mode_info.num_crtc)
 162                return 0;
 163        else {
 164                struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
 165                struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
 166                                acrtc->base.state);
 167
 168
 169                if (acrtc_state->stream == NULL) {
 170                        DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
 171                                  crtc);
 172                        return 0;
 173                }
 174
 175                return dc_stream_get_vblank_counter(acrtc_state->stream);
 176        }
 177}
 178
 179static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
 180                                  u32 *vbl, u32 *position)
 181{
 182        uint32_t v_blank_start, v_blank_end, h_position, v_position;
 183
 184        if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
 185                return -EINVAL;
 186        else {
 187                struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
 188                struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
 189                                                acrtc->base.state);
 190
 191                if (acrtc_state->stream ==  NULL) {
 192                        DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
 193                                  crtc);
 194                        return 0;
 195                }
 196
 197                /*
 198                 * TODO rework base driver to use values directly.
 199                 * for now parse it back into reg-format
 200                 */
 201                dc_stream_get_scanoutpos(acrtc_state->stream,
 202                                         &v_blank_start,
 203                                         &v_blank_end,
 204                                         &h_position,
 205                                         &v_position);
 206
 207                *position = v_position | (h_position << 16);
 208                *vbl = v_blank_start | (v_blank_end << 16);
 209        }
 210
 211        return 0;
 212}
 213
 214static bool dm_is_idle(void *handle)
 215{
 216        /* XXX todo */
 217        return true;
 218}
 219
 220static int dm_wait_for_idle(void *handle)
 221{
 222        /* XXX todo */
 223        return 0;
 224}
 225
 226static bool dm_check_soft_reset(void *handle)
 227{
 228        return false;
 229}
 230
 231static int dm_soft_reset(void *handle)
 232{
 233        /* XXX todo */
 234        return 0;
 235}
 236
 237static struct amdgpu_crtc *
 238get_crtc_by_otg_inst(struct amdgpu_device *adev,
 239                     int otg_inst)
 240{
 241        struct drm_device *dev = adev->ddev;
 242        struct drm_crtc *crtc;
 243        struct amdgpu_crtc *amdgpu_crtc;
 244
 245        if (otg_inst == -1) {
 246                WARN_ON(1);
 247                return adev->mode_info.crtcs[0];
 248        }
 249
 250        list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
 251                amdgpu_crtc = to_amdgpu_crtc(crtc);
 252
 253                if (amdgpu_crtc->otg_inst == otg_inst)
 254                        return amdgpu_crtc;
 255        }
 256
 257        return NULL;
 258}
 259
 260static inline bool amdgpu_dm_vrr_active(struct dm_crtc_state *dm_state)
 261{
 262        return dm_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE ||
 263               dm_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
 264}
 265
 266static void dm_pflip_high_irq(void *interrupt_params)
 267{
 268        struct amdgpu_crtc *amdgpu_crtc;
 269        struct common_irq_params *irq_params = interrupt_params;
 270        struct amdgpu_device *adev = irq_params->adev;
 271        unsigned long flags;
 272        struct drm_pending_vblank_event *e;
 273        struct dm_crtc_state *acrtc_state;
 274        uint32_t vpos, hpos, v_blank_start, v_blank_end;
 275        bool vrr_active;
 276
 277        amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
 278
 279        /* IRQ could occur when in initial stage */
 280        /* TODO work and BO cleanup */
 281        if (amdgpu_crtc == NULL) {
 282                DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
 283                return;
 284        }
 285
 286        spin_lock_irqsave(&adev->ddev->event_lock, flags);
 287
 288        if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
 289                DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
 290                                                 amdgpu_crtc->pflip_status,
 291                                                 AMDGPU_FLIP_SUBMITTED,
 292                                                 amdgpu_crtc->crtc_id,
 293                                                 amdgpu_crtc);
 294                spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 295                return;
 296        }
 297
 298        /* page flip completed. */
 299        e = amdgpu_crtc->event;
 300        amdgpu_crtc->event = NULL;
 301
 302        if (!e)
 303                WARN_ON(1);
 304
 305        acrtc_state = to_dm_crtc_state(amdgpu_crtc->base.state);
 306        vrr_active = amdgpu_dm_vrr_active(acrtc_state);
 307
 308        /* Fixed refresh rate, or VRR scanout position outside front-porch? */
 309        if (!vrr_active ||
 310            !dc_stream_get_scanoutpos(acrtc_state->stream, &v_blank_start,
 311                                      &v_blank_end, &hpos, &vpos) ||
 312            (vpos < v_blank_start)) {
 313                /* Update to correct count and vblank timestamp if racing with
 314                 * vblank irq. This also updates to the correct vblank timestamp
 315                 * even in VRR mode, as scanout is past the front-porch atm.
 316                 */
 317                drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
 318
 319                /* Wake up userspace by sending the pageflip event with proper
 320                 * count and timestamp of vblank of flip completion.
 321                 */
 322                if (e) {
 323                        drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
 324
 325                        /* Event sent, so done with vblank for this flip */
 326                        drm_crtc_vblank_put(&amdgpu_crtc->base);
 327                }
 328        } else if (e) {
 329                /* VRR active and inside front-porch: vblank count and
 330                 * timestamp for pageflip event will only be up to date after
 331                 * drm_crtc_handle_vblank() has been executed from late vblank
 332                 * irq handler after start of back-porch (vline 0). We queue the
 333                 * pageflip event for send-out by drm_crtc_handle_vblank() with
 334                 * updated timestamp and count, once it runs after us.
 335                 *
 336                 * We need to open-code this instead of using the helper
 337                 * drm_crtc_arm_vblank_event(), as that helper would
 338                 * call drm_crtc_accurate_vblank_count(), which we must
 339                 * not call in VRR mode while we are in front-porch!
 340                 */
 341
 342                /* sequence will be replaced by real count during send-out. */
 343                e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
 344                e->pipe = amdgpu_crtc->crtc_id;
 345
 346                list_add_tail(&e->base.link, &adev->ddev->vblank_event_list);
 347                e = NULL;
 348        }
 349
 350        /* Keep track of vblank of this flip for flip throttling. We use the
 351         * cooked hw counter, as that one incremented at start of this vblank
 352         * of pageflip completion, so last_flip_vblank is the forbidden count
 353         * for queueing new pageflips if vsync + VRR is enabled.
 354         */
 355        amdgpu_crtc->last_flip_vblank = amdgpu_get_vblank_counter_kms(adev->ddev,
 356                                                        amdgpu_crtc->crtc_id);
 357
 358        amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
 359        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 360
 361        DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
 362                         amdgpu_crtc->crtc_id, amdgpu_crtc,
 363                         vrr_active, (int) !e);
 364}
 365
 366static void dm_vupdate_high_irq(void *interrupt_params)
 367{
 368        struct common_irq_params *irq_params = interrupt_params;
 369        struct amdgpu_device *adev = irq_params->adev;
 370        struct amdgpu_crtc *acrtc;
 371        struct dm_crtc_state *acrtc_state;
 372        unsigned long flags;
 373
 374        acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
 375
 376        if (acrtc) {
 377                acrtc_state = to_dm_crtc_state(acrtc->base.state);
 378
 379                DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
 380                                 amdgpu_dm_vrr_active(acrtc_state));
 381
 382                /* Core vblank handling is done here after end of front-porch in
 383                 * vrr mode, as vblank timestamping will give valid results
 384                 * while now done after front-porch. This will also deliver
 385                 * page-flip completion events that have been queued to us
 386                 * if a pageflip happened inside front-porch.
 387                 */
 388                if (amdgpu_dm_vrr_active(acrtc_state)) {
 389                        drm_crtc_handle_vblank(&acrtc->base);
 390
 391                        /* BTR processing for pre-DCE12 ASICs */
 392                        if (acrtc_state->stream &&
 393                            adev->family < AMDGPU_FAMILY_AI) {
 394                                spin_lock_irqsave(&adev->ddev->event_lock, flags);
 395                                mod_freesync_handle_v_update(
 396                                    adev->dm.freesync_module,
 397                                    acrtc_state->stream,
 398                                    &acrtc_state->vrr_params);
 399
 400                                dc_stream_adjust_vmin_vmax(
 401                                    adev->dm.dc,
 402                                    acrtc_state->stream,
 403                                    &acrtc_state->vrr_params.adjust);
 404                                spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 405                        }
 406                }
 407        }
 408}
 409
 410static void dm_crtc_high_irq(void *interrupt_params)
 411{
 412        struct common_irq_params *irq_params = interrupt_params;
 413        struct amdgpu_device *adev = irq_params->adev;
 414        struct amdgpu_crtc *acrtc;
 415        struct dm_crtc_state *acrtc_state;
 416        unsigned long flags;
 417
 418        acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
 419
 420        if (acrtc) {
 421                acrtc_state = to_dm_crtc_state(acrtc->base.state);
 422
 423                DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
 424                                 amdgpu_dm_vrr_active(acrtc_state));
 425
 426                /* Core vblank handling at start of front-porch is only possible
 427                 * in non-vrr mode, as only there vblank timestamping will give
 428                 * valid results while done in front-porch. Otherwise defer it
 429                 * to dm_vupdate_high_irq after end of front-porch.
 430                 */
 431                if (!amdgpu_dm_vrr_active(acrtc_state))
 432                        drm_crtc_handle_vblank(&acrtc->base);
 433
 434                /* Following stuff must happen at start of vblank, for crc
 435                 * computation and below-the-range btr support in vrr mode.
 436                 */
 437                amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
 438
 439                if (acrtc_state->stream && adev->family >= AMDGPU_FAMILY_AI &&
 440                    acrtc_state->vrr_params.supported &&
 441                    acrtc_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE) {
 442                        spin_lock_irqsave(&adev->ddev->event_lock, flags);
 443                        mod_freesync_handle_v_update(
 444                                adev->dm.freesync_module,
 445                                acrtc_state->stream,
 446                                &acrtc_state->vrr_params);
 447
 448                        dc_stream_adjust_vmin_vmax(
 449                                adev->dm.dc,
 450                                acrtc_state->stream,
 451                                &acrtc_state->vrr_params.adjust);
 452                        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 453                }
 454        }
 455}
 456
 457static int dm_set_clockgating_state(void *handle,
 458                  enum amd_clockgating_state state)
 459{
 460        return 0;
 461}
 462
 463static int dm_set_powergating_state(void *handle,
 464                  enum amd_powergating_state state)
 465{
 466        return 0;
 467}
 468
 469/* Prototypes of private functions */
 470static int dm_early_init(void* handle);
 471
 472/* Allocate memory for FBC compressed data  */
 473static void amdgpu_dm_fbc_init(struct drm_connector *connector)
 474{
 475        struct drm_device *dev = connector->dev;
 476        struct amdgpu_device *adev = dev->dev_private;
 477        struct dm_comressor_info *compressor = &adev->dm.compressor;
 478        struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
 479        struct drm_display_mode *mode;
 480        unsigned long max_size = 0;
 481
 482        if (adev->dm.dc->fbc_compressor == NULL)
 483                return;
 484
 485        if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
 486                return;
 487
 488        if (compressor->bo_ptr)
 489                return;
 490
 491
 492        list_for_each_entry(mode, &connector->modes, head) {
 493                if (max_size < mode->htotal * mode->vtotal)
 494                        max_size = mode->htotal * mode->vtotal;
 495        }
 496
 497        if (max_size) {
 498                int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
 499                            AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
 500                            &compressor->gpu_addr, &compressor->cpu_addr);
 501
 502                if (r)
 503                        DRM_ERROR("DM: Failed to initialize FBC\n");
 504                else {
 505                        adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
 506                        DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
 507                }
 508
 509        }
 510
 511}
 512
 513static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
 514                                          int pipe, bool *enabled,
 515                                          unsigned char *buf, int max_bytes)
 516{
 517        struct drm_device *dev = dev_get_drvdata(kdev);
 518        struct amdgpu_device *adev = dev->dev_private;
 519        struct drm_connector *connector;
 520        struct drm_connector_list_iter conn_iter;
 521        struct amdgpu_dm_connector *aconnector;
 522        int ret = 0;
 523
 524        *enabled = false;
 525
 526        mutex_lock(&adev->dm.audio_lock);
 527
 528        drm_connector_list_iter_begin(dev, &conn_iter);
 529        drm_for_each_connector_iter(connector, &conn_iter) {
 530                aconnector = to_amdgpu_dm_connector(connector);
 531                if (aconnector->audio_inst != port)
 532                        continue;
 533
 534                *enabled = true;
 535                ret = drm_eld_size(connector->eld);
 536                memcpy(buf, connector->eld, min(max_bytes, ret));
 537
 538                break;
 539        }
 540        drm_connector_list_iter_end(&conn_iter);
 541
 542        mutex_unlock(&adev->dm.audio_lock);
 543
 544        DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
 545
 546        return ret;
 547}
 548
 549static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
 550        .get_eld = amdgpu_dm_audio_component_get_eld,
 551};
 552
 553static int amdgpu_dm_audio_component_bind(struct device *kdev,
 554                                       struct device *hda_kdev, void *data)
 555{
 556        struct drm_device *dev = dev_get_drvdata(kdev);
 557        struct amdgpu_device *adev = dev->dev_private;
 558        struct drm_audio_component *acomp = data;
 559
 560        acomp->ops = &amdgpu_dm_audio_component_ops;
 561        acomp->dev = kdev;
 562        adev->dm.audio_component = acomp;
 563
 564        return 0;
 565}
 566
 567static void amdgpu_dm_audio_component_unbind(struct device *kdev,
 568                                          struct device *hda_kdev, void *data)
 569{
 570        struct drm_device *dev = dev_get_drvdata(kdev);
 571        struct amdgpu_device *adev = dev->dev_private;
 572        struct drm_audio_component *acomp = data;
 573
 574        acomp->ops = NULL;
 575        acomp->dev = NULL;
 576        adev->dm.audio_component = NULL;
 577}
 578
 579static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
 580        .bind   = amdgpu_dm_audio_component_bind,
 581        .unbind = amdgpu_dm_audio_component_unbind,
 582};
 583
 584static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
 585{
 586        int i, ret;
 587
 588        if (!amdgpu_audio)
 589                return 0;
 590
 591        adev->mode_info.audio.enabled = true;
 592
 593        adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
 594
 595        for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
 596                adev->mode_info.audio.pin[i].channels = -1;
 597                adev->mode_info.audio.pin[i].rate = -1;
 598                adev->mode_info.audio.pin[i].bits_per_sample = -1;
 599                adev->mode_info.audio.pin[i].status_bits = 0;
 600                adev->mode_info.audio.pin[i].category_code = 0;
 601                adev->mode_info.audio.pin[i].connected = false;
 602                adev->mode_info.audio.pin[i].id =
 603                        adev->dm.dc->res_pool->audios[i]->inst;
 604                adev->mode_info.audio.pin[i].offset = 0;
 605        }
 606
 607        ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
 608        if (ret < 0)
 609                return ret;
 610
 611        adev->dm.audio_registered = true;
 612
 613        return 0;
 614}
 615
 616static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
 617{
 618        if (!amdgpu_audio)
 619                return;
 620
 621        if (!adev->mode_info.audio.enabled)
 622                return;
 623
 624        if (adev->dm.audio_registered) {
 625                component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
 626                adev->dm.audio_registered = false;
 627        }
 628
 629        /* TODO: Disable audio? */
 630
 631        adev->mode_info.audio.enabled = false;
 632}
 633
 634void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
 635{
 636        struct drm_audio_component *acomp = adev->dm.audio_component;
 637
 638        if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
 639                DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
 640
 641                acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
 642                                                 pin, -1);
 643        }
 644}
 645
 646static int amdgpu_dm_init(struct amdgpu_device *adev)
 647{
 648        struct dc_init_data init_data;
 649        adev->dm.ddev = adev->ddev;
 650        adev->dm.adev = adev;
 651
 652        /* Zero all the fields */
 653        memset(&init_data, 0, sizeof(init_data));
 654
 655        mutex_init(&adev->dm.dc_lock);
 656        mutex_init(&adev->dm.audio_lock);
 657
 658        if(amdgpu_dm_irq_init(adev)) {
 659                DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
 660                goto error;
 661        }
 662
 663        init_data.asic_id.chip_family = adev->family;
 664
 665        init_data.asic_id.pci_revision_id = adev->rev_id;
 666        init_data.asic_id.hw_internal_rev = adev->external_rev_id;
 667
 668        init_data.asic_id.vram_width = adev->gmc.vram_width;
 669        /* TODO: initialize init_data.asic_id.vram_type here!!!! */
 670        init_data.asic_id.atombios_base_address =
 671                adev->mode_info.atom_context->bios;
 672
 673        init_data.driver = adev;
 674
 675        adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
 676
 677        if (!adev->dm.cgs_device) {
 678                DRM_ERROR("amdgpu: failed to create cgs device.\n");
 679                goto error;
 680        }
 681
 682        init_data.cgs_device = adev->dm.cgs_device;
 683
 684        init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
 685
 686        /*
 687         * TODO debug why this doesn't work on Raven
 688         */
 689        if (adev->flags & AMD_IS_APU &&
 690            adev->asic_type >= CHIP_CARRIZO &&
 691            adev->asic_type < CHIP_RAVEN)
 692                init_data.flags.gpu_vm_support = true;
 693
 694        if (amdgpu_dc_feature_mask & DC_FBC_MASK)
 695                init_data.flags.fbc_support = true;
 696
 697        init_data.flags.power_down_display_on_boot = true;
 698
 699#ifdef CONFIG_DRM_AMD_DC_DCN2_0
 700        init_data.soc_bounding_box = adev->dm.soc_bounding_box;
 701#endif
 702
 703        /* Display Core create. */
 704        adev->dm.dc = dc_create(&init_data);
 705
 706        if (adev->dm.dc) {
 707                DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
 708        } else {
 709                DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
 710                goto error;
 711        }
 712
 713        adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
 714        if (!adev->dm.freesync_module) {
 715                DRM_ERROR(
 716                "amdgpu: failed to initialize freesync_module.\n");
 717        } else
 718                DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
 719                                adev->dm.freesync_module);
 720
 721        amdgpu_dm_init_color_mod();
 722
 723        if (amdgpu_dm_initialize_drm_device(adev)) {
 724                DRM_ERROR(
 725                "amdgpu: failed to initialize sw for display support.\n");
 726                goto error;
 727        }
 728
 729        /* Update the actual used number of crtc */
 730        adev->mode_info.num_crtc = adev->dm.display_indexes_num;
 731
 732        /* TODO: Add_display_info? */
 733
 734        /* TODO use dynamic cursor width */
 735        adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
 736        adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
 737
 738        if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
 739                DRM_ERROR(
 740                "amdgpu: failed to initialize sw for display support.\n");
 741                goto error;
 742        }
 743
 744#if defined(CONFIG_DEBUG_FS)
 745        if (dtn_debugfs_init(adev))
 746                DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
 747#endif
 748
 749        DRM_DEBUG_DRIVER("KMS initialized.\n");
 750
 751        return 0;
 752error:
 753        amdgpu_dm_fini(adev);
 754
 755        return -EINVAL;
 756}
 757
 758static void amdgpu_dm_fini(struct amdgpu_device *adev)
 759{
 760        amdgpu_dm_audio_fini(adev);
 761
 762        amdgpu_dm_destroy_drm_device(&adev->dm);
 763
 764        /* DC Destroy TODO: Replace destroy DAL */
 765        if (adev->dm.dc)
 766                dc_destroy(&adev->dm.dc);
 767        /*
 768         * TODO: pageflip, vlank interrupt
 769         *
 770         * amdgpu_dm_irq_fini(adev);
 771         */
 772
 773        if (adev->dm.cgs_device) {
 774                amdgpu_cgs_destroy_device(adev->dm.cgs_device);
 775                adev->dm.cgs_device = NULL;
 776        }
 777        if (adev->dm.freesync_module) {
 778                mod_freesync_destroy(adev->dm.freesync_module);
 779                adev->dm.freesync_module = NULL;
 780        }
 781
 782        mutex_destroy(&adev->dm.audio_lock);
 783        mutex_destroy(&adev->dm.dc_lock);
 784
 785        return;
 786}
 787
 788static int load_dmcu_fw(struct amdgpu_device *adev)
 789{
 790        const char *fw_name_dmcu = NULL;
 791        int r;
 792        const struct dmcu_firmware_header_v1_0 *hdr;
 793
 794        switch(adev->asic_type) {
 795        case CHIP_BONAIRE:
 796        case CHIP_HAWAII:
 797        case CHIP_KAVERI:
 798        case CHIP_KABINI:
 799        case CHIP_MULLINS:
 800        case CHIP_TONGA:
 801        case CHIP_FIJI:
 802        case CHIP_CARRIZO:
 803        case CHIP_STONEY:
 804        case CHIP_POLARIS11:
 805        case CHIP_POLARIS10:
 806        case CHIP_POLARIS12:
 807        case CHIP_VEGAM:
 808        case CHIP_VEGA10:
 809        case CHIP_VEGA12:
 810        case CHIP_VEGA20:
 811        case CHIP_NAVI10:
 812                return 0;
 813        case CHIP_RAVEN:
 814                if (ASICREV_IS_PICASSO(adev->external_rev_id))
 815                        fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
 816                else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
 817                        fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
 818                else
 819                        return 0;
 820                break;
 821        default:
 822                DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
 823                return -EINVAL;
 824        }
 825
 826        if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
 827                DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
 828                return 0;
 829        }
 830
 831        r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
 832        if (r == -ENOENT) {
 833                /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
 834                DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
 835                adev->dm.fw_dmcu = NULL;
 836                return 0;
 837        }
 838        if (r) {
 839                dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
 840                        fw_name_dmcu);
 841                return r;
 842        }
 843
 844        r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
 845        if (r) {
 846                dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
 847                        fw_name_dmcu);
 848                release_firmware(adev->dm.fw_dmcu);
 849                adev->dm.fw_dmcu = NULL;
 850                return r;
 851        }
 852
 853        hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
 854        adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
 855        adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
 856        adev->firmware.fw_size +=
 857                ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
 858
 859        adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
 860        adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
 861        adev->firmware.fw_size +=
 862                ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
 863
 864        adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
 865
 866        DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
 867
 868        return 0;
 869}
 870
 871static int dm_sw_init(void *handle)
 872{
 873        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 874
 875        return load_dmcu_fw(adev);
 876}
 877
 878static int dm_sw_fini(void *handle)
 879{
 880        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 881
 882        if(adev->dm.fw_dmcu) {
 883                release_firmware(adev->dm.fw_dmcu);
 884                adev->dm.fw_dmcu = NULL;
 885        }
 886
 887        return 0;
 888}
 889
 890static int detect_mst_link_for_all_connectors(struct drm_device *dev)
 891{
 892        struct amdgpu_dm_connector *aconnector;
 893        struct drm_connector *connector;
 894        int ret = 0;
 895
 896        drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
 897
 898        list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
 899                aconnector = to_amdgpu_dm_connector(connector);
 900                if (aconnector->dc_link->type == dc_connection_mst_branch &&
 901                    aconnector->mst_mgr.aux) {
 902                        DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
 903                                        aconnector, aconnector->base.base.id);
 904
 905                        ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
 906                        if (ret < 0) {
 907                                DRM_ERROR("DM_MST: Failed to start MST\n");
 908                                ((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
 909                                return ret;
 910                                }
 911                        }
 912        }
 913
 914        drm_modeset_unlock(&dev->mode_config.connection_mutex);
 915        return ret;
 916}
 917
 918static int dm_late_init(void *handle)
 919{
 920        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 921
 922        struct dmcu_iram_parameters params;
 923        unsigned int linear_lut[16];
 924        int i;
 925        struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
 926        bool ret = false;
 927
 928        for (i = 0; i < 16; i++)
 929                linear_lut[i] = 0xFFFF * i / 15;
 930
 931        params.set = 0;
 932        params.backlight_ramping_start = 0xCCCC;
 933        params.backlight_ramping_reduction = 0xCCCCCCCC;
 934        params.backlight_lut_array_size = 16;
 935        params.backlight_lut_array = linear_lut;
 936
 937        /* todo will enable for navi10 */
 938        if (adev->asic_type <= CHIP_RAVEN) {
 939                ret = dmcu_load_iram(dmcu, params);
 940
 941                if (!ret)
 942                        return -EINVAL;
 943        }
 944
 945        return detect_mst_link_for_all_connectors(adev->ddev);
 946}
 947
 948static void s3_handle_mst(struct drm_device *dev, bool suspend)
 949{
 950        struct amdgpu_dm_connector *aconnector;
 951        struct drm_connector *connector;
 952        struct drm_dp_mst_topology_mgr *mgr;
 953        int ret;
 954        bool need_hotplug = false;
 955
 956        drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
 957
 958        list_for_each_entry(connector, &dev->mode_config.connector_list,
 959                            head) {
 960                aconnector = to_amdgpu_dm_connector(connector);
 961                if (aconnector->dc_link->type != dc_connection_mst_branch ||
 962                    aconnector->mst_port)
 963                        continue;
 964
 965                mgr = &aconnector->mst_mgr;
 966
 967                if (suspend) {
 968                        drm_dp_mst_topology_mgr_suspend(mgr);
 969                } else {
 970                        ret = drm_dp_mst_topology_mgr_resume(mgr);
 971                        if (ret < 0) {
 972                                drm_dp_mst_topology_mgr_set_mst(mgr, false);
 973                                need_hotplug = true;
 974                        }
 975                }
 976        }
 977
 978        drm_modeset_unlock(&dev->mode_config.connection_mutex);
 979
 980        if (need_hotplug)
 981                drm_kms_helper_hotplug_event(dev);
 982}
 983
 984/**
 985 * dm_hw_init() - Initialize DC device
 986 * @handle: The base driver device containing the amdpgu_dm device.
 987 *
 988 * Initialize the &struct amdgpu_display_manager device. This involves calling
 989 * the initializers of each DM component, then populating the struct with them.
 990 *
 991 * Although the function implies hardware initialization, both hardware and
 992 * software are initialized here. Splitting them out to their relevant init
 993 * hooks is a future TODO item.
 994 *
 995 * Some notable things that are initialized here:
 996 *
 997 * - Display Core, both software and hardware
 998 * - DC modules that we need (freesync and color management)
 999 * - DRM software states
1000 * - Interrupt sources and handlers
1001 * - Vblank support
1002 * - Debug FS entries, if enabled
1003 */
1004static int dm_hw_init(void *handle)
1005{
1006        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1007        /* Create DAL display manager */
1008        amdgpu_dm_init(adev);
1009        amdgpu_dm_hpd_init(adev);
1010
1011        return 0;
1012}
1013
1014/**
1015 * dm_hw_fini() - Teardown DC device
1016 * @handle: The base driver device containing the amdpgu_dm device.
1017 *
1018 * Teardown components within &struct amdgpu_display_manager that require
1019 * cleanup. This involves cleaning up the DRM device, DC, and any modules that
1020 * were loaded. Also flush IRQ workqueues and disable them.
1021 */
1022static int dm_hw_fini(void *handle)
1023{
1024        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1025
1026        amdgpu_dm_hpd_fini(adev);
1027
1028        amdgpu_dm_irq_fini(adev);
1029        amdgpu_dm_fini(adev);
1030        return 0;
1031}
1032
1033static int dm_suspend(void *handle)
1034{
1035        struct amdgpu_device *adev = handle;
1036        struct amdgpu_display_manager *dm = &adev->dm;
1037        int ret = 0;
1038
1039        WARN_ON(adev->dm.cached_state);
1040        adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
1041
1042        s3_handle_mst(adev->ddev, true);
1043
1044        amdgpu_dm_irq_suspend(adev);
1045
1046
1047        dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
1048
1049        return ret;
1050}
1051
1052static struct amdgpu_dm_connector *
1053amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
1054                                             struct drm_crtc *crtc)
1055{
1056        uint32_t i;
1057        struct drm_connector_state *new_con_state;
1058        struct drm_connector *connector;
1059        struct drm_crtc *crtc_from_state;
1060
1061        for_each_new_connector_in_state(state, connector, new_con_state, i) {
1062                crtc_from_state = new_con_state->crtc;
1063
1064                if (crtc_from_state == crtc)
1065                        return to_amdgpu_dm_connector(connector);
1066        }
1067
1068        return NULL;
1069}
1070
1071static void emulated_link_detect(struct dc_link *link)
1072{
1073        struct dc_sink_init_data sink_init_data = { 0 };
1074        struct display_sink_capability sink_caps = { 0 };
1075        enum dc_edid_status edid_status;
1076        struct dc_context *dc_ctx = link->ctx;
1077        struct dc_sink *sink = NULL;
1078        struct dc_sink *prev_sink = NULL;
1079
1080        link->type = dc_connection_none;
1081        prev_sink = link->local_sink;
1082
1083        if (prev_sink != NULL)
1084                dc_sink_retain(prev_sink);
1085
1086        switch (link->connector_signal) {
1087        case SIGNAL_TYPE_HDMI_TYPE_A: {
1088                sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1089                sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1090                break;
1091        }
1092
1093        case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1094                sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1095                sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1096                break;
1097        }
1098
1099        case SIGNAL_TYPE_DVI_DUAL_LINK: {
1100                sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1101                sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1102                break;
1103        }
1104
1105        case SIGNAL_TYPE_LVDS: {
1106                sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1107                sink_caps.signal = SIGNAL_TYPE_LVDS;
1108                break;
1109        }
1110
1111        case SIGNAL_TYPE_EDP: {
1112                sink_caps.transaction_type =
1113                        DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1114                sink_caps.signal = SIGNAL_TYPE_EDP;
1115                break;
1116        }
1117
1118        case SIGNAL_TYPE_DISPLAY_PORT: {
1119                sink_caps.transaction_type =
1120                        DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1121                sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
1122                break;
1123        }
1124
1125        default:
1126                DC_ERROR("Invalid connector type! signal:%d\n",
1127                        link->connector_signal);
1128                return;
1129        }
1130
1131        sink_init_data.link = link;
1132        sink_init_data.sink_signal = sink_caps.signal;
1133
1134        sink = dc_sink_create(&sink_init_data);
1135        if (!sink) {
1136                DC_ERROR("Failed to create sink!\n");
1137                return;
1138        }
1139
1140        /* dc_sink_create returns a new reference */
1141        link->local_sink = sink;
1142
1143        edid_status = dm_helpers_read_local_edid(
1144                        link->ctx,
1145                        link,
1146                        sink);
1147
1148        if (edid_status != EDID_OK)
1149                DC_ERROR("Failed to read EDID");
1150
1151}
1152
1153static int dm_resume(void *handle)
1154{
1155        struct amdgpu_device *adev = handle;
1156        struct drm_device *ddev = adev->ddev;
1157        struct amdgpu_display_manager *dm = &adev->dm;
1158        struct amdgpu_dm_connector *aconnector;
1159        struct drm_connector *connector;
1160        struct drm_crtc *crtc;
1161        struct drm_crtc_state *new_crtc_state;
1162        struct dm_crtc_state *dm_new_crtc_state;
1163        struct drm_plane *plane;
1164        struct drm_plane_state *new_plane_state;
1165        struct dm_plane_state *dm_new_plane_state;
1166        struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1167        enum dc_connection_type new_connection_type = dc_connection_none;
1168        int i;
1169
1170        /* Recreate dc_state - DC invalidates it when setting power state to S3. */
1171        dc_release_state(dm_state->context);
1172        dm_state->context = dc_create_state(dm->dc);
1173        /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1174        dc_resource_state_construct(dm->dc, dm_state->context);
1175
1176        /* power on hardware */
1177        dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1178
1179        /* program HPD filter */
1180        dc_resume(dm->dc);
1181
1182        /* On resume we need to  rewrite the MSTM control bits to enamble MST*/
1183        s3_handle_mst(ddev, false);
1184
1185        /*
1186         * early enable HPD Rx IRQ, should be done before set mode as short
1187         * pulse interrupts are used for MST
1188         */
1189        amdgpu_dm_irq_resume_early(adev);
1190
1191        /* Do detection*/
1192        list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
1193                aconnector = to_amdgpu_dm_connector(connector);
1194
1195                /*
1196                 * this is the case when traversing through already created
1197                 * MST connectors, should be skipped
1198                 */
1199                if (aconnector->mst_port)
1200                        continue;
1201
1202                mutex_lock(&aconnector->hpd_lock);
1203                if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1204                        DRM_ERROR("KMS: Failed to detect connector\n");
1205
1206                if (aconnector->base.force && new_connection_type == dc_connection_none)
1207                        emulated_link_detect(aconnector->dc_link);
1208                else
1209                        dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
1210
1211                if (aconnector->fake_enable && aconnector->dc_link->local_sink)
1212                        aconnector->fake_enable = false;
1213
1214                if (aconnector->dc_sink)
1215                        dc_sink_release(aconnector->dc_sink);
1216                aconnector->dc_sink = NULL;
1217                amdgpu_dm_update_connector_after_detect(aconnector);
1218                mutex_unlock(&aconnector->hpd_lock);
1219        }
1220
1221        /* Force mode set in atomic commit */
1222        for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
1223                new_crtc_state->active_changed = true;
1224
1225        /*
1226         * atomic_check is expected to create the dc states. We need to release
1227         * them here, since they were duplicated as part of the suspend
1228         * procedure.
1229         */
1230        for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1231                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1232                if (dm_new_crtc_state->stream) {
1233                        WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1234                        dc_stream_release(dm_new_crtc_state->stream);
1235                        dm_new_crtc_state->stream = NULL;
1236                }
1237        }
1238
1239        for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1240                dm_new_plane_state = to_dm_plane_state(new_plane_state);
1241                if (dm_new_plane_state->dc_state) {
1242                        WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1243                        dc_plane_state_release(dm_new_plane_state->dc_state);
1244                        dm_new_plane_state->dc_state = NULL;
1245                }
1246        }
1247
1248        drm_atomic_helper_resume(ddev, dm->cached_state);
1249
1250        dm->cached_state = NULL;
1251
1252        amdgpu_dm_irq_resume_late(adev);
1253
1254        return 0;
1255}
1256
1257/**
1258 * DOC: DM Lifecycle
1259 *
1260 * DM (and consequently DC) is registered in the amdgpu base driver as a IP
1261 * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
1262 * the base driver's device list to be initialized and torn down accordingly.
1263 *
1264 * The functions to do so are provided as hooks in &struct amd_ip_funcs.
1265 */
1266
1267static const struct amd_ip_funcs amdgpu_dm_funcs = {
1268        .name = "dm",
1269        .early_init = dm_early_init,
1270        .late_init = dm_late_init,
1271        .sw_init = dm_sw_init,
1272        .sw_fini = dm_sw_fini,
1273        .hw_init = dm_hw_init,
1274        .hw_fini = dm_hw_fini,
1275        .suspend = dm_suspend,
1276        .resume = dm_resume,
1277        .is_idle = dm_is_idle,
1278        .wait_for_idle = dm_wait_for_idle,
1279        .check_soft_reset = dm_check_soft_reset,
1280        .soft_reset = dm_soft_reset,
1281        .set_clockgating_state = dm_set_clockgating_state,
1282        .set_powergating_state = dm_set_powergating_state,
1283};
1284
1285const struct amdgpu_ip_block_version dm_ip_block =
1286{
1287        .type = AMD_IP_BLOCK_TYPE_DCE,
1288        .major = 1,
1289        .minor = 0,
1290        .rev = 0,
1291        .funcs = &amdgpu_dm_funcs,
1292};
1293
1294
1295/**
1296 * DOC: atomic
1297 *
1298 * *WIP*
1299 */
1300
1301static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1302        .fb_create = amdgpu_display_user_framebuffer_create,
1303        .output_poll_changed = drm_fb_helper_output_poll_changed,
1304        .atomic_check = amdgpu_dm_atomic_check,
1305        .atomic_commit = amdgpu_dm_atomic_commit,
1306};
1307
1308static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1309        .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1310};
1311
1312static void
1313amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1314{
1315        struct drm_connector *connector = &aconnector->base;
1316        struct drm_device *dev = connector->dev;
1317        struct dc_sink *sink;
1318
1319        /* MST handled by drm_mst framework */
1320        if (aconnector->mst_mgr.mst_state == true)
1321                return;
1322
1323
1324        sink = aconnector->dc_link->local_sink;
1325        if (sink)
1326                dc_sink_retain(sink);
1327
1328        /*
1329         * Edid mgmt connector gets first update only in mode_valid hook and then
1330         * the connector sink is set to either fake or physical sink depends on link status.
1331         * Skip if already done during boot.
1332         */
1333        if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1334                        && aconnector->dc_em_sink) {
1335
1336                /*
1337                 * For S3 resume with headless use eml_sink to fake stream
1338                 * because on resume connector->sink is set to NULL
1339                 */
1340                mutex_lock(&dev->mode_config.mutex);
1341
1342                if (sink) {
1343                        if (aconnector->dc_sink) {
1344                                amdgpu_dm_update_freesync_caps(connector, NULL);
1345                                /*
1346                                 * retain and release below are used to
1347                                 * bump up refcount for sink because the link doesn't point
1348                                 * to it anymore after disconnect, so on next crtc to connector
1349                                 * reshuffle by UMD we will get into unwanted dc_sink release
1350                                 */
1351                                dc_sink_release(aconnector->dc_sink);
1352                        }
1353                        aconnector->dc_sink = sink;
1354                        dc_sink_retain(aconnector->dc_sink);
1355                        amdgpu_dm_update_freesync_caps(connector,
1356                                        aconnector->edid);
1357                } else {
1358                        amdgpu_dm_update_freesync_caps(connector, NULL);
1359                        if (!aconnector->dc_sink) {
1360                                aconnector->dc_sink = aconnector->dc_em_sink;
1361                                dc_sink_retain(aconnector->dc_sink);
1362                        }
1363                }
1364
1365                mutex_unlock(&dev->mode_config.mutex);
1366
1367                if (sink)
1368                        dc_sink_release(sink);
1369                return;
1370        }
1371
1372        /*
1373         * TODO: temporary guard to look for proper fix
1374         * if this sink is MST sink, we should not do anything
1375         */
1376        if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
1377                dc_sink_release(sink);
1378                return;
1379        }
1380
1381        if (aconnector->dc_sink == sink) {
1382                /*
1383                 * We got a DP short pulse (Link Loss, DP CTS, etc...).
1384                 * Do nothing!!
1385                 */
1386                DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1387                                aconnector->connector_id);
1388                if (sink)
1389                        dc_sink_release(sink);
1390                return;
1391        }
1392
1393        DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1394                aconnector->connector_id, aconnector->dc_sink, sink);
1395
1396        mutex_lock(&dev->mode_config.mutex);
1397
1398        /*
1399         * 1. Update status of the drm connector
1400         * 2. Send an event and let userspace tell us what to do
1401         */
1402        if (sink) {
1403                /*
1404                 * TODO: check if we still need the S3 mode update workaround.
1405                 * If yes, put it here.
1406                 */
1407                if (aconnector->dc_sink)
1408                        amdgpu_dm_update_freesync_caps(connector, NULL);
1409
1410                aconnector->dc_sink = sink;
1411                dc_sink_retain(aconnector->dc_sink);
1412                if (sink->dc_edid.length == 0) {
1413                        aconnector->edid = NULL;
1414                        drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1415                } else {
1416                        aconnector->edid =
1417                                (struct edid *) sink->dc_edid.raw_edid;
1418
1419
1420                        drm_connector_update_edid_property(connector,
1421                                        aconnector->edid);
1422                        drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1423                                            aconnector->edid);
1424                }
1425                amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1426
1427        } else {
1428                drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1429                amdgpu_dm_update_freesync_caps(connector, NULL);
1430                drm_connector_update_edid_property(connector, NULL);
1431                aconnector->num_modes = 0;
1432                dc_sink_release(aconnector->dc_sink);
1433                aconnector->dc_sink = NULL;
1434                aconnector->edid = NULL;
1435        }
1436
1437        mutex_unlock(&dev->mode_config.mutex);
1438
1439        if (sink)
1440                dc_sink_release(sink);
1441}
1442
1443static void handle_hpd_irq(void *param)
1444{
1445        struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1446        struct drm_connector *connector = &aconnector->base;
1447        struct drm_device *dev = connector->dev;
1448        enum dc_connection_type new_connection_type = dc_connection_none;
1449
1450        /*
1451         * In case of failure or MST no need to update connector status or notify the OS
1452         * since (for MST case) MST does this in its own context.
1453         */
1454        mutex_lock(&aconnector->hpd_lock);
1455
1456        if (aconnector->fake_enable)
1457                aconnector->fake_enable = false;
1458
1459        if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1460                DRM_ERROR("KMS: Failed to detect connector\n");
1461
1462        if (aconnector->base.force && new_connection_type == dc_connection_none) {
1463                emulated_link_detect(aconnector->dc_link);
1464
1465
1466                drm_modeset_lock_all(dev);
1467                dm_restore_drm_connector_state(dev, connector);
1468                drm_modeset_unlock_all(dev);
1469
1470                if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1471                        drm_kms_helper_hotplug_event(dev);
1472
1473        } else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1474                amdgpu_dm_update_connector_after_detect(aconnector);
1475
1476
1477                drm_modeset_lock_all(dev);
1478                dm_restore_drm_connector_state(dev, connector);
1479                drm_modeset_unlock_all(dev);
1480
1481                if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1482                        drm_kms_helper_hotplug_event(dev);
1483        }
1484        mutex_unlock(&aconnector->hpd_lock);
1485
1486}
1487
1488static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1489{
1490        uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1491        uint8_t dret;
1492        bool new_irq_handled = false;
1493        int dpcd_addr;
1494        int dpcd_bytes_to_read;
1495
1496        const int max_process_count = 30;
1497        int process_count = 0;
1498
1499        const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1500
1501        if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1502                dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1503                /* DPCD 0x200 - 0x201 for downstream IRQ */
1504                dpcd_addr = DP_SINK_COUNT;
1505        } else {
1506                dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1507                /* DPCD 0x2002 - 0x2005 for downstream IRQ */
1508                dpcd_addr = DP_SINK_COUNT_ESI;
1509        }
1510
1511        dret = drm_dp_dpcd_read(
1512                &aconnector->dm_dp_aux.aux,
1513                dpcd_addr,
1514                esi,
1515                dpcd_bytes_to_read);
1516
1517        while (dret == dpcd_bytes_to_read &&
1518                process_count < max_process_count) {
1519                uint8_t retry;
1520                dret = 0;
1521
1522                process_count++;
1523
1524                DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1525                /* handle HPD short pulse irq */
1526                if (aconnector->mst_mgr.mst_state)
1527                        drm_dp_mst_hpd_irq(
1528                                &aconnector->mst_mgr,
1529                                esi,
1530                                &new_irq_handled);
1531
1532                if (new_irq_handled) {
1533                        /* ACK at DPCD to notify down stream */
1534                        const int ack_dpcd_bytes_to_write =
1535                                dpcd_bytes_to_read - 1;
1536
1537                        for (retry = 0; retry < 3; retry++) {
1538                                uint8_t wret;
1539
1540                                wret = drm_dp_dpcd_write(
1541                                        &aconnector->dm_dp_aux.aux,
1542                                        dpcd_addr + 1,
1543                                        &esi[1],
1544                                        ack_dpcd_bytes_to_write);
1545                                if (wret == ack_dpcd_bytes_to_write)
1546                                        break;
1547                        }
1548
1549                        /* check if there is new irq to be handled */
1550                        dret = drm_dp_dpcd_read(
1551                                &aconnector->dm_dp_aux.aux,
1552                                dpcd_addr,
1553                                esi,
1554                                dpcd_bytes_to_read);
1555
1556                        new_irq_handled = false;
1557                } else {
1558                        break;
1559                }
1560        }
1561
1562        if (process_count == max_process_count)
1563                DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1564}
1565
1566static void handle_hpd_rx_irq(void *param)
1567{
1568        struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1569        struct drm_connector *connector = &aconnector->base;
1570        struct drm_device *dev = connector->dev;
1571        struct dc_link *dc_link = aconnector->dc_link;
1572        bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1573        enum dc_connection_type new_connection_type = dc_connection_none;
1574
1575        /*
1576         * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1577         * conflict, after implement i2c helper, this mutex should be
1578         * retired.
1579         */
1580        if (dc_link->type != dc_connection_mst_branch)
1581                mutex_lock(&aconnector->hpd_lock);
1582
1583        if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1584                        !is_mst_root_connector) {
1585                /* Downstream Port status changed. */
1586                if (!dc_link_detect_sink(dc_link, &new_connection_type))
1587                        DRM_ERROR("KMS: Failed to detect connector\n");
1588
1589                if (aconnector->base.force && new_connection_type == dc_connection_none) {
1590                        emulated_link_detect(dc_link);
1591
1592                        if (aconnector->fake_enable)
1593                                aconnector->fake_enable = false;
1594
1595                        amdgpu_dm_update_connector_after_detect(aconnector);
1596
1597
1598                        drm_modeset_lock_all(dev);
1599                        dm_restore_drm_connector_state(dev, connector);
1600                        drm_modeset_unlock_all(dev);
1601
1602                        drm_kms_helper_hotplug_event(dev);
1603                } else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1604
1605                        if (aconnector->fake_enable)
1606                                aconnector->fake_enable = false;
1607
1608                        amdgpu_dm_update_connector_after_detect(aconnector);
1609
1610
1611                        drm_modeset_lock_all(dev);
1612                        dm_restore_drm_connector_state(dev, connector);
1613                        drm_modeset_unlock_all(dev);
1614
1615                        drm_kms_helper_hotplug_event(dev);
1616                }
1617        }
1618        if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1619            (dc_link->type == dc_connection_mst_branch))
1620                dm_handle_hpd_rx_irq(aconnector);
1621
1622        if (dc_link->type != dc_connection_mst_branch) {
1623                drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1624                mutex_unlock(&aconnector->hpd_lock);
1625        }
1626}
1627
1628static void register_hpd_handlers(struct amdgpu_device *adev)
1629{
1630        struct drm_device *dev = adev->ddev;
1631        struct drm_connector *connector;
1632        struct amdgpu_dm_connector *aconnector;
1633        const struct dc_link *dc_link;
1634        struct dc_interrupt_params int_params = {0};
1635
1636        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1637        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1638
1639        list_for_each_entry(connector,
1640                        &dev->mode_config.connector_list, head) {
1641
1642                aconnector = to_amdgpu_dm_connector(connector);
1643                dc_link = aconnector->dc_link;
1644
1645                if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1646                        int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1647                        int_params.irq_source = dc_link->irq_source_hpd;
1648
1649                        amdgpu_dm_irq_register_interrupt(adev, &int_params,
1650                                        handle_hpd_irq,
1651                                        (void *) aconnector);
1652                }
1653
1654                if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1655
1656                        /* Also register for DP short pulse (hpd_rx). */
1657                        int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1658                        int_params.irq_source = dc_link->irq_source_hpd_rx;
1659
1660                        amdgpu_dm_irq_register_interrupt(adev, &int_params,
1661                                        handle_hpd_rx_irq,
1662                                        (void *) aconnector);
1663                }
1664        }
1665}
1666
1667/* Register IRQ sources and initialize IRQ callbacks */
1668static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1669{
1670        struct dc *dc = adev->dm.dc;
1671        struct common_irq_params *c_irq_params;
1672        struct dc_interrupt_params int_params = {0};
1673        int r;
1674        int i;
1675        unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1676
1677        if (adev->asic_type >= CHIP_VEGA10)
1678                client_id = SOC15_IH_CLIENTID_DCE;
1679
1680        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1681        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1682
1683        /*
1684         * Actions of amdgpu_irq_add_id():
1685         * 1. Register a set() function with base driver.
1686         *    Base driver will call set() function to enable/disable an
1687         *    interrupt in DC hardware.
1688         * 2. Register amdgpu_dm_irq_handler().
1689         *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1690         *    coming from DC hardware.
1691         *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1692         *    for acknowledging and handling. */
1693
1694        /* Use VBLANK interrupt */
1695        for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1696                r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1697                if (r) {
1698                        DRM_ERROR("Failed to add crtc irq id!\n");
1699                        return r;
1700                }
1701
1702                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1703                int_params.irq_source =
1704                        dc_interrupt_to_irq_source(dc, i, 0);
1705
1706                c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1707
1708                c_irq_params->adev = adev;
1709                c_irq_params->irq_src = int_params.irq_source;
1710
1711                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1712                                dm_crtc_high_irq, c_irq_params);
1713        }
1714
1715        /* Use VUPDATE interrupt */
1716        for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
1717                r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
1718                if (r) {
1719                        DRM_ERROR("Failed to add vupdate irq id!\n");
1720                        return r;
1721                }
1722
1723                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1724                int_params.irq_source =
1725                        dc_interrupt_to_irq_source(dc, i, 0);
1726
1727                c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1728
1729                c_irq_params->adev = adev;
1730                c_irq_params->irq_src = int_params.irq_source;
1731
1732                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1733                                dm_vupdate_high_irq, c_irq_params);
1734        }
1735
1736        /* Use GRPH_PFLIP interrupt */
1737        for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1738                        i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1739                r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1740                if (r) {
1741                        DRM_ERROR("Failed to add page flip irq id!\n");
1742                        return r;
1743                }
1744
1745                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1746                int_params.irq_source =
1747                        dc_interrupt_to_irq_source(dc, i, 0);
1748
1749                c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1750
1751                c_irq_params->adev = adev;
1752                c_irq_params->irq_src = int_params.irq_source;
1753
1754                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1755                                dm_pflip_high_irq, c_irq_params);
1756
1757        }
1758
1759        /* HPD */
1760        r = amdgpu_irq_add_id(adev, client_id,
1761                        VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1762        if (r) {
1763                DRM_ERROR("Failed to add hpd irq id!\n");
1764                return r;
1765        }
1766
1767        register_hpd_handlers(adev);
1768
1769        return 0;
1770}
1771
1772#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1773/* Register IRQ sources and initialize IRQ callbacks */
1774static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1775{
1776        struct dc *dc = adev->dm.dc;
1777        struct common_irq_params *c_irq_params;
1778        struct dc_interrupt_params int_params = {0};
1779        int r;
1780        int i;
1781
1782        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1783        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1784
1785        /*
1786         * Actions of amdgpu_irq_add_id():
1787         * 1. Register a set() function with base driver.
1788         *    Base driver will call set() function to enable/disable an
1789         *    interrupt in DC hardware.
1790         * 2. Register amdgpu_dm_irq_handler().
1791         *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1792         *    coming from DC hardware.
1793         *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1794         *    for acknowledging and handling.
1795         */
1796
1797        /* Use VSTARTUP interrupt */
1798        for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1799                        i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1800                        i++) {
1801                r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1802
1803                if (r) {
1804                        DRM_ERROR("Failed to add crtc irq id!\n");
1805                        return r;
1806                }
1807
1808                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1809                int_params.irq_source =
1810                        dc_interrupt_to_irq_source(dc, i, 0);
1811
1812                c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1813
1814                c_irq_params->adev = adev;
1815                c_irq_params->irq_src = int_params.irq_source;
1816
1817                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1818                                dm_crtc_high_irq, c_irq_params);
1819        }
1820
1821        /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
1822         * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
1823         * to trigger at end of each vblank, regardless of state of the lock,
1824         * matching DCE behaviour.
1825         */
1826        for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
1827             i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
1828             i++) {
1829                r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
1830
1831                if (r) {
1832                        DRM_ERROR("Failed to add vupdate irq id!\n");
1833                        return r;
1834                }
1835
1836                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1837                int_params.irq_source =
1838                        dc_interrupt_to_irq_source(dc, i, 0);
1839
1840                c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1841
1842                c_irq_params->adev = adev;
1843                c_irq_params->irq_src = int_params.irq_source;
1844
1845                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1846                                dm_vupdate_high_irq, c_irq_params);
1847        }
1848
1849        /* Use GRPH_PFLIP interrupt */
1850        for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1851                        i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1852                        i++) {
1853                r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1854                if (r) {
1855                        DRM_ERROR("Failed to add page flip irq id!\n");
1856                        return r;
1857                }
1858
1859                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1860                int_params.irq_source =
1861                        dc_interrupt_to_irq_source(dc, i, 0);
1862
1863                c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1864
1865                c_irq_params->adev = adev;
1866                c_irq_params->irq_src = int_params.irq_source;
1867
1868                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1869                                dm_pflip_high_irq, c_irq_params);
1870
1871        }
1872
1873        /* HPD */
1874        r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1875                        &adev->hpd_irq);
1876        if (r) {
1877                DRM_ERROR("Failed to add hpd irq id!\n");
1878                return r;
1879        }
1880
1881        register_hpd_handlers(adev);
1882
1883        return 0;
1884}
1885#endif
1886
1887/*
1888 * Acquires the lock for the atomic state object and returns
1889 * the new atomic state.
1890 *
1891 * This should only be called during atomic check.
1892 */
1893static int dm_atomic_get_state(struct drm_atomic_state *state,
1894                               struct dm_atomic_state **dm_state)
1895{
1896        struct drm_device *dev = state->dev;
1897        struct amdgpu_device *adev = dev->dev_private;
1898        struct amdgpu_display_manager *dm = &adev->dm;
1899        struct drm_private_state *priv_state;
1900
1901        if (*dm_state)
1902                return 0;
1903
1904        priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
1905        if (IS_ERR(priv_state))
1906                return PTR_ERR(priv_state);
1907
1908        *dm_state = to_dm_atomic_state(priv_state);
1909
1910        return 0;
1911}
1912
1913struct dm_atomic_state *
1914dm_atomic_get_new_state(struct drm_atomic_state *state)
1915{
1916        struct drm_device *dev = state->dev;
1917        struct amdgpu_device *adev = dev->dev_private;
1918        struct amdgpu_display_manager *dm = &adev->dm;
1919        struct drm_private_obj *obj;
1920        struct drm_private_state *new_obj_state;
1921        int i;
1922
1923        for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
1924                if (obj->funcs == dm->atomic_obj.funcs)
1925                        return to_dm_atomic_state(new_obj_state);
1926        }
1927
1928        return NULL;
1929}
1930
1931struct dm_atomic_state *
1932dm_atomic_get_old_state(struct drm_atomic_state *state)
1933{
1934        struct drm_device *dev = state->dev;
1935        struct amdgpu_device *adev = dev->dev_private;
1936        struct amdgpu_display_manager *dm = &adev->dm;
1937        struct drm_private_obj *obj;
1938        struct drm_private_state *old_obj_state;
1939        int i;
1940
1941        for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
1942                if (obj->funcs == dm->atomic_obj.funcs)
1943                        return to_dm_atomic_state(old_obj_state);
1944        }
1945
1946        return NULL;
1947}
1948
1949static struct drm_private_state *
1950dm_atomic_duplicate_state(struct drm_private_obj *obj)
1951{
1952        struct dm_atomic_state *old_state, *new_state;
1953
1954        new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
1955        if (!new_state)
1956                return NULL;
1957
1958        __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
1959
1960        old_state = to_dm_atomic_state(obj->state);
1961
1962        if (old_state && old_state->context)
1963                new_state->context = dc_copy_state(old_state->context);
1964
1965        if (!new_state->context) {
1966                kfree(new_state);
1967                return NULL;
1968        }
1969
1970        return &new_state->base;
1971}
1972
1973static void dm_atomic_destroy_state(struct drm_private_obj *obj,
1974                                    struct drm_private_state *state)
1975{
1976        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1977
1978        if (dm_state && dm_state->context)
1979                dc_release_state(dm_state->context);
1980
1981        kfree(dm_state);
1982}
1983
1984static struct drm_private_state_funcs dm_atomic_state_funcs = {
1985        .atomic_duplicate_state = dm_atomic_duplicate_state,
1986        .atomic_destroy_state = dm_atomic_destroy_state,
1987};
1988
1989static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1990{
1991        struct dm_atomic_state *state;
1992        int r;
1993
1994        adev->mode_info.mode_config_initialized = true;
1995
1996        adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1997        adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1998
1999        adev->ddev->mode_config.max_width = 16384;
2000        adev->ddev->mode_config.max_height = 16384;
2001
2002        adev->ddev->mode_config.preferred_depth = 24;
2003        adev->ddev->mode_config.prefer_shadow = 1;
2004        /* indicates support for immediate flip */
2005        adev->ddev->mode_config.async_page_flip = true;
2006
2007        adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
2008
2009        state = kzalloc(sizeof(*state), GFP_KERNEL);
2010        if (!state)
2011                return -ENOMEM;
2012
2013        state->context = dc_create_state(adev->dm.dc);
2014        if (!state->context) {
2015                kfree(state);
2016                return -ENOMEM;
2017        }
2018
2019        dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
2020
2021        drm_atomic_private_obj_init(adev->ddev,
2022                                    &adev->dm.atomic_obj,
2023                                    &state->base,
2024                                    &dm_atomic_state_funcs);
2025
2026        r = amdgpu_display_modeset_create_props(adev);
2027        if (r)
2028                return r;
2029
2030        r = amdgpu_dm_audio_init(adev);
2031        if (r)
2032                return r;
2033
2034        return 0;
2035}
2036
2037#define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
2038#define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
2039
2040#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2041        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2042
2043static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
2044{
2045#if defined(CONFIG_ACPI)
2046        struct amdgpu_dm_backlight_caps caps;
2047
2048        if (dm->backlight_caps.caps_valid)
2049                return;
2050
2051        amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
2052        if (caps.caps_valid) {
2053                dm->backlight_caps.min_input_signal = caps.min_input_signal;
2054                dm->backlight_caps.max_input_signal = caps.max_input_signal;
2055                dm->backlight_caps.caps_valid = true;
2056        } else {
2057                dm->backlight_caps.min_input_signal =
2058                                AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2059                dm->backlight_caps.max_input_signal =
2060                                AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2061        }
2062#else
2063        dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2064        dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2065#endif
2066}
2067
2068static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
2069{
2070        struct amdgpu_display_manager *dm = bl_get_data(bd);
2071        struct amdgpu_dm_backlight_caps caps;
2072        uint32_t brightness = bd->props.brightness;
2073
2074        amdgpu_dm_update_backlight_caps(dm);
2075        caps = dm->backlight_caps;
2076        /*
2077         * The brightness input is in the range 0-255
2078         * It needs to be rescaled to be between the
2079         * requested min and max input signal
2080         *
2081         * It also needs to be scaled up by 0x101 to
2082         * match the DC interface which has a range of
2083         * 0 to 0xffff
2084         */
2085        brightness =
2086                brightness
2087                * 0x101
2088                * (caps.max_input_signal - caps.min_input_signal)
2089                / AMDGPU_MAX_BL_LEVEL
2090                + caps.min_input_signal * 0x101;
2091
2092        if (dc_link_set_backlight_level(dm->backlight_link,
2093                        brightness, 0))
2094                return 0;
2095        else
2096                return 1;
2097}
2098
2099static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
2100{
2101        struct amdgpu_display_manager *dm = bl_get_data(bd);
2102        int ret = dc_link_get_backlight_level(dm->backlight_link);
2103
2104        if (ret == DC_ERROR_UNEXPECTED)
2105                return bd->props.brightness;
2106        return ret;
2107}
2108
2109static const struct backlight_ops amdgpu_dm_backlight_ops = {
2110        .get_brightness = amdgpu_dm_backlight_get_brightness,
2111        .update_status  = amdgpu_dm_backlight_update_status,
2112};
2113
2114static void
2115amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
2116{
2117        char bl_name[16];
2118        struct backlight_properties props = { 0 };
2119
2120        amdgpu_dm_update_backlight_caps(dm);
2121
2122        props.max_brightness = AMDGPU_MAX_BL_LEVEL;
2123        props.brightness = AMDGPU_MAX_BL_LEVEL;
2124        props.type = BACKLIGHT_RAW;
2125
2126        snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
2127                        dm->adev->ddev->primary->index);
2128
2129        dm->backlight_dev = backlight_device_register(bl_name,
2130                        dm->adev->ddev->dev,
2131                        dm,
2132                        &amdgpu_dm_backlight_ops,
2133                        &props);
2134
2135        if (IS_ERR(dm->backlight_dev))
2136                DRM_ERROR("DM: Backlight registration failed!\n");
2137        else
2138                DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
2139}
2140
2141#endif
2142
2143static int initialize_plane(struct amdgpu_display_manager *dm,
2144                            struct amdgpu_mode_info *mode_info, int plane_id,
2145                            enum drm_plane_type plane_type,
2146                            const struct dc_plane_cap *plane_cap)
2147{
2148        struct drm_plane *plane;
2149        unsigned long possible_crtcs;
2150        int ret = 0;
2151
2152        plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
2153        if (!plane) {
2154                DRM_ERROR("KMS: Failed to allocate plane\n");
2155                return -ENOMEM;
2156        }
2157        plane->type = plane_type;
2158
2159        /*
2160         * HACK: IGT tests expect that the primary plane for a CRTC
2161         * can only have one possible CRTC. Only expose support for
2162         * any CRTC if they're not going to be used as a primary plane
2163         * for a CRTC - like overlay or underlay planes.
2164         */
2165        possible_crtcs = 1 << plane_id;
2166        if (plane_id >= dm->dc->caps.max_streams)
2167                possible_crtcs = 0xff;
2168
2169        ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2170
2171        if (ret) {
2172                DRM_ERROR("KMS: Failed to initialize plane\n");
2173                kfree(plane);
2174                return ret;
2175        }
2176
2177        if (mode_info)
2178                mode_info->planes[plane_id] = plane;
2179
2180        return ret;
2181}
2182
2183
2184static void register_backlight_device(struct amdgpu_display_manager *dm,
2185                                      struct dc_link *link)
2186{
2187#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2188        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2189
2190        if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2191            link->type != dc_connection_none) {
2192                /*
2193                 * Event if registration failed, we should continue with
2194                 * DM initialization because not having a backlight control
2195                 * is better then a black screen.
2196                 */
2197                amdgpu_dm_register_backlight_device(dm);
2198
2199                if (dm->backlight_dev)
2200                        dm->backlight_link = link;
2201        }
2202#endif
2203}
2204
2205
2206/*
2207 * In this architecture, the association
2208 * connector -> encoder -> crtc
2209 * id not really requried. The crtc and connector will hold the
2210 * display_index as an abstraction to use with DAL component
2211 *
2212 * Returns 0 on success
2213 */
2214static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2215{
2216        struct amdgpu_display_manager *dm = &adev->dm;
2217        int32_t i;
2218        struct amdgpu_dm_connector *aconnector = NULL;
2219        struct amdgpu_encoder *aencoder = NULL;
2220        struct amdgpu_mode_info *mode_info = &adev->mode_info;
2221        uint32_t link_cnt;
2222        int32_t primary_planes;
2223        enum dc_connection_type new_connection_type = dc_connection_none;
2224        const struct dc_plane_cap *plane;
2225
2226        link_cnt = dm->dc->caps.max_links;
2227        if (amdgpu_dm_mode_config_init(dm->adev)) {
2228                DRM_ERROR("DM: Failed to initialize mode config\n");
2229                return -EINVAL;
2230        }
2231
2232        /* There is one primary plane per CRTC */
2233        primary_planes = dm->dc->caps.max_streams;
2234        ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
2235
2236        /*
2237         * Initialize primary planes, implicit planes for legacy IOCTLS.
2238         * Order is reversed to match iteration order in atomic check.
2239         */
2240        for (i = (primary_planes - 1); i >= 0; i--) {
2241                plane = &dm->dc->caps.planes[i];
2242
2243                if (initialize_plane(dm, mode_info, i,
2244                                     DRM_PLANE_TYPE_PRIMARY, plane)) {
2245                        DRM_ERROR("KMS: Failed to initialize primary plane\n");
2246                        goto fail;
2247                }
2248        }
2249
2250        /*
2251         * Initialize overlay planes, index starting after primary planes.
2252         * These planes have a higher DRM index than the primary planes since
2253         * they should be considered as having a higher z-order.
2254         * Order is reversed to match iteration order in atomic check.
2255         *
2256         * Only support DCN for now, and only expose one so we don't encourage
2257         * userspace to use up all the pipes.
2258         */
2259        for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2260                struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2261
2262                if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2263                        continue;
2264
2265                if (!plane->blends_with_above || !plane->blends_with_below)
2266                        continue;
2267
2268                if (!plane->pixel_format_support.argb8888)
2269                        continue;
2270
2271                if (initialize_plane(dm, NULL, primary_planes + i,
2272                                     DRM_PLANE_TYPE_OVERLAY, plane)) {
2273                        DRM_ERROR("KMS: Failed to initialize overlay plane\n");
2274                        goto fail;
2275                }
2276
2277                /* Only create one overlay plane. */
2278                break;
2279        }
2280
2281        for (i = 0; i < dm->dc->caps.max_streams; i++)
2282                if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2283                        DRM_ERROR("KMS: Failed to initialize crtc\n");
2284                        goto fail;
2285                }
2286
2287        dm->display_indexes_num = dm->dc->caps.max_streams;
2288
2289        /* loops over all connectors on the board */
2290        for (i = 0; i < link_cnt; i++) {
2291                struct dc_link *link = NULL;
2292
2293                if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
2294                        DRM_ERROR(
2295                                "KMS: Cannot support more than %d display indexes\n",
2296                                        AMDGPU_DM_MAX_DISPLAY_INDEX);
2297                        continue;
2298                }
2299
2300                aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
2301                if (!aconnector)
2302                        goto fail;
2303
2304                aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
2305                if (!aencoder)
2306                        goto fail;
2307
2308                if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2309                        DRM_ERROR("KMS: Failed to initialize encoder\n");
2310                        goto fail;
2311                }
2312
2313                if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2314                        DRM_ERROR("KMS: Failed to initialize connector\n");
2315                        goto fail;
2316                }
2317
2318                link = dc_get_link_at_index(dm->dc, i);
2319
2320                if (!dc_link_detect_sink(link, &new_connection_type))
2321                        DRM_ERROR("KMS: Failed to detect connector\n");
2322
2323                if (aconnector->base.force && new_connection_type == dc_connection_none) {
2324                        emulated_link_detect(link);
2325                        amdgpu_dm_update_connector_after_detect(aconnector);
2326
2327                } else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
2328                        amdgpu_dm_update_connector_after_detect(aconnector);
2329                        register_backlight_device(dm, link);
2330                }
2331
2332
2333        }
2334
2335        /* Software is initialized. Now we can register interrupt handlers. */
2336        switch (adev->asic_type) {
2337        case CHIP_BONAIRE:
2338        case CHIP_HAWAII:
2339        case CHIP_KAVERI:
2340        case CHIP_KABINI:
2341        case CHIP_MULLINS:
2342        case CHIP_TONGA:
2343        case CHIP_FIJI:
2344        case CHIP_CARRIZO:
2345        case CHIP_STONEY:
2346        case CHIP_POLARIS11:
2347        case CHIP_POLARIS10:
2348        case CHIP_POLARIS12:
2349        case CHIP_VEGAM:
2350        case CHIP_VEGA10:
2351        case CHIP_VEGA12:
2352        case CHIP_VEGA20:
2353                if (dce110_register_irq_handlers(dm->adev)) {
2354                        DRM_ERROR("DM: Failed to initialize IRQ\n");
2355                        goto fail;
2356                }
2357                break;
2358#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2359        case CHIP_RAVEN:
2360#if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2361        case CHIP_NAVI10:
2362#endif
2363                if (dcn10_register_irq_handlers(dm->adev)) {
2364                        DRM_ERROR("DM: Failed to initialize IRQ\n");
2365                        goto fail;
2366                }
2367                break;
2368#endif
2369        default:
2370                DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2371                goto fail;
2372        }
2373
2374        if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2375                dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2376
2377        return 0;
2378fail:
2379        kfree(aencoder);
2380        kfree(aconnector);
2381
2382        return -EINVAL;
2383}
2384
2385static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2386{
2387        drm_mode_config_cleanup(dm->ddev);
2388        drm_atomic_private_obj_fini(&dm->atomic_obj);
2389        return;
2390}
2391
2392/******************************************************************************
2393 * amdgpu_display_funcs functions
2394 *****************************************************************************/
2395
2396/*
2397 * dm_bandwidth_update - program display watermarks
2398 *
2399 * @adev: amdgpu_device pointer
2400 *
2401 * Calculate and program the display watermarks and line buffer allocation.
2402 */
2403static void dm_bandwidth_update(struct amdgpu_device *adev)
2404{
2405        /* TODO: implement later */
2406}
2407
2408static const struct amdgpu_display_funcs dm_display_funcs = {
2409        .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2410        .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2411        .backlight_set_level = NULL, /* never called for DC */
2412        .backlight_get_level = NULL, /* never called for DC */
2413        .hpd_sense = NULL,/* called unconditionally */
2414        .hpd_set_polarity = NULL, /* called unconditionally */
2415        .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2416        .page_flip_get_scanoutpos =
2417                dm_crtc_get_scanoutpos,/* called unconditionally */
2418        .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2419        .add_connector = NULL, /* VBIOS parsing. DAL does it. */
2420};
2421
2422#if defined(CONFIG_DEBUG_KERNEL_DC)
2423
2424static ssize_t s3_debug_store(struct device *device,
2425                              struct device_attribute *attr,
2426                              const char *buf,
2427                              size_t count)
2428{
2429        int ret;
2430        int s3_state;
2431        struct pci_dev *pdev = to_pci_dev(device);
2432        struct drm_device *drm_dev = pci_get_drvdata(pdev);
2433        struct amdgpu_device *adev = drm_dev->dev_private;
2434
2435        ret = kstrtoint(buf, 0, &s3_state);
2436
2437        if (ret == 0) {
2438                if (s3_state) {
2439                        dm_resume(adev);
2440                        drm_kms_helper_hotplug_event(adev->ddev);
2441                } else
2442                        dm_suspend(adev);
2443        }
2444
2445        return ret == 0 ? count : 0;
2446}
2447
2448DEVICE_ATTR_WO(s3_debug);
2449
2450#endif
2451
2452static int dm_early_init(void *handle)
2453{
2454        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2455
2456        switch (adev->asic_type) {
2457        case CHIP_BONAIRE:
2458        case CHIP_HAWAII:
2459                adev->mode_info.num_crtc = 6;
2460                adev->mode_info.num_hpd = 6;
2461                adev->mode_info.num_dig = 6;
2462                break;
2463        case CHIP_KAVERI:
2464                adev->mode_info.num_crtc = 4;
2465                adev->mode_info.num_hpd = 6;
2466                adev->mode_info.num_dig = 7;
2467                break;
2468        case CHIP_KABINI:
2469        case CHIP_MULLINS:
2470                adev->mode_info.num_crtc = 2;
2471                adev->mode_info.num_hpd = 6;
2472                adev->mode_info.num_dig = 6;
2473                break;
2474        case CHIP_FIJI:
2475        case CHIP_TONGA:
2476                adev->mode_info.num_crtc = 6;
2477                adev->mode_info.num_hpd = 6;
2478                adev->mode_info.num_dig = 7;
2479                break;
2480        case CHIP_CARRIZO:
2481                adev->mode_info.num_crtc = 3;
2482                adev->mode_info.num_hpd = 6;
2483                adev->mode_info.num_dig = 9;
2484                break;
2485        case CHIP_STONEY:
2486                adev->mode_info.num_crtc = 2;
2487                adev->mode_info.num_hpd = 6;
2488                adev->mode_info.num_dig = 9;
2489                break;
2490        case CHIP_POLARIS11:
2491        case CHIP_POLARIS12:
2492                adev->mode_info.num_crtc = 5;
2493                adev->mode_info.num_hpd = 5;
2494                adev->mode_info.num_dig = 5;
2495                break;
2496        case CHIP_POLARIS10:
2497        case CHIP_VEGAM:
2498                adev->mode_info.num_crtc = 6;
2499                adev->mode_info.num_hpd = 6;
2500                adev->mode_info.num_dig = 6;
2501                break;
2502        case CHIP_VEGA10:
2503        case CHIP_VEGA12:
2504        case CHIP_VEGA20:
2505                adev->mode_info.num_crtc = 6;
2506                adev->mode_info.num_hpd = 6;
2507                adev->mode_info.num_dig = 6;
2508                break;
2509#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2510        case CHIP_RAVEN:
2511                adev->mode_info.num_crtc = 4;
2512                adev->mode_info.num_hpd = 4;
2513                adev->mode_info.num_dig = 4;
2514                break;
2515#endif
2516#if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2517        case CHIP_NAVI10:
2518                adev->mode_info.num_crtc = 6;
2519                adev->mode_info.num_hpd = 6;
2520                adev->mode_info.num_dig = 6;
2521                break;
2522#endif
2523        default:
2524                DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2525                return -EINVAL;
2526        }
2527
2528        amdgpu_dm_set_irq_funcs(adev);
2529
2530        if (adev->mode_info.funcs == NULL)
2531                adev->mode_info.funcs = &dm_display_funcs;
2532
2533        /*
2534         * Note: Do NOT change adev->audio_endpt_rreg and
2535         * adev->audio_endpt_wreg because they are initialised in
2536         * amdgpu_device_init()
2537         */
2538#if defined(CONFIG_DEBUG_KERNEL_DC)
2539        device_create_file(
2540                adev->ddev->dev,
2541                &dev_attr_s3_debug);
2542#endif
2543
2544        return 0;
2545}
2546
2547static bool modeset_required(struct drm_crtc_state *crtc_state,
2548                             struct dc_stream_state *new_stream,
2549                             struct dc_stream_state *old_stream)
2550{
2551        if (!drm_atomic_crtc_needs_modeset(crtc_state))
2552                return false;
2553
2554        if (!crtc_state->enable)
2555                return false;
2556
2557        return crtc_state->active;
2558}
2559
2560static bool modereset_required(struct drm_crtc_state *crtc_state)
2561{
2562        if (!drm_atomic_crtc_needs_modeset(crtc_state))
2563                return false;
2564
2565        return !crtc_state->enable || !crtc_state->active;
2566}
2567
2568static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2569{
2570        drm_encoder_cleanup(encoder);
2571        kfree(encoder);
2572}
2573
2574static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2575        .destroy = amdgpu_dm_encoder_destroy,
2576};
2577
2578
2579static int fill_dc_scaling_info(const struct drm_plane_state *state,
2580                                struct dc_scaling_info *scaling_info)
2581{
2582        int scale_w, scale_h;
2583
2584        memset(scaling_info, 0, sizeof(*scaling_info));
2585
2586        /* Source is fixed 16.16 but we ignore mantissa for now... */
2587        scaling_info->src_rect.x = state->src_x >> 16;
2588        scaling_info->src_rect.y = state->src_y >> 16;
2589
2590        scaling_info->src_rect.width = state->src_w >> 16;
2591        if (scaling_info->src_rect.width == 0)
2592                return -EINVAL;
2593
2594        scaling_info->src_rect.height = state->src_h >> 16;
2595        if (scaling_info->src_rect.height == 0)
2596                return -EINVAL;
2597
2598        scaling_info->dst_rect.x = state->crtc_x;
2599        scaling_info->dst_rect.y = state->crtc_y;
2600
2601        if (state->crtc_w == 0)
2602                return -EINVAL;
2603
2604        scaling_info->dst_rect.width = state->crtc_w;
2605
2606        if (state->crtc_h == 0)
2607                return -EINVAL;
2608
2609        scaling_info->dst_rect.height = state->crtc_h;
2610
2611        /* DRM doesn't specify clipping on destination output. */
2612        scaling_info->clip_rect = scaling_info->dst_rect;
2613
2614        /* TODO: Validate scaling per-format with DC plane caps */
2615        scale_w = scaling_info->dst_rect.width * 1000 /
2616                  scaling_info->src_rect.width;
2617
2618        if (scale_w < 250 || scale_w > 16000)
2619                return -EINVAL;
2620
2621        scale_h = scaling_info->dst_rect.height * 1000 /
2622                  scaling_info->src_rect.height;
2623
2624        if (scale_h < 250 || scale_h > 16000)
2625                return -EINVAL;
2626
2627        /*
2628         * The "scaling_quality" can be ignored for now, quality = 0 has DC
2629         * assume reasonable defaults based on the format.
2630         */
2631
2632        return 0;
2633}
2634
2635static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2636                       uint64_t *tiling_flags)
2637{
2638        struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2639        int r = amdgpu_bo_reserve(rbo, false);
2640
2641        if (unlikely(r)) {
2642                /* Don't show error message when returning -ERESTARTSYS */
2643                if (r != -ERESTARTSYS)
2644                        DRM_ERROR("Unable to reserve buffer: %d\n", r);
2645                return r;
2646        }
2647
2648        if (tiling_flags)
2649                amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2650
2651        amdgpu_bo_unreserve(rbo);
2652
2653        return r;
2654}
2655
2656static inline uint64_t get_dcc_address(uint64_t address, uint64_t tiling_flags)
2657{
2658        uint32_t offset = AMDGPU_TILING_GET(tiling_flags, DCC_OFFSET_256B);
2659
2660        return offset ? (address + offset * 256) : 0;
2661}
2662
2663static int
2664fill_plane_dcc_attributes(struct amdgpu_device *adev,
2665                          const struct amdgpu_framebuffer *afb,
2666                          const enum surface_pixel_format format,
2667                          const enum dc_rotation_angle rotation,
2668                          const union plane_size *plane_size,
2669                          const union dc_tiling_info *tiling_info,
2670                          const uint64_t info,
2671                          struct dc_plane_dcc_param *dcc,
2672                          struct dc_plane_address *address)
2673{
2674        struct dc *dc = adev->dm.dc;
2675        struct dc_dcc_surface_param input;
2676        struct dc_surface_dcc_cap output;
2677        uint32_t offset = AMDGPU_TILING_GET(info, DCC_OFFSET_256B);
2678        uint32_t i64b = AMDGPU_TILING_GET(info, DCC_INDEPENDENT_64B) != 0;
2679        uint64_t dcc_address;
2680
2681        memset(&input, 0, sizeof(input));
2682        memset(&output, 0, sizeof(output));
2683
2684        if (!offset)
2685                return 0;
2686
2687        if (format >= SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2688                return 0;
2689
2690        if (!dc->cap_funcs.get_dcc_compression_cap)
2691                return -EINVAL;
2692
2693        input.format = format;
2694        input.surface_size.width = plane_size->grph.surface_size.width;
2695        input.surface_size.height = plane_size->grph.surface_size.height;
2696        input.swizzle_mode = tiling_info->gfx9.swizzle;
2697
2698        if (rotation == ROTATION_ANGLE_0 || rotation == ROTATION_ANGLE_180)
2699                input.scan = SCAN_DIRECTION_HORIZONTAL;
2700        else if (rotation == ROTATION_ANGLE_90 || rotation == ROTATION_ANGLE_270)
2701                input.scan = SCAN_DIRECTION_VERTICAL;
2702
2703        if (!dc->cap_funcs.get_dcc_compression_cap(dc, &input, &output))
2704                return -EINVAL;
2705
2706        if (!output.capable)
2707                return -EINVAL;
2708
2709        if (i64b == 0 && output.grph.rgb.independent_64b_blks != 0)
2710                return -EINVAL;
2711
2712        dcc->enable = 1;
2713        dcc->grph.meta_pitch =
2714                AMDGPU_TILING_GET(info, DCC_PITCH_MAX) + 1;
2715        dcc->grph.independent_64b_blks = i64b;
2716
2717        dcc_address = get_dcc_address(afb->address, info);
2718        address->grph.meta_addr.low_part = lower_32_bits(dcc_address);
2719        address->grph.meta_addr.high_part = upper_32_bits(dcc_address);
2720
2721        return 0;
2722}
2723
2724static int
2725fill_plane_buffer_attributes(struct amdgpu_device *adev,
2726                             const struct amdgpu_framebuffer *afb,
2727                             const enum surface_pixel_format format,
2728                             const enum dc_rotation_angle rotation,
2729                             const uint64_t tiling_flags,
2730                             union dc_tiling_info *tiling_info,
2731                             union plane_size *plane_size,
2732                             struct dc_plane_dcc_param *dcc,
2733                             struct dc_plane_address *address)
2734{
2735        const struct drm_framebuffer *fb = &afb->base;
2736        int ret;
2737
2738        memset(tiling_info, 0, sizeof(*tiling_info));
2739        memset(plane_size, 0, sizeof(*plane_size));
2740        memset(dcc, 0, sizeof(*dcc));
2741        memset(address, 0, sizeof(*address));
2742
2743        if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2744                plane_size->grph.surface_size.x = 0;
2745                plane_size->grph.surface_size.y = 0;
2746                plane_size->grph.surface_size.width = fb->width;
2747                plane_size->grph.surface_size.height = fb->height;
2748                plane_size->grph.surface_pitch =
2749                        fb->pitches[0] / fb->format->cpp[0];
2750
2751                address->type = PLN_ADDR_TYPE_GRAPHICS;
2752                address->grph.addr.low_part = lower_32_bits(afb->address);
2753                address->grph.addr.high_part = upper_32_bits(afb->address);
2754        } else if (format < SURFACE_PIXEL_FORMAT_INVALID) {
2755                uint64_t chroma_addr = afb->address + fb->offsets[1];
2756
2757                plane_size->video.luma_size.x = 0;
2758                plane_size->video.luma_size.y = 0;
2759                plane_size->video.luma_size.width = fb->width;
2760                plane_size->video.luma_size.height = fb->height;
2761                plane_size->video.luma_pitch =
2762                        fb->pitches[0] / fb->format->cpp[0];
2763
2764                plane_size->video.chroma_size.x = 0;
2765                plane_size->video.chroma_size.y = 0;
2766                /* TODO: set these based on surface format */
2767                plane_size->video.chroma_size.width = fb->width / 2;
2768                plane_size->video.chroma_size.height = fb->height / 2;
2769
2770                plane_size->video.chroma_pitch =
2771                        fb->pitches[1] / fb->format->cpp[1];
2772
2773                address->type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2774                address->video_progressive.luma_addr.low_part =
2775                        lower_32_bits(afb->address);
2776                address->video_progressive.luma_addr.high_part =
2777                        upper_32_bits(afb->address);
2778                address->video_progressive.chroma_addr.low_part =
2779                        lower_32_bits(chroma_addr);
2780                address->video_progressive.chroma_addr.high_part =
2781                        upper_32_bits(chroma_addr);
2782        }
2783
2784        /* Fill GFX8 params */
2785        if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2786                unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2787
2788                bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2789                bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2790                mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2791                tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2792                num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2793
2794                /* XXX fix me for VI */
2795                tiling_info->gfx8.num_banks = num_banks;
2796                tiling_info->gfx8.array_mode =
2797                                DC_ARRAY_2D_TILED_THIN1;
2798                tiling_info->gfx8.tile_split = tile_split;
2799                tiling_info->gfx8.bank_width = bankw;
2800                tiling_info->gfx8.bank_height = bankh;
2801                tiling_info->gfx8.tile_aspect = mtaspect;
2802                tiling_info->gfx8.tile_mode =
2803                                DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2804        } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2805                        == DC_ARRAY_1D_TILED_THIN1) {
2806                tiling_info->gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2807        }
2808
2809        tiling_info->gfx8.pipe_config =
2810                        AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2811
2812        if (adev->asic_type == CHIP_VEGA10 ||
2813            adev->asic_type == CHIP_VEGA12 ||
2814            adev->asic_type == CHIP_VEGA20 ||
2815#if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2816            adev->asic_type == CHIP_NAVI10 ||
2817#endif
2818            adev->asic_type == CHIP_RAVEN) {
2819                /* Fill GFX9 params */
2820                tiling_info->gfx9.num_pipes =
2821                        adev->gfx.config.gb_addr_config_fields.num_pipes;
2822                tiling_info->gfx9.num_banks =
2823                        adev->gfx.config.gb_addr_config_fields.num_banks;
2824                tiling_info->gfx9.pipe_interleave =
2825                        adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2826                tiling_info->gfx9.num_shader_engines =
2827                        adev->gfx.config.gb_addr_config_fields.num_se;
2828                tiling_info->gfx9.max_compressed_frags =
2829                        adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2830                tiling_info->gfx9.num_rb_per_se =
2831                        adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2832                tiling_info->gfx9.swizzle =
2833                        AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2834                tiling_info->gfx9.shaderEnable = 1;
2835
2836                ret = fill_plane_dcc_attributes(adev, afb, format, rotation,
2837                                                plane_size, tiling_info,
2838                                                tiling_flags, dcc, address);
2839                if (ret)
2840                        return ret;
2841        }
2842
2843        return 0;
2844}
2845
2846static void
2847fill_blending_from_plane_state(const struct drm_plane_state *plane_state,
2848                               bool *per_pixel_alpha, bool *global_alpha,
2849                               int *global_alpha_value)
2850{
2851        *per_pixel_alpha = false;
2852        *global_alpha = false;
2853        *global_alpha_value = 0xff;
2854
2855        if (plane_state->plane->type != DRM_PLANE_TYPE_OVERLAY)
2856                return;
2857
2858        if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) {
2859                static const uint32_t alpha_formats[] = {
2860                        DRM_FORMAT_ARGB8888,
2861                        DRM_FORMAT_RGBA8888,
2862                        DRM_FORMAT_ABGR8888,
2863                };
2864                uint32_t format = plane_state->fb->format->format;
2865                unsigned int i;
2866
2867                for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
2868                        if (format == alpha_formats[i]) {
2869                                *per_pixel_alpha = true;
2870                                break;
2871                        }
2872                }
2873        }
2874
2875        if (plane_state->alpha < 0xffff) {
2876                *global_alpha = true;
2877                *global_alpha_value = plane_state->alpha >> 8;
2878        }
2879}
2880
2881static int
2882fill_plane_color_attributes(const struct drm_plane_state *plane_state,
2883                            const enum surface_pixel_format format,
2884                            enum dc_color_space *color_space)
2885{
2886        bool full_range;
2887
2888        *color_space = COLOR_SPACE_SRGB;
2889
2890        /* DRM color properties only affect non-RGB formats. */
2891        if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2892                return 0;
2893
2894        full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2895
2896        switch (plane_state->color_encoding) {
2897        case DRM_COLOR_YCBCR_BT601:
2898                if (full_range)
2899                        *color_space = COLOR_SPACE_YCBCR601;
2900                else
2901                        *color_space = COLOR_SPACE_YCBCR601_LIMITED;
2902                break;
2903
2904        case DRM_COLOR_YCBCR_BT709:
2905                if (full_range)
2906                        *color_space = COLOR_SPACE_YCBCR709;
2907                else
2908                        *color_space = COLOR_SPACE_YCBCR709_LIMITED;
2909                break;
2910
2911        case DRM_COLOR_YCBCR_BT2020:
2912                if (full_range)
2913                        *color_space = COLOR_SPACE_2020_YCBCR;
2914                else
2915                        return -EINVAL;
2916                break;
2917
2918        default:
2919                return -EINVAL;
2920        }
2921
2922        return 0;
2923}
2924
2925static int
2926fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2927                            const struct drm_plane_state *plane_state,
2928                            const uint64_t tiling_flags,
2929                            struct dc_plane_info *plane_info,
2930                            struct dc_plane_address *address)
2931{
2932        const struct drm_framebuffer *fb = plane_state->fb;
2933        const struct amdgpu_framebuffer *afb =
2934                to_amdgpu_framebuffer(plane_state->fb);
2935        struct drm_format_name_buf format_name;
2936        int ret;
2937
2938        memset(plane_info, 0, sizeof(*plane_info));
2939
2940        switch (fb->format->format) {
2941        case DRM_FORMAT_C8:
2942                plane_info->format =
2943                        SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2944                break;
2945        case DRM_FORMAT_RGB565:
2946                plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2947                break;
2948        case DRM_FORMAT_XRGB8888:
2949        case DRM_FORMAT_ARGB8888:
2950                plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2951                break;
2952        case DRM_FORMAT_XRGB2101010:
2953        case DRM_FORMAT_ARGB2101010:
2954                plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2955                break;
2956        case DRM_FORMAT_XBGR2101010:
2957        case DRM_FORMAT_ABGR2101010:
2958                plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2959                break;
2960        case DRM_FORMAT_XBGR8888:
2961        case DRM_FORMAT_ABGR8888:
2962                plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2963                break;
2964        case DRM_FORMAT_NV21:
2965                plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2966                break;
2967        case DRM_FORMAT_NV12:
2968                plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2969                break;
2970        default:
2971                DRM_ERROR(
2972                        "Unsupported screen format %s\n",
2973                        drm_get_format_name(fb->format->format, &format_name));
2974                return -EINVAL;
2975        }
2976
2977        switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
2978        case DRM_MODE_ROTATE_0:
2979                plane_info->rotation = ROTATION_ANGLE_0;
2980                break;
2981        case DRM_MODE_ROTATE_90:
2982                plane_info->rotation = ROTATION_ANGLE_90;
2983                break;
2984        case DRM_MODE_ROTATE_180:
2985                plane_info->rotation = ROTATION_ANGLE_180;
2986                break;
2987        case DRM_MODE_ROTATE_270:
2988                plane_info->rotation = ROTATION_ANGLE_270;
2989                break;
2990        default:
2991                plane_info->rotation = ROTATION_ANGLE_0;
2992                break;
2993        }
2994
2995        plane_info->visible = true;
2996        plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
2997
2998        ret = fill_plane_color_attributes(plane_state, plane_info->format,
2999                                          &plane_info->color_space);
3000        if (ret)
3001                return ret;
3002
3003        ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
3004                                           plane_info->rotation, tiling_flags,
3005                                           &plane_info->tiling_info,
3006                                           &plane_info->plane_size,
3007                                           &plane_info->dcc, address);
3008        if (ret)
3009                return ret;
3010
3011        fill_blending_from_plane_state(
3012                plane_state, &plane_info->per_pixel_alpha,
3013                &plane_info->global_alpha, &plane_info->global_alpha_value);
3014
3015        return 0;
3016}
3017
3018static int fill_dc_plane_attributes(struct amdgpu_device *adev,
3019                                    struct dc_plane_state *dc_plane_state,
3020                                    struct drm_plane_state *plane_state,
3021                                    struct drm_crtc_state *crtc_state)
3022{
3023        struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3024        const struct amdgpu_framebuffer *amdgpu_fb =
3025                to_amdgpu_framebuffer(plane_state->fb);
3026        struct dc_scaling_info scaling_info;
3027        struct dc_plane_info plane_info;
3028        uint64_t tiling_flags;
3029        int ret;
3030
3031        ret = fill_dc_scaling_info(plane_state, &scaling_info);
3032        if (ret)
3033                return ret;
3034
3035        dc_plane_state->src_rect = scaling_info.src_rect;
3036        dc_plane_state->dst_rect = scaling_info.dst_rect;
3037        dc_plane_state->clip_rect = scaling_info.clip_rect;
3038        dc_plane_state->scaling_quality = scaling_info.scaling_quality;
3039
3040        ret = get_fb_info(amdgpu_fb, &tiling_flags);
3041        if (ret)
3042                return ret;
3043
3044        ret = fill_dc_plane_info_and_addr(adev, plane_state, tiling_flags,
3045                                          &plane_info,
3046                                          &dc_plane_state->address);
3047        if (ret)
3048                return ret;
3049
3050        dc_plane_state->format = plane_info.format;
3051        dc_plane_state->color_space = plane_info.color_space;
3052        dc_plane_state->format = plane_info.format;
3053        dc_plane_state->plane_size = plane_info.plane_size;
3054        dc_plane_state->rotation = plane_info.rotation;
3055        dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
3056        dc_plane_state->stereo_format = plane_info.stereo_format;
3057        dc_plane_state->tiling_info = plane_info.tiling_info;
3058        dc_plane_state->visible = plane_info.visible;
3059        dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
3060        dc_plane_state->global_alpha = plane_info.global_alpha;
3061        dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
3062        dc_plane_state->dcc = plane_info.dcc;
3063
3064        /*
3065         * Always set input transfer function, since plane state is refreshed
3066         * every time.
3067         */
3068        ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
3069        if (ret)
3070                return ret;
3071
3072        return 0;
3073}
3074
3075static void update_stream_scaling_settings(const struct drm_display_mode *mode,
3076                                           const struct dm_connector_state *dm_state,
3077                                           struct dc_stream_state *stream)
3078{
3079        enum amdgpu_rmx_type rmx_type;
3080
3081        struct rect src = { 0 }; /* viewport in composition space*/
3082        struct rect dst = { 0 }; /* stream addressable area */
3083
3084        /* no mode. nothing to be done */
3085        if (!mode)
3086                return;
3087
3088        /* Full screen scaling by default */
3089        src.width = mode->hdisplay;
3090        src.height = mode->vdisplay;
3091        dst.width = stream->timing.h_addressable;
3092        dst.height = stream->timing.v_addressable;
3093
3094        if (dm_state) {
3095                rmx_type = dm_state->scaling;
3096                if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
3097                        if (src.width * dst.height <
3098                                        src.height * dst.width) {
3099                                /* height needs less upscaling/more downscaling */
3100                                dst.width = src.width *
3101                                                dst.height / src.height;
3102                        } else {
3103                                /* width needs less upscaling/more downscaling */
3104                                dst.height = src.height *
3105                                                dst.width / src.width;
3106                        }
3107                } else if (rmx_type == RMX_CENTER) {
3108                        dst = src;
3109                }
3110
3111                dst.x = (stream->timing.h_addressable - dst.width) / 2;
3112                dst.y = (stream->timing.v_addressable - dst.height) / 2;
3113
3114                if (dm_state->underscan_enable) {
3115                        dst.x += dm_state->underscan_hborder / 2;
3116                        dst.y += dm_state->underscan_vborder / 2;
3117                        dst.width -= dm_state->underscan_hborder;
3118                        dst.height -= dm_state->underscan_vborder;
3119                }
3120        }
3121
3122        stream->src = src;
3123        stream->dst = dst;
3124
3125        DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
3126                        dst.x, dst.y, dst.width, dst.height);
3127
3128}
3129
3130static enum dc_color_depth
3131convert_color_depth_from_display_info(const struct drm_connector *connector,
3132                                      const struct drm_connector_state *state)
3133{
3134        uint8_t bpc = (uint8_t)connector->display_info.bpc;
3135
3136        /* Assume 8 bpc by default if no bpc is specified. */
3137        bpc = bpc ? bpc : 8;
3138
3139        if (!state)
3140                state = connector->state;
3141
3142        if (state) {
3143                /*
3144                 * Cap display bpc based on the user requested value.
3145                 *
3146                 * The value for state->max_bpc may not correctly updated
3147                 * depending on when the connector gets added to the state
3148                 * or if this was called outside of atomic check, so it
3149                 * can't be used directly.
3150                 */
3151                bpc = min(bpc, state->max_requested_bpc);
3152
3153                /* Round down to the nearest even number. */
3154                bpc = bpc - (bpc & 1);
3155        }
3156
3157        switch (bpc) {
3158        case 0:
3159                /*
3160                 * Temporary Work around, DRM doesn't parse color depth for
3161                 * EDID revision before 1.4
3162                 * TODO: Fix edid parsing
3163                 */
3164                return COLOR_DEPTH_888;
3165        case 6:
3166                return COLOR_DEPTH_666;
3167        case 8:
3168                return COLOR_DEPTH_888;
3169        case 10:
3170                return COLOR_DEPTH_101010;
3171        case 12:
3172                return COLOR_DEPTH_121212;
3173        case 14:
3174                return COLOR_DEPTH_141414;
3175        case 16:
3176                return COLOR_DEPTH_161616;
3177        default:
3178                return COLOR_DEPTH_UNDEFINED;
3179        }
3180}
3181
3182static enum dc_aspect_ratio
3183get_aspect_ratio(const struct drm_display_mode *mode_in)
3184{
3185        /* 1-1 mapping, since both enums follow the HDMI spec. */
3186        return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
3187}
3188
3189static enum dc_color_space
3190get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
3191{
3192        enum dc_color_space color_space = COLOR_SPACE_SRGB;
3193
3194        switch (dc_crtc_timing->pixel_encoding) {
3195        case PIXEL_ENCODING_YCBCR422:
3196        case PIXEL_ENCODING_YCBCR444:
3197        case PIXEL_ENCODING_YCBCR420:
3198        {
3199                /*
3200                 * 27030khz is the separation point between HDTV and SDTV
3201                 * according to HDMI spec, we use YCbCr709 and YCbCr601
3202                 * respectively
3203                 */
3204                if (dc_crtc_timing->pix_clk_100hz > 270300) {
3205                        if (dc_crtc_timing->flags.Y_ONLY)
3206                                color_space =
3207                                        COLOR_SPACE_YCBCR709_LIMITED;
3208                        else
3209                                color_space = COLOR_SPACE_YCBCR709;
3210                } else {
3211                        if (dc_crtc_timing->flags.Y_ONLY)
3212                                color_space =
3213                                        COLOR_SPACE_YCBCR601_LIMITED;
3214                        else
3215                                color_space = COLOR_SPACE_YCBCR601;
3216                }
3217
3218        }
3219        break;
3220        case PIXEL_ENCODING_RGB:
3221                color_space = COLOR_SPACE_SRGB;
3222                break;
3223
3224        default:
3225                WARN_ON(1);
3226                break;
3227        }
3228
3229        return color_space;
3230}
3231
3232static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
3233{
3234        if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3235                return;
3236
3237        timing_out->display_color_depth--;
3238}
3239
3240static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
3241                                                const struct drm_display_info *info)
3242{
3243        int normalized_clk;
3244        if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3245                return;
3246        do {
3247                normalized_clk = timing_out->pix_clk_100hz / 10;
3248                /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
3249                if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3250                        normalized_clk /= 2;
3251                /* Adjusting pix clock following on HDMI spec based on colour depth */
3252                switch (timing_out->display_color_depth) {
3253                case COLOR_DEPTH_101010:
3254                        normalized_clk = (normalized_clk * 30) / 24;
3255                        break;
3256                case COLOR_DEPTH_121212:
3257                        normalized_clk = (normalized_clk * 36) / 24;
3258                        break;
3259                case COLOR_DEPTH_161616:
3260                        normalized_clk = (normalized_clk * 48) / 24;
3261                        break;
3262                default:
3263                        return;
3264                }
3265                if (normalized_clk <= info->max_tmds_clock)
3266                        return;
3267                reduce_mode_colour_depth(timing_out);
3268
3269        } while (timing_out->display_color_depth > COLOR_DEPTH_888);
3270
3271}
3272
3273static void fill_stream_properties_from_drm_display_mode(
3274        struct dc_stream_state *stream,
3275        const struct drm_display_mode *mode_in,
3276        const struct drm_connector *connector,
3277        const struct drm_connector_state *connector_state,
3278        const struct dc_stream_state *old_stream)
3279{
3280        struct dc_crtc_timing *timing_out = &stream->timing;
3281        const struct drm_display_info *info = &connector->display_info;
3282
3283        memset(timing_out, 0, sizeof(struct dc_crtc_timing));
3284
3285        timing_out->h_border_left = 0;
3286        timing_out->h_border_right = 0;
3287        timing_out->v_border_top = 0;
3288        timing_out->v_border_bottom = 0;
3289        /* TODO: un-hardcode */
3290        if (drm_mode_is_420_only(info, mode_in)
3291                        && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3292                timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3293        else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
3294                        && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3295                timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
3296        else
3297                timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
3298
3299        timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
3300        timing_out->display_color_depth = convert_color_depth_from_display_info(
3301                connector, connector_state);
3302        timing_out->scan_type = SCANNING_TYPE_NODATA;
3303        timing_out->hdmi_vic = 0;
3304
3305        if(old_stream) {
3306                timing_out->vic = old_stream->timing.vic;
3307                timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
3308                timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
3309        } else {
3310                timing_out->vic = drm_match_cea_mode(mode_in);
3311                if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
3312                        timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
3313                if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
3314                        timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
3315        }
3316
3317        timing_out->h_addressable = mode_in->crtc_hdisplay;
3318        timing_out->h_total = mode_in->crtc_htotal;
3319        timing_out->h_sync_width =
3320                mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
3321        timing_out->h_front_porch =
3322                mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
3323        timing_out->v_total = mode_in->crtc_vtotal;
3324        timing_out->v_addressable = mode_in->crtc_vdisplay;
3325        timing_out->v_front_porch =
3326                mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
3327        timing_out->v_sync_width =
3328                mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
3329        timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
3330        timing_out->aspect_ratio = get_aspect_ratio(mode_in);
3331
3332        stream->output_color_space = get_output_color_space(timing_out);
3333
3334        stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
3335        stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
3336        if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3337                adjust_colour_depth_from_display_info(timing_out, info);
3338}
3339
3340static void fill_audio_info(struct audio_info *audio_info,
3341                            const struct drm_connector *drm_connector,
3342                            const struct dc_sink *dc_sink)
3343{
3344        int i = 0;
3345        int cea_revision = 0;
3346        const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
3347
3348        audio_info->manufacture_id = edid_caps->manufacturer_id;
3349        audio_info->product_id = edid_caps->product_id;
3350
3351        cea_revision = drm_connector->display_info.cea_rev;
3352
3353        strscpy(audio_info->display_name,
3354                edid_caps->display_name,
3355                AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
3356
3357        if (cea_revision >= 3) {
3358                audio_info->mode_count = edid_caps->audio_mode_count;
3359
3360                for (i = 0; i < audio_info->mode_count; ++i) {
3361                        audio_info->modes[i].format_code =
3362                                        (enum audio_format_code)
3363                                        (edid_caps->audio_modes[i].format_code);
3364                        audio_info->modes[i].channel_count =
3365                                        edid_caps->audio_modes[i].channel_count;
3366                        audio_info->modes[i].sample_rates.all =
3367                                        edid_caps->audio_modes[i].sample_rate;
3368                        audio_info->modes[i].sample_size =
3369                                        edid_caps->audio_modes[i].sample_size;
3370                }
3371        }
3372
3373        audio_info->flags.all = edid_caps->speaker_flags;
3374
3375        /* TODO: We only check for the progressive mode, check for interlace mode too */
3376        if (drm_connector->latency_present[0]) {
3377                audio_info->video_latency = drm_connector->video_latency[0];
3378                audio_info->audio_latency = drm_connector->audio_latency[0];
3379        }
3380
3381        /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
3382
3383}
3384
3385static void
3386copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
3387                                      struct drm_display_mode *dst_mode)
3388{
3389        dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
3390        dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
3391        dst_mode->crtc_clock = src_mode->crtc_clock;
3392        dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
3393        dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
3394        dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
3395        dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
3396        dst_mode->crtc_htotal = src_mode->crtc_htotal;
3397        dst_mode->crtc_hskew = src_mode->crtc_hskew;
3398        dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
3399        dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
3400        dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
3401        dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
3402        dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
3403}
3404
3405static void
3406decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
3407                                        const struct drm_display_mode *native_mode,
3408                                        bool scale_enabled)
3409{
3410        if (scale_enabled) {
3411                copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3412        } else if (native_mode->clock == drm_mode->clock &&
3413                        native_mode->htotal == drm_mode->htotal &&
3414                        native_mode->vtotal == drm_mode->vtotal) {
3415                copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3416        } else {
3417                /* no scaling nor amdgpu inserted, no need to patch */
3418        }
3419}
3420
3421static struct dc_sink *
3422create_fake_sink(struct amdgpu_dm_connector *aconnector)
3423{
3424        struct dc_sink_init_data sink_init_data = { 0 };
3425        struct dc_sink *sink = NULL;
3426        sink_init_data.link = aconnector->dc_link;
3427        sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
3428
3429        sink = dc_sink_create(&sink_init_data);
3430        if (!sink) {
3431                DRM_ERROR("Failed to create sink!\n");
3432                return NULL;
3433        }
3434        sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
3435
3436        return sink;
3437}
3438
3439static void set_multisync_trigger_params(
3440                struct dc_stream_state *stream)
3441{
3442        if (stream->triggered_crtc_reset.enabled) {
3443                stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
3444                stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
3445        }
3446}
3447
3448static void set_master_stream(struct dc_stream_state *stream_set[],
3449                              int stream_count)
3450{
3451        int j, highest_rfr = 0, master_stream = 0;
3452
3453        for (j = 0;  j < stream_count; j++) {
3454                if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
3455                        int refresh_rate = 0;
3456
3457                        refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
3458                                (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
3459                        if (refresh_rate > highest_rfr) {
3460                                highest_rfr = refresh_rate;
3461                                master_stream = j;
3462                        }
3463                }
3464        }
3465        for (j = 0;  j < stream_count; j++) {
3466                if (stream_set[j])
3467                        stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
3468        }
3469}
3470
3471static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
3472{
3473        int i = 0;
3474
3475        if (context->stream_count < 2)
3476                return;
3477        for (i = 0; i < context->stream_count ; i++) {
3478                if (!context->streams[i])
3479                        continue;
3480                /*
3481                 * TODO: add a function to read AMD VSDB bits and set
3482                 * crtc_sync_master.multi_sync_enabled flag
3483                 * For now it's set to false
3484                 */
3485                set_multisync_trigger_params(context->streams[i]);
3486        }
3487        set_master_stream(context->streams, context->stream_count);
3488}
3489
3490static struct dc_stream_state *
3491create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
3492                       const struct drm_display_mode *drm_mode,
3493                       const struct dm_connector_state *dm_state,
3494                       const struct dc_stream_state *old_stream)
3495{
3496        struct drm_display_mode *preferred_mode = NULL;
3497        struct drm_connector *drm_connector;
3498        const struct drm_connector_state *con_state =
3499                dm_state ? &dm_state->base : NULL;
3500        struct dc_stream_state *stream = NULL;
3501        struct drm_display_mode mode = *drm_mode;
3502        bool native_mode_found = false;
3503        bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
3504        int mode_refresh;
3505        int preferred_refresh = 0;
3506
3507        struct dc_sink *sink = NULL;
3508        if (aconnector == NULL) {
3509                DRM_ERROR("aconnector is NULL!\n");
3510                return stream;
3511        }
3512
3513        drm_connector = &aconnector->base;
3514
3515        if (!aconnector->dc_sink) {
3516                sink = create_fake_sink(aconnector);
3517                if (!sink)
3518                        return stream;
3519        } else {
3520                sink = aconnector->dc_sink;
3521                dc_sink_retain(sink);
3522        }
3523
3524        stream = dc_create_stream_for_sink(sink);
3525
3526        if (stream == NULL) {
3527                DRM_ERROR("Failed to create stream for sink!\n");
3528                goto finish;
3529        }
3530
3531        stream->dm_stream_context = aconnector;
3532
3533        list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
3534                /* Search for preferred mode */
3535                if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
3536                        native_mode_found = true;
3537                        break;
3538                }
3539        }
3540        if (!native_mode_found)
3541                preferred_mode = list_first_entry_or_null(
3542                                &aconnector->base.modes,
3543                                struct drm_display_mode,
3544                                head);
3545
3546        mode_refresh = drm_mode_vrefresh(&mode);
3547
3548        if (preferred_mode == NULL) {
3549                /*
3550                 * This may not be an error, the use case is when we have no
3551                 * usermode calls to reset and set mode upon hotplug. In this
3552                 * case, we call set mode ourselves to restore the previous mode
3553                 * and the modelist may not be filled in in time.
3554                 */
3555                DRM_DEBUG_DRIVER("No preferred mode found\n");
3556        } else {
3557                decide_crtc_timing_for_drm_display_mode(
3558                                &mode, preferred_mode,
3559                                dm_state ? (dm_state->scaling != RMX_OFF) : false);
3560                preferred_refresh = drm_mode_vrefresh(preferred_mode);
3561        }
3562
3563        if (!dm_state)
3564                drm_mode_set_crtcinfo(&mode, 0);
3565
3566        /*
3567        * If scaling is enabled and refresh rate didn't change
3568        * we copy the vic and polarities of the old timings
3569        */
3570        if (!scale || mode_refresh != preferred_refresh)
3571                fill_stream_properties_from_drm_display_mode(stream,
3572                        &mode, &aconnector->base, con_state, NULL);
3573        else
3574                fill_stream_properties_from_drm_display_mode(stream,
3575                        &mode, &aconnector->base, con_state, old_stream);
3576
3577#ifdef CONFIG_DRM_AMD_DC_DSC_SUPPORT
3578        /* stream->timing.flags.DSC = 0; */
3579        /*  */
3580        /* if (aconnector->dc_link && */
3581        /*              aconnector->dc_link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT #<{(|&& */
3582        /*              aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.is_dsc_supported|)}>#) */
3583        /*      if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc, */
3584        /*                      &aconnector->dc_link->dpcd_caps.dsc_caps, */
3585        /*                      dc_link_bandwidth_kbps(aconnector->dc_link, dc_link_get_link_cap(aconnector->dc_link)), */
3586        /*                      &stream->timing, */
3587        /*                      &stream->timing.dsc_cfg)) */
3588        /*              stream->timing.flags.DSC = 1; */
3589#endif
3590
3591        update_stream_scaling_settings(&mode, dm_state, stream);
3592
3593        fill_audio_info(
3594                &stream->audio_info,
3595                drm_connector,
3596                sink);
3597
3598        update_stream_signal(stream, sink);
3599
3600finish:
3601        dc_sink_release(sink);
3602
3603        return stream;
3604}
3605
3606static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
3607{
3608        drm_crtc_cleanup(crtc);
3609        kfree(crtc);
3610}
3611
3612static void dm_crtc_destroy_state(struct drm_crtc *crtc,
3613                                  struct drm_crtc_state *state)
3614{
3615        struct dm_crtc_state *cur = to_dm_crtc_state(state);
3616
3617        /* TODO Destroy dc_stream objects are stream object is flattened */
3618        if (cur->stream)
3619                dc_stream_release(cur->stream);
3620
3621
3622        __drm_atomic_helper_crtc_destroy_state(state);
3623
3624
3625        kfree(state);
3626}
3627
3628static void dm_crtc_reset_state(struct drm_crtc *crtc)
3629{
3630        struct dm_crtc_state *state;
3631
3632        if (crtc->state)
3633                dm_crtc_destroy_state(crtc, crtc->state);
3634
3635        state = kzalloc(sizeof(*state), GFP_KERNEL);
3636        if (WARN_ON(!state))
3637                return;
3638
3639        crtc->state = &state->base;
3640        crtc->state->crtc = crtc;
3641
3642}
3643
3644static struct drm_crtc_state *
3645dm_crtc_duplicate_state(struct drm_crtc *crtc)
3646{
3647        struct dm_crtc_state *state, *cur;
3648
3649        cur = to_dm_crtc_state(crtc->state);
3650
3651        if (WARN_ON(!crtc->state))
3652                return NULL;
3653
3654        state = kzalloc(sizeof(*state), GFP_KERNEL);
3655        if (!state)
3656                return NULL;
3657
3658        __drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
3659
3660        if (cur->stream) {
3661                state->stream = cur->stream;
3662                dc_stream_retain(state->stream);
3663        }
3664
3665        state->active_planes = cur->active_planes;
3666        state->interrupts_enabled = cur->interrupts_enabled;
3667        state->vrr_params = cur->vrr_params;
3668        state->vrr_infopacket = cur->vrr_infopacket;
3669        state->abm_level = cur->abm_level;
3670        state->vrr_supported = cur->vrr_supported;
3671        state->freesync_config = cur->freesync_config;
3672        state->crc_enabled = cur->crc_enabled;
3673        state->cm_has_degamma = cur->cm_has_degamma;
3674        state->cm_is_degamma_srgb = cur->cm_is_degamma_srgb;
3675
3676        /* TODO Duplicate dc_stream after objects are stream object is flattened */
3677
3678        return &state->base;
3679}
3680
3681static inline int dm_set_vupdate_irq(struct drm_crtc *crtc, bool enable)
3682{
3683        enum dc_irq_source irq_source;
3684        struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3685        struct amdgpu_device *adev = crtc->dev->dev_private;
3686        int rc;
3687
3688        irq_source = IRQ_TYPE_VUPDATE + acrtc->otg_inst;
3689
3690        rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3691
3692        DRM_DEBUG_DRIVER("crtc %d - vupdate irq %sabling: r=%d\n",
3693                         acrtc->crtc_id, enable ? "en" : "dis", rc);
3694        return rc;
3695}
3696
3697static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
3698{
3699        enum dc_irq_source irq_source;
3700        struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3701        struct amdgpu_device *adev = crtc->dev->dev_private;
3702        struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3703        int rc = 0;
3704
3705        if (enable) {
3706                /* vblank irq on -> Only need vupdate irq in vrr mode */
3707                if (amdgpu_dm_vrr_active(acrtc_state))
3708                        rc = dm_set_vupdate_irq(crtc, true);
3709        } else {
3710                /* vblank irq off -> vupdate irq off */
3711                rc = dm_set_vupdate_irq(crtc, false);
3712        }
3713
3714        if (rc)
3715                return rc;
3716
3717        irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3718        return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3719}
3720
3721static int dm_enable_vblank(struct drm_crtc *crtc)
3722{
3723        return dm_set_vblank(crtc, true);
3724}
3725
3726static void dm_disable_vblank(struct drm_crtc *crtc)
3727{
3728        dm_set_vblank(crtc, false);
3729}
3730
3731/* Implemented only the options currently availible for the driver */
3732static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
3733        .reset = dm_crtc_reset_state,
3734        .destroy = amdgpu_dm_crtc_destroy,
3735        .gamma_set = drm_atomic_helper_legacy_gamma_set,
3736        .set_config = drm_atomic_helper_set_config,
3737        .page_flip = drm_atomic_helper_page_flip,
3738        .atomic_duplicate_state = dm_crtc_duplicate_state,
3739        .atomic_destroy_state = dm_crtc_destroy_state,
3740        .set_crc_source = amdgpu_dm_crtc_set_crc_source,
3741        .verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
3742        .enable_vblank = dm_enable_vblank,
3743        .disable_vblank = dm_disable_vblank,
3744};
3745
3746static enum drm_connector_status
3747amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
3748{
3749        bool connected;
3750        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3751
3752        /*
3753         * Notes:
3754         * 1. This interface is NOT called in context of HPD irq.
3755         * 2. This interface *is called* in context of user-mode ioctl. Which
3756         * makes it a bad place for *any* MST-related activity.
3757         */
3758
3759        if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
3760            !aconnector->fake_enable)
3761                connected = (aconnector->dc_sink != NULL);
3762        else
3763                connected = (aconnector->base.force == DRM_FORCE_ON);
3764
3765        return (connected ? connector_status_connected :
3766                        connector_status_disconnected);
3767}
3768
3769int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
3770                                            struct drm_connector_state *connector_state,
3771                                            struct drm_property *property,
3772                                            uint64_t val)
3773{
3774        struct drm_device *dev = connector->dev;
3775        struct amdgpu_device *adev = dev->dev_private;
3776        struct dm_connector_state *dm_old_state =
3777                to_dm_connector_state(connector->state);
3778        struct dm_connector_state *dm_new_state =
3779                to_dm_connector_state(connector_state);
3780
3781        int ret = -EINVAL;
3782
3783        if (property == dev->mode_config.scaling_mode_property) {
3784                enum amdgpu_rmx_type rmx_type;
3785
3786                switch (val) {
3787                case DRM_MODE_SCALE_CENTER:
3788                        rmx_type = RMX_CENTER;
3789                        break;
3790                case DRM_MODE_SCALE_ASPECT:
3791                        rmx_type = RMX_ASPECT;
3792                        break;
3793                case DRM_MODE_SCALE_FULLSCREEN:
3794                        rmx_type = RMX_FULL;
3795                        break;
3796                case DRM_MODE_SCALE_NONE:
3797                default:
3798                        rmx_type = RMX_OFF;
3799                        break;
3800                }
3801
3802                if (dm_old_state->scaling == rmx_type)
3803                        return 0;
3804
3805                dm_new_state->scaling = rmx_type;
3806                ret = 0;
3807        } else if (property == adev->mode_info.underscan_hborder_property) {
3808                dm_new_state->underscan_hborder = val;
3809                ret = 0;
3810        } else if (property == adev->mode_info.underscan_vborder_property) {
3811                dm_new_state->underscan_vborder = val;
3812                ret = 0;
3813        } else if (property == adev->mode_info.underscan_property) {
3814                dm_new_state->underscan_enable = val;
3815                ret = 0;
3816        } else if (property == adev->mode_info.abm_level_property) {
3817                dm_new_state->abm_level = val;
3818                ret = 0;
3819        }
3820
3821        return ret;
3822}
3823
3824int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3825                                            const struct drm_connector_state *state,
3826                                            struct drm_property *property,
3827                                            uint64_t *val)
3828{
3829        struct drm_device *dev = connector->dev;
3830        struct amdgpu_device *adev = dev->dev_private;
3831        struct dm_connector_state *dm_state =
3832                to_dm_connector_state(state);
3833        int ret = -EINVAL;
3834
3835        if (property == dev->mode_config.scaling_mode_property) {
3836                switch (dm_state->scaling) {
3837                case RMX_CENTER:
3838                        *val = DRM_MODE_SCALE_CENTER;
3839                        break;
3840                case RMX_ASPECT:
3841                        *val = DRM_MODE_SCALE_ASPECT;
3842                        break;
3843                case RMX_FULL:
3844                        *val = DRM_MODE_SCALE_FULLSCREEN;
3845                        break;
3846                case RMX_OFF:
3847                default:
3848                        *val = DRM_MODE_SCALE_NONE;
3849                        break;
3850                }
3851                ret = 0;
3852        } else if (property == adev->mode_info.underscan_hborder_property) {
3853                *val = dm_state->underscan_hborder;
3854                ret = 0;
3855        } else if (property == adev->mode_info.underscan_vborder_property) {
3856                *val = dm_state->underscan_vborder;
3857                ret = 0;
3858        } else if (property == adev->mode_info.underscan_property) {
3859                *val = dm_state->underscan_enable;
3860                ret = 0;
3861        } else if (property == adev->mode_info.abm_level_property) {
3862                *val = dm_state->abm_level;
3863                ret = 0;
3864        }
3865
3866        return ret;
3867}
3868
3869static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
3870{
3871        struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
3872
3873        drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
3874}
3875
3876static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
3877{
3878        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3879        const struct dc_link *link = aconnector->dc_link;
3880        struct amdgpu_device *adev = connector->dev->dev_private;
3881        struct amdgpu_display_manager *dm = &adev->dm;
3882
3883#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3884        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3885
3886        if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
3887            link->type != dc_connection_none &&
3888            dm->backlight_dev) {
3889                backlight_device_unregister(dm->backlight_dev);
3890                dm->backlight_dev = NULL;
3891        }
3892#endif
3893
3894        if (aconnector->dc_em_sink)
3895                dc_sink_release(aconnector->dc_em_sink);
3896        aconnector->dc_em_sink = NULL;
3897        if (aconnector->dc_sink)
3898                dc_sink_release(aconnector->dc_sink);
3899        aconnector->dc_sink = NULL;
3900
3901        drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
3902        drm_connector_unregister(connector);
3903        drm_connector_cleanup(connector);
3904        if (aconnector->i2c) {
3905                i2c_del_adapter(&aconnector->i2c->base);
3906                kfree(aconnector->i2c);
3907        }
3908
3909        kfree(connector);
3910}
3911
3912void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
3913{
3914        struct dm_connector_state *state =
3915                to_dm_connector_state(connector->state);
3916
3917        if (connector->state)
3918                __drm_atomic_helper_connector_destroy_state(connector->state);
3919
3920        kfree(state);
3921
3922        state = kzalloc(sizeof(*state), GFP_KERNEL);
3923
3924        if (state) {
3925                state->scaling = RMX_OFF;
3926                state->underscan_enable = false;
3927                state->underscan_hborder = 0;
3928                state->underscan_vborder = 0;
3929                state->base.max_requested_bpc = 8;
3930
3931                if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
3932                        state->abm_level = amdgpu_dm_abm_level;
3933
3934                __drm_atomic_helper_connector_reset(connector, &state->base);
3935        }
3936}
3937
3938struct drm_connector_state *
3939amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
3940{
3941        struct dm_connector_state *state =
3942                to_dm_connector_state(connector->state);
3943
3944        struct dm_connector_state *new_state =
3945                        kmemdup(state, sizeof(*state), GFP_KERNEL);
3946
3947        if (!new_state)
3948                return NULL;
3949
3950        __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
3951
3952        new_state->freesync_capable = state->freesync_capable;
3953        new_state->abm_level = state->abm_level;
3954        new_state->scaling = state->scaling;
3955        new_state->underscan_enable = state->underscan_enable;
3956        new_state->underscan_hborder = state->underscan_hborder;
3957        new_state->underscan_vborder = state->underscan_vborder;
3958
3959        return &new_state->base;
3960}
3961
3962static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
3963        .reset = amdgpu_dm_connector_funcs_reset,
3964        .detect = amdgpu_dm_connector_detect,
3965        .fill_modes = drm_helper_probe_single_connector_modes,
3966        .destroy = amdgpu_dm_connector_destroy,
3967        .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
3968        .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
3969        .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
3970        .atomic_get_property = amdgpu_dm_connector_atomic_get_property,
3971        .early_unregister = amdgpu_dm_connector_unregister
3972};
3973
3974static int get_modes(struct drm_connector *connector)
3975{
3976        return amdgpu_dm_connector_get_modes(connector);
3977}
3978
3979static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
3980{
3981        struct dc_sink_init_data init_params = {
3982                        .link = aconnector->dc_link,
3983                        .sink_signal = SIGNAL_TYPE_VIRTUAL
3984        };
3985        struct edid *edid;
3986
3987        if (!aconnector->base.edid_blob_ptr) {
3988                DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
3989                                aconnector->base.name);
3990
3991                aconnector->base.force = DRM_FORCE_OFF;
3992                aconnector->base.override_edid = false;
3993                return;
3994        }
3995
3996        edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
3997
3998        aconnector->edid = edid;
3999
4000        aconnector->dc_em_sink = dc_link_add_remote_sink(
4001                aconnector->dc_link,
4002                (uint8_t *)edid,
4003                (edid->extensions + 1) * EDID_LENGTH,
4004                &init_params);
4005
4006        if (aconnector->base.force == DRM_FORCE_ON) {
4007                aconnector->dc_sink = aconnector->dc_link->local_sink ?
4008                aconnector->dc_link->local_sink :
4009                aconnector->dc_em_sink;
4010                dc_sink_retain(aconnector->dc_sink);
4011        }
4012}
4013
4014static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
4015{
4016        struct dc_link *link = (struct dc_link *)aconnector->dc_link;
4017
4018        /*
4019         * In case of headless boot with force on for DP managed connector
4020         * Those settings have to be != 0 to get initial modeset
4021         */
4022        if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
4023                link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
4024                link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
4025        }
4026
4027
4028        aconnector->base.override_edid = true;
4029        create_eml_sink(aconnector);
4030}
4031
4032enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
4033                                   struct drm_display_mode *mode)
4034{
4035        int result = MODE_ERROR;
4036        struct dc_sink *dc_sink;
4037        struct amdgpu_device *adev = connector->dev->dev_private;
4038        /* TODO: Unhardcode stream count */
4039        struct dc_stream_state *stream;
4040        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4041        enum dc_status dc_result = DC_OK;
4042
4043        if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
4044                        (mode->flags & DRM_MODE_FLAG_DBLSCAN))
4045                return result;
4046
4047        /*
4048         * Only run this the first time mode_valid is called to initilialize
4049         * EDID mgmt
4050         */
4051        if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
4052                !aconnector->dc_em_sink)
4053                handle_edid_mgmt(aconnector);
4054
4055        dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
4056
4057        if (dc_sink == NULL) {
4058                DRM_ERROR("dc_sink is NULL!\n");
4059                goto fail;
4060        }
4061
4062        stream = create_stream_for_sink(aconnector, mode, NULL, NULL);
4063        if (stream == NULL) {
4064                DRM_ERROR("Failed to create stream for sink!\n");
4065                goto fail;
4066        }
4067
4068        dc_result = dc_validate_stream(adev->dm.dc, stream);
4069
4070        if (dc_result == DC_OK)
4071                result = MODE_OK;
4072        else
4073                DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
4074                              mode->vdisplay,
4075                              mode->hdisplay,
4076                              mode->clock,
4077                              dc_result);
4078
4079        dc_stream_release(stream);
4080
4081fail:
4082        /* TODO: error handling*/
4083        return result;
4084}
4085
4086static int fill_hdr_info_packet(const struct drm_connector_state *state,
4087                                struct dc_info_packet *out)
4088{
4089        struct hdmi_drm_infoframe frame;
4090        unsigned char buf[30]; /* 26 + 4 */
4091        ssize_t len;
4092        int ret, i;
4093
4094        memset(out, 0, sizeof(*out));
4095
4096        if (!state->hdr_output_metadata)
4097                return 0;
4098
4099        ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
4100        if (ret)
4101                return ret;
4102
4103        len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
4104        if (len < 0)
4105                return (int)len;
4106
4107        /* Static metadata is a fixed 26 bytes + 4 byte header. */
4108        if (len != 30)
4109                return -EINVAL;
4110
4111        /* Prepare the infopacket for DC. */
4112        switch (state->connector->connector_type) {
4113        case DRM_MODE_CONNECTOR_HDMIA:
4114                out->hb0 = 0x87; /* type */
4115                out->hb1 = 0x01; /* version */
4116                out->hb2 = 0x1A; /* length */
4117                out->sb[0] = buf[3]; /* checksum */
4118                i = 1;
4119                break;
4120
4121        case DRM_MODE_CONNECTOR_DisplayPort:
4122        case DRM_MODE_CONNECTOR_eDP:
4123                out->hb0 = 0x00; /* sdp id, zero */
4124                out->hb1 = 0x87; /* type */
4125                out->hb2 = 0x1D; /* payload len - 1 */
4126                out->hb3 = (0x13 << 2); /* sdp version */
4127                out->sb[0] = 0x01; /* version */
4128                out->sb[1] = 0x1A; /* length */
4129                i = 2;
4130                break;
4131
4132        default:
4133                return -EINVAL;
4134        }
4135
4136        memcpy(&out->sb[i], &buf[4], 26);
4137        out->valid = true;
4138
4139        print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
4140                       sizeof(out->sb), false);
4141
4142        return 0;
4143}
4144
4145static bool
4146is_hdr_metadata_different(const struct drm_connector_state *old_state,
4147                          const struct drm_connector_state *new_state)
4148{
4149        struct drm_property_blob *old_blob = old_state->hdr_output_metadata;
4150        struct drm_property_blob *new_blob = new_state->hdr_output_metadata;
4151
4152        if (old_blob != new_blob) {
4153                if (old_blob && new_blob &&
4154                    old_blob->length == new_blob->length)
4155                        return memcmp(old_blob->data, new_blob->data,
4156                                      old_blob->length);
4157
4158                return true;
4159        }
4160
4161        return false;
4162}
4163
4164static int
4165amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
4166                                 struct drm_atomic_state *state)
4167{
4168        struct drm_connector_state *new_con_state =
4169                drm_atomic_get_new_connector_state(state, conn);
4170        struct drm_connector_state *old_con_state =
4171                drm_atomic_get_old_connector_state(state, conn);
4172        struct drm_crtc *crtc = new_con_state->crtc;
4173        struct drm_crtc_state *new_crtc_state;
4174        int ret;
4175
4176        if (!crtc)
4177                return 0;
4178
4179        if (is_hdr_metadata_different(old_con_state, new_con_state)) {
4180                struct dc_info_packet hdr_infopacket;
4181
4182                ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
4183                if (ret)
4184                        return ret;
4185
4186                new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
4187                if (IS_ERR(new_crtc_state))
4188                        return PTR_ERR(new_crtc_state);
4189
4190                /*
4191                 * DC considers the stream backends changed if the
4192                 * static metadata changes. Forcing the modeset also
4193                 * gives a simple way for userspace to switch from
4194                 * 8bpc to 10bpc when setting the metadata to enter
4195                 * or exit HDR.
4196                 *
4197                 * Changing the static metadata after it's been
4198                 * set is permissible, however. So only force a
4199                 * modeset if we're entering or exiting HDR.
4200                 */
4201                new_crtc_state->mode_changed =
4202                        !old_con_state->hdr_output_metadata ||
4203                        !new_con_state->hdr_output_metadata;
4204        }
4205
4206        return 0;
4207}
4208
4209static const struct drm_connector_helper_funcs
4210amdgpu_dm_connector_helper_funcs = {
4211        /*
4212         * If hotplugging a second bigger display in FB Con mode, bigger resolution
4213         * modes will be filtered by drm_mode_validate_size(), and those modes
4214         * are missing after user start lightdm. So we need to renew modes list.
4215         * in get_modes call back, not just return the modes count
4216         */
4217        .get_modes = get_modes,
4218        .mode_valid = amdgpu_dm_connector_mode_valid,
4219        .atomic_check = amdgpu_dm_connector_atomic_check,
4220};
4221
4222static void dm_crtc_helper_disable(struct drm_crtc *crtc)
4223{
4224}
4225
4226static bool does_crtc_have_active_cursor(struct drm_crtc_state *new_crtc_state)
4227{
4228        struct drm_device *dev = new_crtc_state->crtc->dev;
4229        struct drm_plane *plane;
4230
4231        drm_for_each_plane_mask(plane, dev, new_crtc_state->plane_mask) {
4232                if (plane->type == DRM_PLANE_TYPE_CURSOR)
4233                        return true;
4234        }
4235
4236        return false;
4237}
4238
4239static int count_crtc_active_planes(struct drm_crtc_state *new_crtc_state)
4240{
4241        struct drm_atomic_state *state = new_crtc_state->state;
4242        struct drm_plane *plane;
4243        int num_active = 0;
4244
4245        drm_for_each_plane_mask(plane, state->dev, new_crtc_state->plane_mask) {
4246                struct drm_plane_state *new_plane_state;
4247
4248                /* Cursor planes are "fake". */
4249                if (plane->type == DRM_PLANE_TYPE_CURSOR)
4250                        continue;
4251
4252                new_plane_state = drm_atomic_get_new_plane_state(state, plane);
4253
4254                if (!new_plane_state) {
4255                        /*
4256                         * The plane is enable on the CRTC and hasn't changed
4257                         * state. This means that it previously passed
4258                         * validation and is therefore enabled.
4259                         */
4260                        num_active += 1;
4261                        continue;
4262                }
4263
4264                /* We need a framebuffer to be considered enabled. */
4265                num_active += (new_plane_state->fb != NULL);
4266        }
4267
4268        return num_active;
4269}
4270
4271/*
4272 * Sets whether interrupts should be enabled on a specific CRTC.
4273 * We require that the stream be enabled and that there exist active
4274 * DC planes on the stream.
4275 */
4276static void
4277dm_update_crtc_interrupt_state(struct drm_crtc *crtc,
4278                               struct drm_crtc_state *new_crtc_state)
4279{
4280        struct dm_crtc_state *dm_new_crtc_state =
4281                to_dm_crtc_state(new_crtc_state);
4282
4283        dm_new_crtc_state->active_planes = 0;
4284        dm_new_crtc_state->interrupts_enabled = false;
4285
4286        if (!dm_new_crtc_state->stream)
4287                return;
4288
4289        dm_new_crtc_state->active_planes =
4290                count_crtc_active_planes(new_crtc_state);
4291
4292        dm_new_crtc_state->interrupts_enabled =
4293                dm_new_crtc_state->active_planes > 0;
4294}
4295
4296static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
4297                                       struct drm_crtc_state *state)
4298{
4299        struct amdgpu_device *adev = crtc->dev->dev_private;
4300        struct dc *dc = adev->dm.dc;
4301        struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
4302        int ret = -EINVAL;
4303
4304        /*
4305         * Update interrupt state for the CRTC. This needs to happen whenever
4306         * the CRTC has changed or whenever any of its planes have changed.
4307         * Atomic check satisfies both of these requirements since the CRTC
4308         * is added to the state by DRM during drm_atomic_helper_check_planes.
4309         */
4310        dm_update_crtc_interrupt_state(crtc, state);
4311
4312        if (unlikely(!dm_crtc_state->stream &&
4313                     modeset_required(state, NULL, dm_crtc_state->stream))) {
4314                WARN_ON(1);
4315                return ret;
4316        }
4317
4318        /* In some use cases, like reset, no stream is attached */
4319        if (!dm_crtc_state->stream)
4320                return 0;
4321
4322        /*
4323         * We want at least one hardware plane enabled to use
4324         * the stream with a cursor enabled.
4325         */
4326        if (state->enable && state->active &&
4327            does_crtc_have_active_cursor(state) &&
4328            dm_crtc_state->active_planes == 0)
4329                return -EINVAL;
4330
4331        if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
4332                return 0;
4333
4334        return ret;
4335}
4336
4337static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
4338                                      const struct drm_display_mode *mode,
4339                                      struct drm_display_mode *adjusted_mode)
4340{
4341        return true;
4342}
4343
4344static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
4345        .disable = dm_crtc_helper_disable,
4346        .atomic_check = dm_crtc_helper_atomic_check,
4347        .mode_fixup = dm_crtc_helper_mode_fixup
4348};
4349
4350static void dm_encoder_helper_disable(struct drm_encoder *encoder)
4351{
4352
4353}
4354
4355static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
4356                                          struct drm_crtc_state *crtc_state,
4357                                          struct drm_connector_state *conn_state)
4358{
4359        return 0;
4360}
4361
4362const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
4363        .disable = dm_encoder_helper_disable,
4364        .atomic_check = dm_encoder_helper_atomic_check
4365};
4366
4367static void dm_drm_plane_reset(struct drm_plane *plane)
4368{
4369        struct dm_plane_state *amdgpu_state = NULL;
4370
4371        if (plane->state)
4372                plane->funcs->atomic_destroy_state(plane, plane->state);
4373
4374        amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
4375        WARN_ON(amdgpu_state == NULL);
4376
4377        if (amdgpu_state)
4378                __drm_atomic_helper_plane_reset(plane, &amdgpu_state->base);
4379}
4380
4381static struct drm_plane_state *
4382dm_drm_plane_duplicate_state(struct drm_plane *plane)
4383{
4384        struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
4385
4386        old_dm_plane_state = to_dm_plane_state(plane->state);
4387        dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
4388        if (!dm_plane_state)
4389                return NULL;
4390
4391        __drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
4392
4393        if (old_dm_plane_state->dc_state) {
4394                dm_plane_state->dc_state = old_dm_plane_state->dc_state;
4395                dc_plane_state_retain(dm_plane_state->dc_state);
4396        }
4397
4398        return &dm_plane_state->base;
4399}
4400
4401void dm_drm_plane_destroy_state(struct drm_plane *plane,
4402                                struct drm_plane_state *state)
4403{
4404        struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
4405
4406        if (dm_plane_state->dc_state)
4407                dc_plane_state_release(dm_plane_state->dc_state);
4408
4409        drm_atomic_helper_plane_destroy_state(plane, state);
4410}
4411
4412static const struct drm_plane_funcs dm_plane_funcs = {
4413        .update_plane   = drm_atomic_helper_update_plane,
4414        .disable_plane  = drm_atomic_helper_disable_plane,
4415        .destroy        = drm_primary_helper_destroy,
4416        .reset = dm_drm_plane_reset,
4417        .atomic_duplicate_state = dm_drm_plane_duplicate_state,
4418        .atomic_destroy_state = dm_drm_plane_destroy_state,
4419};
4420
4421static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
4422                                      struct drm_plane_state *new_state)
4423{
4424        struct amdgpu_framebuffer *afb;
4425        struct drm_gem_object *obj;
4426        struct amdgpu_device *adev;
4427        struct amdgpu_bo *rbo;
4428        struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
4429        struct list_head list;
4430        struct ttm_validate_buffer tv;
4431        struct ww_acquire_ctx ticket;
4432        uint64_t tiling_flags;
4433        uint32_t domain;
4434        int r;
4435
4436        dm_plane_state_old = to_dm_plane_state(plane->state);
4437        dm_plane_state_new = to_dm_plane_state(new_state);
4438
4439        if (!new_state->fb) {
4440                DRM_DEBUG_DRIVER("No FB bound\n");
4441                return 0;
4442        }
4443
4444        afb = to_amdgpu_framebuffer(new_state->fb);
4445        obj = new_state->fb->obj[0];
4446        rbo = gem_to_amdgpu_bo(obj);
4447        adev = amdgpu_ttm_adev(rbo->tbo.bdev);
4448        INIT_LIST_HEAD(&list);
4449
4450        tv.bo = &rbo->tbo;
4451        tv.num_shared = 1;
4452        list_add(&tv.head, &list);
4453
4454        r = ttm_eu_reserve_buffers(&ticket, &list, false, NULL, true);
4455        if (r) {
4456                dev_err(adev->dev, "fail to reserve bo (%d)\n", r);
4457                return r;
4458        }
4459
4460        if (plane->type != DRM_PLANE_TYPE_CURSOR)
4461                domain = amdgpu_display_supported_domains(adev);
4462        else
4463                domain = AMDGPU_GEM_DOMAIN_VRAM;
4464
4465        r = amdgpu_bo_pin(rbo, domain);
4466        if (unlikely(r != 0)) {
4467                if (r != -ERESTARTSYS)
4468                        DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
4469                ttm_eu_backoff_reservation(&ticket, &list);
4470                return r;
4471        }
4472
4473        r = amdgpu_ttm_alloc_gart(&rbo->tbo);
4474        if (unlikely(r != 0)) {
4475                amdgpu_bo_unpin(rbo);
4476                ttm_eu_backoff_reservation(&ticket, &list);
4477                DRM_ERROR("%p bind failed\n", rbo);
4478                return r;
4479        }
4480
4481        amdgpu_bo_get_tiling_flags(rbo, &tiling_flags);
4482
4483        ttm_eu_backoff_reservation(&ticket, &list);
4484
4485        afb->address = amdgpu_bo_gpu_offset(rbo);
4486
4487        amdgpu_bo_ref(rbo);
4488
4489        if (dm_plane_state_new->dc_state &&
4490                        dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
4491                struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
4492
4493                fill_plane_buffer_attributes(
4494                        adev, afb, plane_state->format, plane_state->rotation,
4495                        tiling_flags, &plane_state->tiling_info,
4496                        &plane_state->plane_size, &plane_state->dcc,
4497                        &plane_state->address);
4498        }
4499
4500        return 0;
4501}
4502
4503static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
4504                                       struct drm_plane_state *old_state)
4505{
4506        struct amdgpu_bo *rbo;
4507        int r;
4508
4509        if (!old_state->fb)
4510                return;
4511
4512        rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
4513        r = amdgpu_bo_reserve(rbo, false);
4514        if (unlikely(r)) {
4515                DRM_ERROR("failed to reserve rbo before unpin\n");
4516                return;
4517        }
4518
4519        amdgpu_bo_unpin(rbo);
4520        amdgpu_bo_unreserve(rbo);
4521        amdgpu_bo_unref(&rbo);
4522}
4523
4524static int dm_plane_atomic_check(struct drm_plane *plane,
4525                                 struct drm_plane_state *state)
4526{
4527        struct amdgpu_device *adev = plane->dev->dev_private;
4528        struct dc *dc = adev->dm.dc;
4529        struct dm_plane_state *dm_plane_state;
4530        struct dc_scaling_info scaling_info;
4531        int ret;
4532
4533        dm_plane_state = to_dm_plane_state(state);
4534
4535        if (!dm_plane_state->dc_state)
4536                return 0;
4537
4538        ret = fill_dc_scaling_info(state, &scaling_info);
4539        if (ret)
4540                return ret;
4541
4542        if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
4543                return 0;
4544
4545        return -EINVAL;
4546}
4547
4548static int dm_plane_atomic_async_check(struct drm_plane *plane,
4549                                       struct drm_plane_state *new_plane_state)
4550{
4551        struct drm_plane_state *old_plane_state =
4552                drm_atomic_get_old_plane_state(new_plane_state->state, plane);
4553
4554        /* Only support async updates on cursor planes. */
4555        if (plane->type != DRM_PLANE_TYPE_CURSOR)
4556                return -EINVAL;
4557
4558        /*
4559         * DRM calls prepare_fb and cleanup_fb on new_plane_state for
4560         * async commits so don't allow fb changes.
4561         */
4562        if (old_plane_state->fb != new_plane_state->fb)
4563                return -EINVAL;
4564
4565        return 0;
4566}
4567
4568static void dm_plane_atomic_async_update(struct drm_plane *plane,
4569                                         struct drm_plane_state *new_state)
4570{
4571        struct drm_plane_state *old_state =
4572                drm_atomic_get_old_plane_state(new_state->state, plane);
4573
4574        swap(plane->state->fb, new_state->fb);
4575
4576        plane->state->src_x = new_state->src_x;
4577        plane->state->src_y = new_state->src_y;
4578        plane->state->src_w = new_state->src_w;
4579        plane->state->src_h = new_state->src_h;
4580        plane->state->crtc_x = new_state->crtc_x;
4581        plane->state->crtc_y = new_state->crtc_y;
4582        plane->state->crtc_w = new_state->crtc_w;
4583        plane->state->crtc_h = new_state->crtc_h;
4584
4585        handle_cursor_update(plane, old_state);
4586}
4587
4588static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
4589        .prepare_fb = dm_plane_helper_prepare_fb,
4590        .cleanup_fb = dm_plane_helper_cleanup_fb,
4591        .atomic_check = dm_plane_atomic_check,
4592        .atomic_async_check = dm_plane_atomic_async_check,
4593        .atomic_async_update = dm_plane_atomic_async_update
4594};
4595
4596/*
4597 * TODO: these are currently initialized to rgb formats only.
4598 * For future use cases we should either initialize them dynamically based on
4599 * plane capabilities, or initialize this array to all formats, so internal drm
4600 * check will succeed, and let DC implement proper check
4601 */
4602static const uint32_t rgb_formats[] = {
4603        DRM_FORMAT_XRGB8888,
4604        DRM_FORMAT_ARGB8888,
4605        DRM_FORMAT_RGBA8888,
4606        DRM_FORMAT_XRGB2101010,
4607        DRM_FORMAT_XBGR2101010,
4608        DRM_FORMAT_ARGB2101010,
4609        DRM_FORMAT_ABGR2101010,
4610        DRM_FORMAT_XBGR8888,
4611        DRM_FORMAT_ABGR8888,
4612        DRM_FORMAT_RGB565,
4613};
4614
4615static const uint32_t overlay_formats[] = {
4616        DRM_FORMAT_XRGB8888,
4617        DRM_FORMAT_ARGB8888,
4618        DRM_FORMAT_RGBA8888,
4619        DRM_FORMAT_XBGR8888,
4620        DRM_FORMAT_ABGR8888,
4621        DRM_FORMAT_RGB565
4622};
4623
4624static const u32 cursor_formats[] = {
4625        DRM_FORMAT_ARGB8888
4626};
4627
4628static int get_plane_formats(const struct drm_plane *plane,
4629                             const struct dc_plane_cap *plane_cap,
4630                             uint32_t *formats, int max_formats)
4631{
4632        int i, num_formats = 0;
4633
4634        /*
4635         * TODO: Query support for each group of formats directly from
4636         * DC plane caps. This will require adding more formats to the
4637         * caps list.
4638         */
4639
4640        switch (plane->type) {
4641        case DRM_PLANE_TYPE_PRIMARY:
4642                for (i = 0; i < ARRAY_SIZE(rgb_formats); ++i) {
4643                        if (num_formats >= max_formats)
4644                                break;
4645
4646                        formats[num_formats++] = rgb_formats[i];
4647                }
4648
4649                if (plane_cap && plane_cap->pixel_format_support.nv12)
4650                        formats[num_formats++] = DRM_FORMAT_NV12;
4651                break;
4652
4653        case DRM_PLANE_TYPE_OVERLAY:
4654                for (i = 0; i < ARRAY_SIZE(overlay_formats); ++i) {
4655                        if (num_formats >= max_formats)
4656                                break;
4657
4658                        formats[num_formats++] = overlay_formats[i];
4659                }
4660                break;
4661
4662        case DRM_PLANE_TYPE_CURSOR:
4663                for (i = 0; i < ARRAY_SIZE(cursor_formats); ++i) {
4664                        if (num_formats >= max_formats)
4665                                break;
4666
4667                        formats[num_formats++] = cursor_formats[i];
4668                }
4669                break;
4670        }
4671
4672        return num_formats;
4673}
4674
4675static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
4676                                struct drm_plane *plane,
4677                                unsigned long possible_crtcs,
4678                                const struct dc_plane_cap *plane_cap)
4679{
4680        uint32_t formats[32];
4681        int num_formats;
4682        int res = -EPERM;
4683
4684        num_formats = get_plane_formats(plane, plane_cap, formats,
4685                                        ARRAY_SIZE(formats));
4686
4687        res = drm_universal_plane_init(dm->adev->ddev, plane, possible_crtcs,
4688                                       &dm_plane_funcs, formats, num_formats,
4689                                       NULL, plane->type, NULL);
4690        if (res)
4691                return res;
4692
4693        if (plane->type == DRM_PLANE_TYPE_OVERLAY &&
4694            plane_cap && plane_cap->per_pixel_alpha) {
4695                unsigned int blend_caps = BIT(DRM_MODE_BLEND_PIXEL_NONE) |
4696                                          BIT(DRM_MODE_BLEND_PREMULTI);
4697
4698                drm_plane_create_alpha_property(plane);
4699                drm_plane_create_blend_mode_property(plane, blend_caps);
4700        }
4701
4702        if (plane->type == DRM_PLANE_TYPE_PRIMARY &&
4703            plane_cap && plane_cap->pixel_format_support.nv12) {
4704                /* This only affects YUV formats. */
4705                drm_plane_create_color_properties(
4706                        plane,
4707                        BIT(DRM_COLOR_YCBCR_BT601) |
4708                        BIT(DRM_COLOR_YCBCR_BT709),
4709                        BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
4710                        BIT(DRM_COLOR_YCBCR_FULL_RANGE),
4711                        DRM_COLOR_YCBCR_BT709, DRM_COLOR_YCBCR_LIMITED_RANGE);
4712        }
4713
4714        drm_plane_helper_add(plane, &dm_plane_helper_funcs);
4715
4716        /* Create (reset) the plane state */
4717        if (plane->funcs->reset)
4718                plane->funcs->reset(plane);
4719
4720        return 0;
4721}
4722
4723static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
4724                               struct drm_plane *plane,
4725                               uint32_t crtc_index)
4726{
4727        struct amdgpu_crtc *acrtc = NULL;
4728        struct drm_plane *cursor_plane;
4729
4730        int res = -ENOMEM;
4731
4732        cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
4733        if (!cursor_plane)
4734                goto fail;
4735
4736        cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
4737        res = amdgpu_dm_plane_init(dm, cursor_plane, 0, NULL);
4738
4739        acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
4740        if (!acrtc)
4741                goto fail;
4742
4743        res = drm_crtc_init_with_planes(
4744                        dm->ddev,
4745                        &acrtc->base,
4746                        plane,
4747                        cursor_plane,
4748                        &amdgpu_dm_crtc_funcs, NULL);
4749
4750        if (res)
4751                goto fail;
4752
4753        drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
4754
4755        /* Create (reset) the plane state */
4756        if (acrtc->base.funcs->reset)
4757                acrtc->base.funcs->reset(&acrtc->base);
4758
4759        acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
4760        acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
4761
4762        acrtc->crtc_id = crtc_index;
4763        acrtc->base.enabled = false;
4764        acrtc->otg_inst = -1;
4765
4766        dm->adev->mode_info.crtcs[crtc_index] = acrtc;
4767        drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
4768                                   true, MAX_COLOR_LUT_ENTRIES);
4769        drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
4770
4771        return 0;
4772
4773fail:
4774        kfree(acrtc);
4775        kfree(cursor_plane);
4776        return res;
4777}
4778
4779
4780static int to_drm_connector_type(enum signal_type st)
4781{
4782        switch (st) {
4783        case SIGNAL_TYPE_HDMI_TYPE_A:
4784                return DRM_MODE_CONNECTOR_HDMIA;
4785        case SIGNAL_TYPE_EDP:
4786                return DRM_MODE_CONNECTOR_eDP;
4787        case SIGNAL_TYPE_LVDS:
4788                return DRM_MODE_CONNECTOR_LVDS;
4789        case SIGNAL_TYPE_RGB:
4790                return DRM_MODE_CONNECTOR_VGA;
4791        case SIGNAL_TYPE_DISPLAY_PORT:
4792        case SIGNAL_TYPE_DISPLAY_PORT_MST:
4793                return DRM_MODE_CONNECTOR_DisplayPort;
4794        case SIGNAL_TYPE_DVI_DUAL_LINK:
4795        case SIGNAL_TYPE_DVI_SINGLE_LINK:
4796                return DRM_MODE_CONNECTOR_DVID;
4797        case SIGNAL_TYPE_VIRTUAL:
4798                return DRM_MODE_CONNECTOR_VIRTUAL;
4799
4800        default:
4801                return DRM_MODE_CONNECTOR_Unknown;
4802        }
4803}
4804
4805static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
4806{
4807        return drm_encoder_find(connector->dev, NULL, connector->encoder_ids[0]);
4808}
4809
4810static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
4811{
4812        struct drm_encoder *encoder;
4813        struct amdgpu_encoder *amdgpu_encoder;
4814
4815        encoder = amdgpu_dm_connector_to_encoder(connector);
4816
4817        if (encoder == NULL)
4818                return;
4819
4820        amdgpu_encoder = to_amdgpu_encoder(encoder);
4821
4822        amdgpu_encoder->native_mode.clock = 0;
4823
4824        if (!list_empty(&connector->probed_modes)) {
4825                struct drm_display_mode *preferred_mode = NULL;
4826
4827                list_for_each_entry(preferred_mode,
4828                                    &connector->probed_modes,
4829                                    head) {
4830                        if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
4831                                amdgpu_encoder->native_mode = *preferred_mode;
4832
4833                        break;
4834                }
4835
4836        }
4837}
4838
4839static struct drm_display_mode *
4840amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
4841                             char *name,
4842                             int hdisplay, int vdisplay)
4843{
4844        struct drm_device *dev = encoder->dev;
4845        struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4846        struct drm_display_mode *mode = NULL;
4847        struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4848
4849        mode = drm_mode_duplicate(dev, native_mode);
4850
4851        if (mode == NULL)
4852                return NULL;
4853
4854        mode->hdisplay = hdisplay;
4855        mode->vdisplay = vdisplay;
4856        mode->type &= ~DRM_MODE_TYPE_PREFERRED;
4857        strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
4858
4859        return mode;
4860
4861}
4862
4863static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
4864                                                 struct drm_connector *connector)
4865{
4866        struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
4867        struct drm_display_mode *mode = NULL;
4868        struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
4869        struct amdgpu_dm_connector *amdgpu_dm_connector =
4870                                to_amdgpu_dm_connector(connector);
4871        int i;
4872        int n;
4873        struct mode_size {
4874                char name[DRM_DISPLAY_MODE_LEN];
4875                int w;
4876                int h;
4877        } common_modes[] = {
4878                {  "640x480",  640,  480},
4879                {  "800x600",  800,  600},
4880                { "1024x768", 1024,  768},
4881                { "1280x720", 1280,  720},
4882                { "1280x800", 1280,  800},
4883                {"1280x1024", 1280, 1024},
4884                { "1440x900", 1440,  900},
4885                {"1680x1050", 1680, 1050},
4886                {"1600x1200", 1600, 1200},
4887                {"1920x1080", 1920, 1080},
4888                {"1920x1200", 1920, 1200}
4889        };
4890
4891        n = ARRAY_SIZE(common_modes);
4892
4893        for (i = 0; i < n; i++) {
4894                struct drm_display_mode *curmode = NULL;
4895                bool mode_existed = false;
4896
4897                if (common_modes[i].w > native_mode->hdisplay ||
4898                    common_modes[i].h > native_mode->vdisplay ||
4899                   (common_modes[i].w == native_mode->hdisplay &&
4900                    common_modes[i].h == native_mode->vdisplay))
4901                        continue;
4902
4903                list_for_each_entry(curmode, &connector->probed_modes, head) {
4904                        if (common_modes[i].w == curmode->hdisplay &&
4905                            common_modes[i].h == curmode->vdisplay) {
4906                                mode_existed = true;
4907                                break;
4908                        }
4909                }
4910
4911                if (mode_existed)
4912                        continue;
4913
4914                mode = amdgpu_dm_create_common_mode(encoder,
4915                                common_modes[i].name, common_modes[i].w,
4916                                common_modes[i].h);
4917                drm_mode_probed_add(connector, mode);
4918                amdgpu_dm_connector->num_modes++;
4919        }
4920}
4921
4922static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
4923                                              struct edid *edid)
4924{
4925        struct amdgpu_dm_connector *amdgpu_dm_connector =
4926                        to_amdgpu_dm_connector(connector);
4927
4928        if (edid) {
4929                /* empty probed_modes */
4930                INIT_LIST_HEAD(&connector->probed_modes);
4931                amdgpu_dm_connector->num_modes =
4932                                drm_add_edid_modes(connector, edid);
4933
4934                /* sorting the probed modes before calling function
4935                 * amdgpu_dm_get_native_mode() since EDID can have
4936                 * more than one preferred mode. The modes that are
4937                 * later in the probed mode list could be of higher
4938                 * and preferred resolution. For example, 3840x2160
4939                 * resolution in base EDID preferred timing and 4096x2160
4940                 * preferred resolution in DID extension block later.
4941                 */
4942                drm_mode_sort(&connector->probed_modes);
4943                amdgpu_dm_get_native_mode(connector);
4944        } else {
4945                amdgpu_dm_connector->num_modes = 0;
4946        }
4947}
4948
4949static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
4950{
4951        struct amdgpu_dm_connector *amdgpu_dm_connector =
4952                        to_amdgpu_dm_connector(connector);
4953        struct drm_encoder *encoder;
4954        struct edid *edid = amdgpu_dm_connector->edid;
4955
4956        encoder = amdgpu_dm_connector_to_encoder(connector);
4957
4958        if (!edid || !drm_edid_is_valid(edid)) {
4959                amdgpu_dm_connector->num_modes =
4960                                drm_add_modes_noedid(connector, 640, 480);
4961        } else {
4962                amdgpu_dm_connector_ddc_get_modes(connector, edid);
4963                amdgpu_dm_connector_add_common_modes(encoder, connector);
4964        }
4965        amdgpu_dm_fbc_init(connector);
4966
4967        return amdgpu_dm_connector->num_modes;
4968}
4969
4970void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
4971                                     struct amdgpu_dm_connector *aconnector,
4972                                     int connector_type,
4973                                     struct dc_link *link,
4974                                     int link_index)
4975{
4976        struct amdgpu_device *adev = dm->ddev->dev_private;
4977
4978        /*
4979         * Some of the properties below require access to state, like bpc.
4980         * Allocate some default initial connector state with our reset helper.
4981         */
4982        if (aconnector->base.funcs->reset)
4983                aconnector->base.funcs->reset(&aconnector->base);
4984
4985        aconnector->connector_id = link_index;
4986        aconnector->dc_link = link;
4987        aconnector->base.interlace_allowed = false;
4988        aconnector->base.doublescan_allowed = false;
4989        aconnector->base.stereo_allowed = false;
4990        aconnector->base.dpms = DRM_MODE_DPMS_OFF;
4991        aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
4992        aconnector->audio_inst = -1;
4993        mutex_init(&aconnector->hpd_lock);
4994
4995        /*
4996         * configure support HPD hot plug connector_>polled default value is 0
4997         * which means HPD hot plug not supported
4998         */
4999        switch (connector_type) {
5000        case DRM_MODE_CONNECTOR_HDMIA:
5001                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5002                aconnector->base.ycbcr_420_allowed =
5003                        link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
5004                break;
5005        case DRM_MODE_CONNECTOR_DisplayPort:
5006                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5007                aconnector->base.ycbcr_420_allowed =
5008                        link->link_enc->features.dp_ycbcr420_supported ? true : false;
5009                break;
5010        case DRM_MODE_CONNECTOR_DVID:
5011                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5012                break;
5013        default:
5014                break;
5015        }
5016
5017        drm_object_attach_property(&aconnector->base.base,
5018                                dm->ddev->mode_config.scaling_mode_property,
5019                                DRM_MODE_SCALE_NONE);
5020
5021        drm_object_attach_property(&aconnector->base.base,
5022                                adev->mode_info.underscan_property,
5023                                UNDERSCAN_OFF);
5024        drm_object_attach_property(&aconnector->base.base,
5025                                adev->mode_info.underscan_hborder_property,
5026                                0);
5027        drm_object_attach_property(&aconnector->base.base,
5028                                adev->mode_info.underscan_vborder_property,
5029                                0);
5030
5031        drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
5032
5033        /* This defaults to the max in the range, but we want 8bpc. */
5034        aconnector->base.state->max_bpc = 8;
5035        aconnector->base.state->max_requested_bpc = 8;
5036
5037        if (connector_type == DRM_MODE_CONNECTOR_eDP &&
5038            dc_is_dmcu_initialized(adev->dm.dc)) {
5039                drm_object_attach_property(&aconnector->base.base,
5040                                adev->mode_info.abm_level_property, 0);
5041        }
5042
5043        if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
5044            connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
5045            connector_type == DRM_MODE_CONNECTOR_eDP) {
5046                drm_object_attach_property(
5047                        &aconnector->base.base,
5048                        dm->ddev->mode_config.hdr_output_metadata_property, 0);
5049
5050                drm_connector_attach_vrr_capable_property(
5051                        &aconnector->base);
5052        }
5053}
5054
5055static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
5056                              struct i2c_msg *msgs, int num)
5057{
5058        struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
5059        struct ddc_service *ddc_service = i2c->ddc_service;
5060        struct i2c_command cmd;
5061        int i;
5062        int result = -EIO;
5063
5064        cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
5065
5066        if (!cmd.payloads)
5067                return result;
5068
5069        cmd.number_of_payloads = num;
5070        cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
5071        cmd.speed = 100;
5072
5073        for (i = 0; i < num; i++) {
5074                cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
5075                cmd.payloads[i].address = msgs[i].addr;
5076                cmd.payloads[i].length = msgs[i].len;
5077                cmd.payloads[i].data = msgs[i].buf;
5078        }
5079
5080        if (dc_submit_i2c(
5081                        ddc_service->ctx->dc,
5082                        ddc_service->ddc_pin->hw_info.ddc_channel,
5083                        &cmd))
5084                result = num;
5085
5086        kfree(cmd.payloads);
5087        return result;
5088}
5089
5090static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
5091{
5092        return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
5093}
5094
5095static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
5096        .master_xfer = amdgpu_dm_i2c_xfer,
5097        .functionality = amdgpu_dm_i2c_func,
5098};
5099
5100static struct amdgpu_i2c_adapter *
5101create_i2c(struct ddc_service *ddc_service,
5102           int link_index,
5103           int *res)
5104{
5105        struct amdgpu_device *adev = ddc_service->ctx->driver_context;
5106        struct amdgpu_i2c_adapter *i2c;
5107
5108        i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
5109        if (!i2c)
5110                return NULL;
5111        i2c->base.owner = THIS_MODULE;
5112        i2c->base.class = I2C_CLASS_DDC;
5113        i2c->base.dev.parent = &adev->pdev->dev;
5114        i2c->base.algo = &amdgpu_dm_i2c_algo;
5115        snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
5116        i2c_set_adapdata(&i2c->base, i2c);
5117        i2c->ddc_service = ddc_service;
5118        i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
5119
5120        return i2c;
5121}
5122
5123
5124/*
5125 * Note: this function assumes that dc_link_detect() was called for the
5126 * dc_link which will be represented by this aconnector.
5127 */
5128static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
5129                                    struct amdgpu_dm_connector *aconnector,
5130                                    uint32_t link_index,
5131                                    struct amdgpu_encoder *aencoder)
5132{
5133        int res = 0;
5134        int connector_type;
5135        struct dc *dc = dm->dc;
5136        struct dc_link *link = dc_get_link_at_index(dc, link_index);
5137        struct amdgpu_i2c_adapter *i2c;
5138
5139        link->priv = aconnector;
5140
5141        DRM_DEBUG_DRIVER("%s()\n", __func__);
5142
5143        i2c = create_i2c(link->ddc, link->link_index, &res);
5144        if (!i2c) {
5145                DRM_ERROR("Failed to create i2c adapter data\n");
5146                return -ENOMEM;
5147        }
5148
5149        aconnector->i2c = i2c;
5150        res = i2c_add_adapter(&i2c->base);
5151
5152        if (res) {
5153                DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
5154                goto out_free;
5155        }
5156
5157        connector_type = to_drm_connector_type(link->connector_signal);
5158
5159        res = drm_connector_init(
5160                        dm->ddev,
5161                        &aconnector->base,
5162                        &amdgpu_dm_connector_funcs,
5163                        connector_type);
5164
5165        if (res) {
5166                DRM_ERROR("connector_init failed\n");
5167                aconnector->connector_id = -1;
5168                goto out_free;
5169        }
5170
5171        drm_connector_helper_add(
5172                        &aconnector->base,
5173                        &amdgpu_dm_connector_helper_funcs);
5174
5175        amdgpu_dm_connector_init_helper(
5176                dm,
5177                aconnector,
5178                connector_type,
5179                link,
5180                link_index);
5181
5182        drm_connector_attach_encoder(
5183                &aconnector->base, &aencoder->base);
5184
5185        drm_connector_register(&aconnector->base);
5186#if defined(CONFIG_DEBUG_FS)
5187        connector_debugfs_init(aconnector);
5188        aconnector->debugfs_dpcd_address = 0;
5189        aconnector->debugfs_dpcd_size = 0;
5190#endif
5191
5192        if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
5193                || connector_type == DRM_MODE_CONNECTOR_eDP)
5194                amdgpu_dm_initialize_dp_connector(dm, aconnector);
5195
5196out_free:
5197        if (res) {
5198                kfree(i2c);
5199                aconnector->i2c = NULL;
5200        }
5201        return res;
5202}
5203
5204int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
5205{
5206        switch (adev->mode_info.num_crtc) {
5207        case 1:
5208                return 0x1;
5209        case 2:
5210                return 0x3;
5211        case 3:
5212                return 0x7;
5213        case 4:
5214                return 0xf;
5215        case 5:
5216                return 0x1f;
5217        case 6:
5218        default:
5219                return 0x3f;
5220        }
5221}
5222
5223static int amdgpu_dm_encoder_init(struct drm_device *dev,
5224                                  struct amdgpu_encoder *aencoder,
5225                                  uint32_t link_index)
5226{
5227        struct amdgpu_device *adev = dev->dev_private;
5228
5229        int res = drm_encoder_init(dev,
5230                                   &aencoder->base,
5231                                   &amdgpu_dm_encoder_funcs,
5232                                   DRM_MODE_ENCODER_TMDS,
5233                                   NULL);
5234
5235        aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
5236
5237        if (!res)
5238                aencoder->encoder_id = link_index;
5239        else
5240                aencoder->encoder_id = -1;
5241
5242        drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
5243
5244        return res;
5245}
5246
5247static void manage_dm_interrupts(struct amdgpu_device *adev,
5248                                 struct amdgpu_crtc *acrtc,
5249                                 bool enable)
5250{
5251        /*
5252         * this is not correct translation but will work as soon as VBLANK
5253         * constant is the same as PFLIP
5254         */
5255        int irq_type =
5256                amdgpu_display_crtc_idx_to_irq_type(
5257                        adev,
5258                        acrtc->crtc_id);
5259
5260        if (enable) {
5261                drm_crtc_vblank_on(&acrtc->base);
5262                amdgpu_irq_get(
5263                        adev,
5264                        &adev->pageflip_irq,
5265                        irq_type);
5266        } else {
5267
5268                amdgpu_irq_put(
5269                        adev,
5270                        &adev->pageflip_irq,
5271                        irq_type);
5272                drm_crtc_vblank_off(&acrtc->base);
5273        }
5274}
5275
5276static bool
5277is_scaling_state_different(const struct dm_connector_state *dm_state,
5278                           const struct dm_connector_state *old_dm_state)
5279{
5280        if (dm_state->scaling != old_dm_state->scaling)
5281                return true;
5282        if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
5283                if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
5284                        return true;
5285        } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
5286                if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
5287                        return true;
5288        } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
5289                   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
5290                return true;
5291        return false;
5292}
5293
5294static void remove_stream(struct amdgpu_device *adev,
5295                          struct amdgpu_crtc *acrtc,
5296                          struct dc_stream_state *stream)
5297{
5298        /* this is the update mode case */
5299
5300        acrtc->otg_inst = -1;
5301        acrtc->enabled = false;
5302}
5303
5304static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
5305                               struct dc_cursor_position *position)
5306{
5307        struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5308        int x, y;
5309        int xorigin = 0, yorigin = 0;
5310
5311        position->enable = false;
5312        position->x = 0;
5313        position->y = 0;
5314
5315        if (!crtc || !plane->state->fb)
5316                return 0;
5317
5318        if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
5319            (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
5320                DRM_ERROR("%s: bad cursor width or height %d x %d\n",
5321                          __func__,
5322                          plane->state->crtc_w,
5323                          plane->state->crtc_h);
5324                return -EINVAL;
5325        }
5326
5327        x = plane->state->crtc_x;
5328        y = plane->state->crtc_y;
5329
5330        if (x <= -amdgpu_crtc->max_cursor_width ||
5331            y <= -amdgpu_crtc->max_cursor_height)
5332                return 0;
5333
5334        if (crtc->primary->state) {
5335                /* avivo cursor are offset into the total surface */
5336                x += crtc->primary->state->src_x >> 16;
5337                y += crtc->primary->state->src_y >> 16;
5338        }
5339
5340        if (x < 0) {
5341                xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
5342                x = 0;
5343        }
5344        if (y < 0) {
5345                yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
5346                y = 0;
5347        }
5348        position->enable = true;
5349        position->x = x;
5350        position->y = y;
5351        position->x_hotspot = xorigin;
5352        position->y_hotspot = yorigin;
5353
5354        return 0;
5355}
5356
5357static void handle_cursor_update(struct drm_plane *plane,
5358                                 struct drm_plane_state *old_plane_state)
5359{
5360        struct amdgpu_device *adev = plane->dev->dev_private;
5361        struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
5362        struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
5363        struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
5364        struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5365        uint64_t address = afb ? afb->address : 0;
5366        struct dc_cursor_position position;
5367        struct dc_cursor_attributes attributes;
5368        int ret;
5369
5370        if (!plane->state->fb && !old_plane_state->fb)
5371                return;
5372
5373        DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
5374                         __func__,
5375                         amdgpu_crtc->crtc_id,
5376                         plane->state->crtc_w,
5377                         plane->state->crtc_h);
5378
5379        ret = get_cursor_position(plane, crtc, &position);
5380        if (ret)
5381                return;
5382
5383        if (!position.enable) {
5384                /* turn off cursor */
5385                if (crtc_state && crtc_state->stream) {
5386                        mutex_lock(&adev->dm.dc_lock);
5387                        dc_stream_set_cursor_position(crtc_state->stream,
5388                                                      &position);
5389                        mutex_unlock(&adev->dm.dc_lock);
5390                }
5391                return;
5392        }
5393
5394        amdgpu_crtc->cursor_width = plane->state->crtc_w;
5395        amdgpu_crtc->cursor_height = plane->state->crtc_h;
5396
5397        memset(&attributes, 0, sizeof(attributes));
5398        attributes.address.high_part = upper_32_bits(address);
5399        attributes.address.low_part  = lower_32_bits(address);
5400        attributes.width             = plane->state->crtc_w;
5401        attributes.height            = plane->state->crtc_h;
5402        attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
5403        attributes.rotation_angle    = 0;
5404        attributes.attribute_flags.value = 0;
5405
5406        attributes.pitch = attributes.width;
5407
5408        if (crtc_state->stream) {
5409                mutex_lock(&adev->dm.dc_lock);
5410                if (!dc_stream_set_cursor_attributes(crtc_state->stream,
5411                                                         &attributes))
5412                        DRM_ERROR("DC failed to set cursor attributes\n");
5413
5414                if (!dc_stream_set_cursor_position(crtc_state->stream,
5415                                                   &position))
5416                        DRM_ERROR("DC failed to set cursor position\n");
5417                mutex_unlock(&adev->dm.dc_lock);
5418        }
5419}
5420
5421static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
5422{
5423
5424        assert_spin_locked(&acrtc->base.dev->event_lock);
5425        WARN_ON(acrtc->event);
5426
5427        acrtc->event = acrtc->base.state->event;
5428
5429        /* Set the flip status */
5430        acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
5431
5432        /* Mark this event as consumed */
5433        acrtc->base.state->event = NULL;
5434
5435        DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
5436                                                 acrtc->crtc_id);
5437}
5438
5439static void update_freesync_state_on_stream(
5440        struct amdgpu_display_manager *dm,
5441        struct dm_crtc_state *new_crtc_state,
5442        struct dc_stream_state *new_stream,
5443        struct dc_plane_state *surface,
5444        u32 flip_timestamp_in_us)
5445{
5446        struct mod_vrr_params vrr_params;
5447        struct dc_info_packet vrr_infopacket = {0};
5448        struct amdgpu_device *adev = dm->adev;
5449        unsigned long flags;
5450
5451        if (!new_stream)
5452                return;
5453
5454        /*
5455         * TODO: Determine why min/max totals and vrefresh can be 0 here.
5456         * For now it's sufficient to just guard against these conditions.
5457         */
5458
5459        if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5460                return;
5461
5462        spin_lock_irqsave(&adev->ddev->event_lock, flags);
5463        vrr_params = new_crtc_state->vrr_params;
5464
5465        if (surface) {
5466                mod_freesync_handle_preflip(
5467                        dm->freesync_module,
5468                        surface,
5469                        new_stream,
5470                        flip_timestamp_in_us,
5471                        &vrr_params);
5472
5473                if (adev->family < AMDGPU_FAMILY_AI &&
5474                    amdgpu_dm_vrr_active(new_crtc_state)) {
5475                        mod_freesync_handle_v_update(dm->freesync_module,
5476                                                     new_stream, &vrr_params);
5477
5478                        /* Need to call this before the frame ends. */
5479                        dc_stream_adjust_vmin_vmax(dm->dc,
5480                                                   new_crtc_state->stream,
5481                                                   &vrr_params.adjust);
5482                }
5483        }
5484
5485        mod_freesync_build_vrr_infopacket(
5486                dm->freesync_module,
5487                new_stream,
5488                &vrr_params,
5489                PACKET_TYPE_VRR,
5490                TRANSFER_FUNC_UNKNOWN,
5491                &vrr_infopacket);
5492
5493        new_crtc_state->freesync_timing_changed |=
5494                (memcmp(&new_crtc_state->vrr_params.adjust,
5495                        &vrr_params.adjust,
5496                        sizeof(vrr_params.adjust)) != 0);
5497
5498        new_crtc_state->freesync_vrr_info_changed |=
5499                (memcmp(&new_crtc_state->vrr_infopacket,
5500                        &vrr_infopacket,
5501                        sizeof(vrr_infopacket)) != 0);
5502
5503        new_crtc_state->vrr_params = vrr_params;
5504        new_crtc_state->vrr_infopacket = vrr_infopacket;
5505
5506        new_stream->adjust = new_crtc_state->vrr_params.adjust;
5507        new_stream->vrr_infopacket = vrr_infopacket;
5508
5509        if (new_crtc_state->freesync_vrr_info_changed)
5510                DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
5511                              new_crtc_state->base.crtc->base.id,
5512                              (int)new_crtc_state->base.vrr_enabled,
5513                              (int)vrr_params.state);
5514
5515        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5516}
5517
5518static void pre_update_freesync_state_on_stream(
5519        struct amdgpu_display_manager *dm,
5520        struct dm_crtc_state *new_crtc_state)
5521{
5522        struct dc_stream_state *new_stream = new_crtc_state->stream;
5523        struct mod_vrr_params vrr_params;
5524        struct mod_freesync_config config = new_crtc_state->freesync_config;
5525        struct amdgpu_device *adev = dm->adev;
5526        unsigned long flags;
5527
5528        if (!new_stream)
5529                return;
5530
5531        /*
5532         * TODO: Determine why min/max totals and vrefresh can be 0 here.
5533         * For now it's sufficient to just guard against these conditions.
5534         */
5535        if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5536                return;
5537
5538        spin_lock_irqsave(&adev->ddev->event_lock, flags);
5539        vrr_params = new_crtc_state->vrr_params;
5540
5541        if (new_crtc_state->vrr_supported &&
5542            config.min_refresh_in_uhz &&
5543            config.max_refresh_in_uhz) {
5544                config.state = new_crtc_state->base.vrr_enabled ?
5545                        VRR_STATE_ACTIVE_VARIABLE :
5546                        VRR_STATE_INACTIVE;
5547        } else {
5548                config.state = VRR_STATE_UNSUPPORTED;
5549        }
5550
5551        mod_freesync_build_vrr_params(dm->freesync_module,
5552                                      new_stream,
5553                                      &config, &vrr_params);
5554
5555        new_crtc_state->freesync_timing_changed |=
5556                (memcmp(&new_crtc_state->vrr_params.adjust,
5557                        &vrr_params.adjust,
5558                        sizeof(vrr_params.adjust)) != 0);
5559
5560        new_crtc_state->vrr_params = vrr_params;
5561        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5562}
5563
5564static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
5565                                            struct dm_crtc_state *new_state)
5566{
5567        bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
5568        bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
5569
5570        if (!old_vrr_active && new_vrr_active) {
5571                /* Transition VRR inactive -> active:
5572                 * While VRR is active, we must not disable vblank irq, as a
5573                 * reenable after disable would compute bogus vblank/pflip
5574                 * timestamps if it likely happened inside display front-porch.
5575                 *
5576                 * We also need vupdate irq for the actual core vblank handling
5577                 * at end of vblank.
5578                 */
5579                dm_set_vupdate_irq(new_state->base.crtc, true);
5580                drm_crtc_vblank_get(new_state->base.crtc);
5581                DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
5582                                 __func__, new_state->base.crtc->base.id);
5583        } else if (old_vrr_active && !new_vrr_active) {
5584                /* Transition VRR active -> inactive:
5585                 * Allow vblank irq disable again for fixed refresh rate.
5586                 */
5587                dm_set_vupdate_irq(new_state->base.crtc, false);
5588                drm_crtc_vblank_put(new_state->base.crtc);
5589                DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
5590                                 __func__, new_state->base.crtc->base.id);
5591        }
5592}
5593
5594static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
5595{
5596        struct drm_plane *plane;
5597        struct drm_plane_state *old_plane_state, *new_plane_state;
5598        int i;
5599
5600        /*
5601         * TODO: Make this per-stream so we don't issue redundant updates for
5602         * commits with multiple streams.
5603         */
5604        for_each_oldnew_plane_in_state(state, plane, old_plane_state,
5605                                       new_plane_state, i)
5606                if (plane->type == DRM_PLANE_TYPE_CURSOR)
5607                        handle_cursor_update(plane, old_plane_state);
5608}
5609
5610static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
5611                                    struct dc_state *dc_state,
5612                                    struct drm_device *dev,
5613                                    struct amdgpu_display_manager *dm,
5614                                    struct drm_crtc *pcrtc,
5615                                    bool wait_for_vblank)
5616{
5617        uint32_t i;
5618        uint64_t timestamp_ns;
5619        struct drm_plane *plane;
5620        struct drm_plane_state *old_plane_state, *new_plane_state;
5621        struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
5622        struct drm_crtc_state *new_pcrtc_state =
5623                        drm_atomic_get_new_crtc_state(state, pcrtc);
5624        struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
5625        struct dm_crtc_state *dm_old_crtc_state =
5626                        to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
5627        int planes_count = 0, vpos, hpos;
5628        long r;
5629        unsigned long flags;
5630        struct amdgpu_bo *abo;
5631        uint64_t tiling_flags;
5632        uint32_t target_vblank, last_flip_vblank;
5633        bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
5634        bool pflip_present = false;
5635        struct {
5636                struct dc_surface_update surface_updates[MAX_SURFACES];
5637                struct dc_plane_info plane_infos[MAX_SURFACES];
5638                struct dc_scaling_info scaling_infos[MAX_SURFACES];
5639                struct dc_flip_addrs flip_addrs[MAX_SURFACES];
5640                struct dc_stream_update stream_update;
5641        } *bundle;
5642
5643        bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
5644
5645        if (!bundle) {
5646                dm_error("Failed to allocate update bundle\n");
5647                goto cleanup;
5648        }
5649
5650        /*
5651         * Disable the cursor first if we're disabling all the planes.
5652         * It'll remain on the screen after the planes are re-enabled
5653         * if we don't.
5654         */
5655        if (acrtc_state->active_planes == 0)
5656                amdgpu_dm_commit_cursors(state);
5657
5658        /* update planes when needed */
5659        for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
5660                struct drm_crtc *crtc = new_plane_state->crtc;
5661                struct drm_crtc_state *new_crtc_state;
5662                struct drm_framebuffer *fb = new_plane_state->fb;
5663                bool plane_needs_flip;
5664                struct dc_plane_state *dc_plane;
5665                struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
5666
5667                /* Cursor plane is handled after stream updates */
5668                if (plane->type == DRM_PLANE_TYPE_CURSOR)
5669                        continue;
5670
5671                if (!fb || !crtc || pcrtc != crtc)
5672                        continue;
5673
5674                new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
5675                if (!new_crtc_state->active)
5676                        continue;
5677
5678                dc_plane = dm_new_plane_state->dc_state;
5679
5680                bundle->surface_updates[planes_count].surface = dc_plane;
5681                if (new_pcrtc_state->color_mgmt_changed) {
5682                        bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
5683                        bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
5684                }
5685
5686                fill_dc_scaling_info(new_plane_state,
5687                                     &bundle->scaling_infos[planes_count]);
5688
5689                bundle->surface_updates[planes_count].scaling_info =
5690                        &bundle->scaling_infos[planes_count];
5691
5692                plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
5693
5694                pflip_present = pflip_present || plane_needs_flip;
5695
5696                if (!plane_needs_flip) {
5697                        planes_count += 1;
5698                        continue;
5699                }
5700
5701                abo = gem_to_amdgpu_bo(fb->obj[0]);
5702
5703                /*
5704                 * Wait for all fences on this FB. Do limited wait to avoid
5705                 * deadlock during GPU reset when this fence will not signal
5706                 * but we hold reservation lock for the BO.
5707                 */
5708                r = reservation_object_wait_timeout_rcu(abo->tbo.resv, true,
5709                                                        false,
5710                                                        msecs_to_jiffies(5000));
5711                if (unlikely(r <= 0))
5712                        DRM_ERROR("Waiting for fences timed out or interrupted!");
5713
5714                /*
5715                 * TODO This might fail and hence better not used, wait
5716                 * explicitly on fences instead
5717                 * and in general should be called for
5718                 * blocking commit to as per framework helpers
5719                 */
5720                r = amdgpu_bo_reserve(abo, true);
5721                if (unlikely(r != 0))
5722                        DRM_ERROR("failed to reserve buffer before flip\n");
5723
5724                amdgpu_bo_get_tiling_flags(abo, &tiling_flags);
5725
5726                amdgpu_bo_unreserve(abo);
5727
5728                fill_dc_plane_info_and_addr(
5729                        dm->adev, new_plane_state, tiling_flags,
5730                        &bundle->plane_infos[planes_count],
5731                        &bundle->flip_addrs[planes_count].address);
5732
5733                bundle->surface_updates[planes_count].plane_info =
5734                        &bundle->plane_infos[planes_count];
5735
5736                bundle->flip_addrs[planes_count].flip_immediate =
5737                                (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
5738
5739                timestamp_ns = ktime_get_ns();
5740                bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
5741                bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
5742                bundle->surface_updates[planes_count].surface = dc_plane;
5743
5744                if (!bundle->surface_updates[planes_count].surface) {
5745                        DRM_ERROR("No surface for CRTC: id=%d\n",
5746                                        acrtc_attach->crtc_id);
5747                        continue;
5748                }
5749
5750                if (plane == pcrtc->primary)
5751                        update_freesync_state_on_stream(
5752                                dm,
5753                                acrtc_state,
5754                                acrtc_state->stream,
5755                                dc_plane,
5756                                bundle->flip_addrs[planes_count].flip_timestamp_in_us);
5757
5758                DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x\n",
5759                                 __func__,
5760                                 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
5761                                 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
5762
5763                planes_count += 1;
5764
5765        }
5766
5767        if (pflip_present) {
5768                if (!vrr_active) {
5769                        /* Use old throttling in non-vrr fixed refresh rate mode
5770                         * to keep flip scheduling based on target vblank counts
5771                         * working in a backwards compatible way, e.g., for
5772                         * clients using the GLX_OML_sync_control extension or
5773                         * DRI3/Present extension with defined target_msc.
5774                         */
5775                        last_flip_vblank = amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id);
5776                }
5777                else {
5778                        /* For variable refresh rate mode only:
5779                         * Get vblank of last completed flip to avoid > 1 vrr
5780                         * flips per video frame by use of throttling, but allow
5781                         * flip programming anywhere in the possibly large
5782                         * variable vrr vblank interval for fine-grained flip
5783                         * timing control and more opportunity to avoid stutter
5784                         * on late submission of flips.
5785                         */
5786                        spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5787                        last_flip_vblank = acrtc_attach->last_flip_vblank;
5788                        spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5789                }
5790
5791                target_vblank = last_flip_vblank + wait_for_vblank;
5792
5793                /*
5794                 * Wait until we're out of the vertical blank period before the one
5795                 * targeted by the flip
5796                 */
5797                while ((acrtc_attach->enabled &&
5798                        (amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
5799                                                            0, &vpos, &hpos, NULL,
5800                                                            NULL, &pcrtc->hwmode)
5801                         & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
5802                        (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
5803                        (int)(target_vblank -
5804                          amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id)) > 0)) {
5805                        usleep_range(1000, 1100);
5806                }
5807
5808                if (acrtc_attach->base.state->event) {
5809                        drm_crtc_vblank_get(pcrtc);
5810
5811                        spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5812
5813                        WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
5814                        prepare_flip_isr(acrtc_attach);
5815
5816                        spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5817                }
5818
5819                if (acrtc_state->stream) {
5820                        if (acrtc_state->freesync_vrr_info_changed)
5821                                bundle->stream_update.vrr_infopacket =
5822                                        &acrtc_state->stream->vrr_infopacket;
5823                }
5824        }
5825
5826        /* Update the planes if changed or disable if we don't have any. */
5827        if ((planes_count || acrtc_state->active_planes == 0) &&
5828                acrtc_state->stream) {
5829                if (new_pcrtc_state->mode_changed) {
5830                        bundle->stream_update.src = acrtc_state->stream->src;
5831                        bundle->stream_update.dst = acrtc_state->stream->dst;
5832                }
5833
5834                if (new_pcrtc_state->color_mgmt_changed) {
5835                        /*
5836                         * TODO: This isn't fully correct since we've actually
5837                         * already modified the stream in place.
5838                         */
5839                        bundle->stream_update.gamut_remap =
5840                                &acrtc_state->stream->gamut_remap_matrix;
5841                        bundle->stream_update.output_csc_transform =
5842                                &acrtc_state->stream->csc_color_matrix;
5843                        bundle->stream_update.out_transfer_func =
5844                                acrtc_state->stream->out_transfer_func;
5845                }
5846
5847                acrtc_state->stream->abm_level = acrtc_state->abm_level;
5848                if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
5849                        bundle->stream_update.abm_level = &acrtc_state->abm_level;
5850
5851                /*
5852                 * If FreeSync state on the stream has changed then we need to
5853                 * re-adjust the min/max bounds now that DC doesn't handle this
5854                 * as part of commit.
5855                 */
5856                if (amdgpu_dm_vrr_active(dm_old_crtc_state) !=
5857                    amdgpu_dm_vrr_active(acrtc_state)) {
5858                        spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
5859                        dc_stream_adjust_vmin_vmax(
5860                                dm->dc, acrtc_state->stream,
5861                                &acrtc_state->vrr_params.adjust);
5862                        spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
5863                }
5864
5865                mutex_lock(&dm->dc_lock);
5866                dc_commit_updates_for_stream(dm->dc,
5867                                                     bundle->surface_updates,
5868                                                     planes_count,
5869                                                     acrtc_state->stream,
5870                                                     &bundle->stream_update,
5871                                                     dc_state);
5872                mutex_unlock(&dm->dc_lock);
5873        }
5874
5875        /*
5876         * Update cursor state *after* programming all the planes.
5877         * This avoids redundant programming in the case where we're going
5878         * to be disabling a single plane - those pipes are being disabled.
5879         */
5880        if (acrtc_state->active_planes)
5881                amdgpu_dm_commit_cursors(state);
5882
5883cleanup:
5884        kfree(bundle);
5885}
5886
5887static void amdgpu_dm_commit_audio(struct drm_device *dev,
5888                                   struct drm_atomic_state *state)
5889{
5890        struct amdgpu_device *adev = dev->dev_private;
5891        struct amdgpu_dm_connector *aconnector;
5892        struct drm_connector *connector;
5893        struct drm_connector_state *old_con_state, *new_con_state;
5894        struct drm_crtc_state *new_crtc_state;
5895        struct dm_crtc_state *new_dm_crtc_state;
5896        const struct dc_stream_status *status;
5897        int i, inst;
5898
5899        /* Notify device removals. */
5900        for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5901                if (old_con_state->crtc != new_con_state->crtc) {
5902                        /* CRTC changes require notification. */
5903                        goto notify;
5904                }
5905
5906                if (!new_con_state->crtc)
5907                        continue;
5908
5909                new_crtc_state = drm_atomic_get_new_crtc_state(
5910                        state, new_con_state->crtc);
5911
5912                if (!new_crtc_state)
5913                        continue;
5914
5915                if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5916                        continue;
5917
5918        notify:
5919                aconnector = to_amdgpu_dm_connector(connector);
5920
5921                mutex_lock(&adev->dm.audio_lock);
5922                inst = aconnector->audio_inst;
5923                aconnector->audio_inst = -1;
5924                mutex_unlock(&adev->dm.audio_lock);
5925
5926                amdgpu_dm_audio_eld_notify(adev, inst);
5927        }
5928
5929        /* Notify audio device additions. */
5930        for_each_new_connector_in_state(state, connector, new_con_state, i) {
5931                if (!new_con_state->crtc)
5932                        continue;
5933
5934                new_crtc_state = drm_atomic_get_new_crtc_state(
5935                        state, new_con_state->crtc);
5936
5937                if (!new_crtc_state)
5938                        continue;
5939
5940                if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5941                        continue;
5942
5943                new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
5944                if (!new_dm_crtc_state->stream)
5945                        continue;
5946
5947                status = dc_stream_get_status(new_dm_crtc_state->stream);
5948                if (!status)
5949                        continue;
5950
5951                aconnector = to_amdgpu_dm_connector(connector);
5952
5953                mutex_lock(&adev->dm.audio_lock);
5954                inst = status->audio_inst;
5955                aconnector->audio_inst = inst;
5956                mutex_unlock(&adev->dm.audio_lock);
5957
5958                amdgpu_dm_audio_eld_notify(adev, inst);
5959        }
5960}
5961
5962/*
5963 * Enable interrupts on CRTCs that are newly active, undergone
5964 * a modeset, or have active planes again.
5965 *
5966 * Done in two passes, based on the for_modeset flag:
5967 * Pass 1: For CRTCs going through modeset
5968 * Pass 2: For CRTCs going from 0 to n active planes
5969 *
5970 * Interrupts can only be enabled after the planes are programmed,
5971 * so this requires a two-pass approach since we don't want to
5972 * just defer the interrupts until after commit planes every time.
5973 */
5974static void amdgpu_dm_enable_crtc_interrupts(struct drm_device *dev,
5975                                             struct drm_atomic_state *state,
5976                                             bool for_modeset)
5977{
5978        struct amdgpu_device *adev = dev->dev_private;
5979        struct drm_crtc *crtc;
5980        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5981        int i;
5982
5983        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5984                                      new_crtc_state, i) {
5985                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5986                struct dm_crtc_state *dm_new_crtc_state =
5987                        to_dm_crtc_state(new_crtc_state);
5988                struct dm_crtc_state *dm_old_crtc_state =
5989                        to_dm_crtc_state(old_crtc_state);
5990                bool modeset = drm_atomic_crtc_needs_modeset(new_crtc_state);
5991                bool run_pass;
5992
5993                run_pass = (for_modeset && modeset) ||
5994                           (!for_modeset && !modeset &&
5995                            !dm_old_crtc_state->interrupts_enabled);
5996
5997                if (!run_pass)
5998                        continue;
5999
6000                if (!dm_new_crtc_state->interrupts_enabled)
6001                        continue;
6002
6003                manage_dm_interrupts(adev, acrtc, true);
6004
6005#ifdef CONFIG_DEBUG_FS
6006                /* The stream has changed so CRC capture needs to re-enabled. */
6007                if (dm_new_crtc_state->crc_enabled) {
6008                        dm_new_crtc_state->crc_enabled = false;
6009                        amdgpu_dm_crtc_set_crc_source(crtc, "auto");
6010                }
6011#endif
6012        }
6013}
6014
6015/*
6016 * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
6017 * @crtc_state: the DRM CRTC state
6018 * @stream_state: the DC stream state.
6019 *
6020 * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
6021 * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
6022 */
6023static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
6024                                                struct dc_stream_state *stream_state)
6025{
6026        stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
6027}
6028
6029static int amdgpu_dm_atomic_commit(struct drm_device *dev,
6030                                   struct drm_atomic_state *state,
6031                                   bool nonblock)
6032{
6033        struct drm_crtc *crtc;
6034        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6035        struct amdgpu_device *adev = dev->dev_private;
6036        int i;
6037
6038        /*
6039         * We evade vblank and pflip interrupts on CRTCs that are undergoing
6040         * a modeset, being disabled, or have no active planes.
6041         *
6042         * It's done in atomic commit rather than commit tail for now since
6043         * some of these interrupt handlers access the current CRTC state and
6044         * potentially the stream pointer itself.
6045         *
6046         * Since the atomic state is swapped within atomic commit and not within
6047         * commit tail this would leave to new state (that hasn't been committed yet)
6048         * being accesssed from within the handlers.
6049         *
6050         * TODO: Fix this so we can do this in commit tail and not have to block
6051         * in atomic check.
6052         */
6053        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6054                struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6055                struct dm_crtc_state *dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6056                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6057
6058                if (dm_old_crtc_state->interrupts_enabled &&
6059                    (!dm_new_crtc_state->interrupts_enabled ||
6060                     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
6061                        /*
6062                         * Drop the extra vblank reference added by CRC
6063                         * capture if applicable.
6064                         */
6065                        if (dm_new_crtc_state->crc_enabled)
6066                                drm_crtc_vblank_put(crtc);
6067
6068                        /*
6069                         * Only keep CRC capture enabled if there's
6070                         * still a stream for the CRTC.
6071                         */
6072                        if (!dm_new_crtc_state->stream)
6073                                dm_new_crtc_state->crc_enabled = false;
6074
6075                        manage_dm_interrupts(adev, acrtc, false);
6076                }
6077        }
6078        /*
6079         * Add check here for SoC's that support hardware cursor plane, to
6080         * unset legacy_cursor_update
6081         */
6082
6083        return drm_atomic_helper_commit(dev, state, nonblock);
6084
6085        /*TODO Handle EINTR, reenable IRQ*/
6086}
6087
6088/**
6089 * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
6090 * @state: The atomic state to commit
6091 *
6092 * This will tell DC to commit the constructed DC state from atomic_check,
6093 * programming the hardware. Any failures here implies a hardware failure, since
6094 * atomic check should have filtered anything non-kosher.
6095 */
6096static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
6097{
6098        struct drm_device *dev = state->dev;
6099        struct amdgpu_device *adev = dev->dev_private;
6100        struct amdgpu_display_manager *dm = &adev->dm;
6101        struct dm_atomic_state *dm_state;
6102        struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
6103        uint32_t i, j;
6104        struct drm_crtc *crtc;
6105        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6106        unsigned long flags;
6107        bool wait_for_vblank = true;
6108        struct drm_connector *connector;
6109        struct drm_connector_state *old_con_state, *new_con_state;
6110        struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6111        int crtc_disable_count = 0;
6112
6113        drm_atomic_helper_update_legacy_modeset_state(dev, state);
6114
6115        dm_state = dm_atomic_get_new_state(state);
6116        if (dm_state && dm_state->context) {
6117                dc_state = dm_state->context;
6118        } else {
6119                /* No state changes, retain current state. */
6120                dc_state_temp = dc_create_state(dm->dc);
6121                ASSERT(dc_state_temp);
6122                dc_state = dc_state_temp;
6123                dc_resource_state_copy_construct_current(dm->dc, dc_state);
6124        }
6125
6126        /* update changed items */
6127        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6128                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6129
6130                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6131                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6132
6133                DRM_DEBUG_DRIVER(
6134                        "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6135                        "planes_changed:%d, mode_changed:%d,active_changed:%d,"
6136                        "connectors_changed:%d\n",
6137                        acrtc->crtc_id,
6138                        new_crtc_state->enable,
6139                        new_crtc_state->active,
6140                        new_crtc_state->planes_changed,
6141                        new_crtc_state->mode_changed,
6142                        new_crtc_state->active_changed,
6143                        new_crtc_state->connectors_changed);
6144
6145                /* Copy all transient state flags into dc state */
6146                if (dm_new_crtc_state->stream) {
6147                        amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
6148                                                            dm_new_crtc_state->stream);
6149                }
6150
6151                /* handles headless hotplug case, updating new_state and
6152                 * aconnector as needed
6153                 */
6154
6155                if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
6156
6157                        DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
6158
6159                        if (!dm_new_crtc_state->stream) {
6160                                /*
6161                                 * this could happen because of issues with
6162                                 * userspace notifications delivery.
6163                                 * In this case userspace tries to set mode on
6164                                 * display which is disconnected in fact.
6165                                 * dc_sink is NULL in this case on aconnector.
6166                                 * We expect reset mode will come soon.
6167                                 *
6168                                 * This can also happen when unplug is done
6169                                 * during resume sequence ended
6170                                 *
6171                                 * In this case, we want to pretend we still
6172                                 * have a sink to keep the pipe running so that
6173                                 * hw state is consistent with the sw state
6174                                 */
6175                                DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6176                                                __func__, acrtc->base.base.id);
6177                                continue;
6178                        }
6179
6180                        if (dm_old_crtc_state->stream)
6181                                remove_stream(adev, acrtc, dm_old_crtc_state->stream);
6182
6183                        pm_runtime_get_noresume(dev->dev);
6184
6185                        acrtc->enabled = true;
6186                        acrtc->hw_mode = new_crtc_state->mode;
6187                        crtc->hwmode = new_crtc_state->mode;
6188                } else if (modereset_required(new_crtc_state)) {
6189                        DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
6190
6191                        /* i.e. reset mode */
6192                        if (dm_old_crtc_state->stream)
6193                                remove_stream(adev, acrtc, dm_old_crtc_state->stream);
6194                }
6195        } /* for_each_crtc_in_state() */
6196
6197        if (dc_state) {
6198                dm_enable_per_frame_crtc_master_sync(dc_state);
6199                mutex_lock(&dm->dc_lock);
6200                WARN_ON(!dc_commit_state(dm->dc, dc_state));
6201                mutex_unlock(&dm->dc_lock);
6202        }
6203
6204        for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6205                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6206
6207                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6208
6209                if (dm_new_crtc_state->stream != NULL) {
6210                        const struct dc_stream_status *status =
6211                                        dc_stream_get_status(dm_new_crtc_state->stream);
6212
6213                        if (!status)
6214                                status = dc_stream_get_status_from_state(dc_state,
6215                                                                         dm_new_crtc_state->stream);
6216
6217                        if (!status)
6218                                DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
6219                        else
6220                                acrtc->otg_inst = status->primary_otg_inst;
6221                }
6222        }
6223
6224        /* Handle connector state changes */
6225        for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6226                struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6227                struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6228                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6229                struct dc_surface_update dummy_updates[MAX_SURFACES];
6230                struct dc_stream_update stream_update;
6231                struct dc_info_packet hdr_packet;
6232                struct dc_stream_status *status = NULL;
6233                bool abm_changed, hdr_changed, scaling_changed;
6234
6235                memset(&dummy_updates, 0, sizeof(dummy_updates));
6236                memset(&stream_update, 0, sizeof(stream_update));
6237
6238                if (acrtc) {
6239                        new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
6240                        old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
6241                }
6242
6243                /* Skip any modesets/resets */
6244                if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
6245                        continue;
6246
6247                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6248                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6249
6250                scaling_changed = is_scaling_state_different(dm_new_con_state,
6251                                                             dm_old_con_state);
6252
6253                abm_changed = dm_new_crtc_state->abm_level !=
6254                              dm_old_crtc_state->abm_level;
6255
6256                hdr_changed =
6257                        is_hdr_metadata_different(old_con_state, new_con_state);
6258
6259                if (!scaling_changed && !abm_changed && !hdr_changed)
6260                        continue;
6261
6262                if (scaling_changed) {
6263                        update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
6264                                        dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
6265
6266                        stream_update.src = dm_new_crtc_state->stream->src;
6267                        stream_update.dst = dm_new_crtc_state->stream->dst;
6268                }
6269
6270                if (abm_changed) {
6271                        dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
6272
6273                        stream_update.abm_level = &dm_new_crtc_state->abm_level;
6274                }
6275
6276                if (hdr_changed) {
6277                        fill_hdr_info_packet(new_con_state, &hdr_packet);
6278                        stream_update.hdr_static_metadata = &hdr_packet;
6279                }
6280
6281                status = dc_stream_get_status(dm_new_crtc_state->stream);
6282                WARN_ON(!status);
6283                WARN_ON(!status->plane_count);
6284
6285                /*
6286                 * TODO: DC refuses to perform stream updates without a dc_surface_update.
6287                 * Here we create an empty update on each plane.
6288                 * To fix this, DC should permit updating only stream properties.
6289                 */
6290                for (j = 0; j < status->plane_count; j++)
6291                        dummy_updates[j].surface = status->plane_states[0];
6292
6293
6294                mutex_lock(&dm->dc_lock);
6295                dc_commit_updates_for_stream(dm->dc,
6296                                                     dummy_updates,
6297                                                     status->plane_count,
6298                                                     dm_new_crtc_state->stream,
6299                                                     &stream_update,
6300                                                     dc_state);
6301                mutex_unlock(&dm->dc_lock);
6302        }
6303
6304        /* Count number of newly disabled CRTCs for dropping PM refs later. */
6305        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
6306                                      new_crtc_state, i) {
6307                if (old_crtc_state->active && !new_crtc_state->active)
6308                        crtc_disable_count++;
6309
6310                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6311                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6312
6313                /* Update freesync active state. */
6314                pre_update_freesync_state_on_stream(dm, dm_new_crtc_state);
6315
6316                /* Handle vrr on->off / off->on transitions */
6317                amdgpu_dm_handle_vrr_transition(dm_old_crtc_state,
6318                                                dm_new_crtc_state);
6319        }
6320
6321        /* Enable interrupts for CRTCs going through a modeset. */
6322        amdgpu_dm_enable_crtc_interrupts(dev, state, true);
6323
6324        for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
6325                if (new_crtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC)
6326                        wait_for_vblank = false;
6327
6328        /* update planes when needed per crtc*/
6329        for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
6330                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6331
6332                if (dm_new_crtc_state->stream)
6333                        amdgpu_dm_commit_planes(state, dc_state, dev,
6334                                                dm, crtc, wait_for_vblank);
6335        }
6336
6337        /* Enable interrupts for CRTCs going from 0 to n active planes. */
6338        amdgpu_dm_enable_crtc_interrupts(dev, state, false);
6339
6340        /* Update audio instances for each connector. */
6341        amdgpu_dm_commit_audio(dev, state);
6342
6343        /*
6344         * send vblank event on all events not handled in flip and
6345         * mark consumed event for drm_atomic_helper_commit_hw_done
6346         */
6347        spin_lock_irqsave(&adev->ddev->event_lock, flags);
6348        for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6349
6350                if (new_crtc_state->event)
6351                        drm_send_event_locked(dev, &new_crtc_state->event->base);
6352
6353                new_crtc_state->event = NULL;
6354        }
6355        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
6356
6357        /* Signal HW programming completion */
6358        drm_atomic_helper_commit_hw_done(state);
6359
6360        if (wait_for_vblank)
6361                drm_atomic_helper_wait_for_flip_done(dev, state);
6362
6363        drm_atomic_helper_cleanup_planes(dev, state);
6364
6365        /*
6366         * Finally, drop a runtime PM reference for each newly disabled CRTC,
6367         * so we can put the GPU into runtime suspend if we're not driving any
6368         * displays anymore
6369         */
6370        for (i = 0; i < crtc_disable_count; i++)
6371                pm_runtime_put_autosuspend(dev->dev);
6372        pm_runtime_mark_last_busy(dev->dev);
6373
6374        if (dc_state_temp)
6375                dc_release_state(dc_state_temp);
6376}
6377
6378
6379static int dm_force_atomic_commit(struct drm_connector *connector)
6380{
6381        int ret = 0;
6382        struct drm_device *ddev = connector->dev;
6383        struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
6384        struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6385        struct drm_plane *plane = disconnected_acrtc->base.primary;
6386        struct drm_connector_state *conn_state;
6387        struct drm_crtc_state *crtc_state;
6388        struct drm_plane_state *plane_state;
6389
6390        if (!state)
6391                return -ENOMEM;
6392
6393        state->acquire_ctx = ddev->mode_config.acquire_ctx;
6394
6395        /* Construct an atomic state to restore previous display setting */
6396
6397        /*
6398         * Attach connectors to drm_atomic_state
6399         */
6400        conn_state = drm_atomic_get_connector_state(state, connector);
6401
6402        ret = PTR_ERR_OR_ZERO(conn_state);
6403        if (ret)
6404                goto err;
6405
6406        /* Attach crtc to drm_atomic_state*/
6407        crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
6408
6409        ret = PTR_ERR_OR_ZERO(crtc_state);
6410        if (ret)
6411                goto err;
6412
6413        /* force a restore */
6414        crtc_state->mode_changed = true;
6415
6416        /* Attach plane to drm_atomic_state */
6417        plane_state = drm_atomic_get_plane_state(state, plane);
6418
6419        ret = PTR_ERR_OR_ZERO(plane_state);
6420        if (ret)
6421                goto err;
6422
6423
6424        /* Call commit internally with the state we just constructed */
6425        ret = drm_atomic_commit(state);
6426        if (!ret)
6427                return 0;
6428
6429err:
6430        DRM_ERROR("Restoring old state failed with %i\n", ret);
6431        drm_atomic_state_put(state);
6432
6433        return ret;
6434}
6435
6436/*
6437 * This function handles all cases when set mode does not come upon hotplug.
6438 * This includes when a display is unplugged then plugged back into the
6439 * same port and when running without usermode desktop manager supprot
6440 */
6441void dm_restore_drm_connector_state(struct drm_device *dev,
6442                                    struct drm_connector *connector)
6443{
6444        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6445        struct amdgpu_crtc *disconnected_acrtc;
6446        struct dm_crtc_state *acrtc_state;
6447
6448        if (!aconnector->dc_sink || !connector->state || !connector->encoder)
6449                return;
6450
6451        disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6452        if (!disconnected_acrtc)
6453                return;
6454
6455        acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
6456        if (!acrtc_state->stream)
6457                return;
6458
6459        /*
6460         * If the previous sink is not released and different from the current,
6461         * we deduce we are in a state where we can not rely on usermode call
6462         * to turn on the display, so we do it here
6463         */
6464        if (acrtc_state->stream->sink != aconnector->dc_sink)
6465                dm_force_atomic_commit(&aconnector->base);
6466}
6467
6468/*
6469 * Grabs all modesetting locks to serialize against any blocking commits,
6470 * Waits for completion of all non blocking commits.
6471 */
6472static int do_aquire_global_lock(struct drm_device *dev,
6473                                 struct drm_atomic_state *state)
6474{
6475        struct drm_crtc *crtc;
6476        struct drm_crtc_commit *commit;
6477        long ret;
6478
6479        /*
6480         * Adding all modeset locks to aquire_ctx will
6481         * ensure that when the framework release it the
6482         * extra locks we are locking here will get released to
6483         */
6484        ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
6485        if (ret)
6486                return ret;
6487
6488        list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6489                spin_lock(&crtc->commit_lock);
6490                commit = list_first_entry_or_null(&crtc->commit_list,
6491                                struct drm_crtc_commit, commit_entry);
6492                if (commit)
6493                        drm_crtc_commit_get(commit);
6494                spin_unlock(&crtc->commit_lock);
6495
6496                if (!commit)
6497                        continue;
6498
6499                /*
6500                 * Make sure all pending HW programming completed and
6501                 * page flips done
6502                 */
6503                ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
6504
6505                if (ret > 0)
6506                        ret = wait_for_completion_interruptible_timeout(
6507                                        &commit->flip_done, 10*HZ);
6508
6509                if (ret == 0)
6510                        DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
6511                                  "timed out\n", crtc->base.id, crtc->name);
6512
6513                drm_crtc_commit_put(commit);
6514        }
6515
6516        return ret < 0 ? ret : 0;
6517}
6518
6519static void get_freesync_config_for_crtc(
6520        struct dm_crtc_state *new_crtc_state,
6521        struct dm_connector_state *new_con_state)
6522{
6523        struct mod_freesync_config config = {0};
6524        struct amdgpu_dm_connector *aconnector =
6525                        to_amdgpu_dm_connector(new_con_state->base.connector);
6526        struct drm_display_mode *mode = &new_crtc_state->base.mode;
6527        int vrefresh = drm_mode_vrefresh(mode);
6528
6529        new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
6530                                        vrefresh >= aconnector->min_vfreq &&
6531                                        vrefresh <= aconnector->max_vfreq;
6532
6533        if (new_crtc_state->vrr_supported) {
6534                new_crtc_state->stream->ignore_msa_timing_param = true;
6535                config.state = new_crtc_state->base.vrr_enabled ?
6536                                VRR_STATE_ACTIVE_VARIABLE :
6537                                VRR_STATE_INACTIVE;
6538                config.min_refresh_in_uhz =
6539                                aconnector->min_vfreq * 1000000;
6540                config.max_refresh_in_uhz =
6541                                aconnector->max_vfreq * 1000000;
6542                config.vsif_supported = true;
6543                config.btr = true;
6544        }
6545
6546        new_crtc_state->freesync_config = config;
6547}
6548
6549static void reset_freesync_config_for_crtc(
6550        struct dm_crtc_state *new_crtc_state)
6551{
6552        new_crtc_state->vrr_supported = false;
6553
6554        memset(&new_crtc_state->vrr_params, 0,
6555               sizeof(new_crtc_state->vrr_params));
6556        memset(&new_crtc_state->vrr_infopacket, 0,
6557               sizeof(new_crtc_state->vrr_infopacket));
6558}
6559
6560static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
6561                                struct drm_atomic_state *state,
6562                                struct drm_crtc *crtc,
6563                                struct drm_crtc_state *old_crtc_state,
6564                                struct drm_crtc_state *new_crtc_state,
6565                                bool enable,
6566                                bool *lock_and_validation_needed)
6567{
6568        struct dm_atomic_state *dm_state = NULL;
6569        struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6570        struct dc_stream_state *new_stream;
6571        int ret = 0;
6572
6573        /*
6574         * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
6575         * update changed items
6576         */
6577        struct amdgpu_crtc *acrtc = NULL;
6578        struct amdgpu_dm_connector *aconnector = NULL;
6579        struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
6580        struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
6581
6582        new_stream = NULL;
6583
6584        dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6585        dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6586        acrtc = to_amdgpu_crtc(crtc);
6587        aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
6588
6589        /* TODO This hack should go away */
6590        if (aconnector && enable) {
6591                /* Make sure fake sink is created in plug-in scenario */
6592                drm_new_conn_state = drm_atomic_get_new_connector_state(state,
6593                                                            &aconnector->base);
6594                drm_old_conn_state = drm_atomic_get_old_connector_state(state,
6595                                                            &aconnector->base);
6596
6597                if (IS_ERR(drm_new_conn_state)) {
6598                        ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
6599                        goto fail;
6600                }
6601
6602                dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
6603                dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
6604
6605                if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6606                        goto skip_modeset;
6607
6608                new_stream = create_stream_for_sink(aconnector,
6609                                                     &new_crtc_state->mode,
6610                                                    dm_new_conn_state,
6611                                                    dm_old_crtc_state->stream);
6612
6613                /*
6614                 * we can have no stream on ACTION_SET if a display
6615                 * was disconnected during S3, in this case it is not an
6616                 * error, the OS will be updated after detection, and
6617                 * will do the right thing on next atomic commit
6618                 */
6619
6620                if (!new_stream) {
6621                        DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6622                                        __func__, acrtc->base.base.id);
6623                        ret = -ENOMEM;
6624                        goto fail;
6625                }
6626
6627                dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6628
6629                ret = fill_hdr_info_packet(drm_new_conn_state,
6630                                           &new_stream->hdr_static_metadata);
6631                if (ret)
6632                        goto fail;
6633
6634                /*
6635                 * If we already removed the old stream from the context
6636                 * (and set the new stream to NULL) then we can't reuse
6637                 * the old stream even if the stream and scaling are unchanged.
6638                 * We'll hit the BUG_ON and black screen.
6639                 *
6640                 * TODO: Refactor this function to allow this check to work
6641                 * in all conditions.
6642                 */
6643                if (dm_new_crtc_state->stream &&
6644                    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
6645                    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
6646                        new_crtc_state->mode_changed = false;
6647                        DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
6648                                         new_crtc_state->mode_changed);
6649                }
6650        }
6651
6652        /* mode_changed flag may get updated above, need to check again */
6653        if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6654                goto skip_modeset;
6655
6656        DRM_DEBUG_DRIVER(
6657                "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6658                "planes_changed:%d, mode_changed:%d,active_changed:%d,"
6659                "connectors_changed:%d\n",
6660                acrtc->crtc_id,
6661                new_crtc_state->enable,
6662                new_crtc_state->active,
6663                new_crtc_state->planes_changed,
6664                new_crtc_state->mode_changed,
6665                new_crtc_state->active_changed,
6666                new_crtc_state->connectors_changed);
6667
6668        /* Remove stream for any changed/disabled CRTC */
6669        if (!enable) {
6670
6671                if (!dm_old_crtc_state->stream)
6672                        goto skip_modeset;
6673
6674                ret = dm_atomic_get_state(state, &dm_state);
6675                if (ret)
6676                        goto fail;
6677
6678                DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
6679                                crtc->base.id);
6680
6681                /* i.e. reset mode */
6682                if (dc_remove_stream_from_ctx(
6683                                dm->dc,
6684                                dm_state->context,
6685                                dm_old_crtc_state->stream) != DC_OK) {
6686                        ret = -EINVAL;
6687                        goto fail;
6688                }
6689
6690                dc_stream_release(dm_old_crtc_state->stream);
6691                dm_new_crtc_state->stream = NULL;
6692
6693                reset_freesync_config_for_crtc(dm_new_crtc_state);
6694
6695                *lock_and_validation_needed = true;
6696
6697        } else {/* Add stream for any updated/enabled CRTC */
6698                /*
6699                 * Quick fix to prevent NULL pointer on new_stream when
6700                 * added MST connectors not found in existing crtc_state in the chained mode
6701                 * TODO: need to dig out the root cause of that
6702                 */
6703                if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
6704                        goto skip_modeset;
6705
6706                if (modereset_required(new_crtc_state))
6707                        goto skip_modeset;
6708
6709                if (modeset_required(new_crtc_state, new_stream,
6710                                     dm_old_crtc_state->stream)) {
6711
6712                        WARN_ON(dm_new_crtc_state->stream);
6713
6714                        ret = dm_atomic_get_state(state, &dm_state);
6715                        if (ret)
6716                                goto fail;
6717
6718                        dm_new_crtc_state->stream = new_stream;
6719
6720                        dc_stream_retain(new_stream);
6721
6722                        DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
6723                                                crtc->base.id);
6724
6725                        if (dc_add_stream_to_ctx(
6726                                        dm->dc,
6727                                        dm_state->context,
6728                                        dm_new_crtc_state->stream) != DC_OK) {
6729                                ret = -EINVAL;
6730                                goto fail;
6731                        }
6732
6733                        *lock_and_validation_needed = true;
6734                }
6735        }
6736
6737skip_modeset:
6738        /* Release extra reference */
6739        if (new_stream)
6740                 dc_stream_release(new_stream);
6741
6742        /*
6743         * We want to do dc stream updates that do not require a
6744         * full modeset below.
6745         */
6746        if (!(enable && aconnector && new_crtc_state->enable &&
6747              new_crtc_state->active))
6748                return 0;
6749        /*
6750         * Given above conditions, the dc state cannot be NULL because:
6751         * 1. We're in the process of enabling CRTCs (just been added
6752         *    to the dc context, or already is on the context)
6753         * 2. Has a valid connector attached, and
6754         * 3. Is currently active and enabled.
6755         * => The dc stream state currently exists.
6756         */
6757        BUG_ON(dm_new_crtc_state->stream == NULL);
6758
6759        /* Scaling or underscan settings */
6760        if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
6761                update_stream_scaling_settings(
6762                        &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
6763
6764        /* ABM settings */
6765        dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6766
6767        /*
6768         * Color management settings. We also update color properties
6769         * when a modeset is needed, to ensure it gets reprogrammed.
6770         */
6771        if (dm_new_crtc_state->base.color_mgmt_changed ||
6772            drm_atomic_crtc_needs_modeset(new_crtc_state)) {
6773                ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
6774                if (ret)
6775                        goto fail;
6776        }
6777
6778        /* Update Freesync settings. */
6779        get_freesync_config_for_crtc(dm_new_crtc_state,
6780                                     dm_new_conn_state);
6781
6782        return ret;
6783
6784fail:
6785        if (new_stream)
6786                dc_stream_release(new_stream);
6787        return ret;
6788}
6789
6790static bool should_reset_plane(struct drm_atomic_state *state,
6791                               struct drm_plane *plane,
6792                               struct drm_plane_state *old_plane_state,
6793                               struct drm_plane_state *new_plane_state)
6794{
6795        struct drm_plane *other;
6796        struct drm_plane_state *old_other_state, *new_other_state;
6797        struct drm_crtc_state *new_crtc_state;
6798        int i;
6799
6800        /*
6801         * TODO: Remove this hack once the checks below are sufficient
6802         * enough to determine when we need to reset all the planes on
6803         * the stream.
6804         */
6805        if (state->allow_modeset)
6806                return true;
6807
6808        /* Exit early if we know that we're adding or removing the plane. */
6809        if (old_plane_state->crtc != new_plane_state->crtc)
6810                return true;
6811
6812        /* old crtc == new_crtc == NULL, plane not in context. */
6813        if (!new_plane_state->crtc)
6814                return false;
6815
6816        new_crtc_state =
6817                drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
6818
6819        if (!new_crtc_state)
6820                return true;
6821
6822        /* CRTC Degamma changes currently require us to recreate planes. */
6823        if (new_crtc_state->color_mgmt_changed)
6824                return true;
6825
6826        if (drm_atomic_crtc_needs_modeset(new_crtc_state))
6827                return true;
6828
6829        /*
6830         * If there are any new primary or overlay planes being added or
6831         * removed then the z-order can potentially change. To ensure
6832         * correct z-order and pipe acquisition the current DC architecture
6833         * requires us to remove and recreate all existing planes.
6834         *
6835         * TODO: Come up with a more elegant solution for this.
6836         */
6837        for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
6838                if (other->type == DRM_PLANE_TYPE_CURSOR)
6839                        continue;
6840
6841                if (old_other_state->crtc != new_plane_state->crtc &&
6842                    new_other_state->crtc != new_plane_state->crtc)
6843                        continue;
6844
6845                if (old_other_state->crtc != new_other_state->crtc)
6846                        return true;
6847
6848                /* TODO: Remove this once we can handle fast format changes. */
6849                if (old_other_state->fb && new_other_state->fb &&
6850                    old_other_state->fb->format != new_other_state->fb->format)
6851                        return true;
6852        }
6853
6854        return false;
6855}
6856
6857static int dm_update_plane_state(struct dc *dc,
6858                                 struct drm_atomic_state *state,
6859                                 struct drm_plane *plane,
6860                                 struct drm_plane_state *old_plane_state,
6861                                 struct drm_plane_state *new_plane_state,
6862                                 bool enable,
6863                                 bool *lock_and_validation_needed)
6864{
6865
6866        struct dm_atomic_state *dm_state = NULL;
6867        struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6868        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6869        struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
6870        struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
6871        bool needs_reset;
6872        int ret = 0;
6873
6874
6875        new_plane_crtc = new_plane_state->crtc;
6876        old_plane_crtc = old_plane_state->crtc;
6877        dm_new_plane_state = to_dm_plane_state(new_plane_state);
6878        dm_old_plane_state = to_dm_plane_state(old_plane_state);
6879
6880        /*TODO Implement atomic check for cursor plane */
6881        if (plane->type == DRM_PLANE_TYPE_CURSOR)
6882                return 0;
6883
6884        needs_reset = should_reset_plane(state, plane, old_plane_state,
6885                                         new_plane_state);
6886
6887        /* Remove any changed/removed planes */
6888        if (!enable) {
6889                if (!needs_reset)
6890                        return 0;
6891
6892                if (!old_plane_crtc)
6893                        return 0;
6894
6895                old_crtc_state = drm_atomic_get_old_crtc_state(
6896                                state, old_plane_crtc);
6897                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6898
6899                if (!dm_old_crtc_state->stream)
6900                        return 0;
6901
6902                DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
6903                                plane->base.id, old_plane_crtc->base.id);
6904
6905                ret = dm_atomic_get_state(state, &dm_state);
6906                if (ret)
6907                        return ret;
6908
6909                if (!dc_remove_plane_from_context(
6910                                dc,
6911                                dm_old_crtc_state->stream,
6912                                dm_old_plane_state->dc_state,
6913                                dm_state->context)) {
6914
6915                        ret = EINVAL;
6916                        return ret;
6917                }
6918
6919
6920                dc_plane_state_release(dm_old_plane_state->dc_state);
6921                dm_new_plane_state->dc_state = NULL;
6922
6923                *lock_and_validation_needed = true;
6924
6925        } else { /* Add new planes */
6926                struct dc_plane_state *dc_new_plane_state;
6927
6928                if (drm_atomic_plane_disabling(plane->state, new_plane_state))
6929                        return 0;
6930
6931                if (!new_plane_crtc)
6932                        return 0;
6933
6934                new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
6935                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6936
6937                if (!dm_new_crtc_state->stream)
6938                        return 0;
6939
6940                if (!needs_reset)
6941                        return 0;
6942
6943                WARN_ON(dm_new_plane_state->dc_state);
6944
6945                dc_new_plane_state = dc_create_plane_state(dc);
6946                if (!dc_new_plane_state)
6947                        return -ENOMEM;
6948
6949                DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
6950                                plane->base.id, new_plane_crtc->base.id);
6951
6952                ret = fill_dc_plane_attributes(
6953                        new_plane_crtc->dev->dev_private,
6954                        dc_new_plane_state,
6955                        new_plane_state,
6956                        new_crtc_state);
6957                if (ret) {
6958                        dc_plane_state_release(dc_new_plane_state);
6959                        return ret;
6960                }
6961
6962                ret = dm_atomic_get_state(state, &dm_state);
6963                if (ret) {
6964                        dc_plane_state_release(dc_new_plane_state);
6965                        return ret;
6966                }
6967
6968                /*
6969                 * Any atomic check errors that occur after this will
6970                 * not need a release. The plane state will be attached
6971                 * to the stream, and therefore part of the atomic
6972                 * state. It'll be released when the atomic state is
6973                 * cleaned.
6974                 */
6975                if (!dc_add_plane_to_context(
6976                                dc,
6977                                dm_new_crtc_state->stream,
6978                                dc_new_plane_state,
6979                                dm_state->context)) {
6980
6981                        dc_plane_state_release(dc_new_plane_state);
6982                        return -EINVAL;
6983                }
6984
6985                dm_new_plane_state->dc_state = dc_new_plane_state;
6986
6987                /* Tell DC to do a full surface update every time there
6988                 * is a plane change. Inefficient, but works for now.
6989                 */
6990                dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
6991
6992                *lock_and_validation_needed = true;
6993        }
6994
6995
6996        return ret;
6997}
6998
6999static int
7000dm_determine_update_type_for_commit(struct amdgpu_display_manager *dm,
7001                                    struct drm_atomic_state *state,
7002                                    enum surface_update_type *out_type)
7003{
7004        struct dc *dc = dm->dc;
7005        struct dm_atomic_state *dm_state = NULL, *old_dm_state = NULL;
7006        int i, j, num_plane, ret = 0;
7007        struct drm_plane_state *old_plane_state, *new_plane_state;
7008        struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
7009        struct drm_crtc *new_plane_crtc, *old_plane_crtc;
7010        struct drm_plane *plane;
7011
7012        struct drm_crtc *crtc;
7013        struct drm_crtc_state *new_crtc_state, *old_crtc_state;
7014        struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
7015        struct dc_stream_status *status = NULL;
7016
7017        struct dc_surface_update *updates;
7018        enum surface_update_type update_type = UPDATE_TYPE_FAST;
7019
7020        updates = kcalloc(MAX_SURFACES, sizeof(*updates), GFP_KERNEL);
7021
7022        if (!updates) {
7023                DRM_ERROR("Failed to allocate plane updates\n");
7024                /* Set type to FULL to avoid crashing in DC*/
7025                update_type = UPDATE_TYPE_FULL;
7026                goto cleanup;
7027        }
7028
7029        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7030                struct dc_scaling_info scaling_info;
7031                struct dc_stream_update stream_update;
7032
7033                memset(&stream_update, 0, sizeof(stream_update));
7034
7035                new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
7036                old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
7037                num_plane = 0;
7038
7039                if (new_dm_crtc_state->stream != old_dm_crtc_state->stream) {
7040                        update_type = UPDATE_TYPE_FULL;
7041                        goto cleanup;
7042                }
7043
7044                if (!new_dm_crtc_state->stream)
7045                        continue;
7046
7047                for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
7048                        new_plane_crtc = new_plane_state->crtc;
7049                        old_plane_crtc = old_plane_state->crtc;
7050                        new_dm_plane_state = to_dm_plane_state(new_plane_state);
7051                        old_dm_plane_state = to_dm_plane_state(old_plane_state);
7052
7053                        if (plane->type == DRM_PLANE_TYPE_CURSOR)
7054                                continue;
7055
7056                        if (new_dm_plane_state->dc_state != old_dm_plane_state->dc_state) {
7057                                update_type = UPDATE_TYPE_FULL;
7058                                goto cleanup;
7059                        }
7060
7061                        if (crtc != new_plane_crtc)
7062                                continue;
7063
7064                        updates[num_plane].surface = new_dm_plane_state->dc_state;
7065
7066                        if (new_crtc_state->mode_changed) {
7067                                stream_update.dst = new_dm_crtc_state->stream->dst;
7068                                stream_update.src = new_dm_crtc_state->stream->src;
7069                        }
7070
7071                        if (new_crtc_state->color_mgmt_changed) {
7072                                updates[num_plane].gamma =
7073                                                new_dm_plane_state->dc_state->gamma_correction;
7074                                updates[num_plane].in_transfer_func =
7075                                                new_dm_plane_state->dc_state->in_transfer_func;
7076                                stream_update.gamut_remap =
7077                                                &new_dm_crtc_state->stream->gamut_remap_matrix;
7078                                stream_update.output_csc_transform =
7079                                                &new_dm_crtc_state->stream->csc_color_matrix;
7080                                stream_update.out_transfer_func =
7081                                                new_dm_crtc_state->stream->out_transfer_func;
7082                        }
7083
7084                        ret = fill_dc_scaling_info(new_plane_state,
7085                                                   &scaling_info);
7086                        if (ret)
7087                                goto cleanup;
7088
7089                        updates[num_plane].scaling_info = &scaling_info;
7090
7091                        num_plane++;
7092                }
7093
7094                if (num_plane == 0)
7095                        continue;
7096
7097                ret = dm_atomic_get_state(state, &dm_state);
7098                if (ret)
7099                        goto cleanup;
7100
7101                old_dm_state = dm_atomic_get_old_state(state);
7102                if (!old_dm_state) {
7103                        ret = -EINVAL;
7104                        goto cleanup;
7105                }
7106
7107                status = dc_stream_get_status_from_state(old_dm_state->context,
7108                                                         new_dm_crtc_state->stream);
7109
7110                /*
7111                 * TODO: DC modifies the surface during this call so we need
7112                 * to lock here - find a way to do this without locking.
7113                 */
7114                mutex_lock(&dm->dc_lock);
7115                update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
7116                                                                  &stream_update, status);
7117                mutex_unlock(&dm->dc_lock);
7118
7119                if (update_type > UPDATE_TYPE_MED) {
7120                        update_type = UPDATE_TYPE_FULL;
7121                        goto cleanup;
7122                }
7123        }
7124
7125cleanup:
7126        kfree(updates);
7127
7128        *out_type = update_type;
7129        return ret;
7130}
7131
7132/**
7133 * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
7134 * @dev: The DRM device
7135 * @state: The atomic state to commit
7136 *
7137 * Validate that the given atomic state is programmable by DC into hardware.
7138 * This involves constructing a &struct dc_state reflecting the new hardware
7139 * state we wish to commit, then querying DC to see if it is programmable. It's
7140 * important not to modify the existing DC state. Otherwise, atomic_check
7141 * may unexpectedly commit hardware changes.
7142 *
7143 * When validating the DC state, it's important that the right locks are
7144 * acquired. For full updates case which removes/adds/updates streams on one
7145 * CRTC while flipping on another CRTC, acquiring global lock will guarantee
7146 * that any such full update commit will wait for completion of any outstanding
7147 * flip using DRMs synchronization events. See
7148 * dm_determine_update_type_for_commit()
7149 *
7150 * Note that DM adds the affected connectors for all CRTCs in state, when that
7151 * might not seem necessary. This is because DC stream creation requires the
7152 * DC sink, which is tied to the DRM connector state. Cleaning this up should
7153 * be possible but non-trivial - a possible TODO item.
7154 *
7155 * Return: -Error code if validation failed.
7156 */
7157static int amdgpu_dm_atomic_check(struct drm_device *dev,
7158                                  struct drm_atomic_state *state)
7159{
7160        struct amdgpu_device *adev = dev->dev_private;
7161        struct dm_atomic_state *dm_state = NULL;
7162        struct dc *dc = adev->dm.dc;
7163        struct drm_connector *connector;
7164        struct drm_connector_state *old_con_state, *new_con_state;
7165        struct drm_crtc *crtc;
7166        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
7167        struct drm_plane *plane;
7168        struct drm_plane_state *old_plane_state, *new_plane_state;
7169        enum surface_update_type update_type = UPDATE_TYPE_FAST;
7170        enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
7171
7172        int ret, i;
7173
7174        /*
7175         * This bool will be set for true for any modeset/reset
7176         * or plane update which implies non fast surface update.
7177         */
7178        bool lock_and_validation_needed = false;
7179
7180        ret = drm_atomic_helper_check_modeset(dev, state);
7181        if (ret)
7182                goto fail;
7183
7184        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7185                if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
7186                    !new_crtc_state->color_mgmt_changed &&
7187                    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled)
7188                        continue;
7189
7190                if (!new_crtc_state->enable)
7191                        continue;
7192
7193                ret = drm_atomic_add_affected_connectors(state, crtc);
7194                if (ret)
7195                        return ret;
7196
7197                ret = drm_atomic_add_affected_planes(state, crtc);
7198                if (ret)
7199                        goto fail;
7200        }
7201
7202        /*
7203         * Add all primary and overlay planes on the CRTC to the state
7204         * whenever a plane is enabled to maintain correct z-ordering
7205         * and to enable fast surface updates.
7206         */
7207        drm_for_each_crtc(crtc, dev) {
7208                bool modified = false;
7209
7210                for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7211                        if (plane->type == DRM_PLANE_TYPE_CURSOR)
7212                                continue;
7213
7214                        if (new_plane_state->crtc == crtc ||
7215                            old_plane_state->crtc == crtc) {
7216                                modified = true;
7217                                break;
7218                        }
7219                }
7220
7221                if (!modified)
7222                        continue;
7223
7224                drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
7225                        if (plane->type == DRM_PLANE_TYPE_CURSOR)
7226                                continue;
7227
7228                        new_plane_state =
7229                                drm_atomic_get_plane_state(state, plane);
7230
7231                        if (IS_ERR(new_plane_state)) {
7232                                ret = PTR_ERR(new_plane_state);
7233                                goto fail;
7234                        }
7235                }
7236        }
7237
7238        /* Remove exiting planes if they are modified */
7239        for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
7240                ret = dm_update_plane_state(dc, state, plane,
7241                                            old_plane_state,
7242                                            new_plane_state,
7243                                            false,
7244                                            &lock_and_validation_needed);
7245                if (ret)
7246                        goto fail;
7247        }
7248
7249        /* Disable all crtcs which require disable */
7250        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7251                ret = dm_update_crtc_state(&adev->dm, state, crtc,
7252                                           old_crtc_state,
7253                                           new_crtc_state,
7254                                           false,
7255                                           &lock_and_validation_needed);
7256                if (ret)
7257                        goto fail;
7258        }
7259
7260        /* Enable all crtcs which require enable */
7261        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7262                ret = dm_update_crtc_state(&adev->dm, state, crtc,
7263                                           old_crtc_state,
7264                                           new_crtc_state,
7265                                           true,
7266                                           &lock_and_validation_needed);
7267                if (ret)
7268                        goto fail;
7269        }
7270
7271        /* Add new/modified planes */
7272        for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
7273                ret = dm_update_plane_state(dc, state, plane,
7274                                            old_plane_state,
7275                                            new_plane_state,
7276                                            true,
7277                                            &lock_and_validation_needed);
7278                if (ret)
7279                        goto fail;
7280        }
7281
7282        /* Run this here since we want to validate the streams we created */
7283        ret = drm_atomic_helper_check_planes(dev, state);
7284        if (ret)
7285                goto fail;
7286
7287        /* Check scaling and underscan changes*/
7288        /* TODO Removed scaling changes validation due to inability to commit
7289         * new stream into context w\o causing full reset. Need to
7290         * decide how to handle.
7291         */
7292        for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
7293                struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
7294                struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
7295                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
7296
7297                /* Skip any modesets/resets */
7298                if (!acrtc || drm_atomic_crtc_needs_modeset(
7299                                drm_atomic_get_new_crtc_state(state, &acrtc->base)))
7300                        continue;
7301
7302                /* Skip any thing not scale or underscan changes */
7303                if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
7304                        continue;
7305
7306                overall_update_type = UPDATE_TYPE_FULL;
7307                lock_and_validation_needed = true;
7308        }
7309
7310        ret = dm_determine_update_type_for_commit(&adev->dm, state, &update_type);
7311        if (ret)
7312                goto fail;
7313
7314        if (overall_update_type < update_type)
7315                overall_update_type = update_type;
7316
7317        /*
7318         * lock_and_validation_needed was an old way to determine if we need to set
7319         * the global lock. Leaving it in to check if we broke any corner cases
7320         * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
7321         * lock_and_validation_needed false = UPDATE_TYPE_FAST
7322         */
7323        if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
7324                WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
7325
7326        if (overall_update_type > UPDATE_TYPE_FAST) {
7327                ret = dm_atomic_get_state(state, &dm_state);
7328                if (ret)
7329                        goto fail;
7330
7331                ret = do_aquire_global_lock(dev, state);
7332                if (ret)
7333                        goto fail;
7334
7335                if (dc_validate_global_state(dc, dm_state->context, false) != DC_OK) {
7336                        ret = -EINVAL;
7337                        goto fail;
7338                }
7339        } else if (state->legacy_cursor_update) {
7340                /*
7341                 * This is a fast cursor update coming from the plane update
7342                 * helper, check if it can be done asynchronously for better
7343                 * performance.
7344                 */
7345                state->async_update = !drm_atomic_helper_async_check(dev, state);
7346        }
7347
7348        /* Must be success */
7349        WARN_ON(ret);
7350        return ret;
7351
7352fail:
7353        if (ret == -EDEADLK)
7354                DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
7355        else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
7356                DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
7357        else
7358                DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
7359
7360        return ret;
7361}
7362
7363static bool is_dp_capable_without_timing_msa(struct dc *dc,
7364                                             struct amdgpu_dm_connector *amdgpu_dm_connector)
7365{
7366        uint8_t dpcd_data;
7367        bool capable = false;
7368
7369        if (amdgpu_dm_connector->dc_link &&
7370                dm_helpers_dp_read_dpcd(
7371                                NULL,
7372                                amdgpu_dm_connector->dc_link,
7373                                DP_DOWN_STREAM_PORT_COUNT,
7374                                &dpcd_data,
7375                                sizeof(dpcd_data))) {
7376                capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
7377        }
7378
7379        return capable;
7380}
7381void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
7382                                        struct edid *edid)
7383{
7384        int i;
7385        bool edid_check_required;
7386        struct detailed_timing *timing;
7387        struct detailed_non_pixel *data;
7388        struct detailed_data_monitor_range *range;
7389        struct amdgpu_dm_connector *amdgpu_dm_connector =
7390                        to_amdgpu_dm_connector(connector);
7391        struct dm_connector_state *dm_con_state = NULL;
7392
7393        struct drm_device *dev = connector->dev;
7394        struct amdgpu_device *adev = dev->dev_private;
7395        bool freesync_capable = false;
7396
7397        if (!connector->state) {
7398                DRM_ERROR("%s - Connector has no state", __func__);
7399                goto update;
7400        }
7401
7402        if (!edid) {
7403                dm_con_state = to_dm_connector_state(connector->state);
7404
7405                amdgpu_dm_connector->min_vfreq = 0;
7406                amdgpu_dm_connector->max_vfreq = 0;
7407                amdgpu_dm_connector->pixel_clock_mhz = 0;
7408
7409                goto update;
7410        }
7411
7412        dm_con_state = to_dm_connector_state(connector->state);
7413
7414        edid_check_required = false;
7415        if (!amdgpu_dm_connector->dc_sink) {
7416                DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
7417                goto update;
7418        }
7419        if (!adev->dm.freesync_module)
7420                goto update;
7421        /*
7422         * if edid non zero restrict freesync only for dp and edp
7423         */
7424        if (edid) {
7425                if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
7426                        || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
7427                        edid_check_required = is_dp_capable_without_timing_msa(
7428                                                adev->dm.dc,
7429                                                amdgpu_dm_connector);
7430                }
7431        }
7432        if (edid_check_required == true && (edid->version > 1 ||
7433           (edid->version == 1 && edid->revision > 1))) {
7434                for (i = 0; i < 4; i++) {
7435
7436                        timing  = &edid->detailed_timings[i];
7437                        data    = &timing->data.other_data;
7438                        range   = &data->data.range;
7439                        /*
7440                         * Check if monitor has continuous frequency mode
7441                         */
7442                        if (data->type != EDID_DETAIL_MONITOR_RANGE)
7443                                continue;
7444                        /*
7445                         * Check for flag range limits only. If flag == 1 then
7446                         * no additional timing information provided.
7447                         * Default GTF, GTF Secondary curve and CVT are not
7448                         * supported
7449                         */
7450                        if (range->flags != 1)
7451                                continue;
7452
7453                        amdgpu_dm_connector->min_vfreq = range->min_vfreq;
7454                        amdgpu_dm_connector->max_vfreq = range->max_vfreq;
7455                        amdgpu_dm_connector->pixel_clock_mhz =
7456                                range->pixel_clock_mhz * 10;
7457                        break;
7458                }
7459
7460                if (amdgpu_dm_connector->max_vfreq -
7461                    amdgpu_dm_connector->min_vfreq > 10) {
7462
7463                        freesync_capable = true;
7464                }
7465        }
7466
7467update:
7468        if (dm_con_state)
7469                dm_con_state->freesync_capable = freesync_capable;
7470
7471        if (connector->vrr_capable_property)
7472                drm_connector_set_vrr_capable_property(connector,
7473                                                       freesync_capable);
7474}
7475
7476