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#include "dm_services_types.h"
  27#include "dc.h"
  28#include "dc/inc/core_types.h"
  29
  30#include "vid.h"
  31#include "amdgpu.h"
  32#include "amdgpu_display.h"
  33#include "atom.h"
  34#include "amdgpu_dm.h"
  35#include "amdgpu_pm.h"
  36
  37#include "amd_shared.h"
  38#include "amdgpu_dm_irq.h"
  39#include "dm_helpers.h"
  40#include "dm_services_types.h"
  41#include "amdgpu_dm_mst_types.h"
  42
  43#include "ivsrcid/ivsrcid_vislands30.h"
  44
  45#include <linux/module.h>
  46#include <linux/moduleparam.h>
  47#include <linux/version.h>
  48#include <linux/types.h>
  49#include <linux/pm_runtime.h>
  50
  51#include <drm/drmP.h>
  52#include <drm/drm_atomic.h>
  53#include <drm/drm_atomic_helper.h>
  54#include <drm/drm_dp_mst_helper.h>
  55#include <drm/drm_fb_helper.h>
  56#include <drm/drm_edid.h>
  57
  58#include "modules/inc/mod_freesync.h"
  59
  60#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
  61#include "ivsrcid/irqsrcs_dcn_1_0.h"
  62
  63#include "dcn/dcn_1_0_offset.h"
  64#include "dcn/dcn_1_0_sh_mask.h"
  65#include "soc15_hw_ip.h"
  66#include "vega10_ip_offset.h"
  67
  68#include "soc15_common.h"
  69#endif
  70
  71#include "modules/inc/mod_freesync.h"
  72
  73#include "i2caux_interface.h"
  74
  75/* basic init/fini API */
  76static int amdgpu_dm_init(struct amdgpu_device *adev);
  77static void amdgpu_dm_fini(struct amdgpu_device *adev);
  78
  79/* initializes drm_device display related structures, based on the information
  80 * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
  81 * drm_encoder, drm_mode_config
  82 *
  83 * Returns 0 on success
  84 */
  85static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
  86/* removes and deallocates the drm structures, created by the above function */
  87static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
  88
  89static void
  90amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
  91
  92static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
  93                                struct amdgpu_plane *aplane,
  94                                unsigned long possible_crtcs);
  95static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
  96                               struct drm_plane *plane,
  97                               uint32_t link_index);
  98static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
  99                                    struct amdgpu_dm_connector *amdgpu_dm_connector,
 100                                    uint32_t link_index,
 101                                    struct amdgpu_encoder *amdgpu_encoder);
 102static int amdgpu_dm_encoder_init(struct drm_device *dev,
 103                                  struct amdgpu_encoder *aencoder,
 104                                  uint32_t link_index);
 105
 106static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
 107
 108static int amdgpu_dm_atomic_commit(struct drm_device *dev,
 109                                   struct drm_atomic_state *state,
 110                                   bool nonblock);
 111
 112static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
 113
 114static int amdgpu_dm_atomic_check(struct drm_device *dev,
 115                                  struct drm_atomic_state *state);
 116
 117
 118
 119
 120static const enum drm_plane_type dm_plane_type_default[AMDGPU_MAX_PLANES] = {
 121        DRM_PLANE_TYPE_PRIMARY,
 122        DRM_PLANE_TYPE_PRIMARY,
 123        DRM_PLANE_TYPE_PRIMARY,
 124        DRM_PLANE_TYPE_PRIMARY,
 125        DRM_PLANE_TYPE_PRIMARY,
 126        DRM_PLANE_TYPE_PRIMARY,
 127};
 128
 129static const enum drm_plane_type dm_plane_type_carizzo[AMDGPU_MAX_PLANES] = {
 130        DRM_PLANE_TYPE_PRIMARY,
 131        DRM_PLANE_TYPE_PRIMARY,
 132        DRM_PLANE_TYPE_PRIMARY,
 133        DRM_PLANE_TYPE_OVERLAY,/* YUV Capable Underlay */
 134};
 135
 136static const enum drm_plane_type dm_plane_type_stoney[AMDGPU_MAX_PLANES] = {
 137        DRM_PLANE_TYPE_PRIMARY,
 138        DRM_PLANE_TYPE_PRIMARY,
 139        DRM_PLANE_TYPE_OVERLAY, /* YUV Capable Underlay */
 140};
 141
 142/*
 143 * dm_vblank_get_counter
 144 *
 145 * @brief
 146 * Get counter for number of vertical blanks
 147 *
 148 * @param
 149 * struct amdgpu_device *adev - [in] desired amdgpu device
 150 * int disp_idx - [in] which CRTC to get the counter from
 151 *
 152 * @return
 153 * Counter for vertical blanks
 154 */
 155static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
 156{
 157        if (crtc >= adev->mode_info.num_crtc)
 158                return 0;
 159        else {
 160                struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
 161                struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
 162                                acrtc->base.state);
 163
 164
 165                if (acrtc_state->stream == NULL) {
 166                        DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
 167                                  crtc);
 168                        return 0;
 169                }
 170
 171                return dc_stream_get_vblank_counter(acrtc_state->stream);
 172        }
 173}
 174
 175static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
 176                                  u32 *vbl, u32 *position)
 177{
 178        uint32_t v_blank_start, v_blank_end, h_position, v_position;
 179
 180        if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
 181                return -EINVAL;
 182        else {
 183                struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
 184                struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
 185                                                acrtc->base.state);
 186
 187                if (acrtc_state->stream ==  NULL) {
 188                        DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
 189                                  crtc);
 190                        return 0;
 191                }
 192
 193                /*
 194                 * TODO rework base driver to use values directly.
 195                 * for now parse it back into reg-format
 196                 */
 197                dc_stream_get_scanoutpos(acrtc_state->stream,
 198                                         &v_blank_start,
 199                                         &v_blank_end,
 200                                         &h_position,
 201                                         &v_position);
 202
 203                *position = v_position | (h_position << 16);
 204                *vbl = v_blank_start | (v_blank_end << 16);
 205        }
 206
 207        return 0;
 208}
 209
 210static bool dm_is_idle(void *handle)
 211{
 212        /* XXX todo */
 213        return true;
 214}
 215
 216static int dm_wait_for_idle(void *handle)
 217{
 218        /* XXX todo */
 219        return 0;
 220}
 221
 222static bool dm_check_soft_reset(void *handle)
 223{
 224        return false;
 225}
 226
 227static int dm_soft_reset(void *handle)
 228{
 229        /* XXX todo */
 230        return 0;
 231}
 232
 233static struct amdgpu_crtc *
 234get_crtc_by_otg_inst(struct amdgpu_device *adev,
 235                     int otg_inst)
 236{
 237        struct drm_device *dev = adev->ddev;
 238        struct drm_crtc *crtc;
 239        struct amdgpu_crtc *amdgpu_crtc;
 240
 241        /*
 242         * following if is check inherited from both functions where this one is
 243         * used now. Need to be checked why it could happen.
 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 void dm_pflip_high_irq(void *interrupt_params)
 261{
 262        struct amdgpu_crtc *amdgpu_crtc;
 263        struct common_irq_params *irq_params = interrupt_params;
 264        struct amdgpu_device *adev = irq_params->adev;
 265        unsigned long flags;
 266
 267        amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
 268
 269        /* IRQ could occur when in initial stage */
 270        /*TODO work and BO cleanup */
 271        if (amdgpu_crtc == NULL) {
 272                DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
 273                return;
 274        }
 275
 276        spin_lock_irqsave(&adev->ddev->event_lock, flags);
 277
 278        if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
 279                DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
 280                                                 amdgpu_crtc->pflip_status,
 281                                                 AMDGPU_FLIP_SUBMITTED,
 282                                                 amdgpu_crtc->crtc_id,
 283                                                 amdgpu_crtc);
 284                spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 285                return;
 286        }
 287
 288
 289        /* wakeup usersapce */
 290        if (amdgpu_crtc->event) {
 291                /* Update to correct count/ts if racing with vblank irq */
 292                drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
 293
 294                drm_crtc_send_vblank_event(&amdgpu_crtc->base, amdgpu_crtc->event);
 295
 296                /* page flip completed. clean up */
 297                amdgpu_crtc->event = NULL;
 298
 299        } else
 300                WARN_ON(1);
 301
 302        amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
 303        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
 304
 305        DRM_DEBUG_DRIVER("%s - crtc :%d[%p], pflip_stat:AMDGPU_FLIP_NONE\n",
 306                                        __func__, amdgpu_crtc->crtc_id, amdgpu_crtc);
 307
 308        drm_crtc_vblank_put(&amdgpu_crtc->base);
 309}
 310
 311static void dm_crtc_high_irq(void *interrupt_params)
 312{
 313        struct common_irq_params *irq_params = interrupt_params;
 314        struct amdgpu_device *adev = irq_params->adev;
 315        uint8_t crtc_index = 0;
 316        struct amdgpu_crtc *acrtc;
 317
 318        acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
 319
 320        if (acrtc)
 321                crtc_index = acrtc->crtc_id;
 322
 323        drm_handle_vblank(adev->ddev, crtc_index);
 324        amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
 325}
 326
 327static int dm_set_clockgating_state(void *handle,
 328                  enum amd_clockgating_state state)
 329{
 330        return 0;
 331}
 332
 333static int dm_set_powergating_state(void *handle,
 334                  enum amd_powergating_state state)
 335{
 336        return 0;
 337}
 338
 339/* Prototypes of private functions */
 340static int dm_early_init(void* handle);
 341
 342static void hotplug_notify_work_func(struct work_struct *work)
 343{
 344        struct amdgpu_display_manager *dm = container_of(work, struct amdgpu_display_manager, mst_hotplug_work);
 345        struct drm_device *dev = dm->ddev;
 346
 347        drm_kms_helper_hotplug_event(dev);
 348}
 349
 350#if defined(CONFIG_DRM_AMD_DC_FBC)
 351/* Allocate memory for FBC compressed data  */
 352static void amdgpu_dm_fbc_init(struct drm_connector *connector)
 353{
 354        struct drm_device *dev = connector->dev;
 355        struct amdgpu_device *adev = dev->dev_private;
 356        struct dm_comressor_info *compressor = &adev->dm.compressor;
 357        struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
 358        struct drm_display_mode *mode;
 359        unsigned long max_size = 0;
 360
 361        if (adev->dm.dc->fbc_compressor == NULL)
 362                return;
 363
 364        if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
 365                return;
 366
 367        if (compressor->bo_ptr)
 368                return;
 369
 370
 371        list_for_each_entry(mode, &connector->modes, head) {
 372                if (max_size < mode->htotal * mode->vtotal)
 373                        max_size = mode->htotal * mode->vtotal;
 374        }
 375
 376        if (max_size) {
 377                int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
 378                            AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
 379                            &compressor->gpu_addr, &compressor->cpu_addr);
 380
 381                if (r)
 382                        DRM_ERROR("DM: Failed to initialize FBC\n");
 383                else {
 384                        adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
 385                        DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
 386                }
 387
 388        }
 389
 390}
 391#endif
 392
 393
 394/* Init display KMS
 395 *
 396 * Returns 0 on success
 397 */
 398static int amdgpu_dm_init(struct amdgpu_device *adev)
 399{
 400        struct dc_init_data init_data;
 401        adev->dm.ddev = adev->ddev;
 402        adev->dm.adev = adev;
 403
 404        /* Zero all the fields */
 405        memset(&init_data, 0, sizeof(init_data));
 406
 407        if(amdgpu_dm_irq_init(adev)) {
 408                DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
 409                goto error;
 410        }
 411
 412        init_data.asic_id.chip_family = adev->family;
 413
 414        init_data.asic_id.pci_revision_id = adev->rev_id;
 415        init_data.asic_id.hw_internal_rev = adev->external_rev_id;
 416
 417        init_data.asic_id.vram_width = adev->gmc.vram_width;
 418        /* TODO: initialize init_data.asic_id.vram_type here!!!! */
 419        init_data.asic_id.atombios_base_address =
 420                adev->mode_info.atom_context->bios;
 421
 422        init_data.driver = adev;
 423
 424        adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
 425
 426        if (!adev->dm.cgs_device) {
 427                DRM_ERROR("amdgpu: failed to create cgs device.\n");
 428                goto error;
 429        }
 430
 431        init_data.cgs_device = adev->dm.cgs_device;
 432
 433        adev->dm.dal = NULL;
 434
 435        init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
 436
 437        /*
 438         * TODO debug why this doesn't work on Raven
 439         */
 440        if (adev->flags & AMD_IS_APU &&
 441            adev->asic_type >= CHIP_CARRIZO &&
 442            adev->asic_type < CHIP_RAVEN)
 443                init_data.flags.gpu_vm_support = true;
 444
 445        /* Display Core create. */
 446        adev->dm.dc = dc_create(&init_data);
 447
 448        if (adev->dm.dc) {
 449                DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
 450        } else {
 451                DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
 452                goto error;
 453        }
 454
 455        INIT_WORK(&adev->dm.mst_hotplug_work, hotplug_notify_work_func);
 456
 457        adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
 458        if (!adev->dm.freesync_module) {
 459                DRM_ERROR(
 460                "amdgpu: failed to initialize freesync_module.\n");
 461        } else
 462                DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
 463                                adev->dm.freesync_module);
 464
 465        amdgpu_dm_init_color_mod();
 466
 467        if (amdgpu_dm_initialize_drm_device(adev)) {
 468                DRM_ERROR(
 469                "amdgpu: failed to initialize sw for display support.\n");
 470                goto error;
 471        }
 472
 473        /* Update the actual used number of crtc */
 474        adev->mode_info.num_crtc = adev->dm.display_indexes_num;
 475
 476        /* TODO: Add_display_info? */
 477
 478        /* TODO use dynamic cursor width */
 479        adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
 480        adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
 481
 482        if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
 483                DRM_ERROR(
 484                "amdgpu: failed to initialize sw for display support.\n");
 485                goto error;
 486        }
 487
 488        DRM_DEBUG_DRIVER("KMS initialized.\n");
 489
 490        return 0;
 491error:
 492        amdgpu_dm_fini(adev);
 493
 494        return -1;
 495}
 496
 497static void amdgpu_dm_fini(struct amdgpu_device *adev)
 498{
 499        amdgpu_dm_destroy_drm_device(&adev->dm);
 500        /*
 501         * TODO: pageflip, vlank interrupt
 502         *
 503         * amdgpu_dm_irq_fini(adev);
 504         */
 505
 506        if (adev->dm.cgs_device) {
 507                amdgpu_cgs_destroy_device(adev->dm.cgs_device);
 508                adev->dm.cgs_device = NULL;
 509        }
 510        if (adev->dm.freesync_module) {
 511                mod_freesync_destroy(adev->dm.freesync_module);
 512                adev->dm.freesync_module = NULL;
 513        }
 514        /* DC Destroy TODO: Replace destroy DAL */
 515        if (adev->dm.dc)
 516                dc_destroy(&adev->dm.dc);
 517        return;
 518}
 519
 520static int dm_sw_init(void *handle)
 521{
 522        return 0;
 523}
 524
 525static int dm_sw_fini(void *handle)
 526{
 527        return 0;
 528}
 529
 530static int detect_mst_link_for_all_connectors(struct drm_device *dev)
 531{
 532        struct amdgpu_dm_connector *aconnector;
 533        struct drm_connector *connector;
 534        int ret = 0;
 535
 536        drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
 537
 538        list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
 539                aconnector = to_amdgpu_dm_connector(connector);
 540                if (aconnector->dc_link->type == dc_connection_mst_branch &&
 541                    aconnector->mst_mgr.aux) {
 542                        DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
 543                                        aconnector, aconnector->base.base.id);
 544
 545                        ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
 546                        if (ret < 0) {
 547                                DRM_ERROR("DM_MST: Failed to start MST\n");
 548                                ((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
 549                                return ret;
 550                                }
 551                        }
 552        }
 553
 554        drm_modeset_unlock(&dev->mode_config.connection_mutex);
 555        return ret;
 556}
 557
 558static int dm_late_init(void *handle)
 559{
 560        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 561
 562        return detect_mst_link_for_all_connectors(adev->ddev);
 563}
 564
 565static void s3_handle_mst(struct drm_device *dev, bool suspend)
 566{
 567        struct amdgpu_dm_connector *aconnector;
 568        struct drm_connector *connector;
 569
 570        drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
 571
 572        list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
 573                   aconnector = to_amdgpu_dm_connector(connector);
 574                   if (aconnector->dc_link->type == dc_connection_mst_branch &&
 575                                   !aconnector->mst_port) {
 576
 577                           if (suspend)
 578                                   drm_dp_mst_topology_mgr_suspend(&aconnector->mst_mgr);
 579                           else
 580                                   drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr);
 581                   }
 582        }
 583
 584        drm_modeset_unlock(&dev->mode_config.connection_mutex);
 585}
 586
 587static int dm_hw_init(void *handle)
 588{
 589        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 590        /* Create DAL display manager */
 591        amdgpu_dm_init(adev);
 592        amdgpu_dm_hpd_init(adev);
 593
 594        return 0;
 595}
 596
 597static int dm_hw_fini(void *handle)
 598{
 599        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 600
 601        amdgpu_dm_hpd_fini(adev);
 602
 603        amdgpu_dm_irq_fini(adev);
 604        amdgpu_dm_fini(adev);
 605        return 0;
 606}
 607
 608static int dm_suspend(void *handle)
 609{
 610        struct amdgpu_device *adev = handle;
 611        struct amdgpu_display_manager *dm = &adev->dm;
 612        int ret = 0;
 613
 614        s3_handle_mst(adev->ddev, true);
 615
 616        amdgpu_dm_irq_suspend(adev);
 617
 618        WARN_ON(adev->dm.cached_state);
 619        adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
 620
 621        dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
 622
 623        return ret;
 624}
 625
 626static struct amdgpu_dm_connector *
 627amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
 628                                             struct drm_crtc *crtc)
 629{
 630        uint32_t i;
 631        struct drm_connector_state *new_con_state;
 632        struct drm_connector *connector;
 633        struct drm_crtc *crtc_from_state;
 634
 635        for_each_new_connector_in_state(state, connector, new_con_state, i) {
 636                crtc_from_state = new_con_state->crtc;
 637
 638                if (crtc_from_state == crtc)
 639                        return to_amdgpu_dm_connector(connector);
 640        }
 641
 642        return NULL;
 643}
 644
 645static int dm_resume(void *handle)
 646{
 647        struct amdgpu_device *adev = handle;
 648        struct drm_device *ddev = adev->ddev;
 649        struct amdgpu_display_manager *dm = &adev->dm;
 650        struct amdgpu_dm_connector *aconnector;
 651        struct drm_connector *connector;
 652        struct drm_crtc *crtc;
 653        struct drm_crtc_state *new_crtc_state;
 654        struct dm_crtc_state *dm_new_crtc_state;
 655        struct drm_plane *plane;
 656        struct drm_plane_state *new_plane_state;
 657        struct dm_plane_state *dm_new_plane_state;
 658        int ret;
 659        int i;
 660
 661        /* power on hardware */
 662        dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
 663
 664        /* program HPD filter */
 665        dc_resume(dm->dc);
 666
 667        /* On resume we need to  rewrite the MSTM control bits to enamble MST*/
 668        s3_handle_mst(ddev, false);
 669
 670        /*
 671         * early enable HPD Rx IRQ, should be done before set mode as short
 672         * pulse interrupts are used for MST
 673         */
 674        amdgpu_dm_irq_resume_early(adev);
 675
 676        /* Do detection*/
 677        list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
 678                aconnector = to_amdgpu_dm_connector(connector);
 679
 680                /*
 681                 * this is the case when traversing through already created
 682                 * MST connectors, should be skipped
 683                 */
 684                if (aconnector->mst_port)
 685                        continue;
 686
 687                mutex_lock(&aconnector->hpd_lock);
 688                dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
 689
 690                if (aconnector->fake_enable && aconnector->dc_link->local_sink)
 691                        aconnector->fake_enable = false;
 692
 693                aconnector->dc_sink = NULL;
 694                amdgpu_dm_update_connector_after_detect(aconnector);
 695                mutex_unlock(&aconnector->hpd_lock);
 696        }
 697
 698        /* Force mode set in atomic comit */
 699        for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
 700                new_crtc_state->active_changed = true;
 701
 702        /*
 703         * atomic_check is expected to create the dc states. We need to release
 704         * them here, since they were duplicated as part of the suspend
 705         * procedure.
 706         */
 707        for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
 708                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 709                if (dm_new_crtc_state->stream) {
 710                        WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
 711                        dc_stream_release(dm_new_crtc_state->stream);
 712                        dm_new_crtc_state->stream = NULL;
 713                }
 714        }
 715
 716        for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
 717                dm_new_plane_state = to_dm_plane_state(new_plane_state);
 718                if (dm_new_plane_state->dc_state) {
 719                        WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
 720                        dc_plane_state_release(dm_new_plane_state->dc_state);
 721                        dm_new_plane_state->dc_state = NULL;
 722                }
 723        }
 724
 725        ret = drm_atomic_helper_resume(ddev, dm->cached_state);
 726
 727        dm->cached_state = NULL;
 728
 729        amdgpu_dm_irq_resume_late(adev);
 730
 731        return ret;
 732}
 733
 734static const struct amd_ip_funcs amdgpu_dm_funcs = {
 735        .name = "dm",
 736        .early_init = dm_early_init,
 737        .late_init = dm_late_init,
 738        .sw_init = dm_sw_init,
 739        .sw_fini = dm_sw_fini,
 740        .hw_init = dm_hw_init,
 741        .hw_fini = dm_hw_fini,
 742        .suspend = dm_suspend,
 743        .resume = dm_resume,
 744        .is_idle = dm_is_idle,
 745        .wait_for_idle = dm_wait_for_idle,
 746        .check_soft_reset = dm_check_soft_reset,
 747        .soft_reset = dm_soft_reset,
 748        .set_clockgating_state = dm_set_clockgating_state,
 749        .set_powergating_state = dm_set_powergating_state,
 750};
 751
 752const struct amdgpu_ip_block_version dm_ip_block =
 753{
 754        .type = AMD_IP_BLOCK_TYPE_DCE,
 755        .major = 1,
 756        .minor = 0,
 757        .rev = 0,
 758        .funcs = &amdgpu_dm_funcs,
 759};
 760
 761
 762static struct drm_atomic_state *
 763dm_atomic_state_alloc(struct drm_device *dev)
 764{
 765        struct dm_atomic_state *state = kzalloc(sizeof(*state), GFP_KERNEL);
 766
 767        if (!state)
 768                return NULL;
 769
 770        if (drm_atomic_state_init(dev, &state->base) < 0)
 771                goto fail;
 772
 773        return &state->base;
 774
 775fail:
 776        kfree(state);
 777        return NULL;
 778}
 779
 780static void
 781dm_atomic_state_clear(struct drm_atomic_state *state)
 782{
 783        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
 784
 785        if (dm_state->context) {
 786                dc_release_state(dm_state->context);
 787                dm_state->context = NULL;
 788        }
 789
 790        drm_atomic_state_default_clear(state);
 791}
 792
 793static void
 794dm_atomic_state_alloc_free(struct drm_atomic_state *state)
 795{
 796        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
 797        drm_atomic_state_default_release(state);
 798        kfree(dm_state);
 799}
 800
 801static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
 802        .fb_create = amdgpu_display_user_framebuffer_create,
 803        .output_poll_changed = drm_fb_helper_output_poll_changed,
 804        .atomic_check = amdgpu_dm_atomic_check,
 805        .atomic_commit = amdgpu_dm_atomic_commit,
 806        .atomic_state_alloc = dm_atomic_state_alloc,
 807        .atomic_state_clear = dm_atomic_state_clear,
 808        .atomic_state_free = dm_atomic_state_alloc_free
 809};
 810
 811static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
 812        .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
 813};
 814
 815static void
 816amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
 817{
 818        struct drm_connector *connector = &aconnector->base;
 819        struct drm_device *dev = connector->dev;
 820        struct dc_sink *sink;
 821
 822        /* MST handled by drm_mst framework */
 823        if (aconnector->mst_mgr.mst_state == true)
 824                return;
 825
 826
 827        sink = aconnector->dc_link->local_sink;
 828
 829        /* Edid mgmt connector gets first update only in mode_valid hook and then
 830         * the connector sink is set to either fake or physical sink depends on link status.
 831         * don't do it here if u are during boot
 832         */
 833        if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
 834                        && aconnector->dc_em_sink) {
 835
 836                /* For S3 resume with headless use eml_sink to fake stream
 837                 * because on resume connecotr->sink is set ti NULL
 838                 */
 839                mutex_lock(&dev->mode_config.mutex);
 840
 841                if (sink) {
 842                        if (aconnector->dc_sink) {
 843                                amdgpu_dm_remove_sink_from_freesync_module(
 844                                                                connector);
 845                                /* retain and release bellow are used for
 846                                 * bump up refcount for sink because the link don't point
 847                                 * to it anymore after disconnect so on next crtc to connector
 848                                 * reshuffle by UMD we will get into unwanted dc_sink release
 849                                 */
 850                                if (aconnector->dc_sink != aconnector->dc_em_sink)
 851                                        dc_sink_release(aconnector->dc_sink);
 852                        }
 853                        aconnector->dc_sink = sink;
 854                        amdgpu_dm_add_sink_to_freesync_module(
 855                                                connector, aconnector->edid);
 856                } else {
 857                        amdgpu_dm_remove_sink_from_freesync_module(connector);
 858                        if (!aconnector->dc_sink)
 859                                aconnector->dc_sink = aconnector->dc_em_sink;
 860                        else if (aconnector->dc_sink != aconnector->dc_em_sink)
 861                                dc_sink_retain(aconnector->dc_sink);
 862                }
 863
 864                mutex_unlock(&dev->mode_config.mutex);
 865                return;
 866        }
 867
 868        /*
 869         * TODO: temporary guard to look for proper fix
 870         * if this sink is MST sink, we should not do anything
 871         */
 872        if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
 873                return;
 874
 875        if (aconnector->dc_sink == sink) {
 876                /* We got a DP short pulse (Link Loss, DP CTS, etc...).
 877                 * Do nothing!! */
 878                DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
 879                                aconnector->connector_id);
 880                return;
 881        }
 882
 883        DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
 884                aconnector->connector_id, aconnector->dc_sink, sink);
 885
 886        mutex_lock(&dev->mode_config.mutex);
 887
 888        /* 1. Update status of the drm connector
 889         * 2. Send an event and let userspace tell us what to do */
 890        if (sink) {
 891                /* TODO: check if we still need the S3 mode update workaround.
 892                 * If yes, put it here. */
 893                if (aconnector->dc_sink)
 894                        amdgpu_dm_remove_sink_from_freesync_module(
 895                                                        connector);
 896
 897                aconnector->dc_sink = sink;
 898                if (sink->dc_edid.length == 0) {
 899                        aconnector->edid = NULL;
 900                } else {
 901                        aconnector->edid =
 902                                (struct edid *) sink->dc_edid.raw_edid;
 903
 904
 905                        drm_mode_connector_update_edid_property(connector,
 906                                        aconnector->edid);
 907                }
 908                amdgpu_dm_add_sink_to_freesync_module(connector, aconnector->edid);
 909
 910        } else {
 911                amdgpu_dm_remove_sink_from_freesync_module(connector);
 912                drm_mode_connector_update_edid_property(connector, NULL);
 913                aconnector->num_modes = 0;
 914                aconnector->dc_sink = NULL;
 915                aconnector->edid = NULL;
 916        }
 917
 918        mutex_unlock(&dev->mode_config.mutex);
 919}
 920
 921static void handle_hpd_irq(void *param)
 922{
 923        struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
 924        struct drm_connector *connector = &aconnector->base;
 925        struct drm_device *dev = connector->dev;
 926
 927        /* In case of failure or MST no need to update connector status or notify the OS
 928         * since (for MST case) MST does this in it's own context.
 929         */
 930        mutex_lock(&aconnector->hpd_lock);
 931
 932        if (aconnector->fake_enable)
 933                aconnector->fake_enable = false;
 934
 935        if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
 936                amdgpu_dm_update_connector_after_detect(aconnector);
 937
 938
 939                drm_modeset_lock_all(dev);
 940                dm_restore_drm_connector_state(dev, connector);
 941                drm_modeset_unlock_all(dev);
 942
 943                if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
 944                        drm_kms_helper_hotplug_event(dev);
 945        }
 946        mutex_unlock(&aconnector->hpd_lock);
 947
 948}
 949
 950static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
 951{
 952        uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
 953        uint8_t dret;
 954        bool new_irq_handled = false;
 955        int dpcd_addr;
 956        int dpcd_bytes_to_read;
 957
 958        const int max_process_count = 30;
 959        int process_count = 0;
 960
 961        const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
 962
 963        if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
 964                dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
 965                /* DPCD 0x200 - 0x201 for downstream IRQ */
 966                dpcd_addr = DP_SINK_COUNT;
 967        } else {
 968                dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
 969                /* DPCD 0x2002 - 0x2005 for downstream IRQ */
 970                dpcd_addr = DP_SINK_COUNT_ESI;
 971        }
 972
 973        dret = drm_dp_dpcd_read(
 974                &aconnector->dm_dp_aux.aux,
 975                dpcd_addr,
 976                esi,
 977                dpcd_bytes_to_read);
 978
 979        while (dret == dpcd_bytes_to_read &&
 980                process_count < max_process_count) {
 981                uint8_t retry;
 982                dret = 0;
 983
 984                process_count++;
 985
 986                DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
 987                /* handle HPD short pulse irq */
 988                if (aconnector->mst_mgr.mst_state)
 989                        drm_dp_mst_hpd_irq(
 990                                &aconnector->mst_mgr,
 991                                esi,
 992                                &new_irq_handled);
 993
 994                if (new_irq_handled) {
 995                        /* ACK at DPCD to notify down stream */
 996                        const int ack_dpcd_bytes_to_write =
 997                                dpcd_bytes_to_read - 1;
 998
 999                        for (retry = 0; retry < 3; retry++) {
1000                                uint8_t wret;
1001
1002                                wret = drm_dp_dpcd_write(
1003                                        &aconnector->dm_dp_aux.aux,
1004                                        dpcd_addr + 1,
1005                                        &esi[1],
1006                                        ack_dpcd_bytes_to_write);
1007                                if (wret == ack_dpcd_bytes_to_write)
1008                                        break;
1009                        }
1010
1011                        /* check if there is new irq to be handle */
1012                        dret = drm_dp_dpcd_read(
1013                                &aconnector->dm_dp_aux.aux,
1014                                dpcd_addr,
1015                                esi,
1016                                dpcd_bytes_to_read);
1017
1018                        new_irq_handled = false;
1019                } else {
1020                        break;
1021                }
1022        }
1023
1024        if (process_count == max_process_count)
1025                DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1026}
1027
1028static void handle_hpd_rx_irq(void *param)
1029{
1030        struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1031        struct drm_connector *connector = &aconnector->base;
1032        struct drm_device *dev = connector->dev;
1033        struct dc_link *dc_link = aconnector->dc_link;
1034        bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1035
1036        /* TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1037         * conflict, after implement i2c helper, this mutex should be
1038         * retired.
1039         */
1040        if (dc_link->type != dc_connection_mst_branch)
1041                mutex_lock(&aconnector->hpd_lock);
1042
1043        if (dc_link_handle_hpd_rx_irq(dc_link, NULL) &&
1044                        !is_mst_root_connector) {
1045                /* Downstream Port status changed. */
1046                if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1047
1048                        if (aconnector->fake_enable)
1049                                aconnector->fake_enable = false;
1050
1051                        amdgpu_dm_update_connector_after_detect(aconnector);
1052
1053
1054                        drm_modeset_lock_all(dev);
1055                        dm_restore_drm_connector_state(dev, connector);
1056                        drm_modeset_unlock_all(dev);
1057
1058                        drm_kms_helper_hotplug_event(dev);
1059                }
1060        }
1061        if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1062            (dc_link->type == dc_connection_mst_branch))
1063                dm_handle_hpd_rx_irq(aconnector);
1064
1065        if (dc_link->type != dc_connection_mst_branch)
1066                mutex_unlock(&aconnector->hpd_lock);
1067}
1068
1069static void register_hpd_handlers(struct amdgpu_device *adev)
1070{
1071        struct drm_device *dev = adev->ddev;
1072        struct drm_connector *connector;
1073        struct amdgpu_dm_connector *aconnector;
1074        const struct dc_link *dc_link;
1075        struct dc_interrupt_params int_params = {0};
1076
1077        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1078        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1079
1080        list_for_each_entry(connector,
1081                        &dev->mode_config.connector_list, head) {
1082
1083                aconnector = to_amdgpu_dm_connector(connector);
1084                dc_link = aconnector->dc_link;
1085
1086                if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1087                        int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1088                        int_params.irq_source = dc_link->irq_source_hpd;
1089
1090                        amdgpu_dm_irq_register_interrupt(adev, &int_params,
1091                                        handle_hpd_irq,
1092                                        (void *) aconnector);
1093                }
1094
1095                if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1096
1097                        /* Also register for DP short pulse (hpd_rx). */
1098                        int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1099                        int_params.irq_source = dc_link->irq_source_hpd_rx;
1100
1101                        amdgpu_dm_irq_register_interrupt(adev, &int_params,
1102                                        handle_hpd_rx_irq,
1103                                        (void *) aconnector);
1104                }
1105        }
1106}
1107
1108/* Register IRQ sources and initialize IRQ callbacks */
1109static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1110{
1111        struct dc *dc = adev->dm.dc;
1112        struct common_irq_params *c_irq_params;
1113        struct dc_interrupt_params int_params = {0};
1114        int r;
1115        int i;
1116        unsigned client_id = AMDGPU_IH_CLIENTID_LEGACY;
1117
1118        if (adev->asic_type == CHIP_VEGA10 ||
1119            adev->asic_type == CHIP_VEGA12 ||
1120            adev->asic_type == CHIP_VEGA20 ||
1121            adev->asic_type == CHIP_RAVEN)
1122                client_id = SOC15_IH_CLIENTID_DCE;
1123
1124        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1125        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1126
1127        /* Actions of amdgpu_irq_add_id():
1128         * 1. Register a set() function with base driver.
1129         *    Base driver will call set() function to enable/disable an
1130         *    interrupt in DC hardware.
1131         * 2. Register amdgpu_dm_irq_handler().
1132         *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1133         *    coming from DC hardware.
1134         *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1135         *    for acknowledging and handling. */
1136
1137        /* Use VBLANK interrupt */
1138        for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1139                r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1140                if (r) {
1141                        DRM_ERROR("Failed to add crtc irq id!\n");
1142                        return r;
1143                }
1144
1145                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1146                int_params.irq_source =
1147                        dc_interrupt_to_irq_source(dc, i, 0);
1148
1149                c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1150
1151                c_irq_params->adev = adev;
1152                c_irq_params->irq_src = int_params.irq_source;
1153
1154                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1155                                dm_crtc_high_irq, c_irq_params);
1156        }
1157
1158        /* Use GRPH_PFLIP interrupt */
1159        for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1160                        i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1161                r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1162                if (r) {
1163                        DRM_ERROR("Failed to add page flip irq id!\n");
1164                        return r;
1165                }
1166
1167                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1168                int_params.irq_source =
1169                        dc_interrupt_to_irq_source(dc, i, 0);
1170
1171                c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1172
1173                c_irq_params->adev = adev;
1174                c_irq_params->irq_src = int_params.irq_source;
1175
1176                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1177                                dm_pflip_high_irq, c_irq_params);
1178
1179        }
1180
1181        /* HPD */
1182        r = amdgpu_irq_add_id(adev, client_id,
1183                        VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1184        if (r) {
1185                DRM_ERROR("Failed to add hpd irq id!\n");
1186                return r;
1187        }
1188
1189        register_hpd_handlers(adev);
1190
1191        return 0;
1192}
1193
1194#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1195/* Register IRQ sources and initialize IRQ callbacks */
1196static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1197{
1198        struct dc *dc = adev->dm.dc;
1199        struct common_irq_params *c_irq_params;
1200        struct dc_interrupt_params int_params = {0};
1201        int r;
1202        int i;
1203
1204        int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1205        int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1206
1207        /* Actions of amdgpu_irq_add_id():
1208         * 1. Register a set() function with base driver.
1209         *    Base driver will call set() function to enable/disable an
1210         *    interrupt in DC hardware.
1211         * 2. Register amdgpu_dm_irq_handler().
1212         *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1213         *    coming from DC hardware.
1214         *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1215         *    for acknowledging and handling.
1216         * */
1217
1218        /* Use VSTARTUP interrupt */
1219        for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1220                        i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1221                        i++) {
1222                r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1223
1224                if (r) {
1225                        DRM_ERROR("Failed to add crtc irq id!\n");
1226                        return r;
1227                }
1228
1229                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1230                int_params.irq_source =
1231                        dc_interrupt_to_irq_source(dc, i, 0);
1232
1233                c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1234
1235                c_irq_params->adev = adev;
1236                c_irq_params->irq_src = int_params.irq_source;
1237
1238                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1239                                dm_crtc_high_irq, c_irq_params);
1240        }
1241
1242        /* Use GRPH_PFLIP interrupt */
1243        for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1244                        i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1245                        i++) {
1246                r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1247                if (r) {
1248                        DRM_ERROR("Failed to add page flip irq id!\n");
1249                        return r;
1250                }
1251
1252                int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1253                int_params.irq_source =
1254                        dc_interrupt_to_irq_source(dc, i, 0);
1255
1256                c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1257
1258                c_irq_params->adev = adev;
1259                c_irq_params->irq_src = int_params.irq_source;
1260
1261                amdgpu_dm_irq_register_interrupt(adev, &int_params,
1262                                dm_pflip_high_irq, c_irq_params);
1263
1264        }
1265
1266        /* HPD */
1267        r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1268                        &adev->hpd_irq);
1269        if (r) {
1270                DRM_ERROR("Failed to add hpd irq id!\n");
1271                return r;
1272        }
1273
1274        register_hpd_handlers(adev);
1275
1276        return 0;
1277}
1278#endif
1279
1280static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1281{
1282        int r;
1283
1284        adev->mode_info.mode_config_initialized = true;
1285
1286        adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1287        adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1288
1289        adev->ddev->mode_config.max_width = 16384;
1290        adev->ddev->mode_config.max_height = 16384;
1291
1292        adev->ddev->mode_config.preferred_depth = 24;
1293        adev->ddev->mode_config.prefer_shadow = 1;
1294        /* indicate support of immediate flip */
1295        adev->ddev->mode_config.async_page_flip = true;
1296
1297        adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1298
1299        r = amdgpu_display_modeset_create_props(adev);
1300        if (r)
1301                return r;
1302
1303        return 0;
1304}
1305
1306#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1307        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1308
1309static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1310{
1311        struct amdgpu_display_manager *dm = bl_get_data(bd);
1312
1313        if (dc_link_set_backlight_level(dm->backlight_link,
1314                        bd->props.brightness, 0, 0))
1315                return 0;
1316        else
1317                return 1;
1318}
1319
1320static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1321{
1322        return bd->props.brightness;
1323}
1324
1325static const struct backlight_ops amdgpu_dm_backlight_ops = {
1326        .get_brightness = amdgpu_dm_backlight_get_brightness,
1327        .update_status  = amdgpu_dm_backlight_update_status,
1328};
1329
1330static void
1331amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1332{
1333        char bl_name[16];
1334        struct backlight_properties props = { 0 };
1335
1336        props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1337        props.type = BACKLIGHT_RAW;
1338
1339        snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1340                        dm->adev->ddev->primary->index);
1341
1342        dm->backlight_dev = backlight_device_register(bl_name,
1343                        dm->adev->ddev->dev,
1344                        dm,
1345                        &amdgpu_dm_backlight_ops,
1346                        &props);
1347
1348        if (IS_ERR(dm->backlight_dev))
1349                DRM_ERROR("DM: Backlight registration failed!\n");
1350        else
1351                DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1352}
1353
1354#endif
1355
1356static int initialize_plane(struct amdgpu_display_manager *dm,
1357                             struct amdgpu_mode_info *mode_info,
1358                             int plane_id)
1359{
1360        struct amdgpu_plane *plane;
1361        unsigned long possible_crtcs;
1362        int ret = 0;
1363
1364        plane = kzalloc(sizeof(struct amdgpu_plane), GFP_KERNEL);
1365        mode_info->planes[plane_id] = plane;
1366
1367        if (!plane) {
1368                DRM_ERROR("KMS: Failed to allocate plane\n");
1369                return -ENOMEM;
1370        }
1371        plane->base.type = mode_info->plane_type[plane_id];
1372
1373        /*
1374         * HACK: IGT tests expect that each plane can only have one
1375         * one possible CRTC. For now, set one CRTC for each
1376         * plane that is not an underlay, but still allow multiple
1377         * CRTCs for underlay planes.
1378         */
1379        possible_crtcs = 1 << plane_id;
1380        if (plane_id >= dm->dc->caps.max_streams)
1381                possible_crtcs = 0xff;
1382
1383        ret = amdgpu_dm_plane_init(dm, mode_info->planes[plane_id], possible_crtcs);
1384
1385        if (ret) {
1386                DRM_ERROR("KMS: Failed to initialize plane\n");
1387                return ret;
1388        }
1389
1390        return ret;
1391}
1392
1393
1394static void register_backlight_device(struct amdgpu_display_manager *dm,
1395                                      struct dc_link *link)
1396{
1397#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1398        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1399
1400        if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
1401            link->type != dc_connection_none) {
1402                /* Event if registration failed, we should continue with
1403                 * DM initialization because not having a backlight control
1404                 * is better then a black screen.
1405                 */
1406                amdgpu_dm_register_backlight_device(dm);
1407
1408                if (dm->backlight_dev)
1409                        dm->backlight_link = link;
1410        }
1411#endif
1412}
1413
1414
1415/* In this architecture, the association
1416 * connector -> encoder -> crtc
1417 * id not really requried. The crtc and connector will hold the
1418 * display_index as an abstraction to use with DAL component
1419 *
1420 * Returns 0 on success
1421 */
1422static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
1423{
1424        struct amdgpu_display_manager *dm = &adev->dm;
1425        int32_t i;
1426        struct amdgpu_dm_connector *aconnector = NULL;
1427        struct amdgpu_encoder *aencoder = NULL;
1428        struct amdgpu_mode_info *mode_info = &adev->mode_info;
1429        uint32_t link_cnt;
1430        int32_t total_overlay_planes, total_primary_planes;
1431
1432        link_cnt = dm->dc->caps.max_links;
1433        if (amdgpu_dm_mode_config_init(dm->adev)) {
1434                DRM_ERROR("DM: Failed to initialize mode config\n");
1435                return -1;
1436        }
1437
1438        /* Identify the number of planes to be initialized */
1439        total_overlay_planes = dm->dc->caps.max_slave_planes;
1440        total_primary_planes = dm->dc->caps.max_planes - dm->dc->caps.max_slave_planes;
1441
1442        /* First initialize overlay planes, index starting after primary planes */
1443        for (i = (total_overlay_planes - 1); i >= 0; i--) {
1444                if (initialize_plane(dm, mode_info, (total_primary_planes + i))) {
1445                        DRM_ERROR("KMS: Failed to initialize overlay plane\n");
1446                        goto fail;
1447                }
1448        }
1449
1450        /* Initialize primary planes */
1451        for (i = (total_primary_planes - 1); i >= 0; i--) {
1452                if (initialize_plane(dm, mode_info, i)) {
1453                        DRM_ERROR("KMS: Failed to initialize primary plane\n");
1454                        goto fail;
1455                }
1456        }
1457
1458        for (i = 0; i < dm->dc->caps.max_streams; i++)
1459                if (amdgpu_dm_crtc_init(dm, &mode_info->planes[i]->base, i)) {
1460                        DRM_ERROR("KMS: Failed to initialize crtc\n");
1461                        goto fail;
1462                }
1463
1464        dm->display_indexes_num = dm->dc->caps.max_streams;
1465
1466        /* loops over all connectors on the board */
1467        for (i = 0; i < link_cnt; i++) {
1468                struct dc_link *link = NULL;
1469
1470                if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
1471                        DRM_ERROR(
1472                                "KMS: Cannot support more than %d display indexes\n",
1473                                        AMDGPU_DM_MAX_DISPLAY_INDEX);
1474                        continue;
1475                }
1476
1477                aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
1478                if (!aconnector)
1479                        goto fail;
1480
1481                aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
1482                if (!aencoder)
1483                        goto fail;
1484
1485                if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
1486                        DRM_ERROR("KMS: Failed to initialize encoder\n");
1487                        goto fail;
1488                }
1489
1490                if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
1491                        DRM_ERROR("KMS: Failed to initialize connector\n");
1492                        goto fail;
1493                }
1494
1495                link = dc_get_link_at_index(dm->dc, i);
1496
1497                if (dc_link_detect(link, DETECT_REASON_BOOT)) {
1498                        amdgpu_dm_update_connector_after_detect(aconnector);
1499                        register_backlight_device(dm, link);
1500                }
1501
1502
1503        }
1504
1505        /* Software is initialized. Now we can register interrupt handlers. */
1506        switch (adev->asic_type) {
1507        case CHIP_BONAIRE:
1508        case CHIP_HAWAII:
1509        case CHIP_KAVERI:
1510        case CHIP_KABINI:
1511        case CHIP_MULLINS:
1512        case CHIP_TONGA:
1513        case CHIP_FIJI:
1514        case CHIP_CARRIZO:
1515        case CHIP_STONEY:
1516        case CHIP_POLARIS11:
1517        case CHIP_POLARIS10:
1518        case CHIP_POLARIS12:
1519        case CHIP_VEGAM:
1520        case CHIP_VEGA10:
1521        case CHIP_VEGA12:
1522        case CHIP_VEGA20:
1523                if (dce110_register_irq_handlers(dm->adev)) {
1524                        DRM_ERROR("DM: Failed to initialize IRQ\n");
1525                        goto fail;
1526                }
1527                break;
1528#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1529        case CHIP_RAVEN:
1530                if (dcn10_register_irq_handlers(dm->adev)) {
1531                        DRM_ERROR("DM: Failed to initialize IRQ\n");
1532                        goto fail;
1533                }
1534                /*
1535                 * Temporary disable until pplib/smu interaction is implemented
1536                 */
1537                dm->dc->debug.disable_stutter = true;
1538                break;
1539#endif
1540        default:
1541                DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1542                goto fail;
1543        }
1544
1545        return 0;
1546fail:
1547        kfree(aencoder);
1548        kfree(aconnector);
1549        for (i = 0; i < dm->dc->caps.max_planes; i++)
1550                kfree(mode_info->planes[i]);
1551        return -1;
1552}
1553
1554static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
1555{
1556        drm_mode_config_cleanup(dm->ddev);
1557        return;
1558}
1559
1560/******************************************************************************
1561 * amdgpu_display_funcs functions
1562 *****************************************************************************/
1563
1564/**
1565 * dm_bandwidth_update - program display watermarks
1566 *
1567 * @adev: amdgpu_device pointer
1568 *
1569 * Calculate and program the display watermarks and line buffer allocation.
1570 */
1571static void dm_bandwidth_update(struct amdgpu_device *adev)
1572{
1573        /* TODO: implement later */
1574}
1575
1576static void dm_set_backlight_level(struct amdgpu_encoder *amdgpu_encoder,
1577                                     u8 level)
1578{
1579        /* TODO: translate amdgpu_encoder to display_index and call DAL */
1580}
1581
1582static u8 dm_get_backlight_level(struct amdgpu_encoder *amdgpu_encoder)
1583{
1584        /* TODO: translate amdgpu_encoder to display_index and call DAL */
1585        return 0;
1586}
1587
1588static int amdgpu_notify_freesync(struct drm_device *dev, void *data,
1589                                struct drm_file *filp)
1590{
1591        struct mod_freesync_params freesync_params;
1592        uint8_t num_streams;
1593        uint8_t i;
1594
1595        struct amdgpu_device *adev = dev->dev_private;
1596        int r = 0;
1597
1598        /* Get freesync enable flag from DRM */
1599
1600        num_streams = dc_get_current_stream_count(adev->dm.dc);
1601
1602        for (i = 0; i < num_streams; i++) {
1603                struct dc_stream_state *stream;
1604                stream = dc_get_stream_at_index(adev->dm.dc, i);
1605
1606                mod_freesync_update_state(adev->dm.freesync_module,
1607                                          &stream, 1, &freesync_params);
1608        }
1609
1610        return r;
1611}
1612
1613static const struct amdgpu_display_funcs dm_display_funcs = {
1614        .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
1615        .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
1616        .backlight_set_level =
1617                dm_set_backlight_level,/* called unconditionally */
1618        .backlight_get_level =
1619                dm_get_backlight_level,/* called unconditionally */
1620        .hpd_sense = NULL,/* called unconditionally */
1621        .hpd_set_polarity = NULL, /* called unconditionally */
1622        .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
1623        .page_flip_get_scanoutpos =
1624                dm_crtc_get_scanoutpos,/* called unconditionally */
1625        .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
1626        .add_connector = NULL, /* VBIOS parsing. DAL does it. */
1627        .notify_freesync = amdgpu_notify_freesync,
1628
1629};
1630
1631#if defined(CONFIG_DEBUG_KERNEL_DC)
1632
1633static ssize_t s3_debug_store(struct device *device,
1634                              struct device_attribute *attr,
1635                              const char *buf,
1636                              size_t count)
1637{
1638        int ret;
1639        int s3_state;
1640        struct pci_dev *pdev = to_pci_dev(device);
1641        struct drm_device *drm_dev = pci_get_drvdata(pdev);
1642        struct amdgpu_device *adev = drm_dev->dev_private;
1643
1644        ret = kstrtoint(buf, 0, &s3_state);
1645
1646        if (ret == 0) {
1647                if (s3_state) {
1648                        dm_resume(adev);
1649                        drm_kms_helper_hotplug_event(adev->ddev);
1650                } else
1651                        dm_suspend(adev);
1652        }
1653
1654        return ret == 0 ? count : 0;
1655}
1656
1657DEVICE_ATTR_WO(s3_debug);
1658
1659#endif
1660
1661static int dm_early_init(void *handle)
1662{
1663        struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1664
1665        switch (adev->asic_type) {
1666        case CHIP_BONAIRE:
1667        case CHIP_HAWAII:
1668                adev->mode_info.num_crtc = 6;
1669                adev->mode_info.num_hpd = 6;
1670                adev->mode_info.num_dig = 6;
1671                adev->mode_info.plane_type = dm_plane_type_default;
1672                break;
1673        case CHIP_KAVERI:
1674                adev->mode_info.num_crtc = 4;
1675                adev->mode_info.num_hpd = 6;
1676                adev->mode_info.num_dig = 7;
1677                adev->mode_info.plane_type = dm_plane_type_default;
1678                break;
1679        case CHIP_KABINI:
1680        case CHIP_MULLINS:
1681                adev->mode_info.num_crtc = 2;
1682                adev->mode_info.num_hpd = 6;
1683                adev->mode_info.num_dig = 6;
1684                adev->mode_info.plane_type = dm_plane_type_default;
1685                break;
1686        case CHIP_FIJI:
1687        case CHIP_TONGA:
1688                adev->mode_info.num_crtc = 6;
1689                adev->mode_info.num_hpd = 6;
1690                adev->mode_info.num_dig = 7;
1691                adev->mode_info.plane_type = dm_plane_type_default;
1692                break;
1693        case CHIP_CARRIZO:
1694                adev->mode_info.num_crtc = 3;
1695                adev->mode_info.num_hpd = 6;
1696                adev->mode_info.num_dig = 9;
1697                adev->mode_info.plane_type = dm_plane_type_carizzo;
1698                break;
1699        case CHIP_STONEY:
1700                adev->mode_info.num_crtc = 2;
1701                adev->mode_info.num_hpd = 6;
1702                adev->mode_info.num_dig = 9;
1703                adev->mode_info.plane_type = dm_plane_type_stoney;
1704                break;
1705        case CHIP_POLARIS11:
1706        case CHIP_POLARIS12:
1707                adev->mode_info.num_crtc = 5;
1708                adev->mode_info.num_hpd = 5;
1709                adev->mode_info.num_dig = 5;
1710                adev->mode_info.plane_type = dm_plane_type_default;
1711                break;
1712        case CHIP_POLARIS10:
1713        case CHIP_VEGAM:
1714                adev->mode_info.num_crtc = 6;
1715                adev->mode_info.num_hpd = 6;
1716                adev->mode_info.num_dig = 6;
1717                adev->mode_info.plane_type = dm_plane_type_default;
1718                break;
1719        case CHIP_VEGA10:
1720        case CHIP_VEGA12:
1721        case CHIP_VEGA20:
1722                adev->mode_info.num_crtc = 6;
1723                adev->mode_info.num_hpd = 6;
1724                adev->mode_info.num_dig = 6;
1725                adev->mode_info.plane_type = dm_plane_type_default;
1726                break;
1727#if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1728        case CHIP_RAVEN:
1729                adev->mode_info.num_crtc = 4;
1730                adev->mode_info.num_hpd = 4;
1731                adev->mode_info.num_dig = 4;
1732                adev->mode_info.plane_type = dm_plane_type_default;
1733                break;
1734#endif
1735        default:
1736                DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1737                return -EINVAL;
1738        }
1739
1740        amdgpu_dm_set_irq_funcs(adev);
1741
1742        if (adev->mode_info.funcs == NULL)
1743                adev->mode_info.funcs = &dm_display_funcs;
1744
1745        /* Note: Do NOT change adev->audio_endpt_rreg and
1746         * adev->audio_endpt_wreg because they are initialised in
1747         * amdgpu_device_init() */
1748#if defined(CONFIG_DEBUG_KERNEL_DC)
1749        device_create_file(
1750                adev->ddev->dev,
1751                &dev_attr_s3_debug);
1752#endif
1753
1754        return 0;
1755}
1756
1757static bool modeset_required(struct drm_crtc_state *crtc_state,
1758                             struct dc_stream_state *new_stream,
1759                             struct dc_stream_state *old_stream)
1760{
1761        if (!drm_atomic_crtc_needs_modeset(crtc_state))
1762                return false;
1763
1764        if (!crtc_state->enable)
1765                return false;
1766
1767        return crtc_state->active;
1768}
1769
1770static bool modereset_required(struct drm_crtc_state *crtc_state)
1771{
1772        if (!drm_atomic_crtc_needs_modeset(crtc_state))
1773                return false;
1774
1775        return !crtc_state->enable || !crtc_state->active;
1776}
1777
1778static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
1779{
1780        drm_encoder_cleanup(encoder);
1781        kfree(encoder);
1782}
1783
1784static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
1785        .destroy = amdgpu_dm_encoder_destroy,
1786};
1787
1788static bool fill_rects_from_plane_state(const struct drm_plane_state *state,
1789                                        struct dc_plane_state *plane_state)
1790{
1791        plane_state->src_rect.x = state->src_x >> 16;
1792        plane_state->src_rect.y = state->src_y >> 16;
1793        /*we ignore for now mantissa and do not to deal with floating pixels :(*/
1794        plane_state->src_rect.width = state->src_w >> 16;
1795
1796        if (plane_state->src_rect.width == 0)
1797                return false;
1798
1799        plane_state->src_rect.height = state->src_h >> 16;
1800        if (plane_state->src_rect.height == 0)
1801                return false;
1802
1803        plane_state->dst_rect.x = state->crtc_x;
1804        plane_state->dst_rect.y = state->crtc_y;
1805
1806        if (state->crtc_w == 0)
1807                return false;
1808
1809        plane_state->dst_rect.width = state->crtc_w;
1810
1811        if (state->crtc_h == 0)
1812                return false;
1813
1814        plane_state->dst_rect.height = state->crtc_h;
1815
1816        plane_state->clip_rect = plane_state->dst_rect;
1817
1818        switch (state->rotation & DRM_MODE_ROTATE_MASK) {
1819        case DRM_MODE_ROTATE_0:
1820                plane_state->rotation = ROTATION_ANGLE_0;
1821                break;
1822        case DRM_MODE_ROTATE_90:
1823                plane_state->rotation = ROTATION_ANGLE_90;
1824                break;
1825        case DRM_MODE_ROTATE_180:
1826                plane_state->rotation = ROTATION_ANGLE_180;
1827                break;
1828        case DRM_MODE_ROTATE_270:
1829                plane_state->rotation = ROTATION_ANGLE_270;
1830                break;
1831        default:
1832                plane_state->rotation = ROTATION_ANGLE_0;
1833                break;
1834        }
1835
1836        return true;
1837}
1838static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
1839                       uint64_t *tiling_flags)
1840{
1841        struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
1842        int r = amdgpu_bo_reserve(rbo, false);
1843
1844        if (unlikely(r)) {
1845                // Don't show error msg. when return -ERESTARTSYS
1846                if (r != -ERESTARTSYS)
1847                        DRM_ERROR("Unable to reserve buffer: %d\n", r);
1848                return r;
1849        }
1850
1851        if (tiling_flags)
1852                amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
1853
1854        amdgpu_bo_unreserve(rbo);
1855
1856        return r;
1857}
1858
1859static int fill_plane_attributes_from_fb(struct amdgpu_device *adev,
1860                                         struct dc_plane_state *plane_state,
1861                                         const struct amdgpu_framebuffer *amdgpu_fb)
1862{
1863        uint64_t tiling_flags;
1864        unsigned int awidth;
1865        const struct drm_framebuffer *fb = &amdgpu_fb->base;
1866        int ret = 0;
1867        struct drm_format_name_buf format_name;
1868
1869        ret = get_fb_info(
1870                amdgpu_fb,
1871                &tiling_flags);
1872
1873        if (ret)
1874                return ret;
1875
1876        switch (fb->format->format) {
1877        case DRM_FORMAT_C8:
1878                plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
1879                break;
1880        case DRM_FORMAT_RGB565:
1881                plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
1882                break;
1883        case DRM_FORMAT_XRGB8888:
1884        case DRM_FORMAT_ARGB8888:
1885                plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
1886                break;
1887        case DRM_FORMAT_XRGB2101010:
1888        case DRM_FORMAT_ARGB2101010:
1889                plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
1890                break;
1891        case DRM_FORMAT_XBGR2101010:
1892        case DRM_FORMAT_ABGR2101010:
1893                plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
1894                break;
1895        case DRM_FORMAT_NV21:
1896                plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
1897                break;
1898        case DRM_FORMAT_NV12:
1899                plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
1900                break;
1901        default:
1902                DRM_ERROR("Unsupported screen format %s\n",
1903                          drm_get_format_name(fb->format->format, &format_name));
1904                return -EINVAL;
1905        }
1906
1907        if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
1908                plane_state->address.type = PLN_ADDR_TYPE_GRAPHICS;
1909                plane_state->plane_size.grph.surface_size.x = 0;
1910                plane_state->plane_size.grph.surface_size.y = 0;
1911                plane_state->plane_size.grph.surface_size.width = fb->width;
1912                plane_state->plane_size.grph.surface_size.height = fb->height;
1913                plane_state->plane_size.grph.surface_pitch =
1914                                fb->pitches[0] / fb->format->cpp[0];
1915                /* TODO: unhardcode */
1916                plane_state->color_space = COLOR_SPACE_SRGB;
1917
1918        } else {
1919                awidth = ALIGN(fb->width, 64);
1920                plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
1921                plane_state->plane_size.video.luma_size.x = 0;
1922                plane_state->plane_size.video.luma_size.y = 0;
1923                plane_state->plane_size.video.luma_size.width = awidth;
1924                plane_state->plane_size.video.luma_size.height = fb->height;
1925                /* TODO: unhardcode */
1926                plane_state->plane_size.video.luma_pitch = awidth;
1927
1928                plane_state->plane_size.video.chroma_size.x = 0;
1929                plane_state->plane_size.video.chroma_size.y = 0;
1930                plane_state->plane_size.video.chroma_size.width = awidth;
1931                plane_state->plane_size.video.chroma_size.height = fb->height;
1932                plane_state->plane_size.video.chroma_pitch = awidth / 2;
1933
1934                /* TODO: unhardcode */
1935                plane_state->color_space = COLOR_SPACE_YCBCR709;
1936        }
1937
1938        memset(&plane_state->tiling_info, 0, sizeof(plane_state->tiling_info));
1939
1940        /* Fill GFX8 params */
1941        if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
1942                unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
1943
1944                bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
1945                bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
1946                mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
1947                tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
1948                num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
1949
1950                /* XXX fix me for VI */
1951                plane_state->tiling_info.gfx8.num_banks = num_banks;
1952                plane_state->tiling_info.gfx8.array_mode =
1953                                DC_ARRAY_2D_TILED_THIN1;
1954                plane_state->tiling_info.gfx8.tile_split = tile_split;
1955                plane_state->tiling_info.gfx8.bank_width = bankw;
1956                plane_state->tiling_info.gfx8.bank_height = bankh;
1957                plane_state->tiling_info.gfx8.tile_aspect = mtaspect;
1958                plane_state->tiling_info.gfx8.tile_mode =
1959                                DC_ADDR_SURF_MICRO_TILING_DISPLAY;
1960        } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
1961                        == DC_ARRAY_1D_TILED_THIN1) {
1962                plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
1963        }
1964
1965        plane_state->tiling_info.gfx8.pipe_config =
1966                        AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
1967
1968        if (adev->asic_type == CHIP_VEGA10 ||
1969            adev->asic_type == CHIP_VEGA12 ||
1970            adev->asic_type == CHIP_VEGA20 ||
1971            adev->asic_type == CHIP_RAVEN) {
1972                /* Fill GFX9 params */
1973                plane_state->tiling_info.gfx9.num_pipes =
1974                        adev->gfx.config.gb_addr_config_fields.num_pipes;
1975                plane_state->tiling_info.gfx9.num_banks =
1976                        adev->gfx.config.gb_addr_config_fields.num_banks;
1977                plane_state->tiling_info.gfx9.pipe_interleave =
1978                        adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
1979                plane_state->tiling_info.gfx9.num_shader_engines =
1980                        adev->gfx.config.gb_addr_config_fields.num_se;
1981                plane_state->tiling_info.gfx9.max_compressed_frags =
1982                        adev->gfx.config.gb_addr_config_fields.max_compress_frags;
1983                plane_state->tiling_info.gfx9.num_rb_per_se =
1984                        adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
1985                plane_state->tiling_info.gfx9.swizzle =
1986                        AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
1987                plane_state->tiling_info.gfx9.shaderEnable = 1;
1988        }
1989
1990        plane_state->visible = true;
1991        plane_state->scaling_quality.h_taps_c = 0;
1992        plane_state->scaling_quality.v_taps_c = 0;
1993
1994        /* is this needed? is plane_state zeroed at allocation? */
1995        plane_state->scaling_quality.h_taps = 0;
1996        plane_state->scaling_quality.v_taps = 0;
1997        plane_state->stereo_format = PLANE_STEREO_FORMAT_NONE;
1998
1999        return ret;
2000
2001}
2002
2003static int fill_plane_attributes(struct amdgpu_device *adev,
2004                                 struct dc_plane_state *dc_plane_state,
2005                                 struct drm_plane_state *plane_state,
2006                                 struct drm_crtc_state *crtc_state)
2007{
2008        const struct amdgpu_framebuffer *amdgpu_fb =
2009                to_amdgpu_framebuffer(plane_state->fb);
2010        const struct drm_crtc *crtc = plane_state->crtc;
2011        int ret = 0;
2012
2013        if (!fill_rects_from_plane_state(plane_state, dc_plane_state))
2014                return -EINVAL;
2015
2016        ret = fill_plane_attributes_from_fb(
2017                crtc->dev->dev_private,
2018                dc_plane_state,
2019                amdgpu_fb);
2020
2021        if (ret)
2022                return ret;
2023
2024        /*
2025         * Always set input transfer function, since plane state is refreshed
2026         * every time.
2027         */
2028        ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2029        if (ret) {
2030                dc_transfer_func_release(dc_plane_state->in_transfer_func);
2031                dc_plane_state->in_transfer_func = NULL;
2032        }
2033
2034        return ret;
2035}
2036
2037/*****************************************************************************/
2038
2039static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2040                                           const struct dm_connector_state *dm_state,
2041                                           struct dc_stream_state *stream)
2042{
2043        enum amdgpu_rmx_type rmx_type;
2044
2045        struct rect src = { 0 }; /* viewport in composition space*/
2046        struct rect dst = { 0 }; /* stream addressable area */
2047
2048        /* no mode. nothing to be done */
2049        if (!mode)
2050                return;
2051
2052        /* Full screen scaling by default */
2053        src.width = mode->hdisplay;
2054        src.height = mode->vdisplay;
2055        dst.width = stream->timing.h_addressable;
2056        dst.height = stream->timing.v_addressable;
2057
2058        if (dm_state) {
2059                rmx_type = dm_state->scaling;
2060                if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2061                        if (src.width * dst.height <
2062                                        src.height * dst.width) {
2063                                /* height needs less upscaling/more downscaling */
2064                                dst.width = src.width *
2065                                                dst.height / src.height;
2066                        } else {
2067                                /* width needs less upscaling/more downscaling */
2068                                dst.height = src.height *
2069                                                dst.width / src.width;
2070                        }
2071                } else if (rmx_type == RMX_CENTER) {
2072                        dst = src;
2073                }
2074
2075                dst.x = (stream->timing.h_addressable - dst.width) / 2;
2076                dst.y = (stream->timing.v_addressable - dst.height) / 2;
2077
2078                if (dm_state->underscan_enable) {
2079                        dst.x += dm_state->underscan_hborder / 2;
2080                        dst.y += dm_state->underscan_vborder / 2;
2081                        dst.width -= dm_state->underscan_hborder;
2082                        dst.height -= dm_state->underscan_vborder;
2083                }
2084        }
2085
2086        stream->src = src;
2087        stream->dst = dst;
2088
2089        DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2090                        dst.x, dst.y, dst.width, dst.height);
2091
2092}
2093
2094static enum dc_color_depth
2095convert_color_depth_from_display_info(const struct drm_connector *connector)
2096{
2097        uint32_t bpc = connector->display_info.bpc;
2098
2099        switch (bpc) {
2100        case 0:
2101                /* Temporary Work around, DRM don't parse color depth for
2102                 * EDID revision before 1.4
2103                 * TODO: Fix edid parsing
2104                 */
2105                return COLOR_DEPTH_888;
2106        case 6:
2107                return COLOR_DEPTH_666;
2108        case 8:
2109                return COLOR_DEPTH_888;
2110        case 10:
2111                return COLOR_DEPTH_101010;
2112        case 12:
2113                return COLOR_DEPTH_121212;
2114        case 14:
2115                return COLOR_DEPTH_141414;
2116        case 16:
2117                return COLOR_DEPTH_161616;
2118        default:
2119                return COLOR_DEPTH_UNDEFINED;
2120        }
2121}
2122
2123static enum dc_aspect_ratio
2124get_aspect_ratio(const struct drm_display_mode *mode_in)
2125{
2126        int32_t width = mode_in->crtc_hdisplay * 9;
2127        int32_t height = mode_in->crtc_vdisplay * 16;
2128
2129        if ((width - height) < 10 && (width - height) > -10)
2130                return ASPECT_RATIO_16_9;
2131        else
2132                return ASPECT_RATIO_4_3;
2133}
2134
2135static enum dc_color_space
2136get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
2137{
2138        enum dc_color_space color_space = COLOR_SPACE_SRGB;
2139
2140        switch (dc_crtc_timing->pixel_encoding) {
2141        case PIXEL_ENCODING_YCBCR422:
2142        case PIXEL_ENCODING_YCBCR444:
2143        case PIXEL_ENCODING_YCBCR420:
2144        {
2145                /*
2146                 * 27030khz is the separation point between HDTV and SDTV
2147                 * according to HDMI spec, we use YCbCr709 and YCbCr601
2148                 * respectively
2149                 */
2150                if (dc_crtc_timing->pix_clk_khz > 27030) {
2151                        if (dc_crtc_timing->flags.Y_ONLY)
2152                                color_space =
2153                                        COLOR_SPACE_YCBCR709_LIMITED;
2154                        else
2155                                color_space = COLOR_SPACE_YCBCR709;
2156                } else {
2157                        if (dc_crtc_timing->flags.Y_ONLY)
2158                                color_space =
2159                                        COLOR_SPACE_YCBCR601_LIMITED;
2160                        else
2161                                color_space = COLOR_SPACE_YCBCR601;
2162                }
2163
2164        }
2165        break;
2166        case PIXEL_ENCODING_RGB:
2167                color_space = COLOR_SPACE_SRGB;
2168                break;
2169
2170        default:
2171                WARN_ON(1);
2172                break;
2173        }
2174
2175        return color_space;
2176}
2177
2178static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
2179{
2180        if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2181                return;
2182
2183        timing_out->display_color_depth--;
2184}
2185
2186static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
2187                                                const struct drm_display_info *info)
2188{
2189        int normalized_clk;
2190        if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2191                return;
2192        do {
2193                normalized_clk = timing_out->pix_clk_khz;
2194                /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
2195                if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
2196                        normalized_clk /= 2;
2197                /* Adjusting pix clock following on HDMI spec based on colour depth */
2198                switch (timing_out->display_color_depth) {
2199                case COLOR_DEPTH_101010:
2200                        normalized_clk = (normalized_clk * 30) / 24;
2201                        break;
2202                case COLOR_DEPTH_121212:
2203                        normalized_clk = (normalized_clk * 36) / 24;
2204                        break;
2205                case COLOR_DEPTH_161616:
2206                        normalized_clk = (normalized_clk * 48) / 24;
2207                        break;
2208                default:
2209                        return;
2210                }
2211                if (normalized_clk <= info->max_tmds_clock)
2212                        return;
2213                reduce_mode_colour_depth(timing_out);
2214
2215        } while (timing_out->display_color_depth > COLOR_DEPTH_888);
2216
2217}
2218/*****************************************************************************/
2219
2220static void
2221fill_stream_properties_from_drm_display_mode(struct dc_stream_state *stream,
2222                                             const struct drm_display_mode *mode_in,
2223                                             const struct drm_connector *connector)
2224{
2225        struct dc_crtc_timing *timing_out = &stream->timing;
2226        const struct drm_display_info *info = &connector->display_info;
2227
2228        memset(timing_out, 0, sizeof(struct dc_crtc_timing));
2229
2230        timing_out->h_border_left = 0;
2231        timing_out->h_border_right = 0;
2232        timing_out->v_border_top = 0;
2233        timing_out->v_border_bottom = 0;
2234        /* TODO: un-hardcode */
2235        if (drm_mode_is_420_only(info, mode_in)
2236                        && stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2237                timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
2238        else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
2239                        && stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2240                timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
2241        else
2242                timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
2243
2244        timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
2245        timing_out->display_color_depth = convert_color_depth_from_display_info(
2246                        connector);
2247        timing_out->scan_type = SCANNING_TYPE_NODATA;
2248        timing_out->hdmi_vic = 0;
2249        timing_out->vic = drm_match_cea_mode(mode_in);
2250
2251        timing_out->h_addressable = mode_in->crtc_hdisplay;
2252        timing_out->h_total = mode_in->crtc_htotal;
2253        timing_out->h_sync_width =
2254                mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
2255        timing_out->h_front_porch =
2256                mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
2257        timing_out->v_total = mode_in->crtc_vtotal;
2258        timing_out->v_addressable = mode_in->crtc_vdisplay;
2259        timing_out->v_front_porch =
2260                mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
2261        timing_out->v_sync_width =
2262                mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
2263        timing_out->pix_clk_khz = mode_in->crtc_clock;
2264        timing_out->aspect_ratio = get_aspect_ratio(mode_in);
2265        if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
2266                timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
2267        if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
2268                timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
2269
2270        stream->output_color_space = get_output_color_space(timing_out);
2271
2272        stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
2273        stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
2274        if (stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2275                adjust_colour_depth_from_display_info(timing_out, info);
2276}
2277
2278static void fill_audio_info(struct audio_info *audio_info,
2279                            const struct drm_connector *drm_connector,
2280                            const struct dc_sink *dc_sink)
2281{
2282        int i = 0;
2283        int cea_revision = 0;
2284        const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
2285
2286        audio_info->manufacture_id = edid_caps->manufacturer_id;
2287        audio_info->product_id = edid_caps->product_id;
2288
2289        cea_revision = drm_connector->display_info.cea_rev;
2290
2291        strncpy(audio_info->display_name,
2292                edid_caps->display_name,
2293                AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS - 1);
2294
2295        if (cea_revision >= 3) {
2296                audio_info->mode_count = edid_caps->audio_mode_count;
2297
2298                for (i = 0; i < audio_info->mode_count; ++i) {
2299                        audio_info->modes[i].format_code =
2300                                        (enum audio_format_code)
2301                                        (edid_caps->audio_modes[i].format_code);
2302                        audio_info->modes[i].channel_count =
2303                                        edid_caps->audio_modes[i].channel_count;
2304                        audio_info->modes[i].sample_rates.all =
2305                                        edid_caps->audio_modes[i].sample_rate;
2306                        audio_info->modes[i].sample_size =
2307                                        edid_caps->audio_modes[i].sample_size;
2308                }
2309        }
2310
2311        audio_info->flags.all = edid_caps->speaker_flags;
2312
2313        /* TODO: We only check for the progressive mode, check for interlace mode too */
2314        if (drm_connector->latency_present[0]) {
2315                audio_info->video_latency = drm_connector->video_latency[0];
2316                audio_info->audio_latency = drm_connector->audio_latency[0];
2317        }
2318
2319        /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
2320
2321}
2322
2323static void
2324copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
2325                                      struct drm_display_mode *dst_mode)
2326{
2327        dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
2328        dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
2329        dst_mode->crtc_clock = src_mode->crtc_clock;
2330        dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
2331        dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
2332        dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
2333        dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
2334        dst_mode->crtc_htotal = src_mode->crtc_htotal;
2335        dst_mode->crtc_hskew = src_mode->crtc_hskew;
2336        dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
2337        dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
2338        dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
2339        dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
2340        dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
2341}
2342
2343static void
2344decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
2345                                        const struct drm_display_mode *native_mode,
2346                                        bool scale_enabled)
2347{
2348        if (scale_enabled) {
2349                copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2350        } else if (native_mode->clock == drm_mode->clock &&
2351                        native_mode->htotal == drm_mode->htotal &&
2352                        native_mode->vtotal == drm_mode->vtotal) {
2353                copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2354        } else {
2355                /* no scaling nor amdgpu inserted, no need to patch */
2356        }
2357}
2358
2359static struct dc_sink *
2360create_fake_sink(struct amdgpu_dm_connector *aconnector)
2361{
2362        struct dc_sink_init_data sink_init_data = { 0 };
2363        struct dc_sink *sink = NULL;
2364        sink_init_data.link = aconnector->dc_link;
2365        sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
2366
2367        sink = dc_sink_create(&sink_init_data);
2368        if (!sink) {
2369                DRM_ERROR("Failed to create sink!\n");
2370                return NULL;
2371        }
2372        sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
2373
2374        return sink;
2375}
2376
2377static void set_multisync_trigger_params(
2378                struct dc_stream_state *stream)
2379{
2380        if (stream->triggered_crtc_reset.enabled) {
2381                stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
2382                stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
2383        }
2384}
2385
2386static void set_master_stream(struct dc_stream_state *stream_set[],
2387                              int stream_count)
2388{
2389        int j, highest_rfr = 0, master_stream = 0;
2390
2391        for (j = 0;  j < stream_count; j++) {
2392                if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
2393                        int refresh_rate = 0;
2394
2395                        refresh_rate = (stream_set[j]->timing.pix_clk_khz*1000)/
2396                                (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
2397                        if (refresh_rate > highest_rfr) {
2398                                highest_rfr = refresh_rate;
2399                                master_stream = j;
2400                        }
2401                }
2402        }
2403        for (j = 0;  j < stream_count; j++) {
2404                if (stream_set[j])
2405                        stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
2406        }
2407}
2408
2409static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
2410{
2411        int i = 0;
2412
2413        if (context->stream_count < 2)
2414                return;
2415        for (i = 0; i < context->stream_count ; i++) {
2416                if (!context->streams[i])
2417                        continue;
2418                /* TODO: add a function to read AMD VSDB bits and will set
2419                 * crtc_sync_master.multi_sync_enabled flag
2420                 * For now its set to false
2421                 */
2422                set_multisync_trigger_params(context->streams[i]);
2423        }
2424        set_master_stream(context->streams, context->stream_count);
2425}
2426
2427static struct dc_stream_state *
2428create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
2429                       const struct drm_display_mode *drm_mode,
2430                       const struct dm_connector_state *dm_state)
2431{
2432        struct drm_display_mode *preferred_mode = NULL;
2433        struct drm_connector *drm_connector;
2434        struct dc_stream_state *stream = NULL;
2435        struct drm_display_mode mode = *drm_mode;
2436        bool native_mode_found = false;
2437        struct dc_sink *sink = NULL;
2438        if (aconnector == NULL) {
2439                DRM_ERROR("aconnector is NULL!\n");
2440                return stream;
2441        }
2442
2443        drm_connector = &aconnector->base;
2444
2445        if (!aconnector->dc_sink) {
2446                /*
2447                 * Create dc_sink when necessary to MST
2448                 * Don't apply fake_sink to MST
2449                 */
2450                if (aconnector->mst_port) {
2451                        dm_dp_mst_dc_sink_create(drm_connector);
2452                        return stream;
2453                }
2454
2455                sink = create_fake_sink(aconnector);
2456                if (!sink)
2457                        return stream;
2458        } else {
2459                sink = aconnector->dc_sink;
2460        }
2461
2462        stream = dc_create_stream_for_sink(sink);
2463
2464        if (stream == NULL) {
2465                DRM_ERROR("Failed to create stream for sink!\n");
2466                goto finish;
2467        }
2468
2469        list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
2470                /* Search for preferred mode */
2471                if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
2472                        native_mode_found = true;
2473                        break;
2474                }
2475        }
2476        if (!native_mode_found)
2477                preferred_mode = list_first_entry_or_null(
2478                                &aconnector->base.modes,
2479                                struct drm_display_mode,
2480                                head);
2481
2482        if (preferred_mode == NULL) {
2483                /* This may not be an error, the use case is when we we have no
2484                 * usermode calls to reset and set mode upon hotplug. In this
2485                 * case, we call set mode ourselves to restore the previous mode
2486                 * and the modelist may not be filled in in time.
2487                 */
2488                DRM_DEBUG_DRIVER("No preferred mode found\n");
2489        } else {
2490                decide_crtc_timing_for_drm_display_mode(
2491                                &mode, preferred_mode,
2492                                dm_state ? (dm_state->scaling != RMX_OFF) : false);
2493        }
2494
2495        if (!dm_state)
2496                drm_mode_set_crtcinfo(&mode, 0);
2497
2498        fill_stream_properties_from_drm_display_mode(stream,
2499                        &mode, &aconnector->base);
2500        update_stream_scaling_settings(&mode, dm_state, stream);
2501
2502        fill_audio_info(
2503                &stream->audio_info,
2504                drm_connector,
2505                sink);
2506
2507        update_stream_signal(stream);
2508
2509        if (dm_state && dm_state->freesync_capable)
2510                stream->ignore_msa_timing_param = true;
2511finish:
2512        if (sink && sink->sink_signal == SIGNAL_TYPE_VIRTUAL)
2513                dc_sink_release(sink);
2514
2515        return stream;
2516}
2517
2518static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
2519{
2520        drm_crtc_cleanup(crtc);
2521        kfree(crtc);
2522}
2523
2524static void dm_crtc_destroy_state(struct drm_crtc *crtc,
2525                                  struct drm_crtc_state *state)
2526{
2527        struct dm_crtc_state *cur = to_dm_crtc_state(state);
2528
2529        /* TODO Destroy dc_stream objects are stream object is flattened */
2530        if (cur->stream)
2531                dc_stream_release(cur->stream);
2532
2533
2534        __drm_atomic_helper_crtc_destroy_state(state);
2535
2536
2537        kfree(state);
2538}
2539
2540static void dm_crtc_reset_state(struct drm_crtc *crtc)
2541{
2542        struct dm_crtc_state *state;
2543
2544        if (crtc->state)
2545                dm_crtc_destroy_state(crtc, crtc->state);
2546
2547        state = kzalloc(sizeof(*state), GFP_KERNEL);
2548        if (WARN_ON(!state))
2549                return;
2550
2551        crtc->state = &state->base;
2552        crtc->state->crtc = crtc;
2553
2554}
2555
2556static struct drm_crtc_state *
2557dm_crtc_duplicate_state(struct drm_crtc *crtc)
2558{
2559        struct dm_crtc_state *state, *cur;
2560
2561        cur = to_dm_crtc_state(crtc->state);
2562
2563        if (WARN_ON(!crtc->state))
2564                return NULL;
2565
2566        state = kzalloc(sizeof(*state), GFP_KERNEL);
2567        if (!state)
2568                return NULL;
2569
2570        __drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
2571
2572        if (cur->stream) {
2573                state->stream = cur->stream;
2574                dc_stream_retain(state->stream);
2575        }
2576
2577        /* TODO Duplicate dc_stream after objects are stream object is flattened */
2578
2579        return &state->base;
2580}
2581
2582
2583static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
2584{
2585        enum dc_irq_source irq_source;
2586        struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
2587        struct amdgpu_device *adev = crtc->dev->dev_private;
2588
2589        irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
2590        return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2591}
2592
2593static int dm_enable_vblank(struct drm_crtc *crtc)
2594{
2595        return dm_set_vblank(crtc, true);
2596}
2597
2598static void dm_disable_vblank(struct drm_crtc *crtc)
2599{
2600        dm_set_vblank(crtc, false);
2601}
2602
2603/* Implemented only the options currently availible for the driver */
2604static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
2605        .reset = dm_crtc_reset_state,
2606        .destroy = amdgpu_dm_crtc_destroy,
2607        .gamma_set = drm_atomic_helper_legacy_gamma_set,
2608        .set_config = drm_atomic_helper_set_config,
2609        .page_flip = drm_atomic_helper_page_flip,
2610        .atomic_duplicate_state = dm_crtc_duplicate_state,
2611        .atomic_destroy_state = dm_crtc_destroy_state,
2612        .set_crc_source = amdgpu_dm_crtc_set_crc_source,
2613        .enable_vblank = dm_enable_vblank,
2614        .disable_vblank = dm_disable_vblank,
2615};
2616
2617static enum drm_connector_status
2618amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
2619{
2620        bool connected;
2621        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2622
2623        /* Notes:
2624         * 1. This interface is NOT called in context of HPD irq.
2625         * 2. This interface *is called* in context of user-mode ioctl. Which
2626         * makes it a bad place for *any* MST-related activit. */
2627
2628        if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
2629            !aconnector->fake_enable)
2630                connected = (aconnector->dc_sink != NULL);
2631        else
2632                connected = (aconnector->base.force == DRM_FORCE_ON);
2633
2634        return (connected ? connector_status_connected :
2635                        connector_status_disconnected);
2636}
2637
2638int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
2639                                            struct drm_connector_state *connector_state,
2640                                            struct drm_property *property,
2641                                            uint64_t val)
2642{
2643        struct drm_device *dev = connector->dev;
2644        struct amdgpu_device *adev = dev->dev_private;
2645        struct dm_connector_state *dm_old_state =
2646                to_dm_connector_state(connector->state);
2647        struct dm_connector_state *dm_new_state =
2648                to_dm_connector_state(connector_state);
2649
2650        int ret = -EINVAL;
2651
2652        if (property == dev->mode_config.scaling_mode_property) {
2653                enum amdgpu_rmx_type rmx_type;
2654
2655                switch (val) {
2656                case DRM_MODE_SCALE_CENTER:
2657                        rmx_type = RMX_CENTER;
2658                        break;
2659                case DRM_MODE_SCALE_ASPECT:
2660                        rmx_type = RMX_ASPECT;
2661                        break;
2662                case DRM_MODE_SCALE_FULLSCREEN:
2663                        rmx_type = RMX_FULL;
2664                        break;
2665                case DRM_MODE_SCALE_NONE:
2666                default:
2667                        rmx_type = RMX_OFF;
2668                        break;
2669                }
2670
2671                if (dm_old_state->scaling == rmx_type)
2672                        return 0;
2673
2674                dm_new_state->scaling = rmx_type;
2675                ret = 0;
2676        } else if (property == adev->mode_info.underscan_hborder_property) {
2677                dm_new_state->underscan_hborder = val;
2678                ret = 0;
2679        } else if (property == adev->mode_info.underscan_vborder_property) {
2680                dm_new_state->underscan_vborder = val;
2681                ret = 0;
2682        } else if (property == adev->mode_info.underscan_property) {
2683                dm_new_state->underscan_enable = val;
2684                ret = 0;
2685        }
2686
2687        return ret;
2688}
2689
2690int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
2691                                            const struct drm_connector_state *state,
2692                                            struct drm_property *property,
2693                                            uint64_t *val)
2694{
2695        struct drm_device *dev = connector->dev;
2696        struct amdgpu_device *adev = dev->dev_private;
2697        struct dm_connector_state *dm_state =
2698                to_dm_connector_state(state);
2699        int ret = -EINVAL;
2700
2701        if (property == dev->mode_config.scaling_mode_property) {
2702                switch (dm_state->scaling) {
2703                case RMX_CENTER:
2704                        *val = DRM_MODE_SCALE_CENTER;
2705                        break;
2706                case RMX_ASPECT:
2707                        *val = DRM_MODE_SCALE_ASPECT;
2708                        break;
2709                case RMX_FULL:
2710                        *val = DRM_MODE_SCALE_FULLSCREEN;
2711                        break;
2712                case RMX_OFF:
2713                default:
2714                        *val = DRM_MODE_SCALE_NONE;
2715                        break;
2716                }
2717                ret = 0;
2718        } else if (property == adev->mode_info.underscan_hborder_property) {
2719                *val = dm_state->underscan_hborder;
2720                ret = 0;
2721        } else if (property == adev->mode_info.underscan_vborder_property) {
2722                *val = dm_state->underscan_vborder;
2723                ret = 0;
2724        } else if (property == adev->mode_info.underscan_property) {
2725                *val = dm_state->underscan_enable;
2726                ret = 0;
2727        }
2728        return ret;
2729}
2730
2731static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
2732{
2733        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2734        const struct dc_link *link = aconnector->dc_link;
2735        struct amdgpu_device *adev = connector->dev->dev_private;
2736        struct amdgpu_display_manager *dm = &adev->dm;
2737
2738#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2739        defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2740
2741        if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2742            link->type != dc_connection_none &&
2743            dm->backlight_dev) {
2744                backlight_device_unregister(dm->backlight_dev);
2745                dm->backlight_dev = NULL;
2746        }
2747#endif
2748        drm_connector_unregister(connector);
2749        drm_connector_cleanup(connector);
2750        kfree(connector);
2751}
2752
2753void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
2754{
2755        struct dm_connector_state *state =
2756                to_dm_connector_state(connector->state);
2757
2758        if (connector->state)
2759                __drm_atomic_helper_connector_destroy_state(connector->state);
2760
2761        kfree(state);
2762
2763        state = kzalloc(sizeof(*state), GFP_KERNEL);
2764
2765        if (state) {
2766                state->scaling = RMX_OFF;
2767                state->underscan_enable = false;
2768                state->underscan_hborder = 0;
2769                state->underscan_vborder = 0;
2770
2771                __drm_atomic_helper_connector_reset(connector, &state->base);
2772        }
2773}
2774
2775struct drm_connector_state *
2776amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
2777{
2778        struct dm_connector_state *state =
2779                to_dm_connector_state(connector->state);
2780
2781        struct dm_connector_state *new_state =
2782                        kmemdup(state, sizeof(*state), GFP_KERNEL);
2783
2784        if (new_state) {
2785                __drm_atomic_helper_connector_duplicate_state(connector,
2786                                                              &new_state->base);
2787                return &new_state->base;
2788        }
2789
2790        return NULL;
2791}
2792
2793static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
2794        .reset = amdgpu_dm_connector_funcs_reset,
2795        .detect = amdgpu_dm_connector_detect,
2796        .fill_modes = drm_helper_probe_single_connector_modes,
2797        .destroy = amdgpu_dm_connector_destroy,
2798        .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
2799        .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
2800        .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
2801        .atomic_get_property = amdgpu_dm_connector_atomic_get_property
2802};
2803
2804static struct drm_encoder *best_encoder(struct drm_connector *connector)
2805{
2806        int enc_id = connector->encoder_ids[0];
2807        struct drm_mode_object *obj;
2808        struct drm_encoder *encoder;
2809
2810        DRM_DEBUG_DRIVER("Finding the best encoder\n");
2811
2812        /* pick the encoder ids */
2813        if (enc_id) {
2814                obj = drm_mode_object_find(connector->dev, NULL, enc_id, DRM_MODE_OBJECT_ENCODER);
2815                if (!obj) {
2816                        DRM_ERROR("Couldn't find a matching encoder for our connector\n");
2817                        return NULL;
2818                }
2819                encoder = obj_to_encoder(obj);
2820                return encoder;
2821        }
2822        DRM_ERROR("No encoder id\n");
2823        return NULL;
2824}
2825
2826static int get_modes(struct drm_connector *connector)
2827{
2828        return amdgpu_dm_connector_get_modes(connector);
2829}
2830
2831static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
2832{
2833        struct dc_sink_init_data init_params = {
2834                        .link = aconnector->dc_link,
2835                        .sink_signal = SIGNAL_TYPE_VIRTUAL
2836        };
2837        struct edid *edid;
2838
2839        if (!aconnector->base.edid_blob_ptr) {
2840                DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
2841                                aconnector->base.name);
2842
2843                aconnector->base.force = DRM_FORCE_OFF;
2844                aconnector->base.override_edid = false;
2845                return;
2846        }
2847
2848        edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
2849
2850        aconnector->edid = edid;
2851
2852        aconnector->dc_em_sink = dc_link_add_remote_sink(
2853                aconnector->dc_link,
2854                (uint8_t *)edid,
2855                (edid->extensions + 1) * EDID_LENGTH,
2856                &init_params);
2857
2858        if (aconnector->base.force == DRM_FORCE_ON)
2859                aconnector->dc_sink = aconnector->dc_link->local_sink ?
2860                aconnector->dc_link->local_sink :
2861                aconnector->dc_em_sink;
2862}
2863
2864static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
2865{
2866        struct dc_link *link = (struct dc_link *)aconnector->dc_link;
2867
2868        /* In case of headless boot with force on for DP managed connector
2869         * Those settings have to be != 0 to get initial modeset
2870         */
2871        if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
2872                link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
2873                link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
2874        }
2875
2876
2877        aconnector->base.override_edid = true;
2878        create_eml_sink(aconnector);
2879}
2880
2881enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
2882                                   struct drm_display_mode *mode)
2883{
2884        int result = MODE_ERROR;
2885        struct dc_sink *dc_sink;
2886        struct amdgpu_device *adev = connector->dev->dev_private;
2887        /* TODO: Unhardcode stream count */
2888        struct dc_stream_state *stream;
2889        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
2890        enum dc_status dc_result = DC_OK;
2891
2892        if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
2893                        (mode->flags & DRM_MODE_FLAG_DBLSCAN))
2894                return result;
2895
2896        /* Only run this the first time mode_valid is called to initilialize
2897         * EDID mgmt
2898         */
2899        if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
2900                !aconnector->dc_em_sink)
2901                handle_edid_mgmt(aconnector);
2902
2903        dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
2904
2905        if (dc_sink == NULL) {
2906                DRM_ERROR("dc_sink is NULL!\n");
2907                goto fail;
2908        }
2909
2910        stream = create_stream_for_sink(aconnector, mode, NULL);
2911        if (stream == NULL) {
2912                DRM_ERROR("Failed to create stream for sink!\n");
2913                goto fail;
2914        }
2915
2916        dc_result = dc_validate_stream(adev->dm.dc, stream);
2917
2918        if (dc_result == DC_OK)
2919                result = MODE_OK;
2920        else
2921                DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
2922                              mode->vdisplay,
2923                              mode->hdisplay,
2924                              mode->clock,
2925                              dc_result);
2926
2927        dc_stream_release(stream);
2928
2929fail:
2930        /* TODO: error handling*/
2931        return result;
2932}
2933
2934static const struct drm_connector_helper_funcs
2935amdgpu_dm_connector_helper_funcs = {
2936        /*
2937         * If hotplug a second bigger display in FB Con mode, bigger resolution
2938         * modes will be filtered by drm_mode_validate_size(), and those modes
2939         * is missing after user start lightdm. So we need to renew modes list.
2940         * in get_modes call back, not just return the modes count
2941         */
2942        .get_modes = get_modes,
2943        .mode_valid = amdgpu_dm_connector_mode_valid,
2944        .best_encoder = best_encoder
2945};
2946
2947static void dm_crtc_helper_disable(struct drm_crtc *crtc)
2948{
2949}
2950
2951static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
2952                                       struct drm_crtc_state *state)
2953{
2954        struct amdgpu_device *adev = crtc->dev->dev_private;
2955        struct dc *dc = adev->dm.dc;
2956        struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
2957        int ret = -EINVAL;
2958
2959        if (unlikely(!dm_crtc_state->stream &&
2960                     modeset_required(state, NULL, dm_crtc_state->stream))) {
2961                WARN_ON(1);
2962                return ret;
2963        }
2964
2965        /* In some use cases, like reset, no stream  is attached */
2966        if (!dm_crtc_state->stream)
2967                return 0;
2968
2969        if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
2970                return 0;
2971
2972        return ret;
2973}
2974
2975static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
2976                                      const struct drm_display_mode *mode,
2977                                      struct drm_display_mode *adjusted_mode)
2978{
2979        return true;
2980}
2981
2982static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
2983        .disable = dm_crtc_helper_disable,
2984        .atomic_check = dm_crtc_helper_atomic_check,
2985        .mode_fixup = dm_crtc_helper_mode_fixup
2986};
2987
2988static void dm_encoder_helper_disable(struct drm_encoder *encoder)
2989{
2990
2991}
2992
2993static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
2994                                          struct drm_crtc_state *crtc_state,
2995                                          struct drm_connector_state *conn_state)
2996{
2997        return 0;
2998}
2999
3000const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
3001        .disable = dm_encoder_helper_disable,
3002        .atomic_check = dm_encoder_helper_atomic_check
3003};
3004
3005static void dm_drm_plane_reset(struct drm_plane *plane)
3006{
3007        struct dm_plane_state *amdgpu_state = NULL;
3008
3009        if (plane->state)
3010                plane->funcs->atomic_destroy_state(plane, plane->state);
3011
3012        amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
3013        WARN_ON(amdgpu_state == NULL);
3014        
3015        if (amdgpu_state) {
3016                plane->state = &amdgpu_state->base;
3017                plane->state->plane = plane;
3018                plane->state->rotation = DRM_MODE_ROTATE_0;
3019        }
3020}
3021
3022static struct drm_plane_state *
3023dm_drm_plane_duplicate_state(struct drm_plane *plane)
3024{
3025        struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
3026
3027        old_dm_plane_state = to_dm_plane_state(plane->state);
3028        dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
3029        if (!dm_plane_state)
3030                return NULL;
3031
3032        __drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
3033
3034        if (old_dm_plane_state->dc_state) {
3035                dm_plane_state->dc_state = old_dm_plane_state->dc_state;
3036                dc_plane_state_retain(dm_plane_state->dc_state);
3037        }
3038
3039        return &dm_plane_state->base;
3040}
3041
3042void dm_drm_plane_destroy_state(struct drm_plane *plane,
3043                                struct drm_plane_state *state)
3044{
3045        struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3046
3047        if (dm_plane_state->dc_state)
3048                dc_plane_state_release(dm_plane_state->dc_state);
3049
3050        drm_atomic_helper_plane_destroy_state(plane, state);
3051}
3052
3053static const struct drm_plane_funcs dm_plane_funcs = {
3054        .update_plane   = drm_atomic_helper_update_plane,
3055        .disable_plane  = drm_atomic_helper_disable_plane,
3056        .destroy        = drm_plane_cleanup,
3057        .reset = dm_drm_plane_reset,
3058        .atomic_duplicate_state = dm_drm_plane_duplicate_state,
3059        .atomic_destroy_state = dm_drm_plane_destroy_state,
3060};
3061
3062static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
3063                                      struct drm_plane_state *new_state)
3064{
3065        struct amdgpu_framebuffer *afb;
3066        struct drm_gem_object *obj;
3067        struct amdgpu_device *adev;
3068        struct amdgpu_bo *rbo;
3069        uint64_t chroma_addr = 0;
3070        struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
3071        unsigned int awidth;
3072        uint32_t domain;
3073        int r;
3074
3075        dm_plane_state_old = to_dm_plane_state(plane->state);
3076        dm_plane_state_new = to_dm_plane_state(new_state);
3077
3078        if (!new_state->fb) {
3079                DRM_DEBUG_DRIVER("No FB bound\n");
3080                return 0;
3081        }
3082
3083        afb = to_amdgpu_framebuffer(new_state->fb);
3084        obj = new_state->fb->obj[0];
3085        rbo = gem_to_amdgpu_bo(obj);
3086        adev = amdgpu_ttm_adev(rbo->tbo.bdev);
3087        r = amdgpu_bo_reserve(rbo, false);
3088        if (unlikely(r != 0))
3089                return r;
3090
3091        if (plane->type != DRM_PLANE_TYPE_CURSOR)
3092                domain = amdgpu_display_supported_domains(adev);
3093        else
3094                domain = AMDGPU_GEM_DOMAIN_VRAM;
3095
3096        r = amdgpu_bo_pin(rbo, domain, &afb->address);
3097        amdgpu_bo_unreserve(rbo);
3098
3099        if (unlikely(r != 0)) {
3100                if (r != -ERESTARTSYS)
3101                        DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
3102                return r;
3103        }
3104
3105        amdgpu_bo_ref(rbo);
3106
3107        if (dm_plane_state_new->dc_state &&
3108                        dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
3109                struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
3110
3111                if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
3112                        plane_state->address.grph.addr.low_part = lower_32_bits(afb->address);
3113                        plane_state->address.grph.addr.high_part = upper_32_bits(afb->address);
3114                } else {
3115                        awidth = ALIGN(new_state->fb->width, 64);
3116                        plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
3117                        plane_state->address.video_progressive.luma_addr.low_part
3118                                                        = lower_32_bits(afb->address);
3119                        plane_state->address.video_progressive.luma_addr.high_part
3120                                                        = upper_32_bits(afb->address);
3121                        chroma_addr = afb->address + (u64)awidth * new_state->fb->height;
3122                        plane_state->address.video_progressive.chroma_addr.low_part
3123                                                        = lower_32_bits(chroma_addr);
3124                        plane_state->address.video_progressive.chroma_addr.high_part
3125                                                        = upper_32_bits(chroma_addr);
3126                }
3127        }
3128
3129        return 0;
3130}
3131
3132static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
3133                                       struct drm_plane_state *old_state)
3134{
3135        struct amdgpu_bo *rbo;
3136        int r;
3137
3138        if (!old_state->fb)
3139                return;
3140
3141        rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
3142        r = amdgpu_bo_reserve(rbo, false);
3143        if (unlikely(r)) {
3144                DRM_ERROR("failed to reserve rbo before unpin\n");
3145                return;
3146        }
3147
3148        amdgpu_bo_unpin(rbo);
3149        amdgpu_bo_unreserve(rbo);
3150        amdgpu_bo_unref(&rbo);
3151}
3152
3153static int dm_plane_atomic_check(struct drm_plane *plane,
3154                                 struct drm_plane_state *state)
3155{
3156        struct amdgpu_device *adev = plane->dev->dev_private;
3157        struct dc *dc = adev->dm.dc;
3158        struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3159
3160        if (!dm_plane_state->dc_state)
3161                return 0;
3162
3163        if (!fill_rects_from_plane_state(state, dm_plane_state->dc_state))
3164                return -EINVAL;
3165
3166        if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
3167                return 0;
3168
3169        return -EINVAL;
3170}
3171
3172static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
3173        .prepare_fb = dm_plane_helper_prepare_fb,
3174        .cleanup_fb = dm_plane_helper_cleanup_fb,
3175        .atomic_check = dm_plane_atomic_check,
3176};
3177
3178/*
3179 * TODO: these are currently initialized to rgb formats only.
3180 * For future use cases we should either initialize them dynamically based on
3181 * plane capabilities, or initialize this array to all formats, so internal drm
3182 * check will succeed, and let DC to implement proper check
3183 */
3184static const uint32_t rgb_formats[] = {
3185        DRM_FORMAT_RGB888,
3186        DRM_FORMAT_XRGB8888,
3187        DRM_FORMAT_ARGB8888,
3188        DRM_FORMAT_RGBA8888,
3189        DRM_FORMAT_XRGB2101010,
3190        DRM_FORMAT_XBGR2101010,
3191        DRM_FORMAT_ARGB2101010,
3192        DRM_FORMAT_ABGR2101010,
3193};
3194
3195static const uint32_t yuv_formats[] = {
3196        DRM_FORMAT_NV12,
3197        DRM_FORMAT_NV21,
3198};
3199
3200static const u32 cursor_formats[] = {
3201        DRM_FORMAT_ARGB8888
3202};
3203
3204static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
3205                                struct amdgpu_plane *aplane,
3206                                unsigned long possible_crtcs)
3207{
3208        int res = -EPERM;
3209
3210        switch (aplane->base.type) {
3211        case DRM_PLANE_TYPE_PRIMARY:
3212                res = drm_universal_plane_init(
3213                                dm->adev->ddev,
3214                                &aplane->base,
3215                                possible_crtcs,
3216                                &dm_plane_funcs,
3217                                rgb_formats,
3218                                ARRAY_SIZE(rgb_formats),
3219                                NULL, aplane->base.type, NULL);
3220                break;
3221        case DRM_PLANE_TYPE_OVERLAY:
3222                res = drm_universal_plane_init(
3223                                dm->adev->ddev,
3224                                &aplane->base,
3225                                possible_crtcs,
3226                                &dm_plane_funcs,
3227                                yuv_formats,
3228                                ARRAY_SIZE(yuv_formats),
3229                                NULL, aplane->base.type, NULL);
3230                break;
3231        case DRM_PLANE_TYPE_CURSOR:
3232                res = drm_universal_plane_init(
3233                                dm->adev->ddev,
3234                                &aplane->base,
3235                                possible_crtcs,
3236                                &dm_plane_funcs,
3237                                cursor_formats,
3238                                ARRAY_SIZE(cursor_formats),
3239                                NULL, aplane->base.type, NULL);
3240                break;
3241        }
3242
3243        drm_plane_helper_add(&aplane->base, &dm_plane_helper_funcs);
3244
3245        /* Create (reset) the plane state */
3246        if (aplane->base.funcs->reset)
3247                aplane->base.funcs->reset(&aplane->base);
3248
3249
3250        return res;
3251}
3252
3253static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
3254                               struct drm_plane *plane,
3255                               uint32_t crtc_index)
3256{
3257        struct amdgpu_crtc *acrtc = NULL;
3258        struct amdgpu_plane *cursor_plane;
3259
3260        int res = -ENOMEM;
3261
3262        cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
3263        if (!cursor_plane)
3264                goto fail;
3265
3266        cursor_plane->base.type = DRM_PLANE_TYPE_CURSOR;
3267        res = amdgpu_dm_plane_init(dm, cursor_plane, 0);
3268
3269        acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
3270        if (!acrtc)
3271                goto fail;
3272
3273        res = drm_crtc_init_with_planes(
3274                        dm->ddev,
3275                        &acrtc->base,
3276                        plane,
3277                        &cursor_plane->base,
3278                        &amdgpu_dm_crtc_funcs, NULL);
3279
3280        if (res)
3281                goto fail;
3282
3283        drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
3284
3285        /* Create (reset) the plane state */
3286        if (acrtc->base.funcs->reset)
3287                acrtc->base.funcs->reset(&acrtc->base);
3288
3289        acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
3290        acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
3291
3292        acrtc->crtc_id = crtc_index;
3293        acrtc->base.enabled = false;
3294
3295        dm->adev->mode_info.crtcs[crtc_index] = acrtc;
3296        drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
3297                                   true, MAX_COLOR_LUT_ENTRIES);
3298        drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
3299
3300        return 0;
3301
3302fail:
3303        kfree(acrtc);
3304        kfree(cursor_plane);
3305        return res;
3306}
3307
3308
3309static int to_drm_connector_type(enum signal_type st)
3310{
3311        switch (st) {
3312        case SIGNAL_TYPE_HDMI_TYPE_A:
3313                return DRM_MODE_CONNECTOR_HDMIA;
3314        case SIGNAL_TYPE_EDP:
3315                return DRM_MODE_CONNECTOR_eDP;
3316        case SIGNAL_TYPE_RGB:
3317                return DRM_MODE_CONNECTOR_VGA;
3318        case SIGNAL_TYPE_DISPLAY_PORT:
3319        case SIGNAL_TYPE_DISPLAY_PORT_MST:
3320                return DRM_MODE_CONNECTOR_DisplayPort;
3321        case SIGNAL_TYPE_DVI_DUAL_LINK:
3322        case SIGNAL_TYPE_DVI_SINGLE_LINK:
3323                return DRM_MODE_CONNECTOR_DVID;
3324        case SIGNAL_TYPE_VIRTUAL:
3325                return DRM_MODE_CONNECTOR_VIRTUAL;
3326
3327        default:
3328                return DRM_MODE_CONNECTOR_Unknown;
3329        }
3330}
3331
3332static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
3333{
3334        const struct drm_connector_helper_funcs *helper =
3335                connector->helper_private;
3336        struct drm_encoder *encoder;
3337        struct amdgpu_encoder *amdgpu_encoder;
3338
3339        encoder = helper->best_encoder(connector);
3340
3341        if (encoder == NULL)
3342                return;
3343
3344        amdgpu_encoder = to_amdgpu_encoder(encoder);
3345
3346        amdgpu_encoder->native_mode.clock = 0;
3347
3348        if (!list_empty(&connector->probed_modes)) {
3349                struct drm_display_mode *preferred_mode = NULL;
3350
3351                list_for_each_entry(preferred_mode,
3352                                    &connector->probed_modes,
3353                                    head) {
3354                        if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
3355                                amdgpu_encoder->native_mode = *preferred_mode;
3356
3357                        break;
3358                }
3359
3360        }
3361}
3362
3363static struct drm_display_mode *
3364amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
3365                             char *name,
3366                             int hdisplay, int vdisplay)
3367{
3368        struct drm_device *dev = encoder->dev;
3369        struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3370        struct drm_display_mode *mode = NULL;
3371        struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3372
3373        mode = drm_mode_duplicate(dev, native_mode);
3374
3375        if (mode == NULL)
3376                return NULL;
3377
3378        mode->hdisplay = hdisplay;
3379        mode->vdisplay = vdisplay;
3380        mode->type &= ~DRM_MODE_TYPE_PREFERRED;
3381        strncpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
3382
3383        return mode;
3384
3385}
3386
3387static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
3388                                                 struct drm_connector *connector)
3389{
3390        struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3391        struct drm_display_mode *mode = NULL;
3392        struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3393        struct amdgpu_dm_connector *amdgpu_dm_connector =
3394                                to_amdgpu_dm_connector(connector);
3395        int i;
3396        int n;
3397        struct mode_size {
3398                char name[DRM_DISPLAY_MODE_LEN];
3399                int w;
3400                int h;
3401        } common_modes[] = {
3402                {  "640x480",  640,  480},
3403                {  "800x600",  800,  600},
3404                { "1024x768", 1024,  768},
3405                { "1280x720", 1280,  720},
3406                { "1280x800", 1280,  800},
3407                {"1280x1024", 1280, 1024},
3408                { "1440x900", 1440,  900},
3409                {"1680x1050", 1680, 1050},
3410                {"1600x1200", 1600, 1200},
3411                {"1920x1080", 1920, 1080},
3412                {"1920x1200", 1920, 1200}
3413        };
3414
3415        n = ARRAY_SIZE(common_modes);
3416
3417        for (i = 0; i < n; i++) {
3418                struct drm_display_mode *curmode = NULL;
3419                bool mode_existed = false;
3420
3421                if (common_modes[i].w > native_mode->hdisplay ||
3422                    common_modes[i].h > native_mode->vdisplay ||
3423                   (common_modes[i].w == native_mode->hdisplay &&
3424                    common_modes[i].h == native_mode->vdisplay))
3425                        continue;
3426
3427                list_for_each_entry(curmode, &connector->probed_modes, head) {
3428                        if (common_modes[i].w == curmode->hdisplay &&
3429                            common_modes[i].h == curmode->vdisplay) {
3430                                mode_existed = true;
3431                                break;
3432                        }
3433                }
3434
3435                if (mode_existed)
3436                        continue;
3437
3438                mode = amdgpu_dm_create_common_mode(encoder,
3439                                common_modes[i].name, common_modes[i].w,
3440                                common_modes[i].h);
3441                drm_mode_probed_add(connector, mode);
3442                amdgpu_dm_connector->num_modes++;
3443        }
3444}
3445
3446static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
3447                                              struct edid *edid)
3448{
3449        struct amdgpu_dm_connector *amdgpu_dm_connector =
3450                        to_amdgpu_dm_connector(connector);
3451
3452        if (edid) {
3453                /* empty probed_modes */
3454                INIT_LIST_HEAD(&connector->probed_modes);
3455                amdgpu_dm_connector->num_modes =
3456                                drm_add_edid_modes(connector, edid);
3457
3458                amdgpu_dm_get_native_mode(connector);
3459        } else {
3460                amdgpu_dm_connector->num_modes = 0;
3461        }
3462}
3463
3464static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
3465{
3466        const struct drm_connector_helper_funcs *helper =
3467                        connector->helper_private;
3468        struct amdgpu_dm_connector *amdgpu_dm_connector =
3469                        to_amdgpu_dm_connector(connector);
3470        struct drm_encoder *encoder;
3471        struct edid *edid = amdgpu_dm_connector->edid;
3472
3473        encoder = helper->best_encoder(connector);
3474        amdgpu_dm_connector_ddc_get_modes(connector, edid);
3475        amdgpu_dm_connector_add_common_modes(encoder, connector);
3476
3477#if defined(CONFIG_DRM_AMD_DC_FBC)
3478        amdgpu_dm_fbc_init(connector);
3479#endif
3480        return amdgpu_dm_connector->num_modes;
3481}
3482
3483void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
3484                                     struct amdgpu_dm_connector *aconnector,
3485                                     int connector_type,
3486                                     struct dc_link *link,
3487                                     int link_index)
3488{
3489        struct amdgpu_device *adev = dm->ddev->dev_private;
3490
3491        aconnector->connector_id = link_index;
3492        aconnector->dc_link = link;
3493        aconnector->base.interlace_allowed = false;
3494        aconnector->base.doublescan_allowed = false;
3495        aconnector->base.stereo_allowed = false;
3496        aconnector->base.dpms = DRM_MODE_DPMS_OFF;
3497        aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
3498
3499        mutex_init(&aconnector->hpd_lock);
3500
3501        /* configure support HPD hot plug connector_>polled default value is 0
3502         * which means HPD hot plug not supported
3503         */
3504        switch (connector_type) {
3505        case DRM_MODE_CONNECTOR_HDMIA:
3506                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3507                break;
3508        case DRM_MODE_CONNECTOR_DisplayPort:
3509                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3510                break;
3511        case DRM_MODE_CONNECTOR_DVID:
3512                aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3513                break;
3514        default:
3515                break;
3516        }
3517
3518        drm_object_attach_property(&aconnector->base.base,
3519                                dm->ddev->mode_config.scaling_mode_property,
3520                                DRM_MODE_SCALE_NONE);
3521
3522        drm_object_attach_property(&aconnector->base.base,
3523                                adev->mode_info.underscan_property,
3524                                UNDERSCAN_OFF);
3525        drm_object_attach_property(&aconnector->base.base,
3526                                adev->mode_info.underscan_hborder_property,
3527                                0);
3528        drm_object_attach_property(&aconnector->base.base,
3529                                adev->mode_info.underscan_vborder_property,
3530                                0);
3531
3532}
3533
3534static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
3535                              struct i2c_msg *msgs, int num)
3536{
3537        struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
3538        struct ddc_service *ddc_service = i2c->ddc_service;
3539        struct i2c_command cmd;
3540        int i;
3541        int result = -EIO;
3542
3543        cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
3544
3545        if (!cmd.payloads)
3546                return result;
3547
3548        cmd.number_of_payloads = num;
3549        cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
3550        cmd.speed = 100;
3551
3552        for (i = 0; i < num; i++) {
3553                cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
3554                cmd.payloads[i].address = msgs[i].addr;
3555                cmd.payloads[i].length = msgs[i].len;
3556                cmd.payloads[i].data = msgs[i].buf;
3557        }
3558
3559        if (dal_i2caux_submit_i2c_command(
3560                        ddc_service->ctx->i2caux,
3561                        ddc_service->ddc_pin,
3562                        &cmd))
3563                result = num;
3564
3565        kfree(cmd.payloads);
3566        return result;
3567}
3568
3569static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
3570{
3571        return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
3572}
3573
3574static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
3575        .master_xfer = amdgpu_dm_i2c_xfer,
3576        .functionality = amdgpu_dm_i2c_func,
3577};
3578
3579static struct amdgpu_i2c_adapter *
3580create_i2c(struct ddc_service *ddc_service,
3581           int link_index,
3582           int *res)
3583{
3584        struct amdgpu_device *adev = ddc_service->ctx->driver_context;
3585        struct amdgpu_i2c_adapter *i2c;
3586
3587        i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
3588        if (!i2c)
3589                return NULL;
3590        i2c->base.owner = THIS_MODULE;
3591        i2c->base.class = I2C_CLASS_DDC;
3592        i2c->base.dev.parent = &adev->pdev->dev;
3593        i2c->base.algo = &amdgpu_dm_i2c_algo;
3594        snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
3595        i2c_set_adapdata(&i2c->base, i2c);
3596        i2c->ddc_service = ddc_service;
3597
3598        return i2c;
3599}
3600
3601
3602/* Note: this function assumes that dc_link_detect() was called for the
3603 * dc_link which will be represented by this aconnector.
3604 */
3605static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
3606                                    struct amdgpu_dm_connector *aconnector,
3607                                    uint32_t link_index,
3608                                    struct amdgpu_encoder *aencoder)
3609{
3610        int res = 0;
3611        int connector_type;
3612        struct dc *dc = dm->dc;
3613        struct dc_link *link = dc_get_link_at_index(dc, link_index);
3614        struct amdgpu_i2c_adapter *i2c;
3615
3616        link->priv = aconnector;
3617
3618        DRM_DEBUG_DRIVER("%s()\n", __func__);
3619
3620        i2c = create_i2c(link->ddc, link->link_index, &res);
3621        if (!i2c) {
3622                DRM_ERROR("Failed to create i2c adapter data\n");
3623                return -ENOMEM;
3624        }
3625
3626        aconnector->i2c = i2c;
3627        res = i2c_add_adapter(&i2c->base);
3628
3629        if (res) {
3630                DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
3631                goto out_free;
3632        }
3633
3634        connector_type = to_drm_connector_type(link->connector_signal);
3635
3636        res = drm_connector_init(
3637                        dm->ddev,
3638                        &aconnector->base,
3639                        &amdgpu_dm_connector_funcs,
3640                        connector_type);
3641
3642        if (res) {
3643                DRM_ERROR("connector_init failed\n");
3644                aconnector->connector_id = -1;
3645                goto out_free;
3646        }
3647
3648        drm_connector_helper_add(
3649                        &aconnector->base,
3650                        &amdgpu_dm_connector_helper_funcs);
3651
3652        if (aconnector->base.funcs->reset)
3653                aconnector->base.funcs->reset(&aconnector->base);
3654
3655        amdgpu_dm_connector_init_helper(
3656                dm,
3657                aconnector,
3658                connector_type,
3659                link,
3660                link_index);
3661
3662        drm_mode_connector_attach_encoder(
3663                &aconnector->base, &aencoder->base);
3664
3665        drm_connector_register(&aconnector->base);
3666
3667        if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
3668                || connector_type == DRM_MODE_CONNECTOR_eDP)
3669                amdgpu_dm_initialize_dp_connector(dm, aconnector);
3670
3671out_free:
3672        if (res) {
3673                kfree(i2c);
3674                aconnector->i2c = NULL;
3675        }
3676        return res;
3677}
3678
3679int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
3680{
3681        switch (adev->mode_info.num_crtc) {
3682        case 1:
3683                return 0x1;
3684        case 2:
3685                return 0x3;
3686        case 3:
3687                return 0x7;
3688        case 4:
3689                return 0xf;
3690        case 5:
3691                return 0x1f;
3692        case 6:
3693        default:
3694                return 0x3f;
3695        }
3696}
3697
3698static int amdgpu_dm_encoder_init(struct drm_device *dev,
3699                                  struct amdgpu_encoder *aencoder,
3700                                  uint32_t link_index)
3701{
3702        struct amdgpu_device *adev = dev->dev_private;
3703
3704        int res = drm_encoder_init(dev,
3705                                   &aencoder->base,
3706                                   &amdgpu_dm_encoder_funcs,
3707                                   DRM_MODE_ENCODER_TMDS,
3708                                   NULL);
3709
3710        aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
3711
3712        if (!res)
3713                aencoder->encoder_id = link_index;
3714        else
3715                aencoder->encoder_id = -1;
3716
3717        drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
3718
3719        return res;
3720}
3721
3722static void manage_dm_interrupts(struct amdgpu_device *adev,
3723                                 struct amdgpu_crtc *acrtc,
3724                                 bool enable)
3725{
3726        /*
3727         * this is not correct translation but will work as soon as VBLANK
3728         * constant is the same as PFLIP
3729         */
3730        int irq_type =
3731                amdgpu_display_crtc_idx_to_irq_type(
3732                        adev,
3733                        acrtc->crtc_id);
3734
3735        if (enable) {
3736                drm_crtc_vblank_on(&acrtc->base);
3737                amdgpu_irq_get(
3738                        adev,
3739                        &adev->pageflip_irq,
3740                        irq_type);
3741        } else {
3742
3743                amdgpu_irq_put(
3744                        adev,
3745                        &adev->pageflip_irq,
3746                        irq_type);
3747                drm_crtc_vblank_off(&acrtc->base);
3748        }
3749}
3750
3751static bool
3752is_scaling_state_different(const struct dm_connector_state *dm_state,
3753                           const struct dm_connector_state *old_dm_state)
3754{
3755        if (dm_state->scaling != old_dm_state->scaling)
3756                return true;
3757        if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
3758                if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
3759                        return true;
3760        } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
3761                if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
3762                        return true;
3763        } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
3764                   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
3765                return true;
3766        return false;
3767}
3768
3769static void remove_stream(struct amdgpu_device *adev,
3770                          struct amdgpu_crtc *acrtc,
3771                          struct dc_stream_state *stream)
3772{
3773        /* this is the update mode case */
3774        if (adev->dm.freesync_module)
3775                mod_freesync_remove_stream(adev->dm.freesync_module, stream);
3776
3777        acrtc->otg_inst = -1;
3778        acrtc->enabled = false;
3779}
3780
3781static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
3782                               struct dc_cursor_position *position)
3783{
3784        struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3785        int x, y;
3786        int xorigin = 0, yorigin = 0;
3787
3788        if (!crtc || !plane->state->fb) {
3789                position->enable = false;
3790                position->x = 0;
3791                position->y = 0;
3792                return 0;
3793        }
3794
3795        if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
3796            (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
3797                DRM_ERROR("%s: bad cursor width or height %d x %d\n",
3798                          __func__,
3799                          plane->state->crtc_w,
3800                          plane->state->crtc_h);
3801                return -EINVAL;
3802        }
3803
3804        x = plane->state->crtc_x;
3805        y = plane->state->crtc_y;
3806        /* avivo cursor are offset into the total surface */
3807        x += crtc->primary->state->src_x >> 16;
3808        y += crtc->primary->state->src_y >> 16;
3809        if (x < 0) {
3810                xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
3811                x = 0;
3812        }
3813        if (y < 0) {
3814                yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
3815                y = 0;
3816        }
3817        position->enable = true;
3818        position->x = x;
3819        position->y = y;
3820        position->x_hotspot = xorigin;
3821        position->y_hotspot = yorigin;
3822
3823        return 0;
3824}
3825
3826static void handle_cursor_update(struct drm_plane *plane,
3827                                 struct drm_plane_state *old_plane_state)
3828{
3829        struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
3830        struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
3831        struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
3832        struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3833        uint64_t address = afb ? afb->address : 0;
3834        struct dc_cursor_position position;
3835        struct dc_cursor_attributes attributes;
3836        int ret;
3837
3838        if (!plane->state->fb && !old_plane_state->fb)
3839                return;
3840
3841        DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
3842                         __func__,
3843                         amdgpu_crtc->crtc_id,
3844                         plane->state->crtc_w,
3845                         plane->state->crtc_h);
3846
3847        ret = get_cursor_position(plane, crtc, &position);
3848        if (ret)
3849                return;
3850
3851        if (!position.enable) {
3852                /* turn off cursor */
3853                if (crtc_state && crtc_state->stream)
3854                        dc_stream_set_cursor_position(crtc_state->stream,
3855                                                      &position);
3856                return;
3857        }
3858
3859        amdgpu_crtc->cursor_width = plane->state->crtc_w;
3860        amdgpu_crtc->cursor_height = plane->state->crtc_h;
3861
3862        attributes.address.high_part = upper_32_bits(address);
3863        attributes.address.low_part  = lower_32_bits(address);
3864        attributes.width             = plane->state->crtc_w;
3865        attributes.height            = plane->state->crtc_h;
3866        attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
3867        attributes.rotation_angle    = 0;
3868        attributes.attribute_flags.value = 0;
3869
3870        attributes.pitch = attributes.width;
3871
3872        if (crtc_state->stream) {
3873                if (!dc_stream_set_cursor_attributes(crtc_state->stream,
3874                                                         &attributes))
3875                        DRM_ERROR("DC failed to set cursor attributes\n");
3876
3877                if (!dc_stream_set_cursor_position(crtc_state->stream,
3878                                                   &position))
3879                        DRM_ERROR("DC failed to set cursor position\n");
3880        }
3881}
3882
3883static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
3884{
3885
3886        assert_spin_locked(&acrtc->base.dev->event_lock);
3887        WARN_ON(acrtc->event);
3888
3889        acrtc->event = acrtc->base.state->event;
3890
3891        /* Set the flip status */
3892        acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
3893
3894        /* Mark this event as consumed */
3895        acrtc->base.state->event = NULL;
3896
3897        DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
3898                                                 acrtc->crtc_id);
3899}
3900
3901/*
3902 * Executes flip
3903 *
3904 * Waits on all BO's fences and for proper vblank count
3905 */
3906static void amdgpu_dm_do_flip(struct drm_crtc *crtc,
3907                              struct drm_framebuffer *fb,
3908                              uint32_t target,
3909                              struct dc_state *state)
3910{
3911        unsigned long flags;
3912        uint32_t target_vblank;
3913        int r, vpos, hpos;
3914        struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3915        struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
3916        struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
3917        struct amdgpu_device *adev = crtc->dev->dev_private;
3918        bool async_flip = (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
3919        struct dc_flip_addrs addr = { {0} };
3920        /* TODO eliminate or rename surface_update */
3921        struct dc_surface_update surface_updates[1] = { {0} };
3922        struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3923
3924
3925        /* Prepare wait for target vblank early - before the fence-waits */
3926        target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
3927                        amdgpu_get_vblank_counter_kms(crtc->dev, acrtc->crtc_id);
3928
3929        /* TODO This might fail and hence better not used, wait
3930         * explicitly on fences instead
3931         * and in general should be called for
3932         * blocking commit to as per framework helpers
3933         */
3934        r = amdgpu_bo_reserve(abo, true);
3935        if (unlikely(r != 0)) {
3936                DRM_ERROR("failed to reserve buffer before flip\n");
3937                WARN_ON(1);
3938        }
3939
3940        /* Wait for all fences on this FB */
3941        WARN_ON(reservation_object_wait_timeout_rcu(abo->tbo.resv, true, false,
3942                                                                    MAX_SCHEDULE_TIMEOUT) < 0);
3943
3944        amdgpu_bo_unreserve(abo);
3945
3946        /* Wait until we're out of the vertical blank period before the one
3947         * targeted by the flip
3948         */
3949        while ((acrtc->enabled &&
3950                (amdgpu_display_get_crtc_scanoutpos(adev->ddev, acrtc->crtc_id,
3951                                                    0, &vpos, &hpos, NULL,
3952                                                    NULL, &crtc->hwmode)
3953                 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
3954                (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
3955                (int)(target_vblank -
3956                  amdgpu_get_vblank_counter_kms(adev->ddev, acrtc->crtc_id)) > 0)) {
3957                usleep_range(1000, 1100);
3958        }
3959
3960        /* Flip */
3961        spin_lock_irqsave(&crtc->dev->event_lock, flags);
3962        /* update crtc fb */
3963        crtc->primary->fb = fb;
3964
3965        WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
3966        WARN_ON(!acrtc_state->stream);
3967
3968        addr.address.grph.addr.low_part = lower_32_bits(afb->address);
3969        addr.address.grph.addr.high_part = upper_32_bits(afb->address);
3970        addr.flip_immediate = async_flip;
3971
3972
3973        if (acrtc->base.state->event)
3974                prepare_flip_isr(acrtc);
3975
3976        spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
3977
3978        surface_updates->surface = dc_stream_get_status(acrtc_state->stream)->plane_states[0];
3979        surface_updates->flip_addr = &addr;
3980
3981        dc_commit_updates_for_stream(adev->dm.dc,
3982                                             surface_updates,
3983                                             1,
3984                                             acrtc_state->stream,
3985                                             NULL,
3986                                             &surface_updates->surface,
3987                                             state);
3988
3989        DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x \n",
3990                         __func__,
3991                         addr.address.grph.addr.high_part,
3992                         addr.address.grph.addr.low_part);
3993}
3994
3995/*
3996 * TODO this whole function needs to go
3997 *
3998 * dc_surface_update is needlessly complex. See if we can just replace this
3999 * with a dc_plane_state and follow the atomic model a bit more closely here.
4000 */
4001static bool commit_planes_to_stream(
4002                struct dc *dc,
4003                struct dc_plane_state **plane_states,
4004                uint8_t new_plane_count,
4005                struct dm_crtc_state *dm_new_crtc_state,
4006                struct dm_crtc_state *dm_old_crtc_state,
4007                struct dc_state *state)
4008{
4009        /* no need to dynamically allocate this. it's pretty small */
4010        struct dc_surface_update updates[MAX_SURFACES];
4011        struct dc_flip_addrs *flip_addr;
4012        struct dc_plane_info *plane_info;
4013        struct dc_scaling_info *scaling_info;
4014        int i;
4015        struct dc_stream_state *dc_stream = dm_new_crtc_state->stream;
4016        struct dc_stream_update *stream_update =
4017                        kzalloc(sizeof(struct dc_stream_update), GFP_KERNEL);
4018
4019        if (!stream_update) {
4020                BREAK_TO_DEBUGGER();
4021                return false;
4022        }
4023
4024        flip_addr = kcalloc(MAX_SURFACES, sizeof(struct dc_flip_addrs),
4025                            GFP_KERNEL);
4026        plane_info = kcalloc(MAX_SURFACES, sizeof(struct dc_plane_info),
4027                             GFP_KERNEL);
4028        scaling_info = kcalloc(MAX_SURFACES, sizeof(struct dc_scaling_info),
4029                               GFP_KERNEL);
4030
4031        if (!flip_addr || !plane_info || !scaling_info) {
4032                kfree(flip_addr);
4033                kfree(plane_info);
4034                kfree(scaling_info);
4035                kfree(stream_update);
4036                return false;
4037        }
4038
4039        memset(updates, 0, sizeof(updates));
4040
4041        stream_update->src = dc_stream->src;
4042        stream_update->dst = dc_stream->dst;
4043        stream_update->out_transfer_func = dc_stream->out_transfer_func;
4044
4045        for (i = 0; i < new_plane_count; i++) {
4046                updates[i].surface = plane_states[i];
4047                updates[i].gamma =
4048                        (struct dc_gamma *)plane_states[i]->gamma_correction;
4049                updates[i].in_transfer_func = plane_states[i]->in_transfer_func;
4050                flip_addr[i].address = plane_states[i]->address;
4051                flip_addr[i].flip_immediate = plane_states[i]->flip_immediate;
4052                plane_info[i].color_space = plane_states[i]->color_space;
4053                plane_info[i].format = plane_states[i]->format;
4054                plane_info[i].plane_size = plane_states[i]->plane_size;
4055                plane_info[i].rotation = plane_states[i]->rotation;
4056                plane_info[i].horizontal_mirror = plane_states[i]->horizontal_mirror;
4057                plane_info[i].stereo_format = plane_states[i]->stereo_format;
4058                plane_info[i].tiling_info = plane_states[i]->tiling_info;
4059                plane_info[i].visible = plane_states[i]->visible;
4060                plane_info[i].per_pixel_alpha = plane_states[i]->per_pixel_alpha;
4061                plane_info[i].dcc = plane_states[i]->dcc;
4062                scaling_info[i].scaling_quality = plane_states[i]->scaling_quality;
4063                scaling_info[i].src_rect = plane_states[i]->src_rect;
4064                scaling_info[i].dst_rect = plane_states[i]->dst_rect;
4065                scaling_info[i].clip_rect = plane_states[i]->clip_rect;
4066
4067                updates[i].flip_addr = &flip_addr[i];
4068                updates[i].plane_info = &plane_info[i];
4069                updates[i].scaling_info = &scaling_info[i];
4070        }
4071
4072        dc_commit_updates_for_stream(
4073                        dc,
4074                        updates,
4075                        new_plane_count,
4076                        dc_stream, stream_update, plane_states, state);
4077
4078        kfree(flip_addr);
4079        kfree(plane_info);
4080        kfree(scaling_info);
4081        kfree(stream_update);
4082        return true;
4083}
4084
4085static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
4086                                    struct drm_device *dev,
4087                                    struct amdgpu_display_manager *dm,
4088                                    struct drm_crtc *pcrtc,
4089                                    bool *wait_for_vblank)
4090{
4091        uint32_t i;
4092        struct drm_plane *plane;
4093        struct drm_plane_state *old_plane_state, *new_plane_state;
4094        struct dc_stream_state *dc_stream_attach;
4095        struct dc_plane_state *plane_states_constructed[MAX_SURFACES];
4096        struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
4097        struct drm_crtc_state *new_pcrtc_state =
4098                        drm_atomic_get_new_crtc_state(state, pcrtc);
4099        struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
4100        struct dm_crtc_state *dm_old_crtc_state =
4101                        to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
4102        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4103        int planes_count = 0;
4104        unsigned long flags;
4105
4106        /* update planes when needed */
4107        for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
4108                struct drm_crtc *crtc = new_plane_state->crtc;
4109                struct drm_crtc_state *new_crtc_state;
4110                struct drm_framebuffer *fb = new_plane_state->fb;
4111                bool pflip_needed;
4112                struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
4113
4114                if (plane->type == DRM_PLANE_TYPE_CURSOR) {
4115                        handle_cursor_update(plane, old_plane_state);
4116                        continue;
4117                }
4118
4119                if (!fb || !crtc || pcrtc != crtc)
4120                        continue;
4121
4122                new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
4123                if (!new_crtc_state->active)
4124                        continue;
4125
4126                pflip_needed = !state->allow_modeset;
4127
4128                spin_lock_irqsave(&crtc->dev->event_lock, flags);
4129                if (acrtc_attach->pflip_status != AMDGPU_FLIP_NONE) {
4130                        DRM_ERROR("%s: acrtc %d, already busy\n",
4131                                  __func__,
4132                                  acrtc_attach->crtc_id);
4133                        /* In commit tail framework this cannot happen */
4134                        WARN_ON(1);
4135                }
4136                spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4137
4138                if (!pflip_needed || plane->type == DRM_PLANE_TYPE_OVERLAY) {
4139                        WARN_ON(!dm_new_plane_state->dc_state);
4140
4141                        plane_states_constructed[planes_count] = dm_new_plane_state->dc_state;
4142
4143                        dc_stream_attach = acrtc_state->stream;
4144                        planes_count++;
4145
4146                } else if (new_crtc_state->planes_changed) {
4147                        /* Assume even ONE crtc with immediate flip means
4148                         * entire can't wait for VBLANK
4149                         * TODO Check if it's correct
4150                         */
4151                        *wait_for_vblank =
4152                                        new_pcrtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC ?
4153                                false : true;
4154
4155                        /* TODO: Needs rework for multiplane flip */
4156                        if (plane->type == DRM_PLANE_TYPE_PRIMARY)
4157                                drm_crtc_vblank_get(crtc);
4158
4159                        amdgpu_dm_do_flip(
4160                                crtc,
4161                                fb,
4162                                (uint32_t)drm_crtc_vblank_count(crtc) + *wait_for_vblank,
4163                                dm_state->context);
4164                }
4165
4166        }
4167
4168        if (planes_count) {
4169                unsigned long flags;
4170
4171                if (new_pcrtc_state->event) {
4172
4173                        drm_crtc_vblank_get(pcrtc);
4174
4175                        spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4176                        prepare_flip_isr(acrtc_attach);
4177                        spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4178                }
4179
4180
4181                if (false == commit_planes_to_stream(dm->dc,
4182                                                        plane_states_constructed,
4183                                                        planes_count,
4184                                                        acrtc_state,
4185                                                        dm_old_crtc_state,
4186                                                        dm_state->context))
4187                        dm_error("%s: Failed to attach plane!\n", __func__);
4188        } else {
4189                /*TODO BUG Here should go disable planes on CRTC. */
4190        }
4191}
4192
4193/**
4194 * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4195 * @crtc_state: the DRM CRTC state
4196 * @stream_state: the DC stream state.
4197 *
4198 * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4199 * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4200 */
4201static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4202                                                struct dc_stream_state *stream_state)
4203{
4204        stream_state->mode_changed = crtc_state->mode_changed;
4205}
4206
4207static int amdgpu_dm_atomic_commit(struct drm_device *dev,
4208                                   struct drm_atomic_state *state,
4209                                   bool nonblock)
4210{
4211        struct drm_crtc *crtc;
4212        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4213        struct amdgpu_device *adev = dev->dev_private;
4214        int i;
4215
4216        /*
4217         * We evade vblanks and pflips on crtc that
4218         * should be changed. We do it here to flush & disable
4219         * interrupts before drm_swap_state is called in drm_atomic_helper_commit
4220         * it will update crtc->dm_crtc_state->stream pointer which is used in
4221         * the ISRs.
4222         */
4223        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4224                struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4225                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4226
4227                if (drm_atomic_crtc_needs_modeset(new_crtc_state) && dm_old_crtc_state->stream)
4228                        manage_dm_interrupts(adev, acrtc, false);
4229        }
4230        /* Add check here for SoC's that support hardware cursor plane, to
4231         * unset legacy_cursor_update */
4232
4233        return drm_atomic_helper_commit(dev, state, nonblock);
4234
4235        /*TODO Handle EINTR, reenable IRQ*/
4236}
4237
4238static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
4239{
4240        struct drm_device *dev = state->dev;
4241        struct amdgpu_device *adev = dev->dev_private;
4242        struct amdgpu_display_manager *dm = &adev->dm;
4243        struct dm_atomic_state *dm_state;
4244        uint32_t i, j;
4245        struct drm_crtc *crtc;
4246        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4247        unsigned long flags;
4248        bool wait_for_vblank = true;
4249        struct drm_connector *connector;
4250        struct drm_connector_state *old_con_state, *new_con_state;
4251        struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4252        int crtc_disable_count = 0;
4253
4254        drm_atomic_helper_update_legacy_modeset_state(dev, state);
4255
4256        dm_state = to_dm_atomic_state(state);
4257
4258        /* update changed items */
4259        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4260                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4261
4262                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4263                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4264
4265                DRM_DEBUG_DRIVER(
4266                        "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4267                        "planes_changed:%d, mode_changed:%d,active_changed:%d,"
4268                        "connectors_changed:%d\n",
4269                        acrtc->crtc_id,
4270                        new_crtc_state->enable,
4271                        new_crtc_state->active,
4272                        new_crtc_state->planes_changed,
4273                        new_crtc_state->mode_changed,
4274                        new_crtc_state->active_changed,
4275                        new_crtc_state->connectors_changed);
4276
4277                /* Copy all transient state flags into dc state */
4278                if (dm_new_crtc_state->stream) {
4279                        amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4280                                                            dm_new_crtc_state->stream);
4281                }
4282
4283                /* handles headless hotplug case, updating new_state and
4284                 * aconnector as needed
4285                 */
4286
4287                if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4288
4289                        DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
4290
4291                        if (!dm_new_crtc_state->stream) {
4292                                /*
4293                                 * this could happen because of issues with
4294                                 * userspace notifications delivery.
4295                                 * In this case userspace tries to set mode on
4296                                 * display which is disconnect in fact.
4297                                 * dc_sink in NULL in this case on aconnector.
4298                                 * We expect reset mode will come soon.
4299                                 *
4300                                 * This can also happen when unplug is done
4301                                 * during resume sequence ended
4302                                 *
4303                                 * In this case, we want to pretend we still
4304                                 * have a sink to keep the pipe running so that
4305                                 * hw state is consistent with the sw state
4306                                 */
4307                                DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4308                                                __func__, acrtc->base.base.id);
4309                                continue;
4310                        }
4311
4312                        if (dm_old_crtc_state->stream)
4313                                remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4314
4315                        pm_runtime_get_noresume(dev->dev);
4316
4317                        acrtc->enabled = true;
4318                        acrtc->hw_mode = new_crtc_state->mode;
4319                        crtc->hwmode = new_crtc_state->mode;
4320                } else if (modereset_required(new_crtc_state)) {
4321                        DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
4322
4323                        /* i.e. reset mode */
4324                        if (dm_old_crtc_state->stream)
4325                                remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4326                }
4327        } /* for_each_crtc_in_state() */
4328
4329        /*
4330         * Add streams after required streams from new and replaced streams
4331         * are removed from freesync module
4332         */
4333        if (adev->dm.freesync_module) {
4334                for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4335                                              new_crtc_state, i) {
4336                        struct amdgpu_dm_connector *aconnector = NULL;
4337                        struct dm_connector_state *dm_new_con_state = NULL;
4338                        struct amdgpu_crtc *acrtc = NULL;
4339                        bool modeset_needed;
4340
4341                        dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4342                        dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4343                        modeset_needed = modeset_required(
4344                                        new_crtc_state,
4345                                        dm_new_crtc_state->stream,
4346                                        dm_old_crtc_state->stream);
4347                        /* We add stream to freesync if:
4348                         * 1. Said stream is not null, and
4349                         * 2. A modeset is requested. This means that the
4350                         *    stream was removed previously, and needs to be
4351                         *    replaced.
4352                         */
4353                        if (dm_new_crtc_state->stream == NULL ||
4354                                        !modeset_needed)
4355                                continue;
4356
4357                        acrtc = to_amdgpu_crtc(crtc);
4358
4359                        aconnector =
4360                                amdgpu_dm_find_first_crtc_matching_connector(
4361                                        state, crtc);
4362                        if (!aconnector) {
4363                                DRM_DEBUG_DRIVER("Atomic commit: Failed to "
4364                                                 "find connector for acrtc "
4365                                                 "id:%d skipping freesync "
4366                                                 "init\n",
4367                                                 acrtc->crtc_id);
4368                                continue;
4369                        }
4370
4371                        mod_freesync_add_stream(adev->dm.freesync_module,
4372                                                dm_new_crtc_state->stream,
4373                                                &aconnector->caps);
4374                        new_con_state = drm_atomic_get_new_connector_state(
4375                                        state, &aconnector->base);
4376                        dm_new_con_state = to_dm_connector_state(new_con_state);
4377
4378                        mod_freesync_set_user_enable(adev->dm.freesync_module,
4379                                                     &dm_new_crtc_state->stream,
4380                                                     1,
4381                                                     &dm_new_con_state->user_enable);
4382                }
4383        }
4384
4385        if (dm_state->context) {
4386                dm_enable_per_frame_crtc_master_sync(dm_state->context);
4387                WARN_ON(!dc_commit_state(dm->dc, dm_state->context));
4388        }
4389
4390        for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4391                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4392
4393                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4394
4395                if (dm_new_crtc_state->stream != NULL) {
4396                        const struct dc_stream_status *status =
4397                                        dc_stream_get_status(dm_new_crtc_state->stream);
4398
4399                        if (!status)
4400                                DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
4401                        else
4402                                acrtc->otg_inst = status->primary_otg_inst;
4403                }
4404        }
4405
4406        /* Handle scaling and underscan changes*/
4407        for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4408                struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4409                struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
4410                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4411                struct dc_stream_status *status = NULL;
4412
4413                if (acrtc) {
4414                        new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
4415                        old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4416                }
4417
4418                /* Skip any modesets/resets */
4419                if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
4420                        continue;
4421
4422                /* Skip any thing not scale or underscan changes */
4423                if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
4424                        continue;
4425
4426                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4427
4428                update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
4429                                dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
4430
4431                if (!dm_new_crtc_state->stream)
4432                        continue;
4433
4434                status = dc_stream_get_status(dm_new_crtc_state->stream);
4435                WARN_ON(!status);
4436                WARN_ON(!status->plane_count);
4437
4438                /*TODO How it works with MPO ?*/
4439                if (!commit_planes_to_stream(
4440                                dm->dc,
4441                                status->plane_states,
4442                                status->plane_count,
4443                                dm_new_crtc_state,
4444                                to_dm_crtc_state(old_crtc_state),
4445                                dm_state->context))
4446                        dm_error("%s: Failed to update stream scaling!\n", __func__);
4447        }
4448
4449        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4450                        new_crtc_state, i) {
4451                /*
4452                 * loop to enable interrupts on newly arrived crtc
4453                 */
4454                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4455                bool modeset_needed;
4456
4457                if (old_crtc_state->active && !new_crtc_state->active)
4458                        crtc_disable_count++;
4459
4460                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4461                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4462                modeset_needed = modeset_required(
4463                                new_crtc_state,
4464                                dm_new_crtc_state->stream,
4465                                dm_old_crtc_state->stream);
4466
4467                if (dm_new_crtc_state->stream == NULL || !modeset_needed)
4468                        continue;
4469
4470                if (adev->dm.freesync_module)
4471                        mod_freesync_notify_mode_change(
4472                                adev->dm.freesync_module,
4473                                &dm_new_crtc_state->stream, 1);
4474
4475                manage_dm_interrupts(adev, acrtc, true);
4476        }
4477
4478        /* update planes when needed per crtc*/
4479        for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
4480                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4481
4482                if (dm_new_crtc_state->stream)
4483                        amdgpu_dm_commit_planes(state, dev, dm, crtc, &wait_for_vblank);
4484        }
4485
4486
4487        /*
4488         * send vblank event on all events not handled in flip and
4489         * mark consumed event for drm_atomic_helper_commit_hw_done
4490         */
4491        spin_lock_irqsave(&adev->ddev->event_lock, flags);
4492        for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4493
4494                if (new_crtc_state->event)
4495                        drm_send_event_locked(dev, &new_crtc_state->event->base);
4496
4497                new_crtc_state->event = NULL;
4498        }
4499        spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
4500
4501        /* Signal HW programming completion */
4502        drm_atomic_helper_commit_hw_done(state);
4503
4504        if (wait_for_vblank)
4505                drm_atomic_helper_wait_for_flip_done(dev, state);
4506
4507        drm_atomic_helper_cleanup_planes(dev, state);
4508
4509        /* Finally, drop a runtime PM reference for each newly disabled CRTC,
4510         * so we can put the GPU into runtime suspend if we're not driving any
4511         * displays anymore
4512         */
4513        for (i = 0; i < crtc_disable_count; i++)
4514                pm_runtime_put_autosuspend(dev->dev);
4515        pm_runtime_mark_last_busy(dev->dev);
4516}
4517
4518
4519static int dm_force_atomic_commit(struct drm_connector *connector)
4520{
4521        int ret = 0;
4522        struct drm_device *ddev = connector->dev;
4523        struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
4524        struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4525        struct drm_plane *plane = disconnected_acrtc->base.primary;
4526        struct drm_connector_state *conn_state;
4527        struct drm_crtc_state *crtc_state;
4528        struct drm_plane_state *plane_state;
4529
4530        if (!state)
4531                return -ENOMEM;
4532
4533        state->acquire_ctx = ddev->mode_config.acquire_ctx;
4534
4535        /* Construct an atomic state to restore previous display setting */
4536
4537        /*
4538         * Attach connectors to drm_atomic_state
4539         */
4540        conn_state = drm_atomic_get_connector_state(state, connector);
4541
4542        ret = PTR_ERR_OR_ZERO(conn_state);
4543        if (ret)
4544                goto err;
4545
4546        /* Attach crtc to drm_atomic_state*/
4547        crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
4548
4549        ret = PTR_ERR_OR_ZERO(crtc_state);
4550        if (ret)
4551                goto err;
4552
4553        /* force a restore */
4554        crtc_state->mode_changed = true;
4555
4556        /* Attach plane to drm_atomic_state */
4557        plane_state = drm_atomic_get_plane_state(state, plane);
4558
4559        ret = PTR_ERR_OR_ZERO(plane_state);
4560        if (ret)
4561                goto err;
4562
4563
4564        /* Call commit internally with the state we just constructed */
4565        ret = drm_atomic_commit(state);
4566        if (!ret)
4567                return 0;
4568
4569err:
4570        DRM_ERROR("Restoring old state failed with %i\n", ret);
4571        drm_atomic_state_put(state);
4572
4573        return ret;
4574}
4575
4576/*
4577 * This functions handle all cases when set mode does not come upon hotplug.
4578 * This include when the same display is unplugged then plugged back into the
4579 * same port and when we are running without usermode desktop manager supprot
4580 */
4581void dm_restore_drm_connector_state(struct drm_device *dev,
4582                                    struct drm_connector *connector)
4583{
4584        struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4585        struct amdgpu_crtc *disconnected_acrtc;
4586        struct dm_crtc_state *acrtc_state;
4587
4588        if (!aconnector->dc_sink || !connector->state || !connector->encoder)
4589                return;
4590
4591        disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4592        if (!disconnected_acrtc)
4593                return;
4594
4595        acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
4596        if (!acrtc_state->stream)
4597                return;
4598
4599        /*
4600         * If the previous sink is not released and different from the current,
4601         * we deduce we are in a state where we can not rely on usermode call
4602         * to turn on the display, so we do it here
4603         */
4604        if (acrtc_state->stream->sink != aconnector->dc_sink)
4605                dm_force_atomic_commit(&aconnector->base);
4606}
4607
4608/*`
4609 * Grabs all modesetting locks to serialize against any blocking commits,
4610 * Waits for completion of all non blocking commits.
4611 */
4612static int do_aquire_global_lock(struct drm_device *dev,
4613                                 struct drm_atomic_state *state)
4614{
4615        struct drm_crtc *crtc;
4616        struct drm_crtc_commit *commit;
4617        long ret;
4618
4619        /* Adding all modeset locks to aquire_ctx will
4620         * ensure that when the framework release it the
4621         * extra locks we are locking here will get released to
4622         */
4623        ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
4624        if (ret)
4625                return ret;
4626
4627        list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
4628                spin_lock(&crtc->commit_lock);
4629                commit = list_first_entry_or_null(&crtc->commit_list,
4630                                struct drm_crtc_commit, commit_entry);
4631                if (commit)
4632                        drm_crtc_commit_get(commit);
4633                spin_unlock(&crtc->commit_lock);
4634
4635                if (!commit)
4636                        continue;
4637
4638                /* Make sure all pending HW programming completed and
4639                 * page flips done
4640                 */
4641                ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
4642
4643                if (ret > 0)
4644                        ret = wait_for_completion_interruptible_timeout(
4645                                        &commit->flip_done, 10*HZ);
4646
4647                if (ret == 0)
4648                        DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
4649                                  "timed out\n", crtc->base.id, crtc->name);
4650
4651                drm_crtc_commit_put(commit);
4652        }
4653
4654        return ret < 0 ? ret : 0;
4655}
4656
4657static int dm_update_crtcs_state(struct dc *dc,
4658                                 struct drm_atomic_state *state,
4659                                 bool enable,
4660                                 bool *lock_and_validation_needed)
4661{
4662        struct drm_crtc *crtc;
4663        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4664        int i;
4665        struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4666        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4667        struct dc_stream_state *new_stream;
4668        int ret = 0;
4669
4670        /*TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set */
4671        /* update changed items */
4672        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4673                struct amdgpu_crtc *acrtc = NULL;
4674                struct amdgpu_dm_connector *aconnector = NULL;
4675                struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
4676                struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
4677                struct drm_plane_state *new_plane_state = NULL;
4678
4679                new_stream = NULL;
4680
4681                dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4682                dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4683                acrtc = to_amdgpu_crtc(crtc);
4684
4685                new_plane_state = drm_atomic_get_new_plane_state(state, new_crtc_state->crtc->primary);
4686
4687                if (new_crtc_state->enable && new_plane_state && !new_plane_state->fb) {
4688                        ret = -EINVAL;
4689                        goto fail;
4690                }
4691
4692                aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
4693
4694                /* TODO This hack should go away */
4695                if (aconnector && enable) {
4696                        // Make sure fake sink is created in plug-in scenario
4697                        drm_new_conn_state = drm_atomic_get_new_connector_state(state,
4698                                                                    &aconnector->base);
4699                        drm_old_conn_state = drm_atomic_get_old_connector_state(state,
4700                                                                    &aconnector->base);
4701
4702                        if (IS_ERR(drm_new_conn_state)) {
4703                                ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
4704                                break;
4705                        }
4706
4707                        dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
4708                        dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
4709
4710                        new_stream = create_stream_for_sink(aconnector,
4711                                                             &new_crtc_state->mode,
4712                                                            dm_new_conn_state);
4713
4714                        /*
4715                         * we can have no stream on ACTION_SET if a display
4716                         * was disconnected during S3, in this case it not and
4717                         * error, the OS will be updated after detection, and
4718                         * do the right thing on next atomic commit
4719                         */
4720
4721                        if (!new_stream) {
4722                                DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4723                                                __func__, acrtc->base.base.id);
4724                                break;
4725                        }
4726
4727                        if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
4728                            dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
4729                                new_crtc_state->mode_changed = false;
4730                                DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
4731                                                 new_crtc_state->mode_changed);
4732                        }
4733                }
4734
4735                if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4736                        goto next_crtc;
4737
4738                DRM_DEBUG_DRIVER(
4739                        "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4740                        "planes_changed:%d, mode_changed:%d,active_changed:%d,"
4741                        "connectors_changed:%d\n",
4742                        acrtc->crtc_id,
4743                        new_crtc_state->enable,
4744                        new_crtc_state->active,
4745                        new_crtc_state->planes_changed,
4746                        new_crtc_state->mode_changed,
4747                        new_crtc_state->active_changed,
4748                        new_crtc_state->connectors_changed);
4749
4750                /* Remove stream for any changed/disabled CRTC */
4751                if (!enable) {
4752
4753                        if (!dm_old_crtc_state->stream)
4754                                goto next_crtc;
4755
4756                        DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
4757                                        crtc->base.id);
4758
4759                        /* i.e. reset mode */
4760                        if (dc_remove_stream_from_ctx(
4761                                        dc,
4762                                        dm_state->context,
4763                                        dm_old_crtc_state->stream) != DC_OK) {
4764                                ret = -EINVAL;
4765                                goto fail;
4766                        }
4767
4768                        dc_stream_release(dm_old_crtc_state->stream);
4769                        dm_new_crtc_state->stream = NULL;
4770
4771                        *lock_and_validation_needed = true;
4772
4773                } else {/* Add stream for any updated/enabled CRTC */
4774                        /*
4775                         * Quick fix to prevent NULL pointer on new_stream when
4776                         * added MST connectors not found in existing crtc_state in the chained mode
4777                         * TODO: need to dig out the root cause of that
4778                         */
4779                        if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
4780                                goto next_crtc;
4781
4782                        if (modereset_required(new_crtc_state))
4783                                goto next_crtc;
4784
4785                        if (modeset_required(new_crtc_state, new_stream,
4786                                             dm_old_crtc_state->stream)) {
4787
4788                                WARN_ON(dm_new_crtc_state->stream);
4789
4790                                dm_new_crtc_state->stream = new_stream;
4791
4792                                dc_stream_retain(new_stream);
4793
4794                                DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
4795                                                        crtc->base.id);
4796
4797                                if (dc_add_stream_to_ctx(
4798                                                dc,
4799                                                dm_state->context,
4800                                                dm_new_crtc_state->stream) != DC_OK) {
4801                                        ret = -EINVAL;
4802                                        goto fail;
4803                                }
4804
4805                                *lock_and_validation_needed = true;
4806                        }
4807                }
4808
4809next_crtc:
4810                /* Release extra reference */
4811                if (new_stream)
4812                         dc_stream_release(new_stream);
4813
4814                /*
4815                 * We want to do dc stream updates that do not require a
4816                 * full modeset below.
4817                 */
4818                if (!(enable && aconnector && new_crtc_state->enable &&
4819                      new_crtc_state->active))
4820                        continue;
4821                /*
4822                 * Given above conditions, the dc state cannot be NULL because:
4823                 * 1. We're in the process of enabling CRTCs (just been added
4824                 *    to the dc context, or already is on the context)
4825                 * 2. Has a valid connector attached, and
4826                 * 3. Is currently active and enabled.
4827                 * => The dc stream state currently exists.
4828                 */
4829                BUG_ON(dm_new_crtc_state->stream == NULL);
4830
4831                /* Scaling or underscan settings */
4832                if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
4833                        update_stream_scaling_settings(
4834                                &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
4835
4836                /*
4837                 * Color management settings. We also update color properties
4838                 * when a modeset is needed, to ensure it gets reprogrammed.
4839                 */
4840                if (dm_new_crtc_state->base.color_mgmt_changed ||
4841                    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
4842                        ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
4843                        if (ret)
4844                                goto fail;
4845                        amdgpu_dm_set_ctm(dm_new_crtc_state);
4846                }
4847        }
4848
4849        return ret;
4850
4851fail:
4852        if (new_stream)
4853                dc_stream_release(new_stream);
4854        return ret;
4855}
4856
4857static int dm_update_planes_state(struct dc *dc,
4858                                  struct drm_atomic_state *state,
4859                                  bool enable,
4860                                  bool *lock_and_validation_needed)
4861{
4862        struct drm_crtc *new_plane_crtc, *old_plane_crtc;
4863        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4864        struct drm_plane *plane;
4865        struct drm_plane_state *old_plane_state, *new_plane_state;
4866        struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
4867        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4868        struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
4869        int i ;
4870        /* TODO return page_flip_needed() function */
4871        bool pflip_needed  = !state->allow_modeset;
4872        int ret = 0;
4873
4874
4875        /* Add new planes, in reverse order as DC expectation */
4876        for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
4877                new_plane_crtc = new_plane_state->crtc;
4878                old_plane_crtc = old_plane_state->crtc;
4879                dm_new_plane_state = to_dm_plane_state(new_plane_state);
4880                dm_old_plane_state = to_dm_plane_state(old_plane_state);
4881
4882                /*TODO Implement atomic check for cursor plane */
4883                if (plane->type == DRM_PLANE_TYPE_CURSOR)
4884                        continue;
4885
4886                /* Remove any changed/removed planes */
4887                if (!enable) {
4888                        if (pflip_needed &&
4889                            plane->type != DRM_PLANE_TYPE_OVERLAY)
4890                                continue;
4891
4892                        if (!old_plane_crtc)
4893                                continue;
4894
4895                        old_crtc_state = drm_atomic_get_old_crtc_state(
4896                                        state, old_plane_crtc);
4897                        dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4898
4899                        if (!dm_old_crtc_state->stream)
4900                                continue;
4901
4902                        DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
4903                                        plane->base.id, old_plane_crtc->base.id);
4904
4905                        if (!dc_remove_plane_from_context(
4906                                        dc,
4907                                        dm_old_crtc_state->stream,
4908                                        dm_old_plane_state->dc_state,
4909                                        dm_state->context)) {
4910
4911                                ret = EINVAL;
4912                                return ret;
4913                        }
4914
4915
4916                        dc_plane_state_release(dm_old_plane_state->dc_state);
4917                        dm_new_plane_state->dc_state = NULL;
4918
4919                        *lock_and_validation_needed = true;
4920
4921                } else { /* Add new planes */
4922                        struct dc_plane_state *dc_new_plane_state;
4923
4924                        if (drm_atomic_plane_disabling(plane->state, new_plane_state))
4925                                continue;
4926
4927                        if (!new_plane_crtc)
4928                                continue;
4929
4930                        new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
4931                        dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4932
4933                        if (!dm_new_crtc_state->stream)
4934                                continue;
4935
4936                        if (pflip_needed &&
4937                            plane->type != DRM_PLANE_TYPE_OVERLAY)
4938                                continue;
4939
4940                        WARN_ON(dm_new_plane_state->dc_state);
4941
4942                        dc_new_plane_state = dc_create_plane_state(dc);
4943                        if (!dc_new_plane_state)
4944                                return -ENOMEM;
4945
4946                        DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
4947                                        plane->base.id, new_plane_crtc->base.id);
4948
4949                        ret = fill_plane_attributes(
4950                                new_plane_crtc->dev->dev_private,
4951                                dc_new_plane_state,
4952                                new_plane_state,
4953                                new_crtc_state);
4954                        if (ret) {
4955                                dc_plane_state_release(dc_new_plane_state);
4956                                return ret;
4957                        }
4958
4959                        /*
4960                         * Any atomic check errors that occur after this will
4961                         * not need a release. The plane state will be attached
4962                         * to the stream, and therefore part of the atomic
4963                         * state. It'll be released when the atomic state is
4964                         * cleaned.
4965                         */
4966                        if (!dc_add_plane_to_context(
4967                                        dc,
4968                                        dm_new_crtc_state->stream,
4969                                        dc_new_plane_state,
4970                                        dm_state->context)) {
4971
4972                                dc_plane_state_release(dc_new_plane_state);
4973                                return -EINVAL;
4974                        }
4975
4976                        dm_new_plane_state->dc_state = dc_new_plane_state;
4977
4978                        /* Tell DC to do a full surface update every time there
4979                         * is a plane change. Inefficient, but works for now.
4980                         */
4981                        dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
4982
4983                        *lock_and_validation_needed = true;
4984                }
4985        }
4986
4987
4988        return ret;
4989}
4990
4991static int amdgpu_dm_atomic_check(struct drm_device *dev,
4992                                  struct drm_atomic_state *state)
4993{
4994        struct amdgpu_device *adev = dev->dev_private;
4995        struct dc *dc = adev->dm.dc;
4996        struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4997        struct drm_connector *connector;
4998        struct drm_connector_state *old_con_state, *new_con_state;
4999        struct drm_crtc *crtc;
5000        struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5001        int ret, i;
5002
5003        /*
5004         * This bool will be set for true for any modeset/reset
5005         * or plane update which implies non fast surface update.
5006         */
5007        bool lock_and_validation_needed = false;
5008
5009        ret = drm_atomic_helper_check_modeset(dev, state);
5010        if (ret)
5011                goto fail;
5012
5013        for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5014                if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
5015                    !new_crtc_state->color_mgmt_changed)
5016                        continue;
5017
5018                if (!new_crtc_state->enable)
5019                        continue;
5020
5021                ret = drm_atomic_add_affected_connectors(state, crtc);
5022                if (ret)
5023                        return ret;
5024
5025                ret = drm_atomic_add_affected_planes(state, crtc);
5026                if (ret)
5027                        goto fail;
5028        }
5029
5030        dm_state->context = dc_create_state();
5031        ASSERT(dm_state->context);
5032        dc_resource_state_copy_construct_current(dc, dm_state->context);
5033
5034        /* Remove exiting planes if they are modified */
5035        ret = dm_update_planes_state(dc, state, false, &lock_and_validation_needed);
5036        if (ret) {
5037                goto fail;
5038        }
5039
5040        /* Disable all crtcs which require disable */
5041        ret = dm_update_crtcs_state(dc, state, false, &lock_and_validation_needed);
5042        if (ret) {
5043                goto fail;
5044        }
5045
5046        /* Enable all crtcs which require enable */
5047        ret = dm_update_crtcs_state(dc, state, true, &lock_and_validation_needed);
5048        if (ret) {
5049                goto fail;
5050        }
5051
5052        /* Add new/modified planes */
5053        ret = dm_update_planes_state(dc, state, true, &lock_and_validation_needed);
5054        if (ret) {
5055                goto fail;
5056        }
5057
5058        /* Run this here since we want to validate the streams we created */
5059        ret = drm_atomic_helper_check_planes(dev, state);
5060        if (ret)
5061                goto fail;
5062
5063        /* Check scaling and underscan changes*/
5064        /*TODO Removed scaling changes validation due to inability to commit
5065         * new stream into context w\o causing full reset. Need to
5066         * decide how to handle.
5067         */
5068        for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5069                struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5070                struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5071                struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5072
5073                /* Skip any modesets/resets */
5074                if (!acrtc || drm_atomic_crtc_needs_modeset(
5075                                drm_atomic_get_new_crtc_state(state, &acrtc->base)))
5076                        continue;
5077
5078                /* Skip any thing not scale or underscan changes */
5079                if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
5080                        continue;
5081
5082                lock_and_validation_needed = true;
5083        }
5084
5085        /*
5086         * For full updates case when
5087         * removing/adding/updating  streams on once CRTC while flipping
5088         * on another CRTC,
5089         * acquiring global lock  will guarantee that any such full
5090         * update commit
5091         * will wait for completion of any outstanding flip using DRMs
5092         * synchronization events.
5093         */
5094
5095        if (lock_and_validation_needed) {
5096
5097                ret = do_aquire_global_lock(dev, state);
5098                if (ret)
5099                        goto fail;
5100
5101                if (dc_validate_global_state(dc, dm_state->context) != DC_OK) {
5102                        ret = -EINVAL;
5103                        goto fail;
5104                }
5105        }
5106
5107        /* Must be success */
5108        WARN_ON(ret);
5109        return ret;
5110
5111fail:
5112        if (ret == -EDEADLK)
5113                DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
5114        else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
5115                DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
5116        else
5117                DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
5118
5119        return ret;
5120}
5121
5122static bool is_dp_capable_without_timing_msa(struct dc *dc,
5123                                             struct amdgpu_dm_connector *amdgpu_dm_connector)
5124{
5125        uint8_t dpcd_data;
5126        bool capable = false;
5127
5128        if (amdgpu_dm_connector->dc_link &&
5129                dm_helpers_dp_read_dpcd(
5130                                NULL,
5131                                amdgpu_dm_connector->dc_link,
5132                                DP_DOWN_STREAM_PORT_COUNT,
5133                                &dpcd_data,
5134                                sizeof(dpcd_data))) {
5135                capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
5136        }
5137
5138        return capable;
5139}
5140void amdgpu_dm_add_sink_to_freesync_module(struct drm_connector *connector,
5141                                           struct edid *edid)
5142{
5143        int i;
5144        bool edid_check_required;
5145        struct detailed_timing *timing;
5146        struct detailed_non_pixel *data;
5147        struct detailed_data_monitor_range *range;
5148        struct amdgpu_dm_connector *amdgpu_dm_connector =
5149                        to_amdgpu_dm_connector(connector);
5150        struct dm_connector_state *dm_con_state;
5151
5152        struct drm_device *dev = connector->dev;
5153        struct amdgpu_device *adev = dev->dev_private;
5154
5155        if (!connector->state) {
5156                DRM_ERROR("%s - Connector has no state", __func__);
5157                return;
5158        }
5159
5160        dm_con_state = to_dm_connector_state(connector->state);
5161
5162        edid_check_required = false;
5163        if (!amdgpu_dm_connector->dc_sink) {
5164                DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
5165                return;
5166        }
5167        if (!adev->dm.freesync_module)
5168                return;
5169        /*
5170         * if edid non zero restrict freesync only for dp and edp
5171         */
5172        if (edid) {
5173                if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
5174                        || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
5175                        edid_check_required = is_dp_capable_without_timing_msa(
5176                                                adev->dm.dc,
5177                                                amdgpu_dm_connector);
5178                }
5179        }
5180        dm_con_state->freesync_capable = false;
5181        if (edid_check_required == true && (edid->version > 1 ||
5182           (edid->version == 1 && edid->revision > 1))) {
5183                for (i = 0; i < 4; i++) {
5184
5185                        timing  = &edid->detailed_timings[i];
5186                        data    = &timing->data.other_data;
5187                        range   = &data->data.range;
5188                        /*
5189                         * Check if monitor has continuous frequency mode
5190                         */
5191                        if (data->type != EDID_DETAIL_MONITOR_RANGE)
5192                                continue;
5193                        /*
5194                         * Check for flag range limits only. If flag == 1 then
5195                         * no additional timing information provided.
5196                         * Default GTF, GTF Secondary curve and CVT are not
5197                         * supported
5198                         */
5199                        if (range->flags != 1)
5200                                continue;
5201
5202                        amdgpu_dm_connector->min_vfreq = range->min_vfreq;
5203                        amdgpu_dm_connector->max_vfreq = range->max_vfreq;
5204                        amdgpu_dm_connector->pixel_clock_mhz =
5205                                range->pixel_clock_mhz * 10;
5206                        break;
5207                }
5208
5209                if (amdgpu_dm_connector->max_vfreq -
5210                                amdgpu_dm_connector->min_vfreq > 10) {
5211                        amdgpu_dm_connector->caps.supported = true;
5212                        amdgpu_dm_connector->caps.min_refresh_in_micro_hz =
5213                                        amdgpu_dm_connector->min_vfreq * 1000000;
5214                        amdgpu_dm_connector->caps.max_refresh_in_micro_hz =
5215                                        amdgpu_dm_connector->max_vfreq * 1000000;
5216                        dm_con_state->freesync_capable = true;
5217                }
5218        }
5219
5220        /*
5221         * TODO figure out how to notify user-mode or DRM of freesync caps
5222         * once we figure out how to deal with freesync in an upstreamable
5223         * fashion
5224         */
5225
5226}
5227
5228void amdgpu_dm_remove_sink_from_freesync_module(struct drm_connector *connector)
5229{
5230        /*
5231         * TODO fill in once we figure out how to deal with freesync in
5232         * an upstreamable fashion
5233         */
5234}
5235