linux/drivers/gpu/drm/i915/intel_pm.c
<<
>>
Prefs
   1/*
   2 * Copyright © 2012 Intel Corporation
   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 (including the next
  12 * paragraph) shall be included in all copies or substantial portions of the
  13 * Software.
  14 *
  15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21 * IN THE SOFTWARE.
  22 *
  23 * Authors:
  24 *    Eugeni Dodonov <eugeni.dodonov@intel.com>
  25 *
  26 */
  27
  28#include <linux/cpufreq.h>
  29#include <linux/module.h>
  30#include <linux/pm_runtime.h>
  31
  32#include <drm/drm_atomic_helper.h>
  33#include <drm/drm_fourcc.h>
  34#include <drm/drm_plane_helper.h>
  35
  36#include "display/intel_atomic.h"
  37#include "display/intel_display_types.h"
  38#include "display/intel_fbc.h"
  39#include "display/intel_sprite.h"
  40
  41#include "i915_drv.h"
  42#include "i915_irq.h"
  43#include "i915_trace.h"
  44#include "intel_pm.h"
  45#include "intel_sideband.h"
  46#include "../../../platform/x86/intel_ips.h"
  47
  48/**
  49 * DOC: RC6
  50 *
  51 * RC6 is a special power stage which allows the GPU to enter an very
  52 * low-voltage mode when idle, using down to 0V while at this stage.  This
  53 * stage is entered automatically when the GPU is idle when RC6 support is
  54 * enabled, and as soon as new workload arises GPU wakes up automatically as well.
  55 *
  56 * There are different RC6 modes available in Intel GPU, which differentiate
  57 * among each other with the latency required to enter and leave RC6 and
  58 * voltage consumed by the GPU in different states.
  59 *
  60 * The combination of the following flags define which states GPU is allowed
  61 * to enter, while RC6 is the normal RC6 state, RC6p is the deep RC6, and
  62 * RC6pp is deepest RC6. Their support by hardware varies according to the
  63 * GPU, BIOS, chipset and platform. RC6 is usually the safest one and the one
  64 * which brings the most power savings; deeper states save more power, but
  65 * require higher latency to switch to and wake up.
  66 */
  67
  68static void gen9_init_clock_gating(struct drm_i915_private *dev_priv)
  69{
  70        if (HAS_LLC(dev_priv)) {
  71                /*
  72                 * WaCompressedResourceDisplayNewHashMode:skl,kbl
  73                 * Display WA #0390: skl,kbl
  74                 *
  75                 * Must match Sampler, Pixel Back End, and Media. See
  76                 * WaCompressedResourceSamplerPbeMediaNewHashMode.
  77                 */
  78                I915_WRITE(CHICKEN_PAR1_1,
  79                           I915_READ(CHICKEN_PAR1_1) |
  80                           SKL_DE_COMPRESSED_HASH_MODE);
  81        }
  82
  83        /* See Bspec note for PSR2_CTL bit 31, Wa#828:skl,bxt,kbl,cfl */
  84        I915_WRITE(CHICKEN_PAR1_1,
  85                   I915_READ(CHICKEN_PAR1_1) | SKL_EDP_PSR_FIX_RDWRAP);
  86
  87        /* WaEnableChickenDCPR:skl,bxt,kbl,glk,cfl */
  88        I915_WRITE(GEN8_CHICKEN_DCPR_1,
  89                   I915_READ(GEN8_CHICKEN_DCPR_1) | MASK_WAKEMEM);
  90
  91        /* WaFbcTurnOffFbcWatermark:skl,bxt,kbl,cfl */
  92        /* WaFbcWakeMemOn:skl,bxt,kbl,glk,cfl */
  93        I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
  94                   DISP_FBC_WM_DIS |
  95                   DISP_FBC_MEMORY_WAKE);
  96
  97        /* WaFbcHighMemBwCorruptionAvoidance:skl,bxt,kbl,cfl */
  98        I915_WRITE(ILK_DPFC_CHICKEN, I915_READ(ILK_DPFC_CHICKEN) |
  99                   ILK_DPFC_DISABLE_DUMMY0);
 100
 101        if (IS_SKYLAKE(dev_priv)) {
 102                /* WaDisableDopClockGating */
 103                I915_WRITE(GEN7_MISCCPCTL, I915_READ(GEN7_MISCCPCTL)
 104                           & ~GEN7_DOP_CLOCK_GATE_ENABLE);
 105        }
 106}
 107
 108static void bxt_init_clock_gating(struct drm_i915_private *dev_priv)
 109{
 110        gen9_init_clock_gating(dev_priv);
 111
 112        /* WaDisableSDEUnitClockGating:bxt */
 113        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
 114                   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
 115
 116        /*
 117         * FIXME:
 118         * GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ applies on 3x6 GT SKUs only.
 119         */
 120        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
 121                   GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ);
 122
 123        /*
 124         * Wa: Backlight PWM may stop in the asserted state, causing backlight
 125         * to stay fully on.
 126         */
 127        I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
 128                   PWM1_GATING_DIS | PWM2_GATING_DIS);
 129
 130        /*
 131         * Lower the display internal timeout.
 132         * This is needed to avoid any hard hangs when DSI port PLL
 133         * is off and a MMIO access is attempted by any privilege
 134         * application, using batch buffers or any other means.
 135         */
 136        I915_WRITE(RM_TIMEOUT, MMIO_TIMEOUT_US(950));
 137}
 138
 139static void glk_init_clock_gating(struct drm_i915_private *dev_priv)
 140{
 141        gen9_init_clock_gating(dev_priv);
 142
 143        /*
 144         * WaDisablePWMClockGating:glk
 145         * Backlight PWM may stop in the asserted state, causing backlight
 146         * to stay fully on.
 147         */
 148        I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
 149                   PWM1_GATING_DIS | PWM2_GATING_DIS);
 150
 151        /* WaDDIIOTimeout:glk */
 152        if (IS_GLK_REVID(dev_priv, 0, GLK_REVID_A1)) {
 153                u32 val = I915_READ(CHICKEN_MISC_2);
 154                val &= ~(GLK_CL0_PWR_DOWN |
 155                         GLK_CL1_PWR_DOWN |
 156                         GLK_CL2_PWR_DOWN);
 157                I915_WRITE(CHICKEN_MISC_2, val);
 158        }
 159
 160}
 161
 162static void i915_pineview_get_mem_freq(struct drm_i915_private *dev_priv)
 163{
 164        u32 tmp;
 165
 166        tmp = I915_READ(CLKCFG);
 167
 168        switch (tmp & CLKCFG_FSB_MASK) {
 169        case CLKCFG_FSB_533:
 170                dev_priv->fsb_freq = 533; /* 133*4 */
 171                break;
 172        case CLKCFG_FSB_800:
 173                dev_priv->fsb_freq = 800; /* 200*4 */
 174                break;
 175        case CLKCFG_FSB_667:
 176                dev_priv->fsb_freq =  667; /* 167*4 */
 177                break;
 178        case CLKCFG_FSB_400:
 179                dev_priv->fsb_freq = 400; /* 100*4 */
 180                break;
 181        }
 182
 183        switch (tmp & CLKCFG_MEM_MASK) {
 184        case CLKCFG_MEM_533:
 185                dev_priv->mem_freq = 533;
 186                break;
 187        case CLKCFG_MEM_667:
 188                dev_priv->mem_freq = 667;
 189                break;
 190        case CLKCFG_MEM_800:
 191                dev_priv->mem_freq = 800;
 192                break;
 193        }
 194
 195        /* detect pineview DDR3 setting */
 196        tmp = I915_READ(CSHRDDR3CTL);
 197        dev_priv->is_ddr3 = (tmp & CSHRDDR3CTL_DDR3) ? 1 : 0;
 198}
 199
 200static void i915_ironlake_get_mem_freq(struct drm_i915_private *dev_priv)
 201{
 202        u16 ddrpll, csipll;
 203
 204        ddrpll = intel_uncore_read16(&dev_priv->uncore, DDRMPLL1);
 205        csipll = intel_uncore_read16(&dev_priv->uncore, CSIPLL0);
 206
 207        switch (ddrpll & 0xff) {
 208        case 0xc:
 209                dev_priv->mem_freq = 800;
 210                break;
 211        case 0x10:
 212                dev_priv->mem_freq = 1066;
 213                break;
 214        case 0x14:
 215                dev_priv->mem_freq = 1333;
 216                break;
 217        case 0x18:
 218                dev_priv->mem_freq = 1600;
 219                break;
 220        default:
 221                DRM_DEBUG_DRIVER("unknown memory frequency 0x%02x\n",
 222                                 ddrpll & 0xff);
 223                dev_priv->mem_freq = 0;
 224                break;
 225        }
 226
 227        dev_priv->ips.r_t = dev_priv->mem_freq;
 228
 229        switch (csipll & 0x3ff) {
 230        case 0x00c:
 231                dev_priv->fsb_freq = 3200;
 232                break;
 233        case 0x00e:
 234                dev_priv->fsb_freq = 3733;
 235                break;
 236        case 0x010:
 237                dev_priv->fsb_freq = 4266;
 238                break;
 239        case 0x012:
 240                dev_priv->fsb_freq = 4800;
 241                break;
 242        case 0x014:
 243                dev_priv->fsb_freq = 5333;
 244                break;
 245        case 0x016:
 246                dev_priv->fsb_freq = 5866;
 247                break;
 248        case 0x018:
 249                dev_priv->fsb_freq = 6400;
 250                break;
 251        default:
 252                DRM_DEBUG_DRIVER("unknown fsb frequency 0x%04x\n",
 253                                 csipll & 0x3ff);
 254                dev_priv->fsb_freq = 0;
 255                break;
 256        }
 257
 258        if (dev_priv->fsb_freq == 3200) {
 259                dev_priv->ips.c_m = 0;
 260        } else if (dev_priv->fsb_freq > 3200 && dev_priv->fsb_freq <= 4800) {
 261                dev_priv->ips.c_m = 1;
 262        } else {
 263                dev_priv->ips.c_m = 2;
 264        }
 265}
 266
 267static const struct cxsr_latency cxsr_latency_table[] = {
 268        {1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
 269        {1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
 270        {1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
 271        {1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
 272        {1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
 273
 274        {1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
 275        {1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
 276        {1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
 277        {1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
 278        {1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
 279
 280        {1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
 281        {1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
 282        {1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
 283        {1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
 284        {1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
 285
 286        {0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
 287        {0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
 288        {0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
 289        {0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
 290        {0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
 291
 292        {0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
 293        {0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
 294        {0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
 295        {0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
 296        {0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
 297
 298        {0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
 299        {0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
 300        {0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
 301        {0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
 302        {0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
 303};
 304
 305static const struct cxsr_latency *intel_get_cxsr_latency(bool is_desktop,
 306                                                         bool is_ddr3,
 307                                                         int fsb,
 308                                                         int mem)
 309{
 310        const struct cxsr_latency *latency;
 311        int i;
 312
 313        if (fsb == 0 || mem == 0)
 314                return NULL;
 315
 316        for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
 317                latency = &cxsr_latency_table[i];
 318                if (is_desktop == latency->is_desktop &&
 319                    is_ddr3 == latency->is_ddr3 &&
 320                    fsb == latency->fsb_freq && mem == latency->mem_freq)
 321                        return latency;
 322        }
 323
 324        DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
 325
 326        return NULL;
 327}
 328
 329static void chv_set_memory_dvfs(struct drm_i915_private *dev_priv, bool enable)
 330{
 331        u32 val;
 332
 333        vlv_punit_get(dev_priv);
 334
 335        val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
 336        if (enable)
 337                val &= ~FORCE_DDR_HIGH_FREQ;
 338        else
 339                val |= FORCE_DDR_HIGH_FREQ;
 340        val &= ~FORCE_DDR_LOW_FREQ;
 341        val |= FORCE_DDR_FREQ_REQ_ACK;
 342        vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
 343
 344        if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
 345                      FORCE_DDR_FREQ_REQ_ACK) == 0, 3))
 346                DRM_ERROR("timed out waiting for Punit DDR DVFS request\n");
 347
 348        vlv_punit_put(dev_priv);
 349}
 350
 351static void chv_set_memory_pm5(struct drm_i915_private *dev_priv, bool enable)
 352{
 353        u32 val;
 354
 355        vlv_punit_get(dev_priv);
 356
 357        val = vlv_punit_read(dev_priv, PUNIT_REG_DSPSSPM);
 358        if (enable)
 359                val |= DSP_MAXFIFO_PM5_ENABLE;
 360        else
 361                val &= ~DSP_MAXFIFO_PM5_ENABLE;
 362        vlv_punit_write(dev_priv, PUNIT_REG_DSPSSPM, val);
 363
 364        vlv_punit_put(dev_priv);
 365}
 366
 367#define FW_WM(value, plane) \
 368        (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK)
 369
 370static bool _intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
 371{
 372        bool was_enabled;
 373        u32 val;
 374
 375        if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
 376                was_enabled = I915_READ(FW_BLC_SELF_VLV) & FW_CSPWRDWNEN;
 377                I915_WRITE(FW_BLC_SELF_VLV, enable ? FW_CSPWRDWNEN : 0);
 378                POSTING_READ(FW_BLC_SELF_VLV);
 379        } else if (IS_G4X(dev_priv) || IS_I965GM(dev_priv)) {
 380                was_enabled = I915_READ(FW_BLC_SELF) & FW_BLC_SELF_EN;
 381                I915_WRITE(FW_BLC_SELF, enable ? FW_BLC_SELF_EN : 0);
 382                POSTING_READ(FW_BLC_SELF);
 383        } else if (IS_PINEVIEW(dev_priv)) {
 384                val = I915_READ(DSPFW3);
 385                was_enabled = val & PINEVIEW_SELF_REFRESH_EN;
 386                if (enable)
 387                        val |= PINEVIEW_SELF_REFRESH_EN;
 388                else
 389                        val &= ~PINEVIEW_SELF_REFRESH_EN;
 390                I915_WRITE(DSPFW3, val);
 391                POSTING_READ(DSPFW3);
 392        } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv)) {
 393                was_enabled = I915_READ(FW_BLC_SELF) & FW_BLC_SELF_EN;
 394                val = enable ? _MASKED_BIT_ENABLE(FW_BLC_SELF_EN) :
 395                               _MASKED_BIT_DISABLE(FW_BLC_SELF_EN);
 396                I915_WRITE(FW_BLC_SELF, val);
 397                POSTING_READ(FW_BLC_SELF);
 398        } else if (IS_I915GM(dev_priv)) {
 399                /*
 400                 * FIXME can't find a bit like this for 915G, and
 401                 * and yet it does have the related watermark in
 402                 * FW_BLC_SELF. What's going on?
 403                 */
 404                was_enabled = I915_READ(INSTPM) & INSTPM_SELF_EN;
 405                val = enable ? _MASKED_BIT_ENABLE(INSTPM_SELF_EN) :
 406                               _MASKED_BIT_DISABLE(INSTPM_SELF_EN);
 407                I915_WRITE(INSTPM, val);
 408                POSTING_READ(INSTPM);
 409        } else {
 410                return false;
 411        }
 412
 413        trace_intel_memory_cxsr(dev_priv, was_enabled, enable);
 414
 415        DRM_DEBUG_KMS("memory self-refresh is %s (was %s)\n",
 416                      enableddisabled(enable),
 417                      enableddisabled(was_enabled));
 418
 419        return was_enabled;
 420}
 421
 422/**
 423 * intel_set_memory_cxsr - Configure CxSR state
 424 * @dev_priv: i915 device
 425 * @enable: Allow vs. disallow CxSR
 426 *
 427 * Allow or disallow the system to enter a special CxSR
 428 * (C-state self refresh) state. What typically happens in CxSR mode
 429 * is that several display FIFOs may get combined into a single larger
 430 * FIFO for a particular plane (so called max FIFO mode) to allow the
 431 * system to defer memory fetches longer, and the memory will enter
 432 * self refresh.
 433 *
 434 * Note that enabling CxSR does not guarantee that the system enter
 435 * this special mode, nor does it guarantee that the system stays
 436 * in that mode once entered. So this just allows/disallows the system
 437 * to autonomously utilize the CxSR mode. Other factors such as core
 438 * C-states will affect when/if the system actually enters/exits the
 439 * CxSR mode.
 440 *
 441 * Note that on VLV/CHV this actually only controls the max FIFO mode,
 442 * and the system is free to enter/exit memory self refresh at any time
 443 * even when the use of CxSR has been disallowed.
 444 *
 445 * While the system is actually in the CxSR/max FIFO mode, some plane
 446 * control registers will not get latched on vblank. Thus in order to
 447 * guarantee the system will respond to changes in the plane registers
 448 * we must always disallow CxSR prior to making changes to those registers.
 449 * Unfortunately the system will re-evaluate the CxSR conditions at
 450 * frame start which happens after vblank start (which is when the plane
 451 * registers would get latched), so we can't proceed with the plane update
 452 * during the same frame where we disallowed CxSR.
 453 *
 454 * Certain platforms also have a deeper HPLL SR mode. Fortunately the
 455 * HPLL SR mode depends on CxSR itself, so we don't have to hand hold
 456 * the hardware w.r.t. HPLL SR when writing to plane registers.
 457 * Disallowing just CxSR is sufficient.
 458 */
 459bool intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
 460{
 461        bool ret;
 462
 463        mutex_lock(&dev_priv->wm.wm_mutex);
 464        ret = _intel_set_memory_cxsr(dev_priv, enable);
 465        if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
 466                dev_priv->wm.vlv.cxsr = enable;
 467        else if (IS_G4X(dev_priv))
 468                dev_priv->wm.g4x.cxsr = enable;
 469        mutex_unlock(&dev_priv->wm.wm_mutex);
 470
 471        return ret;
 472}
 473
 474/*
 475 * Latency for FIFO fetches is dependent on several factors:
 476 *   - memory configuration (speed, channels)
 477 *   - chipset
 478 *   - current MCH state
 479 * It can be fairly high in some situations, so here we assume a fairly
 480 * pessimal value.  It's a tradeoff between extra memory fetches (if we
 481 * set this value too high, the FIFO will fetch frequently to stay full)
 482 * and power consumption (set it too low to save power and we might see
 483 * FIFO underruns and display "flicker").
 484 *
 485 * A value of 5us seems to be a good balance; safe for very low end
 486 * platforms but not overly aggressive on lower latency configs.
 487 */
 488static const int pessimal_latency_ns = 5000;
 489
 490#define VLV_FIFO_START(dsparb, dsparb2, lo_shift, hi_shift) \
 491        ((((dsparb) >> (lo_shift)) & 0xff) | ((((dsparb2) >> (hi_shift)) & 0x1) << 8))
 492
 493static void vlv_get_fifo_size(struct intel_crtc_state *crtc_state)
 494{
 495        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
 496        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
 497        struct vlv_fifo_state *fifo_state = &crtc_state->wm.vlv.fifo_state;
 498        enum pipe pipe = crtc->pipe;
 499        int sprite0_start, sprite1_start;
 500
 501        switch (pipe) {
 502                u32 dsparb, dsparb2, dsparb3;
 503        case PIPE_A:
 504                dsparb = I915_READ(DSPARB);
 505                dsparb2 = I915_READ(DSPARB2);
 506                sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 0, 0);
 507                sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 8, 4);
 508                break;
 509        case PIPE_B:
 510                dsparb = I915_READ(DSPARB);
 511                dsparb2 = I915_READ(DSPARB2);
 512                sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 16, 8);
 513                sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 24, 12);
 514                break;
 515        case PIPE_C:
 516                dsparb2 = I915_READ(DSPARB2);
 517                dsparb3 = I915_READ(DSPARB3);
 518                sprite0_start = VLV_FIFO_START(dsparb3, dsparb2, 0, 16);
 519                sprite1_start = VLV_FIFO_START(dsparb3, dsparb2, 8, 20);
 520                break;
 521        default:
 522                MISSING_CASE(pipe);
 523                return;
 524        }
 525
 526        fifo_state->plane[PLANE_PRIMARY] = sprite0_start;
 527        fifo_state->plane[PLANE_SPRITE0] = sprite1_start - sprite0_start;
 528        fifo_state->plane[PLANE_SPRITE1] = 511 - sprite1_start;
 529        fifo_state->plane[PLANE_CURSOR] = 63;
 530}
 531
 532static int i9xx_get_fifo_size(struct drm_i915_private *dev_priv,
 533                              enum i9xx_plane_id i9xx_plane)
 534{
 535        u32 dsparb = I915_READ(DSPARB);
 536        int size;
 537
 538        size = dsparb & 0x7f;
 539        if (i9xx_plane == PLANE_B)
 540                size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
 541
 542        DRM_DEBUG_KMS("FIFO size - (0x%08x) %c: %d\n",
 543                      dsparb, plane_name(i9xx_plane), size);
 544
 545        return size;
 546}
 547
 548static int i830_get_fifo_size(struct drm_i915_private *dev_priv,
 549                              enum i9xx_plane_id i9xx_plane)
 550{
 551        u32 dsparb = I915_READ(DSPARB);
 552        int size;
 553
 554        size = dsparb & 0x1ff;
 555        if (i9xx_plane == PLANE_B)
 556                size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
 557        size >>= 1; /* Convert to cachelines */
 558
 559        DRM_DEBUG_KMS("FIFO size - (0x%08x) %c: %d\n",
 560                      dsparb, plane_name(i9xx_plane), size);
 561
 562        return size;
 563}
 564
 565static int i845_get_fifo_size(struct drm_i915_private *dev_priv,
 566                              enum i9xx_plane_id i9xx_plane)
 567{
 568        u32 dsparb = I915_READ(DSPARB);
 569        int size;
 570
 571        size = dsparb & 0x7f;
 572        size >>= 2; /* Convert to cachelines */
 573
 574        DRM_DEBUG_KMS("FIFO size - (0x%08x) %c: %d\n",
 575                      dsparb, plane_name(i9xx_plane), size);
 576
 577        return size;
 578}
 579
 580/* Pineview has different values for various configs */
 581static const struct intel_watermark_params pineview_display_wm = {
 582        .fifo_size = PINEVIEW_DISPLAY_FIFO,
 583        .max_wm = PINEVIEW_MAX_WM,
 584        .default_wm = PINEVIEW_DFT_WM,
 585        .guard_size = PINEVIEW_GUARD_WM,
 586        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
 587};
 588static const struct intel_watermark_params pineview_display_hplloff_wm = {
 589        .fifo_size = PINEVIEW_DISPLAY_FIFO,
 590        .max_wm = PINEVIEW_MAX_WM,
 591        .default_wm = PINEVIEW_DFT_HPLLOFF_WM,
 592        .guard_size = PINEVIEW_GUARD_WM,
 593        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
 594};
 595static const struct intel_watermark_params pineview_cursor_wm = {
 596        .fifo_size = PINEVIEW_CURSOR_FIFO,
 597        .max_wm = PINEVIEW_CURSOR_MAX_WM,
 598        .default_wm = PINEVIEW_CURSOR_DFT_WM,
 599        .guard_size = PINEVIEW_CURSOR_GUARD_WM,
 600        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
 601};
 602static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
 603        .fifo_size = PINEVIEW_CURSOR_FIFO,
 604        .max_wm = PINEVIEW_CURSOR_MAX_WM,
 605        .default_wm = PINEVIEW_CURSOR_DFT_WM,
 606        .guard_size = PINEVIEW_CURSOR_GUARD_WM,
 607        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
 608};
 609static const struct intel_watermark_params i965_cursor_wm_info = {
 610        .fifo_size = I965_CURSOR_FIFO,
 611        .max_wm = I965_CURSOR_MAX_WM,
 612        .default_wm = I965_CURSOR_DFT_WM,
 613        .guard_size = 2,
 614        .cacheline_size = I915_FIFO_LINE_SIZE,
 615};
 616static const struct intel_watermark_params i945_wm_info = {
 617        .fifo_size = I945_FIFO_SIZE,
 618        .max_wm = I915_MAX_WM,
 619        .default_wm = 1,
 620        .guard_size = 2,
 621        .cacheline_size = I915_FIFO_LINE_SIZE,
 622};
 623static const struct intel_watermark_params i915_wm_info = {
 624        .fifo_size = I915_FIFO_SIZE,
 625        .max_wm = I915_MAX_WM,
 626        .default_wm = 1,
 627        .guard_size = 2,
 628        .cacheline_size = I915_FIFO_LINE_SIZE,
 629};
 630static const struct intel_watermark_params i830_a_wm_info = {
 631        .fifo_size = I855GM_FIFO_SIZE,
 632        .max_wm = I915_MAX_WM,
 633        .default_wm = 1,
 634        .guard_size = 2,
 635        .cacheline_size = I830_FIFO_LINE_SIZE,
 636};
 637static const struct intel_watermark_params i830_bc_wm_info = {
 638        .fifo_size = I855GM_FIFO_SIZE,
 639        .max_wm = I915_MAX_WM/2,
 640        .default_wm = 1,
 641        .guard_size = 2,
 642        .cacheline_size = I830_FIFO_LINE_SIZE,
 643};
 644static const struct intel_watermark_params i845_wm_info = {
 645        .fifo_size = I830_FIFO_SIZE,
 646        .max_wm = I915_MAX_WM,
 647        .default_wm = 1,
 648        .guard_size = 2,
 649        .cacheline_size = I830_FIFO_LINE_SIZE,
 650};
 651
 652/**
 653 * intel_wm_method1 - Method 1 / "small buffer" watermark formula
 654 * @pixel_rate: Pipe pixel rate in kHz
 655 * @cpp: Plane bytes per pixel
 656 * @latency: Memory wakeup latency in 0.1us units
 657 *
 658 * Compute the watermark using the method 1 or "small buffer"
 659 * formula. The caller may additonally add extra cachelines
 660 * to account for TLB misses and clock crossings.
 661 *
 662 * This method is concerned with the short term drain rate
 663 * of the FIFO, ie. it does not account for blanking periods
 664 * which would effectively reduce the average drain rate across
 665 * a longer period. The name "small" refers to the fact the
 666 * FIFO is relatively small compared to the amount of data
 667 * fetched.
 668 *
 669 * The FIFO level vs. time graph might look something like:
 670 *
 671 *   |\   |\
 672 *   | \  | \
 673 * __---__---__ (- plane active, _ blanking)
 674 * -> time
 675 *
 676 * or perhaps like this:
 677 *
 678 *   |\|\  |\|\
 679 * __----__----__ (- plane active, _ blanking)
 680 * -> time
 681 *
 682 * Returns:
 683 * The watermark in bytes
 684 */
 685static unsigned int intel_wm_method1(unsigned int pixel_rate,
 686                                     unsigned int cpp,
 687                                     unsigned int latency)
 688{
 689        u64 ret;
 690
 691        ret = mul_u32_u32(pixel_rate, cpp * latency);
 692        ret = DIV_ROUND_UP_ULL(ret, 10000);
 693
 694        return ret;
 695}
 696
 697/**
 698 * intel_wm_method2 - Method 2 / "large buffer" watermark formula
 699 * @pixel_rate: Pipe pixel rate in kHz
 700 * @htotal: Pipe horizontal total
 701 * @width: Plane width in pixels
 702 * @cpp: Plane bytes per pixel
 703 * @latency: Memory wakeup latency in 0.1us units
 704 *
 705 * Compute the watermark using the method 2 or "large buffer"
 706 * formula. The caller may additonally add extra cachelines
 707 * to account for TLB misses and clock crossings.
 708 *
 709 * This method is concerned with the long term drain rate
 710 * of the FIFO, ie. it does account for blanking periods
 711 * which effectively reduce the average drain rate across
 712 * a longer period. The name "large" refers to the fact the
 713 * FIFO is relatively large compared to the amount of data
 714 * fetched.
 715 *
 716 * The FIFO level vs. time graph might look something like:
 717 *
 718 *    |\___       |\___
 719 *    |    \___   |    \___
 720 *    |        \  |        \
 721 * __ --__--__--__--__--__--__ (- plane active, _ blanking)
 722 * -> time
 723 *
 724 * Returns:
 725 * The watermark in bytes
 726 */
 727static unsigned int intel_wm_method2(unsigned int pixel_rate,
 728                                     unsigned int htotal,
 729                                     unsigned int width,
 730                                     unsigned int cpp,
 731                                     unsigned int latency)
 732{
 733        unsigned int ret;
 734
 735        /*
 736         * FIXME remove once all users are computing
 737         * watermarks in the correct place.
 738         */
 739        if (WARN_ON_ONCE(htotal == 0))
 740                htotal = 1;
 741
 742        ret = (latency * pixel_rate) / (htotal * 10000);
 743        ret = (ret + 1) * width * cpp;
 744
 745        return ret;
 746}
 747
 748/**
 749 * intel_calculate_wm - calculate watermark level
 750 * @pixel_rate: pixel clock
 751 * @wm: chip FIFO params
 752 * @fifo_size: size of the FIFO buffer
 753 * @cpp: bytes per pixel
 754 * @latency_ns: memory latency for the platform
 755 *
 756 * Calculate the watermark level (the level at which the display plane will
 757 * start fetching from memory again).  Each chip has a different display
 758 * FIFO size and allocation, so the caller needs to figure that out and pass
 759 * in the correct intel_watermark_params structure.
 760 *
 761 * As the pixel clock runs, the FIFO will be drained at a rate that depends
 762 * on the pixel size.  When it reaches the watermark level, it'll start
 763 * fetching FIFO line sized based chunks from memory until the FIFO fills
 764 * past the watermark point.  If the FIFO drains completely, a FIFO underrun
 765 * will occur, and a display engine hang could result.
 766 */
 767static unsigned int intel_calculate_wm(int pixel_rate,
 768                                       const struct intel_watermark_params *wm,
 769                                       int fifo_size, int cpp,
 770                                       unsigned int latency_ns)
 771{
 772        int entries, wm_size;
 773
 774        /*
 775         * Note: we need to make sure we don't overflow for various clock &
 776         * latency values.
 777         * clocks go from a few thousand to several hundred thousand.
 778         * latency is usually a few thousand
 779         */
 780        entries = intel_wm_method1(pixel_rate, cpp,
 781                                   latency_ns / 100);
 782        entries = DIV_ROUND_UP(entries, wm->cacheline_size) +
 783                wm->guard_size;
 784        DRM_DEBUG_KMS("FIFO entries required for mode: %d\n", entries);
 785
 786        wm_size = fifo_size - entries;
 787        DRM_DEBUG_KMS("FIFO watermark level: %d\n", wm_size);
 788
 789        /* Don't promote wm_size to unsigned... */
 790        if (wm_size > wm->max_wm)
 791                wm_size = wm->max_wm;
 792        if (wm_size <= 0)
 793                wm_size = wm->default_wm;
 794
 795        /*
 796         * Bspec seems to indicate that the value shouldn't be lower than
 797         * 'burst size + 1'. Certainly 830 is quite unhappy with low values.
 798         * Lets go for 8 which is the burst size since certain platforms
 799         * already use a hardcoded 8 (which is what the spec says should be
 800         * done).
 801         */
 802        if (wm_size <= 8)
 803                wm_size = 8;
 804
 805        return wm_size;
 806}
 807
 808static bool is_disabling(int old, int new, int threshold)
 809{
 810        return old >= threshold && new < threshold;
 811}
 812
 813static bool is_enabling(int old, int new, int threshold)
 814{
 815        return old < threshold && new >= threshold;
 816}
 817
 818static int intel_wm_num_levels(struct drm_i915_private *dev_priv)
 819{
 820        return dev_priv->wm.max_level + 1;
 821}
 822
 823static bool intel_wm_plane_visible(const struct intel_crtc_state *crtc_state,
 824                                   const struct intel_plane_state *plane_state)
 825{
 826        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
 827
 828        /* FIXME check the 'enable' instead */
 829        if (!crtc_state->base.active)
 830                return false;
 831
 832        /*
 833         * Treat cursor with fb as always visible since cursor updates
 834         * can happen faster than the vrefresh rate, and the current
 835         * watermark code doesn't handle that correctly. Cursor updates
 836         * which set/clear the fb or change the cursor size are going
 837         * to get throttled by intel_legacy_cursor_update() to work
 838         * around this problem with the watermark code.
 839         */
 840        if (plane->id == PLANE_CURSOR)
 841                return plane_state->base.fb != NULL;
 842        else
 843                return plane_state->base.visible;
 844}
 845
 846static struct intel_crtc *single_enabled_crtc(struct drm_i915_private *dev_priv)
 847{
 848        struct intel_crtc *crtc, *enabled = NULL;
 849
 850        for_each_intel_crtc(&dev_priv->drm, crtc) {
 851                if (intel_crtc_active(crtc)) {
 852                        if (enabled)
 853                                return NULL;
 854                        enabled = crtc;
 855                }
 856        }
 857
 858        return enabled;
 859}
 860
 861static void pineview_update_wm(struct intel_crtc *unused_crtc)
 862{
 863        struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
 864        struct intel_crtc *crtc;
 865        const struct cxsr_latency *latency;
 866        u32 reg;
 867        unsigned int wm;
 868
 869        latency = intel_get_cxsr_latency(!IS_MOBILE(dev_priv),
 870                                         dev_priv->is_ddr3,
 871                                         dev_priv->fsb_freq,
 872                                         dev_priv->mem_freq);
 873        if (!latency) {
 874                DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
 875                intel_set_memory_cxsr(dev_priv, false);
 876                return;
 877        }
 878
 879        crtc = single_enabled_crtc(dev_priv);
 880        if (crtc) {
 881                const struct drm_display_mode *adjusted_mode =
 882                        &crtc->config->base.adjusted_mode;
 883                const struct drm_framebuffer *fb =
 884                        crtc->base.primary->state->fb;
 885                int cpp = fb->format->cpp[0];
 886                int clock = adjusted_mode->crtc_clock;
 887
 888                /* Display SR */
 889                wm = intel_calculate_wm(clock, &pineview_display_wm,
 890                                        pineview_display_wm.fifo_size,
 891                                        cpp, latency->display_sr);
 892                reg = I915_READ(DSPFW1);
 893                reg &= ~DSPFW_SR_MASK;
 894                reg |= FW_WM(wm, SR);
 895                I915_WRITE(DSPFW1, reg);
 896                DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
 897
 898                /* cursor SR */
 899                wm = intel_calculate_wm(clock, &pineview_cursor_wm,
 900                                        pineview_display_wm.fifo_size,
 901                                        4, latency->cursor_sr);
 902                reg = I915_READ(DSPFW3);
 903                reg &= ~DSPFW_CURSOR_SR_MASK;
 904                reg |= FW_WM(wm, CURSOR_SR);
 905                I915_WRITE(DSPFW3, reg);
 906
 907                /* Display HPLL off SR */
 908                wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
 909                                        pineview_display_hplloff_wm.fifo_size,
 910                                        cpp, latency->display_hpll_disable);
 911                reg = I915_READ(DSPFW3);
 912                reg &= ~DSPFW_HPLL_SR_MASK;
 913                reg |= FW_WM(wm, HPLL_SR);
 914                I915_WRITE(DSPFW3, reg);
 915
 916                /* cursor HPLL off SR */
 917                wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
 918                                        pineview_display_hplloff_wm.fifo_size,
 919                                        4, latency->cursor_hpll_disable);
 920                reg = I915_READ(DSPFW3);
 921                reg &= ~DSPFW_HPLL_CURSOR_MASK;
 922                reg |= FW_WM(wm, HPLL_CURSOR);
 923                I915_WRITE(DSPFW3, reg);
 924                DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
 925
 926                intel_set_memory_cxsr(dev_priv, true);
 927        } else {
 928                intel_set_memory_cxsr(dev_priv, false);
 929        }
 930}
 931
 932/*
 933 * Documentation says:
 934 * "If the line size is small, the TLB fetches can get in the way of the
 935 *  data fetches, causing some lag in the pixel data return which is not
 936 *  accounted for in the above formulas. The following adjustment only
 937 *  needs to be applied if eight whole lines fit in the buffer at once.
 938 *  The WM is adjusted upwards by the difference between the FIFO size
 939 *  and the size of 8 whole lines. This adjustment is always performed
 940 *  in the actual pixel depth regardless of whether FBC is enabled or not."
 941 */
 942static unsigned int g4x_tlb_miss_wa(int fifo_size, int width, int cpp)
 943{
 944        int tlb_miss = fifo_size * 64 - width * cpp * 8;
 945
 946        return max(0, tlb_miss);
 947}
 948
 949static void g4x_write_wm_values(struct drm_i915_private *dev_priv,
 950                                const struct g4x_wm_values *wm)
 951{
 952        enum pipe pipe;
 953
 954        for_each_pipe(dev_priv, pipe)
 955                trace_g4x_wm(intel_get_crtc_for_pipe(dev_priv, pipe), wm);
 956
 957        I915_WRITE(DSPFW1,
 958                   FW_WM(wm->sr.plane, SR) |
 959                   FW_WM(wm->pipe[PIPE_B].plane[PLANE_CURSOR], CURSORB) |
 960                   FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY], PLANEB) |
 961                   FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY], PLANEA));
 962        I915_WRITE(DSPFW2,
 963                   (wm->fbc_en ? DSPFW_FBC_SR_EN : 0) |
 964                   FW_WM(wm->sr.fbc, FBC_SR) |
 965                   FW_WM(wm->hpll.fbc, FBC_HPLL_SR) |
 966                   FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEB) |
 967                   FW_WM(wm->pipe[PIPE_A].plane[PLANE_CURSOR], CURSORA) |
 968                   FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0], SPRITEA));
 969        I915_WRITE(DSPFW3,
 970                   (wm->hpll_en ? DSPFW_HPLL_SR_EN : 0) |
 971                   FW_WM(wm->sr.cursor, CURSOR_SR) |
 972                   FW_WM(wm->hpll.cursor, HPLL_CURSOR) |
 973                   FW_WM(wm->hpll.plane, HPLL_SR));
 974
 975        POSTING_READ(DSPFW1);
 976}
 977
 978#define FW_WM_VLV(value, plane) \
 979        (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK_VLV)
 980
 981static void vlv_write_wm_values(struct drm_i915_private *dev_priv,
 982                                const struct vlv_wm_values *wm)
 983{
 984        enum pipe pipe;
 985
 986        for_each_pipe(dev_priv, pipe) {
 987                trace_vlv_wm(intel_get_crtc_for_pipe(dev_priv, pipe), wm);
 988
 989                I915_WRITE(VLV_DDL(pipe),
 990                           (wm->ddl[pipe].plane[PLANE_CURSOR] << DDL_CURSOR_SHIFT) |
 991                           (wm->ddl[pipe].plane[PLANE_SPRITE1] << DDL_SPRITE_SHIFT(1)) |
 992                           (wm->ddl[pipe].plane[PLANE_SPRITE0] << DDL_SPRITE_SHIFT(0)) |
 993                           (wm->ddl[pipe].plane[PLANE_PRIMARY] << DDL_PLANE_SHIFT));
 994        }
 995
 996        /*
 997         * Zero the (unused) WM1 watermarks, and also clear all the
 998         * high order bits so that there are no out of bounds values
 999         * present in the registers during the reprogramming.
1000         */
1001        I915_WRITE(DSPHOWM, 0);
1002        I915_WRITE(DSPHOWM1, 0);
1003        I915_WRITE(DSPFW4, 0);
1004        I915_WRITE(DSPFW5, 0);
1005        I915_WRITE(DSPFW6, 0);
1006
1007        I915_WRITE(DSPFW1,
1008                   FW_WM(wm->sr.plane, SR) |
1009                   FW_WM(wm->pipe[PIPE_B].plane[PLANE_CURSOR], CURSORB) |
1010                   FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_PRIMARY], PLANEB) |
1011                   FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_PRIMARY], PLANEA));
1012        I915_WRITE(DSPFW2,
1013                   FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_SPRITE1], SPRITEB) |
1014                   FW_WM(wm->pipe[PIPE_A].plane[PLANE_CURSOR], CURSORA) |
1015                   FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_SPRITE0], SPRITEA));
1016        I915_WRITE(DSPFW3,
1017                   FW_WM(wm->sr.cursor, CURSOR_SR));
1018
1019        if (IS_CHERRYVIEW(dev_priv)) {
1020                I915_WRITE(DSPFW7_CHV,
1021                           FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE1], SPRITED) |
1022                           FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEC));
1023                I915_WRITE(DSPFW8_CHV,
1024                           FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_SPRITE1], SPRITEF) |
1025                           FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_SPRITE0], SPRITEE));
1026                I915_WRITE(DSPFW9_CHV,
1027                           FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_PRIMARY], PLANEC) |
1028                           FW_WM(wm->pipe[PIPE_C].plane[PLANE_CURSOR], CURSORC));
1029                I915_WRITE(DSPHOWM,
1030                           FW_WM(wm->sr.plane >> 9, SR_HI) |
1031                           FW_WM(wm->pipe[PIPE_C].plane[PLANE_SPRITE1] >> 8, SPRITEF_HI) |
1032                           FW_WM(wm->pipe[PIPE_C].plane[PLANE_SPRITE0] >> 8, SPRITEE_HI) |
1033                           FW_WM(wm->pipe[PIPE_C].plane[PLANE_PRIMARY] >> 8, PLANEC_HI) |
1034                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE1] >> 8, SPRITED_HI) |
1035                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0] >> 8, SPRITEC_HI) |
1036                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY] >> 8, PLANEB_HI) |
1037                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE1] >> 8, SPRITEB_HI) |
1038                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0] >> 8, SPRITEA_HI) |
1039                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY] >> 8, PLANEA_HI));
1040        } else {
1041                I915_WRITE(DSPFW7,
1042                           FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE1], SPRITED) |
1043                           FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEC));
1044                I915_WRITE(DSPHOWM,
1045                           FW_WM(wm->sr.plane >> 9, SR_HI) |
1046                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE1] >> 8, SPRITED_HI) |
1047                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0] >> 8, SPRITEC_HI) |
1048                           FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY] >> 8, PLANEB_HI) |
1049                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE1] >> 8, SPRITEB_HI) |
1050                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0] >> 8, SPRITEA_HI) |
1051                           FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY] >> 8, PLANEA_HI));
1052        }
1053
1054        POSTING_READ(DSPFW1);
1055}
1056
1057#undef FW_WM_VLV
1058
1059static void g4x_setup_wm_latency(struct drm_i915_private *dev_priv)
1060{
1061        /* all latencies in usec */
1062        dev_priv->wm.pri_latency[G4X_WM_LEVEL_NORMAL] = 5;
1063        dev_priv->wm.pri_latency[G4X_WM_LEVEL_SR] = 12;
1064        dev_priv->wm.pri_latency[G4X_WM_LEVEL_HPLL] = 35;
1065
1066        dev_priv->wm.max_level = G4X_WM_LEVEL_HPLL;
1067}
1068
1069static int g4x_plane_fifo_size(enum plane_id plane_id, int level)
1070{
1071        /*
1072         * DSPCNTR[13] supposedly controls whether the
1073         * primary plane can use the FIFO space otherwise
1074         * reserved for the sprite plane. It's not 100% clear
1075         * what the actual FIFO size is, but it looks like we
1076         * can happily set both primary and sprite watermarks
1077         * up to 127 cachelines. So that would seem to mean
1078         * that either DSPCNTR[13] doesn't do anything, or that
1079         * the total FIFO is >= 256 cachelines in size. Either
1080         * way, we don't seem to have to worry about this
1081         * repartitioning as the maximum watermark value the
1082         * register can hold for each plane is lower than the
1083         * minimum FIFO size.
1084         */
1085        switch (plane_id) {
1086        case PLANE_CURSOR:
1087                return 63;
1088        case PLANE_PRIMARY:
1089                return level == G4X_WM_LEVEL_NORMAL ? 127 : 511;
1090        case PLANE_SPRITE0:
1091                return level == G4X_WM_LEVEL_NORMAL ? 127 : 0;
1092        default:
1093                MISSING_CASE(plane_id);
1094                return 0;
1095        }
1096}
1097
1098static int g4x_fbc_fifo_size(int level)
1099{
1100        switch (level) {
1101        case G4X_WM_LEVEL_SR:
1102                return 7;
1103        case G4X_WM_LEVEL_HPLL:
1104                return 15;
1105        default:
1106                MISSING_CASE(level);
1107                return 0;
1108        }
1109}
1110
1111static u16 g4x_compute_wm(const struct intel_crtc_state *crtc_state,
1112                          const struct intel_plane_state *plane_state,
1113                          int level)
1114{
1115        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1116        struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1117        const struct drm_display_mode *adjusted_mode =
1118                &crtc_state->base.adjusted_mode;
1119        unsigned int latency = dev_priv->wm.pri_latency[level] * 10;
1120        unsigned int clock, htotal, cpp, width, wm;
1121
1122        if (latency == 0)
1123                return USHRT_MAX;
1124
1125        if (!intel_wm_plane_visible(crtc_state, plane_state))
1126                return 0;
1127
1128        cpp = plane_state->base.fb->format->cpp[0];
1129
1130        /*
1131         * Not 100% sure which way ELK should go here as the
1132         * spec only says CL/CTG should assume 32bpp and BW
1133         * doesn't need to. But as these things followed the
1134         * mobile vs. desktop lines on gen3 as well, let's
1135         * assume ELK doesn't need this.
1136         *
1137         * The spec also fails to list such a restriction for
1138         * the HPLL watermark, which seems a little strange.
1139         * Let's use 32bpp for the HPLL watermark as well.
1140         */
1141        if (IS_GM45(dev_priv) && plane->id == PLANE_PRIMARY &&
1142            level != G4X_WM_LEVEL_NORMAL)
1143                cpp = max(cpp, 4u);
1144
1145        clock = adjusted_mode->crtc_clock;
1146        htotal = adjusted_mode->crtc_htotal;
1147
1148        if (plane->id == PLANE_CURSOR)
1149                width = plane_state->base.crtc_w;
1150        else
1151                width = drm_rect_width(&plane_state->base.dst);
1152
1153        if (plane->id == PLANE_CURSOR) {
1154                wm = intel_wm_method2(clock, htotal, width, cpp, latency);
1155        } else if (plane->id == PLANE_PRIMARY &&
1156                   level == G4X_WM_LEVEL_NORMAL) {
1157                wm = intel_wm_method1(clock, cpp, latency);
1158        } else {
1159                unsigned int small, large;
1160
1161                small = intel_wm_method1(clock, cpp, latency);
1162                large = intel_wm_method2(clock, htotal, width, cpp, latency);
1163
1164                wm = min(small, large);
1165        }
1166
1167        wm += g4x_tlb_miss_wa(g4x_plane_fifo_size(plane->id, level),
1168                              width, cpp);
1169
1170        wm = DIV_ROUND_UP(wm, 64) + 2;
1171
1172        return min_t(unsigned int, wm, USHRT_MAX);
1173}
1174
1175static bool g4x_raw_plane_wm_set(struct intel_crtc_state *crtc_state,
1176                                 int level, enum plane_id plane_id, u16 value)
1177{
1178        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1179        bool dirty = false;
1180
1181        for (; level < intel_wm_num_levels(dev_priv); level++) {
1182                struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1183
1184                dirty |= raw->plane[plane_id] != value;
1185                raw->plane[plane_id] = value;
1186        }
1187
1188        return dirty;
1189}
1190
1191static bool g4x_raw_fbc_wm_set(struct intel_crtc_state *crtc_state,
1192                               int level, u16 value)
1193{
1194        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1195        bool dirty = false;
1196
1197        /* NORMAL level doesn't have an FBC watermark */
1198        level = max(level, G4X_WM_LEVEL_SR);
1199
1200        for (; level < intel_wm_num_levels(dev_priv); level++) {
1201                struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1202
1203                dirty |= raw->fbc != value;
1204                raw->fbc = value;
1205        }
1206
1207        return dirty;
1208}
1209
1210static u32 ilk_compute_fbc_wm(const struct intel_crtc_state *crtc_state,
1211                              const struct intel_plane_state *plane_state,
1212                              u32 pri_val);
1213
1214static bool g4x_raw_plane_wm_compute(struct intel_crtc_state *crtc_state,
1215                                     const struct intel_plane_state *plane_state)
1216{
1217        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1218        int num_levels = intel_wm_num_levels(to_i915(plane->base.dev));
1219        enum plane_id plane_id = plane->id;
1220        bool dirty = false;
1221        int level;
1222
1223        if (!intel_wm_plane_visible(crtc_state, plane_state)) {
1224                dirty |= g4x_raw_plane_wm_set(crtc_state, 0, plane_id, 0);
1225                if (plane_id == PLANE_PRIMARY)
1226                        dirty |= g4x_raw_fbc_wm_set(crtc_state, 0, 0);
1227                goto out;
1228        }
1229
1230        for (level = 0; level < num_levels; level++) {
1231                struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1232                int wm, max_wm;
1233
1234                wm = g4x_compute_wm(crtc_state, plane_state, level);
1235                max_wm = g4x_plane_fifo_size(plane_id, level);
1236
1237                if (wm > max_wm)
1238                        break;
1239
1240                dirty |= raw->plane[plane_id] != wm;
1241                raw->plane[plane_id] = wm;
1242
1243                if (plane_id != PLANE_PRIMARY ||
1244                    level == G4X_WM_LEVEL_NORMAL)
1245                        continue;
1246
1247                wm = ilk_compute_fbc_wm(crtc_state, plane_state,
1248                                        raw->plane[plane_id]);
1249                max_wm = g4x_fbc_fifo_size(level);
1250
1251                /*
1252                 * FBC wm is not mandatory as we
1253                 * can always just disable its use.
1254                 */
1255                if (wm > max_wm)
1256                        wm = USHRT_MAX;
1257
1258                dirty |= raw->fbc != wm;
1259                raw->fbc = wm;
1260        }
1261
1262        /* mark watermarks as invalid */
1263        dirty |= g4x_raw_plane_wm_set(crtc_state, level, plane_id, USHRT_MAX);
1264
1265        if (plane_id == PLANE_PRIMARY)
1266                dirty |= g4x_raw_fbc_wm_set(crtc_state, level, USHRT_MAX);
1267
1268 out:
1269        if (dirty) {
1270                DRM_DEBUG_KMS("%s watermarks: normal=%d, SR=%d, HPLL=%d\n",
1271                              plane->base.name,
1272                              crtc_state->wm.g4x.raw[G4X_WM_LEVEL_NORMAL].plane[plane_id],
1273                              crtc_state->wm.g4x.raw[G4X_WM_LEVEL_SR].plane[plane_id],
1274                              crtc_state->wm.g4x.raw[G4X_WM_LEVEL_HPLL].plane[plane_id]);
1275
1276                if (plane_id == PLANE_PRIMARY)
1277                        DRM_DEBUG_KMS("FBC watermarks: SR=%d, HPLL=%d\n",
1278                                      crtc_state->wm.g4x.raw[G4X_WM_LEVEL_SR].fbc,
1279                                      crtc_state->wm.g4x.raw[G4X_WM_LEVEL_HPLL].fbc);
1280        }
1281
1282        return dirty;
1283}
1284
1285static bool g4x_raw_plane_wm_is_valid(const struct intel_crtc_state *crtc_state,
1286                                      enum plane_id plane_id, int level)
1287{
1288        const struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1289
1290        return raw->plane[plane_id] <= g4x_plane_fifo_size(plane_id, level);
1291}
1292
1293static bool g4x_raw_crtc_wm_is_valid(const struct intel_crtc_state *crtc_state,
1294                                     int level)
1295{
1296        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1297
1298        if (level > dev_priv->wm.max_level)
1299                return false;
1300
1301        return g4x_raw_plane_wm_is_valid(crtc_state, PLANE_PRIMARY, level) &&
1302                g4x_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE0, level) &&
1303                g4x_raw_plane_wm_is_valid(crtc_state, PLANE_CURSOR, level);
1304}
1305
1306/* mark all levels starting from 'level' as invalid */
1307static void g4x_invalidate_wms(struct intel_crtc *crtc,
1308                               struct g4x_wm_state *wm_state, int level)
1309{
1310        if (level <= G4X_WM_LEVEL_NORMAL) {
1311                enum plane_id plane_id;
1312
1313                for_each_plane_id_on_crtc(crtc, plane_id)
1314                        wm_state->wm.plane[plane_id] = USHRT_MAX;
1315        }
1316
1317        if (level <= G4X_WM_LEVEL_SR) {
1318                wm_state->cxsr = false;
1319                wm_state->sr.cursor = USHRT_MAX;
1320                wm_state->sr.plane = USHRT_MAX;
1321                wm_state->sr.fbc = USHRT_MAX;
1322        }
1323
1324        if (level <= G4X_WM_LEVEL_HPLL) {
1325                wm_state->hpll_en = false;
1326                wm_state->hpll.cursor = USHRT_MAX;
1327                wm_state->hpll.plane = USHRT_MAX;
1328                wm_state->hpll.fbc = USHRT_MAX;
1329        }
1330}
1331
1332static int g4x_compute_pipe_wm(struct intel_crtc_state *crtc_state)
1333{
1334        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1335        struct intel_atomic_state *state =
1336                to_intel_atomic_state(crtc_state->base.state);
1337        struct g4x_wm_state *wm_state = &crtc_state->wm.g4x.optimal;
1338        int num_active_planes = hweight32(crtc_state->active_planes &
1339                                          ~BIT(PLANE_CURSOR));
1340        const struct g4x_pipe_wm *raw;
1341        const struct intel_plane_state *old_plane_state;
1342        const struct intel_plane_state *new_plane_state;
1343        struct intel_plane *plane;
1344        enum plane_id plane_id;
1345        int i, level;
1346        unsigned int dirty = 0;
1347
1348        for_each_oldnew_intel_plane_in_state(state, plane,
1349                                             old_plane_state,
1350                                             new_plane_state, i) {
1351                if (new_plane_state->base.crtc != &crtc->base &&
1352                    old_plane_state->base.crtc != &crtc->base)
1353                        continue;
1354
1355                if (g4x_raw_plane_wm_compute(crtc_state, new_plane_state))
1356                        dirty |= BIT(plane->id);
1357        }
1358
1359        if (!dirty)
1360                return 0;
1361
1362        level = G4X_WM_LEVEL_NORMAL;
1363        if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1364                goto out;
1365
1366        raw = &crtc_state->wm.g4x.raw[level];
1367        for_each_plane_id_on_crtc(crtc, plane_id)
1368                wm_state->wm.plane[plane_id] = raw->plane[plane_id];
1369
1370        level = G4X_WM_LEVEL_SR;
1371
1372        if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1373                goto out;
1374
1375        raw = &crtc_state->wm.g4x.raw[level];
1376        wm_state->sr.plane = raw->plane[PLANE_PRIMARY];
1377        wm_state->sr.cursor = raw->plane[PLANE_CURSOR];
1378        wm_state->sr.fbc = raw->fbc;
1379
1380        wm_state->cxsr = num_active_planes == BIT(PLANE_PRIMARY);
1381
1382        level = G4X_WM_LEVEL_HPLL;
1383
1384        if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1385                goto out;
1386
1387        raw = &crtc_state->wm.g4x.raw[level];
1388        wm_state->hpll.plane = raw->plane[PLANE_PRIMARY];
1389        wm_state->hpll.cursor = raw->plane[PLANE_CURSOR];
1390        wm_state->hpll.fbc = raw->fbc;
1391
1392        wm_state->hpll_en = wm_state->cxsr;
1393
1394        level++;
1395
1396 out:
1397        if (level == G4X_WM_LEVEL_NORMAL)
1398                return -EINVAL;
1399
1400        /* invalidate the higher levels */
1401        g4x_invalidate_wms(crtc, wm_state, level);
1402
1403        /*
1404         * Determine if the FBC watermark(s) can be used. IF
1405         * this isn't the case we prefer to disable the FBC
1406         ( watermark(s) rather than disable the SR/HPLL
1407         * level(s) entirely.
1408         */
1409        wm_state->fbc_en = level > G4X_WM_LEVEL_NORMAL;
1410
1411        if (level >= G4X_WM_LEVEL_SR &&
1412            wm_state->sr.fbc > g4x_fbc_fifo_size(G4X_WM_LEVEL_SR))
1413                wm_state->fbc_en = false;
1414        else if (level >= G4X_WM_LEVEL_HPLL &&
1415                 wm_state->hpll.fbc > g4x_fbc_fifo_size(G4X_WM_LEVEL_HPLL))
1416                wm_state->fbc_en = false;
1417
1418        return 0;
1419}
1420
1421static int g4x_compute_intermediate_wm(struct intel_crtc_state *new_crtc_state)
1422{
1423        struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1424        struct g4x_wm_state *intermediate = &new_crtc_state->wm.g4x.intermediate;
1425        const struct g4x_wm_state *optimal = &new_crtc_state->wm.g4x.optimal;
1426        struct intel_atomic_state *intel_state =
1427                to_intel_atomic_state(new_crtc_state->base.state);
1428        const struct intel_crtc_state *old_crtc_state =
1429                intel_atomic_get_old_crtc_state(intel_state, crtc);
1430        const struct g4x_wm_state *active = &old_crtc_state->wm.g4x.optimal;
1431        enum plane_id plane_id;
1432
1433        if (!new_crtc_state->base.active || drm_atomic_crtc_needs_modeset(&new_crtc_state->base)) {
1434                *intermediate = *optimal;
1435
1436                intermediate->cxsr = false;
1437                intermediate->hpll_en = false;
1438                goto out;
1439        }
1440
1441        intermediate->cxsr = optimal->cxsr && active->cxsr &&
1442                !new_crtc_state->disable_cxsr;
1443        intermediate->hpll_en = optimal->hpll_en && active->hpll_en &&
1444                !new_crtc_state->disable_cxsr;
1445        intermediate->fbc_en = optimal->fbc_en && active->fbc_en;
1446
1447        for_each_plane_id_on_crtc(crtc, plane_id) {
1448                intermediate->wm.plane[plane_id] =
1449                        max(optimal->wm.plane[plane_id],
1450                            active->wm.plane[plane_id]);
1451
1452                WARN_ON(intermediate->wm.plane[plane_id] >
1453                        g4x_plane_fifo_size(plane_id, G4X_WM_LEVEL_NORMAL));
1454        }
1455
1456        intermediate->sr.plane = max(optimal->sr.plane,
1457                                     active->sr.plane);
1458        intermediate->sr.cursor = max(optimal->sr.cursor,
1459                                      active->sr.cursor);
1460        intermediate->sr.fbc = max(optimal->sr.fbc,
1461                                   active->sr.fbc);
1462
1463        intermediate->hpll.plane = max(optimal->hpll.plane,
1464                                       active->hpll.plane);
1465        intermediate->hpll.cursor = max(optimal->hpll.cursor,
1466                                        active->hpll.cursor);
1467        intermediate->hpll.fbc = max(optimal->hpll.fbc,
1468                                     active->hpll.fbc);
1469
1470        WARN_ON((intermediate->sr.plane >
1471                 g4x_plane_fifo_size(PLANE_PRIMARY, G4X_WM_LEVEL_SR) ||
1472                 intermediate->sr.cursor >
1473                 g4x_plane_fifo_size(PLANE_CURSOR, G4X_WM_LEVEL_SR)) &&
1474                intermediate->cxsr);
1475        WARN_ON((intermediate->sr.plane >
1476                 g4x_plane_fifo_size(PLANE_PRIMARY, G4X_WM_LEVEL_HPLL) ||
1477                 intermediate->sr.cursor >
1478                 g4x_plane_fifo_size(PLANE_CURSOR, G4X_WM_LEVEL_HPLL)) &&
1479                intermediate->hpll_en);
1480
1481        WARN_ON(intermediate->sr.fbc > g4x_fbc_fifo_size(1) &&
1482                intermediate->fbc_en && intermediate->cxsr);
1483        WARN_ON(intermediate->hpll.fbc > g4x_fbc_fifo_size(2) &&
1484                intermediate->fbc_en && intermediate->hpll_en);
1485
1486out:
1487        /*
1488         * If our intermediate WM are identical to the final WM, then we can
1489         * omit the post-vblank programming; only update if it's different.
1490         */
1491        if (memcmp(intermediate, optimal, sizeof(*intermediate)) != 0)
1492                new_crtc_state->wm.need_postvbl_update = true;
1493
1494        return 0;
1495}
1496
1497static void g4x_merge_wm(struct drm_i915_private *dev_priv,
1498                         struct g4x_wm_values *wm)
1499{
1500        struct intel_crtc *crtc;
1501        int num_active_crtcs = 0;
1502
1503        wm->cxsr = true;
1504        wm->hpll_en = true;
1505        wm->fbc_en = true;
1506
1507        for_each_intel_crtc(&dev_priv->drm, crtc) {
1508                const struct g4x_wm_state *wm_state = &crtc->wm.active.g4x;
1509
1510                if (!crtc->active)
1511                        continue;
1512
1513                if (!wm_state->cxsr)
1514                        wm->cxsr = false;
1515                if (!wm_state->hpll_en)
1516                        wm->hpll_en = false;
1517                if (!wm_state->fbc_en)
1518                        wm->fbc_en = false;
1519
1520                num_active_crtcs++;
1521        }
1522
1523        if (num_active_crtcs != 1) {
1524                wm->cxsr = false;
1525                wm->hpll_en = false;
1526                wm->fbc_en = false;
1527        }
1528
1529        for_each_intel_crtc(&dev_priv->drm, crtc) {
1530                const struct g4x_wm_state *wm_state = &crtc->wm.active.g4x;
1531                enum pipe pipe = crtc->pipe;
1532
1533                wm->pipe[pipe] = wm_state->wm;
1534                if (crtc->active && wm->cxsr)
1535                        wm->sr = wm_state->sr;
1536                if (crtc->active && wm->hpll_en)
1537                        wm->hpll = wm_state->hpll;
1538        }
1539}
1540
1541static void g4x_program_watermarks(struct drm_i915_private *dev_priv)
1542{
1543        struct g4x_wm_values *old_wm = &dev_priv->wm.g4x;
1544        struct g4x_wm_values new_wm = {};
1545
1546        g4x_merge_wm(dev_priv, &new_wm);
1547
1548        if (memcmp(old_wm, &new_wm, sizeof(new_wm)) == 0)
1549                return;
1550
1551        if (is_disabling(old_wm->cxsr, new_wm.cxsr, true))
1552                _intel_set_memory_cxsr(dev_priv, false);
1553
1554        g4x_write_wm_values(dev_priv, &new_wm);
1555
1556        if (is_enabling(old_wm->cxsr, new_wm.cxsr, true))
1557                _intel_set_memory_cxsr(dev_priv, true);
1558
1559        *old_wm = new_wm;
1560}
1561
1562static void g4x_initial_watermarks(struct intel_atomic_state *state,
1563                                   struct intel_crtc_state *crtc_state)
1564{
1565        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1566        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1567
1568        mutex_lock(&dev_priv->wm.wm_mutex);
1569        crtc->wm.active.g4x = crtc_state->wm.g4x.intermediate;
1570        g4x_program_watermarks(dev_priv);
1571        mutex_unlock(&dev_priv->wm.wm_mutex);
1572}
1573
1574static void g4x_optimize_watermarks(struct intel_atomic_state *state,
1575                                    struct intel_crtc_state *crtc_state)
1576{
1577        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1578        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1579
1580        if (!crtc_state->wm.need_postvbl_update)
1581                return;
1582
1583        mutex_lock(&dev_priv->wm.wm_mutex);
1584        crtc->wm.active.g4x = crtc_state->wm.g4x.optimal;
1585        g4x_program_watermarks(dev_priv);
1586        mutex_unlock(&dev_priv->wm.wm_mutex);
1587}
1588
1589/* latency must be in 0.1us units. */
1590static unsigned int vlv_wm_method2(unsigned int pixel_rate,
1591                                   unsigned int htotal,
1592                                   unsigned int width,
1593                                   unsigned int cpp,
1594                                   unsigned int latency)
1595{
1596        unsigned int ret;
1597
1598        ret = intel_wm_method2(pixel_rate, htotal,
1599                               width, cpp, latency);
1600        ret = DIV_ROUND_UP(ret, 64);
1601
1602        return ret;
1603}
1604
1605static void vlv_setup_wm_latency(struct drm_i915_private *dev_priv)
1606{
1607        /* all latencies in usec */
1608        dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM2] = 3;
1609
1610        dev_priv->wm.max_level = VLV_WM_LEVEL_PM2;
1611
1612        if (IS_CHERRYVIEW(dev_priv)) {
1613                dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM5] = 12;
1614                dev_priv->wm.pri_latency[VLV_WM_LEVEL_DDR_DVFS] = 33;
1615
1616                dev_priv->wm.max_level = VLV_WM_LEVEL_DDR_DVFS;
1617        }
1618}
1619
1620static u16 vlv_compute_wm_level(const struct intel_crtc_state *crtc_state,
1621                                const struct intel_plane_state *plane_state,
1622                                int level)
1623{
1624        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1625        struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1626        const struct drm_display_mode *adjusted_mode =
1627                &crtc_state->base.adjusted_mode;
1628        unsigned int clock, htotal, cpp, width, wm;
1629
1630        if (dev_priv->wm.pri_latency[level] == 0)
1631                return USHRT_MAX;
1632
1633        if (!intel_wm_plane_visible(crtc_state, plane_state))
1634                return 0;
1635
1636        cpp = plane_state->base.fb->format->cpp[0];
1637        clock = adjusted_mode->crtc_clock;
1638        htotal = adjusted_mode->crtc_htotal;
1639        width = crtc_state->pipe_src_w;
1640
1641        if (plane->id == PLANE_CURSOR) {
1642                /*
1643                 * FIXME the formula gives values that are
1644                 * too big for the cursor FIFO, and hence we
1645                 * would never be able to use cursors. For
1646                 * now just hardcode the watermark.
1647                 */
1648                wm = 63;
1649        } else {
1650                wm = vlv_wm_method2(clock, htotal, width, cpp,
1651                                    dev_priv->wm.pri_latency[level] * 10);
1652        }
1653
1654        return min_t(unsigned int, wm, USHRT_MAX);
1655}
1656
1657static bool vlv_need_sprite0_fifo_workaround(unsigned int active_planes)
1658{
1659        return (active_planes & (BIT(PLANE_SPRITE0) |
1660                                 BIT(PLANE_SPRITE1))) == BIT(PLANE_SPRITE1);
1661}
1662
1663static int vlv_compute_fifo(struct intel_crtc_state *crtc_state)
1664{
1665        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1666        const struct g4x_pipe_wm *raw =
1667                &crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM2];
1668        struct vlv_fifo_state *fifo_state = &crtc_state->wm.vlv.fifo_state;
1669        unsigned int active_planes = crtc_state->active_planes & ~BIT(PLANE_CURSOR);
1670        int num_active_planes = hweight32(active_planes);
1671        const int fifo_size = 511;
1672        int fifo_extra, fifo_left = fifo_size;
1673        int sprite0_fifo_extra = 0;
1674        unsigned int total_rate;
1675        enum plane_id plane_id;
1676
1677        /*
1678         * When enabling sprite0 after sprite1 has already been enabled
1679         * we tend to get an underrun unless sprite0 already has some
1680         * FIFO space allcoated. Hence we always allocate at least one
1681         * cacheline for sprite0 whenever sprite1 is enabled.
1682         *
1683         * All other plane enable sequences appear immune to this problem.
1684         */
1685        if (vlv_need_sprite0_fifo_workaround(active_planes))
1686                sprite0_fifo_extra = 1;
1687
1688        total_rate = raw->plane[PLANE_PRIMARY] +
1689                raw->plane[PLANE_SPRITE0] +
1690                raw->plane[PLANE_SPRITE1] +
1691                sprite0_fifo_extra;
1692
1693        if (total_rate > fifo_size)
1694                return -EINVAL;
1695
1696        if (total_rate == 0)
1697                total_rate = 1;
1698
1699        for_each_plane_id_on_crtc(crtc, plane_id) {
1700                unsigned int rate;
1701
1702                if ((active_planes & BIT(plane_id)) == 0) {
1703                        fifo_state->plane[plane_id] = 0;
1704                        continue;
1705                }
1706
1707                rate = raw->plane[plane_id];
1708                fifo_state->plane[plane_id] = fifo_size * rate / total_rate;
1709                fifo_left -= fifo_state->plane[plane_id];
1710        }
1711
1712        fifo_state->plane[PLANE_SPRITE0] += sprite0_fifo_extra;
1713        fifo_left -= sprite0_fifo_extra;
1714
1715        fifo_state->plane[PLANE_CURSOR] = 63;
1716
1717        fifo_extra = DIV_ROUND_UP(fifo_left, num_active_planes ?: 1);
1718
1719        /* spread the remainder evenly */
1720        for_each_plane_id_on_crtc(crtc, plane_id) {
1721                int plane_extra;
1722
1723                if (fifo_left == 0)
1724                        break;
1725
1726                if ((active_planes & BIT(plane_id)) == 0)
1727                        continue;
1728
1729                plane_extra = min(fifo_extra, fifo_left);
1730                fifo_state->plane[plane_id] += plane_extra;
1731                fifo_left -= plane_extra;
1732        }
1733
1734        WARN_ON(active_planes != 0 && fifo_left != 0);
1735
1736        /* give it all to the first plane if none are active */
1737        if (active_planes == 0) {
1738                WARN_ON(fifo_left != fifo_size);
1739                fifo_state->plane[PLANE_PRIMARY] = fifo_left;
1740        }
1741
1742        return 0;
1743}
1744
1745/* mark all levels starting from 'level' as invalid */
1746static void vlv_invalidate_wms(struct intel_crtc *crtc,
1747                               struct vlv_wm_state *wm_state, int level)
1748{
1749        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1750
1751        for (; level < intel_wm_num_levels(dev_priv); level++) {
1752                enum plane_id plane_id;
1753
1754                for_each_plane_id_on_crtc(crtc, plane_id)
1755                        wm_state->wm[level].plane[plane_id] = USHRT_MAX;
1756
1757                wm_state->sr[level].cursor = USHRT_MAX;
1758                wm_state->sr[level].plane = USHRT_MAX;
1759        }
1760}
1761
1762static u16 vlv_invert_wm_value(u16 wm, u16 fifo_size)
1763{
1764        if (wm > fifo_size)
1765                return USHRT_MAX;
1766        else
1767                return fifo_size - wm;
1768}
1769
1770/*
1771 * Starting from 'level' set all higher
1772 * levels to 'value' in the "raw" watermarks.
1773 */
1774static bool vlv_raw_plane_wm_set(struct intel_crtc_state *crtc_state,
1775                                 int level, enum plane_id plane_id, u16 value)
1776{
1777        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1778        int num_levels = intel_wm_num_levels(dev_priv);
1779        bool dirty = false;
1780
1781        for (; level < num_levels; level++) {
1782                struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1783
1784                dirty |= raw->plane[plane_id] != value;
1785                raw->plane[plane_id] = value;
1786        }
1787
1788        return dirty;
1789}
1790
1791static bool vlv_raw_plane_wm_compute(struct intel_crtc_state *crtc_state,
1792                                     const struct intel_plane_state *plane_state)
1793{
1794        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1795        enum plane_id plane_id = plane->id;
1796        int num_levels = intel_wm_num_levels(to_i915(plane->base.dev));
1797        int level;
1798        bool dirty = false;
1799
1800        if (!intel_wm_plane_visible(crtc_state, plane_state)) {
1801                dirty |= vlv_raw_plane_wm_set(crtc_state, 0, plane_id, 0);
1802                goto out;
1803        }
1804
1805        for (level = 0; level < num_levels; level++) {
1806                struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1807                int wm = vlv_compute_wm_level(crtc_state, plane_state, level);
1808                int max_wm = plane_id == PLANE_CURSOR ? 63 : 511;
1809
1810                if (wm > max_wm)
1811                        break;
1812
1813                dirty |= raw->plane[plane_id] != wm;
1814                raw->plane[plane_id] = wm;
1815        }
1816
1817        /* mark all higher levels as invalid */
1818        dirty |= vlv_raw_plane_wm_set(crtc_state, level, plane_id, USHRT_MAX);
1819
1820out:
1821        if (dirty)
1822                DRM_DEBUG_KMS("%s watermarks: PM2=%d, PM5=%d, DDR DVFS=%d\n",
1823                              plane->base.name,
1824                              crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM2].plane[plane_id],
1825                              crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM5].plane[plane_id],
1826                              crtc_state->wm.vlv.raw[VLV_WM_LEVEL_DDR_DVFS].plane[plane_id]);
1827
1828        return dirty;
1829}
1830
1831static bool vlv_raw_plane_wm_is_valid(const struct intel_crtc_state *crtc_state,
1832                                      enum plane_id plane_id, int level)
1833{
1834        const struct g4x_pipe_wm *raw =
1835                &crtc_state->wm.vlv.raw[level];
1836        const struct vlv_fifo_state *fifo_state =
1837                &crtc_state->wm.vlv.fifo_state;
1838
1839        return raw->plane[plane_id] <= fifo_state->plane[plane_id];
1840}
1841
1842static bool vlv_raw_crtc_wm_is_valid(const struct intel_crtc_state *crtc_state, int level)
1843{
1844        return vlv_raw_plane_wm_is_valid(crtc_state, PLANE_PRIMARY, level) &&
1845                vlv_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE0, level) &&
1846                vlv_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE1, level) &&
1847                vlv_raw_plane_wm_is_valid(crtc_state, PLANE_CURSOR, level);
1848}
1849
1850static int vlv_compute_pipe_wm(struct intel_crtc_state *crtc_state)
1851{
1852        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1853        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1854        struct intel_atomic_state *state =
1855                to_intel_atomic_state(crtc_state->base.state);
1856        struct vlv_wm_state *wm_state = &crtc_state->wm.vlv.optimal;
1857        const struct vlv_fifo_state *fifo_state =
1858                &crtc_state->wm.vlv.fifo_state;
1859        int num_active_planes = hweight32(crtc_state->active_planes &
1860                                          ~BIT(PLANE_CURSOR));
1861        bool needs_modeset = drm_atomic_crtc_needs_modeset(&crtc_state->base);
1862        const struct intel_plane_state *old_plane_state;
1863        const struct intel_plane_state *new_plane_state;
1864        struct intel_plane *plane;
1865        enum plane_id plane_id;
1866        int level, ret, i;
1867        unsigned int dirty = 0;
1868
1869        for_each_oldnew_intel_plane_in_state(state, plane,
1870                                             old_plane_state,
1871                                             new_plane_state, i) {
1872                if (new_plane_state->base.crtc != &crtc->base &&
1873                    old_plane_state->base.crtc != &crtc->base)
1874                        continue;
1875
1876                if (vlv_raw_plane_wm_compute(crtc_state, new_plane_state))
1877                        dirty |= BIT(plane->id);
1878        }
1879
1880        /*
1881         * DSPARB registers may have been reset due to the
1882         * power well being turned off. Make sure we restore
1883         * them to a consistent state even if no primary/sprite
1884         * planes are initially active.
1885         */
1886        if (needs_modeset)
1887                crtc_state->fifo_changed = true;
1888
1889        if (!dirty)
1890                return 0;
1891
1892        /* cursor changes don't warrant a FIFO recompute */
1893        if (dirty & ~BIT(PLANE_CURSOR)) {
1894                const struct intel_crtc_state *old_crtc_state =
1895                        intel_atomic_get_old_crtc_state(state, crtc);
1896                const struct vlv_fifo_state *old_fifo_state =
1897                        &old_crtc_state->wm.vlv.fifo_state;
1898
1899                ret = vlv_compute_fifo(crtc_state);
1900                if (ret)
1901                        return ret;
1902
1903                if (needs_modeset ||
1904                    memcmp(old_fifo_state, fifo_state,
1905                           sizeof(*fifo_state)) != 0)
1906                        crtc_state->fifo_changed = true;
1907        }
1908
1909        /* initially allow all levels */
1910        wm_state->num_levels = intel_wm_num_levels(dev_priv);
1911        /*
1912         * Note that enabling cxsr with no primary/sprite planes
1913         * enabled can wedge the pipe. Hence we only allow cxsr
1914         * with exactly one enabled primary/sprite plane.
1915         */
1916        wm_state->cxsr = crtc->pipe != PIPE_C && num_active_planes == 1;
1917
1918        for (level = 0; level < wm_state->num_levels; level++) {
1919                const struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1920                const int sr_fifo_size = INTEL_INFO(dev_priv)->num_pipes * 512 - 1;
1921
1922                if (!vlv_raw_crtc_wm_is_valid(crtc_state, level))
1923                        break;
1924
1925                for_each_plane_id_on_crtc(crtc, plane_id) {
1926                        wm_state->wm[level].plane[plane_id] =
1927                                vlv_invert_wm_value(raw->plane[plane_id],
1928                                                    fifo_state->plane[plane_id]);
1929                }
1930
1931                wm_state->sr[level].plane =
1932                        vlv_invert_wm_value(max3(raw->plane[PLANE_PRIMARY],
1933                                                 raw->plane[PLANE_SPRITE0],
1934                                                 raw->plane[PLANE_SPRITE1]),
1935                                            sr_fifo_size);
1936
1937                wm_state->sr[level].cursor =
1938                        vlv_invert_wm_value(raw->plane[PLANE_CURSOR],
1939                                            63);
1940        }
1941
1942        if (level == 0)
1943                return -EINVAL;
1944
1945        /* limit to only levels we can actually handle */
1946        wm_state->num_levels = level;
1947
1948        /* invalidate the higher levels */
1949        vlv_invalidate_wms(crtc, wm_state, level);
1950
1951        return 0;
1952}
1953
1954#define VLV_FIFO(plane, value) \
1955        (((value) << DSPARB_ ## plane ## _SHIFT_VLV) & DSPARB_ ## plane ## _MASK_VLV)
1956
1957static void vlv_atomic_update_fifo(struct intel_atomic_state *state,
1958                                   struct intel_crtc_state *crtc_state)
1959{
1960        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1961        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1962        struct intel_uncore *uncore = &dev_priv->uncore;
1963        const struct vlv_fifo_state *fifo_state =
1964                &crtc_state->wm.vlv.fifo_state;
1965        int sprite0_start, sprite1_start, fifo_size;
1966
1967        if (!crtc_state->fifo_changed)
1968                return;
1969
1970        sprite0_start = fifo_state->plane[PLANE_PRIMARY];
1971        sprite1_start = fifo_state->plane[PLANE_SPRITE0] + sprite0_start;
1972        fifo_size = fifo_state->plane[PLANE_SPRITE1] + sprite1_start;
1973
1974        WARN_ON(fifo_state->plane[PLANE_CURSOR] != 63);
1975        WARN_ON(fifo_size != 511);
1976
1977        trace_vlv_fifo_size(crtc, sprite0_start, sprite1_start, fifo_size);
1978
1979        /*
1980         * uncore.lock serves a double purpose here. It allows us to
1981         * use the less expensive I915_{READ,WRITE}_FW() functions, and
1982         * it protects the DSPARB registers from getting clobbered by
1983         * parallel updates from multiple pipes.
1984         *
1985         * intel_pipe_update_start() has already disabled interrupts
1986         * for us, so a plain spin_lock() is sufficient here.
1987         */
1988        spin_lock(&uncore->lock);
1989
1990        switch (crtc->pipe) {
1991                u32 dsparb, dsparb2, dsparb3;
1992        case PIPE_A:
1993                dsparb = intel_uncore_read_fw(uncore, DSPARB);
1994                dsparb2 = intel_uncore_read_fw(uncore, DSPARB2);
1995
1996                dsparb &= ~(VLV_FIFO(SPRITEA, 0xff) |
1997                            VLV_FIFO(SPRITEB, 0xff));
1998                dsparb |= (VLV_FIFO(SPRITEA, sprite0_start) |
1999                           VLV_FIFO(SPRITEB, sprite1_start));
2000
2001                dsparb2 &= ~(VLV_FIFO(SPRITEA_HI, 0x1) |
2002                             VLV_FIFO(SPRITEB_HI, 0x1));
2003                dsparb2 |= (VLV_FIFO(SPRITEA_HI, sprite0_start >> 8) |
2004                           VLV_FIFO(SPRITEB_HI, sprite1_start >> 8));
2005
2006                intel_uncore_write_fw(uncore, DSPARB, dsparb);
2007                intel_uncore_write_fw(uncore, DSPARB2, dsparb2);
2008                break;
2009        case PIPE_B:
2010                dsparb = intel_uncore_read_fw(uncore, DSPARB);
2011                dsparb2 = intel_uncore_read_fw(uncore, DSPARB2);
2012
2013                dsparb &= ~(VLV_FIFO(SPRITEC, 0xff) |
2014                            VLV_FIFO(SPRITED, 0xff));
2015                dsparb |= (VLV_FIFO(SPRITEC, sprite0_start) |
2016                           VLV_FIFO(SPRITED, sprite1_start));
2017
2018                dsparb2 &= ~(VLV_FIFO(SPRITEC_HI, 0xff) |
2019                             VLV_FIFO(SPRITED_HI, 0xff));
2020                dsparb2 |= (VLV_FIFO(SPRITEC_HI, sprite0_start >> 8) |
2021                           VLV_FIFO(SPRITED_HI, sprite1_start >> 8));
2022
2023                intel_uncore_write_fw(uncore, DSPARB, dsparb);
2024                intel_uncore_write_fw(uncore, DSPARB2, dsparb2);
2025                break;
2026        case PIPE_C:
2027                dsparb3 = intel_uncore_read_fw(uncore, DSPARB3);
2028                dsparb2 = intel_uncore_read_fw(uncore, DSPARB2);
2029
2030                dsparb3 &= ~(VLV_FIFO(SPRITEE, 0xff) |
2031                             VLV_FIFO(SPRITEF, 0xff));
2032                dsparb3 |= (VLV_FIFO(SPRITEE, sprite0_start) |
2033                            VLV_FIFO(SPRITEF, sprite1_start));
2034
2035                dsparb2 &= ~(VLV_FIFO(SPRITEE_HI, 0xff) |
2036                             VLV_FIFO(SPRITEF_HI, 0xff));
2037                dsparb2 |= (VLV_FIFO(SPRITEE_HI, sprite0_start >> 8) |
2038                           VLV_FIFO(SPRITEF_HI, sprite1_start >> 8));
2039
2040                intel_uncore_write_fw(uncore, DSPARB3, dsparb3);
2041                intel_uncore_write_fw(uncore, DSPARB2, dsparb2);
2042                break;
2043        default:
2044                break;
2045        }
2046
2047        intel_uncore_posting_read_fw(uncore, DSPARB);
2048
2049        spin_unlock(&uncore->lock);
2050}
2051
2052#undef VLV_FIFO
2053
2054static int vlv_compute_intermediate_wm(struct intel_crtc_state *new_crtc_state)
2055{
2056        struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
2057        struct vlv_wm_state *intermediate = &new_crtc_state->wm.vlv.intermediate;
2058        const struct vlv_wm_state *optimal = &new_crtc_state->wm.vlv.optimal;
2059        struct intel_atomic_state *intel_state =
2060                to_intel_atomic_state(new_crtc_state->base.state);
2061        const struct intel_crtc_state *old_crtc_state =
2062                intel_atomic_get_old_crtc_state(intel_state, crtc);
2063        const struct vlv_wm_state *active = &old_crtc_state->wm.vlv.optimal;
2064        int level;
2065
2066        if (!new_crtc_state->base.active || drm_atomic_crtc_needs_modeset(&new_crtc_state->base)) {
2067                *intermediate = *optimal;
2068
2069                intermediate->cxsr = false;
2070                goto out;
2071        }
2072
2073        intermediate->num_levels = min(optimal->num_levels, active->num_levels);
2074        intermediate->cxsr = optimal->cxsr && active->cxsr &&
2075                !new_crtc_state->disable_cxsr;
2076
2077        for (level = 0; level < intermediate->num_levels; level++) {
2078                enum plane_id plane_id;
2079
2080                for_each_plane_id_on_crtc(crtc, plane_id) {
2081                        intermediate->wm[level].plane[plane_id] =
2082                                min(optimal->wm[level].plane[plane_id],
2083                                    active->wm[level].plane[plane_id]);
2084                }
2085
2086                intermediate->sr[level].plane = min(optimal->sr[level].plane,
2087                                                    active->sr[level].plane);
2088                intermediate->sr[level].cursor = min(optimal->sr[level].cursor,
2089                                                     active->sr[level].cursor);
2090        }
2091
2092        vlv_invalidate_wms(crtc, intermediate, level);
2093
2094out:
2095        /*
2096         * If our intermediate WM are identical to the final WM, then we can
2097         * omit the post-vblank programming; only update if it's different.
2098         */
2099        if (memcmp(intermediate, optimal, sizeof(*intermediate)) != 0)
2100                new_crtc_state->wm.need_postvbl_update = true;
2101
2102        return 0;
2103}
2104
2105static void vlv_merge_wm(struct drm_i915_private *dev_priv,
2106                         struct vlv_wm_values *wm)
2107{
2108        struct intel_crtc *crtc;
2109        int num_active_crtcs = 0;
2110
2111        wm->level = dev_priv->wm.max_level;
2112        wm->cxsr = true;
2113
2114        for_each_intel_crtc(&dev_priv->drm, crtc) {
2115                const struct vlv_wm_state *wm_state = &crtc->wm.active.vlv;
2116
2117                if (!crtc->active)
2118                        continue;
2119
2120                if (!wm_state->cxsr)
2121                        wm->cxsr = false;
2122
2123                num_active_crtcs++;
2124                wm->level = min_t(int, wm->level, wm_state->num_levels - 1);
2125        }
2126
2127        if (num_active_crtcs != 1)
2128                wm->cxsr = false;
2129
2130        if (num_active_crtcs > 1)
2131                wm->level = VLV_WM_LEVEL_PM2;
2132
2133        for_each_intel_crtc(&dev_priv->drm, crtc) {
2134                const struct vlv_wm_state *wm_state = &crtc->wm.active.vlv;
2135                enum pipe pipe = crtc->pipe;
2136
2137                wm->pipe[pipe] = wm_state->wm[wm->level];
2138                if (crtc->active && wm->cxsr)
2139                        wm->sr = wm_state->sr[wm->level];
2140
2141                wm->ddl[pipe].plane[PLANE_PRIMARY] = DDL_PRECISION_HIGH | 2;
2142                wm->ddl[pipe].plane[PLANE_SPRITE0] = DDL_PRECISION_HIGH | 2;
2143                wm->ddl[pipe].plane[PLANE_SPRITE1] = DDL_PRECISION_HIGH | 2;
2144                wm->ddl[pipe].plane[PLANE_CURSOR] = DDL_PRECISION_HIGH | 2;
2145        }
2146}
2147
2148static void vlv_program_watermarks(struct drm_i915_private *dev_priv)
2149{
2150        struct vlv_wm_values *old_wm = &dev_priv->wm.vlv;
2151        struct vlv_wm_values new_wm = {};
2152
2153        vlv_merge_wm(dev_priv, &new_wm);
2154
2155        if (memcmp(old_wm, &new_wm, sizeof(new_wm)) == 0)
2156                return;
2157
2158        if (is_disabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_DDR_DVFS))
2159                chv_set_memory_dvfs(dev_priv, false);
2160
2161        if (is_disabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_PM5))
2162                chv_set_memory_pm5(dev_priv, false);
2163
2164        if (is_disabling(old_wm->cxsr, new_wm.cxsr, true))
2165                _intel_set_memory_cxsr(dev_priv, false);
2166
2167        vlv_write_wm_values(dev_priv, &new_wm);
2168
2169        if (is_enabling(old_wm->cxsr, new_wm.cxsr, true))
2170                _intel_set_memory_cxsr(dev_priv, true);
2171
2172        if (is_enabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_PM5))
2173                chv_set_memory_pm5(dev_priv, true);
2174
2175        if (is_enabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_DDR_DVFS))
2176                chv_set_memory_dvfs(dev_priv, true);
2177
2178        *old_wm = new_wm;
2179}
2180
2181static void vlv_initial_watermarks(struct intel_atomic_state *state,
2182                                   struct intel_crtc_state *crtc_state)
2183{
2184        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2185        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2186
2187        mutex_lock(&dev_priv->wm.wm_mutex);
2188        crtc->wm.active.vlv = crtc_state->wm.vlv.intermediate;
2189        vlv_program_watermarks(dev_priv);
2190        mutex_unlock(&dev_priv->wm.wm_mutex);
2191}
2192
2193static void vlv_optimize_watermarks(struct intel_atomic_state *state,
2194                                    struct intel_crtc_state *crtc_state)
2195{
2196        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2197        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2198
2199        if (!crtc_state->wm.need_postvbl_update)
2200                return;
2201
2202        mutex_lock(&dev_priv->wm.wm_mutex);
2203        crtc->wm.active.vlv = crtc_state->wm.vlv.optimal;
2204        vlv_program_watermarks(dev_priv);
2205        mutex_unlock(&dev_priv->wm.wm_mutex);
2206}
2207
2208static void i965_update_wm(struct intel_crtc *unused_crtc)
2209{
2210        struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2211        struct intel_crtc *crtc;
2212        int srwm = 1;
2213        int cursor_sr = 16;
2214        bool cxsr_enabled;
2215
2216        /* Calc sr entries for one plane configs */
2217        crtc = single_enabled_crtc(dev_priv);
2218        if (crtc) {
2219                /* self-refresh has much higher latency */
2220                static const int sr_latency_ns = 12000;
2221                const struct drm_display_mode *adjusted_mode =
2222                        &crtc->config->base.adjusted_mode;
2223                const struct drm_framebuffer *fb =
2224                        crtc->base.primary->state->fb;
2225                int clock = adjusted_mode->crtc_clock;
2226                int htotal = adjusted_mode->crtc_htotal;
2227                int hdisplay = crtc->config->pipe_src_w;
2228                int cpp = fb->format->cpp[0];
2229                int entries;
2230
2231                entries = intel_wm_method2(clock, htotal,
2232                                           hdisplay, cpp, sr_latency_ns / 100);
2233                entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
2234                srwm = I965_FIFO_SIZE - entries;
2235                if (srwm < 0)
2236                        srwm = 1;
2237                srwm &= 0x1ff;
2238                DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
2239                              entries, srwm);
2240
2241                entries = intel_wm_method2(clock, htotal,
2242                                           crtc->base.cursor->state->crtc_w, 4,
2243                                           sr_latency_ns / 100);
2244                entries = DIV_ROUND_UP(entries,
2245                                       i965_cursor_wm_info.cacheline_size) +
2246                        i965_cursor_wm_info.guard_size;
2247
2248                cursor_sr = i965_cursor_wm_info.fifo_size - entries;
2249                if (cursor_sr > i965_cursor_wm_info.max_wm)
2250                        cursor_sr = i965_cursor_wm_info.max_wm;
2251
2252                DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
2253                              "cursor %d\n", srwm, cursor_sr);
2254
2255                cxsr_enabled = true;
2256        } else {
2257                cxsr_enabled = false;
2258                /* Turn off self refresh if both pipes are enabled */
2259                intel_set_memory_cxsr(dev_priv, false);
2260        }
2261
2262        DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
2263                      srwm);
2264
2265        /* 965 has limitations... */
2266        I915_WRITE(DSPFW1, FW_WM(srwm, SR) |
2267                   FW_WM(8, CURSORB) |
2268                   FW_WM(8, PLANEB) |
2269                   FW_WM(8, PLANEA));
2270        I915_WRITE(DSPFW2, FW_WM(8, CURSORA) |
2271                   FW_WM(8, PLANEC_OLD));
2272        /* update cursor SR watermark */
2273        I915_WRITE(DSPFW3, FW_WM(cursor_sr, CURSOR_SR));
2274
2275        if (cxsr_enabled)
2276                intel_set_memory_cxsr(dev_priv, true);
2277}
2278
2279#undef FW_WM
2280
2281static void i9xx_update_wm(struct intel_crtc *unused_crtc)
2282{
2283        struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2284        const struct intel_watermark_params *wm_info;
2285        u32 fwater_lo;
2286        u32 fwater_hi;
2287        int cwm, srwm = 1;
2288        int fifo_size;
2289        int planea_wm, planeb_wm;
2290        struct intel_crtc *crtc, *enabled = NULL;
2291
2292        if (IS_I945GM(dev_priv))
2293                wm_info = &i945_wm_info;
2294        else if (!IS_GEN(dev_priv, 2))
2295                wm_info = &i915_wm_info;
2296        else
2297                wm_info = &i830_a_wm_info;
2298
2299        fifo_size = dev_priv->display.get_fifo_size(dev_priv, PLANE_A);
2300        crtc = intel_get_crtc_for_plane(dev_priv, PLANE_A);
2301        if (intel_crtc_active(crtc)) {
2302                const struct drm_display_mode *adjusted_mode =
2303                        &crtc->config->base.adjusted_mode;
2304                const struct drm_framebuffer *fb =
2305                        crtc->base.primary->state->fb;
2306                int cpp;
2307
2308                if (IS_GEN(dev_priv, 2))
2309                        cpp = 4;
2310                else
2311                        cpp = fb->format->cpp[0];
2312
2313                planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2314                                               wm_info, fifo_size, cpp,
2315                                               pessimal_latency_ns);
2316                enabled = crtc;
2317        } else {
2318                planea_wm = fifo_size - wm_info->guard_size;
2319                if (planea_wm > (long)wm_info->max_wm)
2320                        planea_wm = wm_info->max_wm;
2321        }
2322
2323        if (IS_GEN(dev_priv, 2))
2324                wm_info = &i830_bc_wm_info;
2325
2326        fifo_size = dev_priv->display.get_fifo_size(dev_priv, PLANE_B);
2327        crtc = intel_get_crtc_for_plane(dev_priv, PLANE_B);
2328        if (intel_crtc_active(crtc)) {
2329                const struct drm_display_mode *adjusted_mode =
2330                        &crtc->config->base.adjusted_mode;
2331                const struct drm_framebuffer *fb =
2332                        crtc->base.primary->state->fb;
2333                int cpp;
2334
2335                if (IS_GEN(dev_priv, 2))
2336                        cpp = 4;
2337                else
2338                        cpp = fb->format->cpp[0];
2339
2340                planeb_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2341                                               wm_info, fifo_size, cpp,
2342                                               pessimal_latency_ns);
2343                if (enabled == NULL)
2344                        enabled = crtc;
2345                else
2346                        enabled = NULL;
2347        } else {
2348                planeb_wm = fifo_size - wm_info->guard_size;
2349                if (planeb_wm > (long)wm_info->max_wm)
2350                        planeb_wm = wm_info->max_wm;
2351        }
2352
2353        DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
2354
2355        if (IS_I915GM(dev_priv) && enabled) {
2356                struct drm_i915_gem_object *obj;
2357
2358                obj = intel_fb_obj(enabled->base.primary->state->fb);
2359
2360                /* self-refresh seems busted with untiled */
2361                if (!i915_gem_object_is_tiled(obj))
2362                        enabled = NULL;
2363        }
2364
2365        /*
2366         * Overlay gets an aggressive default since video jitter is bad.
2367         */
2368        cwm = 2;
2369
2370        /* Play safe and disable self-refresh before adjusting watermarks. */
2371        intel_set_memory_cxsr(dev_priv, false);
2372
2373        /* Calc sr entries for one plane configs */
2374        if (HAS_FW_BLC(dev_priv) && enabled) {
2375                /* self-refresh has much higher latency */
2376                static const int sr_latency_ns = 6000;
2377                const struct drm_display_mode *adjusted_mode =
2378                        &enabled->config->base.adjusted_mode;
2379                const struct drm_framebuffer *fb =
2380                        enabled->base.primary->state->fb;
2381                int clock = adjusted_mode->crtc_clock;
2382                int htotal = adjusted_mode->crtc_htotal;
2383                int hdisplay = enabled->config->pipe_src_w;
2384                int cpp;
2385                int entries;
2386
2387                if (IS_I915GM(dev_priv) || IS_I945GM(dev_priv))
2388                        cpp = 4;
2389                else
2390                        cpp = fb->format->cpp[0];
2391
2392                entries = intel_wm_method2(clock, htotal, hdisplay, cpp,
2393                                           sr_latency_ns / 100);
2394                entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
2395                DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
2396                srwm = wm_info->fifo_size - entries;
2397                if (srwm < 0)
2398                        srwm = 1;
2399
2400                if (IS_I945G(dev_priv) || IS_I945GM(dev_priv))
2401                        I915_WRITE(FW_BLC_SELF,
2402                                   FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
2403                else
2404                        I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
2405        }
2406
2407        DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
2408                      planea_wm, planeb_wm, cwm, srwm);
2409
2410        fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
2411        fwater_hi = (cwm & 0x1f);
2412
2413        /* Set request length to 8 cachelines per fetch */
2414        fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
2415        fwater_hi = fwater_hi | (1 << 8);
2416
2417        I915_WRITE(FW_BLC, fwater_lo);
2418        I915_WRITE(FW_BLC2, fwater_hi);
2419
2420        if (enabled)
2421                intel_set_memory_cxsr(dev_priv, true);
2422}
2423
2424static void i845_update_wm(struct intel_crtc *unused_crtc)
2425{
2426        struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2427        struct intel_crtc *crtc;
2428        const struct drm_display_mode *adjusted_mode;
2429        u32 fwater_lo;
2430        int planea_wm;
2431
2432        crtc = single_enabled_crtc(dev_priv);
2433        if (crtc == NULL)
2434                return;
2435
2436        adjusted_mode = &crtc->config->base.adjusted_mode;
2437        planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2438                                       &i845_wm_info,
2439                                       dev_priv->display.get_fifo_size(dev_priv, PLANE_A),
2440                                       4, pessimal_latency_ns);
2441        fwater_lo = I915_READ(FW_BLC) & ~0xfff;
2442        fwater_lo |= (3<<8) | planea_wm;
2443
2444        DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
2445
2446        I915_WRITE(FW_BLC, fwater_lo);
2447}
2448
2449/* latency must be in 0.1us units. */
2450static unsigned int ilk_wm_method1(unsigned int pixel_rate,
2451                                   unsigned int cpp,
2452                                   unsigned int latency)
2453{
2454        unsigned int ret;
2455
2456        ret = intel_wm_method1(pixel_rate, cpp, latency);
2457        ret = DIV_ROUND_UP(ret, 64) + 2;
2458
2459        return ret;
2460}
2461
2462/* latency must be in 0.1us units. */
2463static unsigned int ilk_wm_method2(unsigned int pixel_rate,
2464                                   unsigned int htotal,
2465                                   unsigned int width,
2466                                   unsigned int cpp,
2467                                   unsigned int latency)
2468{
2469        unsigned int ret;
2470
2471        ret = intel_wm_method2(pixel_rate, htotal,
2472                               width, cpp, latency);
2473        ret = DIV_ROUND_UP(ret, 64) + 2;
2474
2475        return ret;
2476}
2477
2478static u32 ilk_wm_fbc(u32 pri_val, u32 horiz_pixels, u8 cpp)
2479{
2480        /*
2481         * Neither of these should be possible since this function shouldn't be
2482         * called if the CRTC is off or the plane is invisible.  But let's be
2483         * extra paranoid to avoid a potential divide-by-zero if we screw up
2484         * elsewhere in the driver.
2485         */
2486        if (WARN_ON(!cpp))
2487                return 0;
2488        if (WARN_ON(!horiz_pixels))
2489                return 0;
2490
2491        return DIV_ROUND_UP(pri_val * 64, horiz_pixels * cpp) + 2;
2492}
2493
2494struct ilk_wm_maximums {
2495        u16 pri;
2496        u16 spr;
2497        u16 cur;
2498        u16 fbc;
2499};
2500
2501/*
2502 * For both WM_PIPE and WM_LP.
2503 * mem_value must be in 0.1us units.
2504 */
2505static u32 ilk_compute_pri_wm(const struct intel_crtc_state *crtc_state,
2506                              const struct intel_plane_state *plane_state,
2507                              u32 mem_value, bool is_lp)
2508{
2509        u32 method1, method2;
2510        int cpp;
2511
2512        if (mem_value == 0)
2513                return U32_MAX;
2514
2515        if (!intel_wm_plane_visible(crtc_state, plane_state))
2516                return 0;
2517
2518        cpp = plane_state->base.fb->format->cpp[0];
2519
2520        method1 = ilk_wm_method1(crtc_state->pixel_rate, cpp, mem_value);
2521
2522        if (!is_lp)
2523                return method1;
2524
2525        method2 = ilk_wm_method2(crtc_state->pixel_rate,
2526                                 crtc_state->base.adjusted_mode.crtc_htotal,
2527                                 drm_rect_width(&plane_state->base.dst),
2528                                 cpp, mem_value);
2529
2530        return min(method1, method2);
2531}
2532
2533/*
2534 * For both WM_PIPE and WM_LP.
2535 * mem_value must be in 0.1us units.
2536 */
2537static u32 ilk_compute_spr_wm(const struct intel_crtc_state *crtc_state,
2538                              const struct intel_plane_state *plane_state,
2539                              u32 mem_value)
2540{
2541        u32 method1, method2;
2542        int cpp;
2543
2544        if (mem_value == 0)
2545                return U32_MAX;
2546
2547        if (!intel_wm_plane_visible(crtc_state, plane_state))
2548                return 0;
2549
2550        cpp = plane_state->base.fb->format->cpp[0];
2551
2552        method1 = ilk_wm_method1(crtc_state->pixel_rate, cpp, mem_value);
2553        method2 = ilk_wm_method2(crtc_state->pixel_rate,
2554                                 crtc_state->base.adjusted_mode.crtc_htotal,
2555                                 drm_rect_width(&plane_state->base.dst),
2556                                 cpp, mem_value);
2557        return min(method1, method2);
2558}
2559
2560/*
2561 * For both WM_PIPE and WM_LP.
2562 * mem_value must be in 0.1us units.
2563 */
2564static u32 ilk_compute_cur_wm(const struct intel_crtc_state *crtc_state,
2565                              const struct intel_plane_state *plane_state,
2566                              u32 mem_value)
2567{
2568        int cpp;
2569
2570        if (mem_value == 0)
2571                return U32_MAX;
2572
2573        if (!intel_wm_plane_visible(crtc_state, plane_state))
2574                return 0;
2575
2576        cpp = plane_state->base.fb->format->cpp[0];
2577
2578        return ilk_wm_method2(crtc_state->pixel_rate,
2579                              crtc_state->base.adjusted_mode.crtc_htotal,
2580                              plane_state->base.crtc_w, cpp, mem_value);
2581}
2582
2583/* Only for WM_LP. */
2584static u32 ilk_compute_fbc_wm(const struct intel_crtc_state *crtc_state,
2585                              const struct intel_plane_state *plane_state,
2586                              u32 pri_val)
2587{
2588        int cpp;
2589
2590        if (!intel_wm_plane_visible(crtc_state, plane_state))
2591                return 0;
2592
2593        cpp = plane_state->base.fb->format->cpp[0];
2594
2595        return ilk_wm_fbc(pri_val, drm_rect_width(&plane_state->base.dst), cpp);
2596}
2597
2598static unsigned int
2599ilk_display_fifo_size(const struct drm_i915_private *dev_priv)
2600{
2601        if (INTEL_GEN(dev_priv) >= 8)
2602                return 3072;
2603        else if (INTEL_GEN(dev_priv) >= 7)
2604                return 768;
2605        else
2606                return 512;
2607}
2608
2609static unsigned int
2610ilk_plane_wm_reg_max(const struct drm_i915_private *dev_priv,
2611                     int level, bool is_sprite)
2612{
2613        if (INTEL_GEN(dev_priv) >= 8)
2614                /* BDW primary/sprite plane watermarks */
2615                return level == 0 ? 255 : 2047;
2616        else if (INTEL_GEN(dev_priv) >= 7)
2617                /* IVB/HSW primary/sprite plane watermarks */
2618                return level == 0 ? 127 : 1023;
2619        else if (!is_sprite)
2620                /* ILK/SNB primary plane watermarks */
2621                return level == 0 ? 127 : 511;
2622        else
2623                /* ILK/SNB sprite plane watermarks */
2624                return level == 0 ? 63 : 255;
2625}
2626
2627static unsigned int
2628ilk_cursor_wm_reg_max(const struct drm_i915_private *dev_priv, int level)
2629{
2630        if (INTEL_GEN(dev_priv) >= 7)
2631                return level == 0 ? 63 : 255;
2632        else
2633                return level == 0 ? 31 : 63;
2634}
2635
2636static unsigned int ilk_fbc_wm_reg_max(const struct drm_i915_private *dev_priv)
2637{
2638        if (INTEL_GEN(dev_priv) >= 8)
2639                return 31;
2640        else
2641                return 15;
2642}
2643
2644/* Calculate the maximum primary/sprite plane watermark */
2645static unsigned int ilk_plane_wm_max(const struct drm_i915_private *dev_priv,
2646                                     int level,
2647                                     const struct intel_wm_config *config,
2648                                     enum intel_ddb_partitioning ddb_partitioning,
2649                                     bool is_sprite)
2650{
2651        unsigned int fifo_size = ilk_display_fifo_size(dev_priv);
2652
2653        /* if sprites aren't enabled, sprites get nothing */
2654        if (is_sprite && !config->sprites_enabled)
2655                return 0;
2656
2657        /* HSW allows LP1+ watermarks even with multiple pipes */
2658        if (level == 0 || config->num_pipes_active > 1) {
2659                fifo_size /= INTEL_INFO(dev_priv)->num_pipes;
2660
2661                /*
2662                 * For some reason the non self refresh
2663                 * FIFO size is only half of the self
2664                 * refresh FIFO size on ILK/SNB.
2665                 */
2666                if (INTEL_GEN(dev_priv) <= 6)
2667                        fifo_size /= 2;
2668        }
2669
2670        if (config->sprites_enabled) {
2671                /* level 0 is always calculated with 1:1 split */
2672                if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
2673                        if (is_sprite)
2674                                fifo_size *= 5;
2675                        fifo_size /= 6;
2676                } else {
2677                        fifo_size /= 2;
2678                }
2679        }
2680
2681        /* clamp to max that the registers can hold */
2682        return min(fifo_size, ilk_plane_wm_reg_max(dev_priv, level, is_sprite));
2683}
2684
2685/* Calculate the maximum cursor plane watermark */
2686static unsigned int ilk_cursor_wm_max(const struct drm_i915_private *dev_priv,
2687                                      int level,
2688                                      const struct intel_wm_config *config)
2689{
2690        /* HSW LP1+ watermarks w/ multiple pipes */
2691        if (level > 0 && config->num_pipes_active > 1)
2692                return 64;
2693
2694        /* otherwise just report max that registers can hold */
2695        return ilk_cursor_wm_reg_max(dev_priv, level);
2696}
2697
2698static void ilk_compute_wm_maximums(const struct drm_i915_private *dev_priv,
2699                                    int level,
2700                                    const struct intel_wm_config *config,
2701                                    enum intel_ddb_partitioning ddb_partitioning,
2702                                    struct ilk_wm_maximums *max)
2703{
2704        max->pri = ilk_plane_wm_max(dev_priv, level, config, ddb_partitioning, false);
2705        max->spr = ilk_plane_wm_max(dev_priv, level, config, ddb_partitioning, true);
2706        max->cur = ilk_cursor_wm_max(dev_priv, level, config);
2707        max->fbc = ilk_fbc_wm_reg_max(dev_priv);
2708}
2709
2710static void ilk_compute_wm_reg_maximums(const struct drm_i915_private *dev_priv,
2711                                        int level,
2712                                        struct ilk_wm_maximums *max)
2713{
2714        max->pri = ilk_plane_wm_reg_max(dev_priv, level, false);
2715        max->spr = ilk_plane_wm_reg_max(dev_priv, level, true);
2716        max->cur = ilk_cursor_wm_reg_max(dev_priv, level);
2717        max->fbc = ilk_fbc_wm_reg_max(dev_priv);
2718}
2719
2720static bool ilk_validate_wm_level(int level,
2721                                  const struct ilk_wm_maximums *max,
2722                                  struct intel_wm_level *result)
2723{
2724        bool ret;
2725
2726        /* already determined to be invalid? */
2727        if (!result->enable)
2728                return false;
2729
2730        result->enable = result->pri_val <= max->pri &&
2731                         result->spr_val <= max->spr &&
2732                         result->cur_val <= max->cur;
2733
2734        ret = result->enable;
2735
2736        /*
2737         * HACK until we can pre-compute everything,
2738         * and thus fail gracefully if LP0 watermarks
2739         * are exceeded...
2740         */
2741        if (level == 0 && !result->enable) {
2742                if (result->pri_val > max->pri)
2743                        DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
2744                                      level, result->pri_val, max->pri);
2745                if (result->spr_val > max->spr)
2746                        DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
2747                                      level, result->spr_val, max->spr);
2748                if (result->cur_val > max->cur)
2749                        DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
2750                                      level, result->cur_val, max->cur);
2751
2752                result->pri_val = min_t(u32, result->pri_val, max->pri);
2753                result->spr_val = min_t(u32, result->spr_val, max->spr);
2754                result->cur_val = min_t(u32, result->cur_val, max->cur);
2755                result->enable = true;
2756        }
2757
2758        return ret;
2759}
2760
2761static void ilk_compute_wm_level(const struct drm_i915_private *dev_priv,
2762                                 const struct intel_crtc *intel_crtc,
2763                                 int level,
2764                                 struct intel_crtc_state *crtc_state,
2765                                 const struct intel_plane_state *pristate,
2766                                 const struct intel_plane_state *sprstate,
2767                                 const struct intel_plane_state *curstate,
2768                                 struct intel_wm_level *result)
2769{
2770        u16 pri_latency = dev_priv->wm.pri_latency[level];
2771        u16 spr_latency = dev_priv->wm.spr_latency[level];
2772        u16 cur_latency = dev_priv->wm.cur_latency[level];
2773
2774        /* WM1+ latency values stored in 0.5us units */
2775        if (level > 0) {
2776                pri_latency *= 5;
2777                spr_latency *= 5;
2778                cur_latency *= 5;
2779        }
2780
2781        if (pristate) {
2782                result->pri_val = ilk_compute_pri_wm(crtc_state, pristate,
2783                                                     pri_latency, level);
2784                result->fbc_val = ilk_compute_fbc_wm(crtc_state, pristate, result->pri_val);
2785        }
2786
2787        if (sprstate)
2788                result->spr_val = ilk_compute_spr_wm(crtc_state, sprstate, spr_latency);
2789
2790        if (curstate)
2791                result->cur_val = ilk_compute_cur_wm(crtc_state, curstate, cur_latency);
2792
2793        result->enable = true;
2794}
2795
2796static u32
2797hsw_compute_linetime_wm(const struct intel_crtc_state *crtc_state)
2798{
2799        const struct intel_atomic_state *intel_state =
2800                to_intel_atomic_state(crtc_state->base.state);
2801        const struct drm_display_mode *adjusted_mode =
2802                &crtc_state->base.adjusted_mode;
2803        u32 linetime, ips_linetime;
2804
2805        if (!crtc_state->base.active)
2806                return 0;
2807        if (WARN_ON(adjusted_mode->crtc_clock == 0))
2808                return 0;
2809        if (WARN_ON(intel_state->cdclk.logical.cdclk == 0))
2810                return 0;
2811
2812        /* The WM are computed with base on how long it takes to fill a single
2813         * row at the given clock rate, multiplied by 8.
2814         * */
2815        linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2816                                     adjusted_mode->crtc_clock);
2817        ips_linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2818                                         intel_state->cdclk.logical.cdclk);
2819
2820        return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
2821               PIPE_WM_LINETIME_TIME(linetime);
2822}
2823
2824static void intel_read_wm_latency(struct drm_i915_private *dev_priv,
2825                                  u16 wm[8])
2826{
2827        struct intel_uncore *uncore = &dev_priv->uncore;
2828
2829        if (INTEL_GEN(dev_priv) >= 9) {
2830                u32 val;
2831                int ret, i;
2832                int level, max_level = ilk_wm_max_level(dev_priv);
2833
2834                /* read the first set of memory latencies[0:3] */
2835                val = 0; /* data0 to be programmed to 0 for first set */
2836                ret = sandybridge_pcode_read(dev_priv,
2837                                             GEN9_PCODE_READ_MEM_LATENCY,
2838                                             &val, NULL);
2839
2840                if (ret) {
2841                        DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2842                        return;
2843                }
2844
2845                wm[0] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2846                wm[1] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2847                                GEN9_MEM_LATENCY_LEVEL_MASK;
2848                wm[2] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2849                                GEN9_MEM_LATENCY_LEVEL_MASK;
2850                wm[3] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2851                                GEN9_MEM_LATENCY_LEVEL_MASK;
2852
2853                /* read the second set of memory latencies[4:7] */
2854                val = 1; /* data0 to be programmed to 1 for second set */
2855                ret = sandybridge_pcode_read(dev_priv,
2856                                             GEN9_PCODE_READ_MEM_LATENCY,
2857                                             &val, NULL);
2858                if (ret) {
2859                        DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2860                        return;
2861                }
2862
2863                wm[4] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2864                wm[5] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2865                                GEN9_MEM_LATENCY_LEVEL_MASK;
2866                wm[6] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2867                                GEN9_MEM_LATENCY_LEVEL_MASK;
2868                wm[7] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2869                                GEN9_MEM_LATENCY_LEVEL_MASK;
2870
2871                /*
2872                 * If a level n (n > 1) has a 0us latency, all levels m (m >= n)
2873                 * need to be disabled. We make sure to sanitize the values out
2874                 * of the punit to satisfy this requirement.
2875                 */
2876                for (level = 1; level <= max_level; level++) {
2877                        if (wm[level] == 0) {
2878                                for (i = level + 1; i <= max_level; i++)
2879                                        wm[i] = 0;
2880                                break;
2881                        }
2882                }
2883
2884                /*
2885                 * WaWmMemoryReadLatency:skl+,glk
2886                 *
2887                 * punit doesn't take into account the read latency so we need
2888                 * to add 2us to the various latency levels we retrieve from the
2889                 * punit when level 0 response data us 0us.
2890                 */
2891                if (wm[0] == 0) {
2892                        wm[0] += 2;
2893                        for (level = 1; level <= max_level; level++) {
2894                                if (wm[level] == 0)
2895                                        break;
2896                                wm[level] += 2;
2897                        }
2898                }
2899
2900                /*
2901                 * WA Level-0 adjustment for 16GB DIMMs: SKL+
2902                 * If we could not get dimm info enable this WA to prevent from
2903                 * any underrun. If not able to get Dimm info assume 16GB dimm
2904                 * to avoid any underrun.
2905                 */
2906                if (dev_priv->dram_info.is_16gb_dimm)
2907                        wm[0] += 1;
2908
2909        } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2910                u64 sskpd = intel_uncore_read64(uncore, MCH_SSKPD);
2911
2912                wm[0] = (sskpd >> 56) & 0xFF;
2913                if (wm[0] == 0)
2914                        wm[0] = sskpd & 0xF;
2915                wm[1] = (sskpd >> 4) & 0xFF;
2916                wm[2] = (sskpd >> 12) & 0xFF;
2917                wm[3] = (sskpd >> 20) & 0x1FF;
2918                wm[4] = (sskpd >> 32) & 0x1FF;
2919        } else if (INTEL_GEN(dev_priv) >= 6) {
2920                u32 sskpd = intel_uncore_read(uncore, MCH_SSKPD);
2921
2922                wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
2923                wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
2924                wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
2925                wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
2926        } else if (INTEL_GEN(dev_priv) >= 5) {
2927                u32 mltr = intel_uncore_read(uncore, MLTR_ILK);
2928
2929                /* ILK primary LP0 latency is 700 ns */
2930                wm[0] = 7;
2931                wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
2932                wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
2933        } else {
2934                MISSING_CASE(INTEL_DEVID(dev_priv));
2935        }
2936}
2937
2938static void intel_fixup_spr_wm_latency(struct drm_i915_private *dev_priv,
2939                                       u16 wm[5])
2940{
2941        /* ILK sprite LP0 latency is 1300 ns */
2942        if (IS_GEN(dev_priv, 5))
2943                wm[0] = 13;
2944}
2945
2946static void intel_fixup_cur_wm_latency(struct drm_i915_private *dev_priv,
2947                                       u16 wm[5])
2948{
2949        /* ILK cursor LP0 latency is 1300 ns */
2950        if (IS_GEN(dev_priv, 5))
2951                wm[0] = 13;
2952}
2953
2954int ilk_wm_max_level(const struct drm_i915_private *dev_priv)
2955{
2956        /* how many WM levels are we expecting */
2957        if (INTEL_GEN(dev_priv) >= 9)
2958                return 7;
2959        else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2960                return 4;
2961        else if (INTEL_GEN(dev_priv) >= 6)
2962                return 3;
2963        else
2964                return 2;
2965}
2966
2967static void intel_print_wm_latency(struct drm_i915_private *dev_priv,
2968                                   const char *name,
2969                                   const u16 wm[8])
2970{
2971        int level, max_level = ilk_wm_max_level(dev_priv);
2972
2973        for (level = 0; level <= max_level; level++) {
2974                unsigned int latency = wm[level];
2975
2976                if (latency == 0) {
2977                        DRM_DEBUG_KMS("%s WM%d latency not provided\n",
2978                                      name, level);
2979                        continue;
2980                }
2981
2982                /*
2983                 * - latencies are in us on gen9.
2984                 * - before then, WM1+ latency values are in 0.5us units
2985                 */
2986                if (INTEL_GEN(dev_priv) >= 9)
2987                        latency *= 10;
2988                else if (level > 0)
2989                        latency *= 5;
2990
2991                DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
2992                              name, level, wm[level],
2993                              latency / 10, latency % 10);
2994        }
2995}
2996
2997static bool ilk_increase_wm_latency(struct drm_i915_private *dev_priv,
2998                                    u16 wm[5], u16 min)
2999{
3000        int level, max_level = ilk_wm_max_level(dev_priv);
3001
3002        if (wm[0] >= min)
3003                return false;
3004
3005        wm[0] = max(wm[0], min);
3006        for (level = 1; level <= max_level; level++)
3007                wm[level] = max_t(u16, wm[level], DIV_ROUND_UP(min, 5));
3008
3009        return true;
3010}
3011
3012static void snb_wm_latency_quirk(struct drm_i915_private *dev_priv)
3013{
3014        bool changed;
3015
3016        /*
3017         * The BIOS provided WM memory latency values are often
3018         * inadequate for high resolution displays. Adjust them.
3019         */
3020        changed = ilk_increase_wm_latency(dev_priv, dev_priv->wm.pri_latency, 12) |
3021                ilk_increase_wm_latency(dev_priv, dev_priv->wm.spr_latency, 12) |
3022                ilk_increase_wm_latency(dev_priv, dev_priv->wm.cur_latency, 12);
3023
3024        if (!changed)
3025                return;
3026
3027        DRM_DEBUG_KMS("WM latency values increased to avoid potential underruns\n");
3028        intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
3029        intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
3030        intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
3031}
3032
3033static void snb_wm_lp3_irq_quirk(struct drm_i915_private *dev_priv)
3034{
3035        /*
3036         * On some SNB machines (Thinkpad X220 Tablet at least)
3037         * LP3 usage can cause vblank interrupts to be lost.
3038         * The DEIIR bit will go high but it looks like the CPU
3039         * never gets interrupted.
3040         *
3041         * It's not clear whether other interrupt source could
3042         * be affected or if this is somehow limited to vblank
3043         * interrupts only. To play it safe we disable LP3
3044         * watermarks entirely.
3045         */
3046        if (dev_priv->wm.pri_latency[3] == 0 &&
3047            dev_priv->wm.spr_latency[3] == 0 &&
3048            dev_priv->wm.cur_latency[3] == 0)
3049                return;
3050
3051        dev_priv->wm.pri_latency[3] = 0;
3052        dev_priv->wm.spr_latency[3] = 0;
3053        dev_priv->wm.cur_latency[3] = 0;
3054
3055        DRM_DEBUG_KMS("LP3 watermarks disabled due to potential for lost interrupts\n");
3056        intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
3057        intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
3058        intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
3059}
3060
3061static void ilk_setup_wm_latency(struct drm_i915_private *dev_priv)
3062{
3063        intel_read_wm_latency(dev_priv, dev_priv->wm.pri_latency);
3064
3065        memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
3066               sizeof(dev_priv->wm.pri_latency));
3067        memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
3068               sizeof(dev_priv->wm.pri_latency));
3069
3070        intel_fixup_spr_wm_latency(dev_priv, dev_priv->wm.spr_latency);
3071        intel_fixup_cur_wm_latency(dev_priv, dev_priv->wm.cur_latency);
3072
3073        intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
3074        intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
3075        intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
3076
3077        if (IS_GEN(dev_priv, 6)) {
3078                snb_wm_latency_quirk(dev_priv);
3079                snb_wm_lp3_irq_quirk(dev_priv);
3080        }
3081}
3082
3083static void skl_setup_wm_latency(struct drm_i915_private *dev_priv)
3084{
3085        intel_read_wm_latency(dev_priv, dev_priv->wm.skl_latency);
3086        intel_print_wm_latency(dev_priv, "Gen9 Plane", dev_priv->wm.skl_latency);
3087}
3088
3089static bool ilk_validate_pipe_wm(const struct drm_i915_private *dev_priv,
3090                                 struct intel_pipe_wm *pipe_wm)
3091{
3092        /* LP0 watermark maximums depend on this pipe alone */
3093        const struct intel_wm_config config = {
3094                .num_pipes_active = 1,
3095                .sprites_enabled = pipe_wm->sprites_enabled,
3096                .sprites_scaled = pipe_wm->sprites_scaled,
3097        };
3098        struct ilk_wm_maximums max;
3099
3100        /* LP0 watermarks always use 1/2 DDB partitioning */
3101        ilk_compute_wm_maximums(dev_priv, 0, &config, INTEL_DDB_PART_1_2, &max);
3102
3103        /* At least LP0 must be valid */
3104        if (!ilk_validate_wm_level(0, &max, &pipe_wm->wm[0])) {
3105                DRM_DEBUG_KMS("LP0 watermark invalid\n");
3106                return false;
3107        }
3108
3109        return true;
3110}
3111
3112/* Compute new watermarks for the pipe */
3113static int ilk_compute_pipe_wm(struct intel_crtc_state *crtc_state)
3114{
3115        struct drm_atomic_state *state = crtc_state->base.state;
3116        struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3117        struct intel_pipe_wm *pipe_wm;
3118        struct drm_device *dev = state->dev;
3119        const struct drm_i915_private *dev_priv = to_i915(dev);
3120        struct drm_plane *plane;
3121        const struct drm_plane_state *plane_state;
3122        const struct intel_plane_state *pristate = NULL;
3123        const struct intel_plane_state *sprstate = NULL;
3124        const struct intel_plane_state *curstate = NULL;
3125        int level, max_level = ilk_wm_max_level(dev_priv), usable_level;
3126        struct ilk_wm_maximums max;
3127
3128        pipe_wm = &crtc_state->wm.ilk.optimal;
3129
3130        drm_atomic_crtc_state_for_each_plane_state(plane, plane_state, &crtc_state->base) {
3131                const struct intel_plane_state *ps = to_intel_plane_state(plane_state);
3132
3133                if (plane->type == DRM_PLANE_TYPE_PRIMARY)
3134                        pristate = ps;
3135                else if (plane->type == DRM_PLANE_TYPE_OVERLAY)
3136                        sprstate = ps;
3137                else if (plane->type == DRM_PLANE_TYPE_CURSOR)
3138                        curstate = ps;
3139        }
3140
3141        pipe_wm->pipe_enabled = crtc_state->base.active;
3142        if (sprstate) {
3143                pipe_wm->sprites_enabled = sprstate->base.visible;
3144                pipe_wm->sprites_scaled = sprstate->base.visible &&
3145                        (drm_rect_width(&sprstate->base.dst) != drm_rect_width(&sprstate->base.src) >> 16 ||
3146                         drm_rect_height(&sprstate->base.dst) != drm_rect_height(&sprstate->base.src) >> 16);
3147        }
3148
3149        usable_level = max_level;
3150
3151        /* ILK/SNB: LP2+ watermarks only w/o sprites */
3152        if (INTEL_GEN(dev_priv) <= 6 && pipe_wm->sprites_enabled)
3153                usable_level = 1;
3154
3155        /* ILK/SNB/IVB: LP1+ watermarks only w/o scaling */
3156        if (pipe_wm->sprites_scaled)
3157                usable_level = 0;
3158
3159        memset(&pipe_wm->wm, 0, sizeof(pipe_wm->wm));
3160        ilk_compute_wm_level(dev_priv, intel_crtc, 0, crtc_state,
3161                             pristate, sprstate, curstate, &pipe_wm->wm[0]);
3162
3163        if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3164                pipe_wm->linetime = hsw_compute_linetime_wm(crtc_state);
3165
3166        if (!ilk_validate_pipe_wm(dev_priv, pipe_wm))
3167                return -EINVAL;
3168
3169        ilk_compute_wm_reg_maximums(dev_priv, 1, &max);
3170
3171        for (level = 1; level <= usable_level; level++) {
3172                struct intel_wm_level *wm = &pipe_wm->wm[level];
3173
3174                ilk_compute_wm_level(dev_priv, intel_crtc, level, crtc_state,
3175                                     pristate, sprstate, curstate, wm);
3176
3177                /*
3178                 * Disable any watermark level that exceeds the
3179                 * register maximums since such watermarks are
3180                 * always invalid.
3181                 */
3182                if (!ilk_validate_wm_level(level, &max, wm)) {
3183                        memset(wm, 0, sizeof(*wm));
3184                        break;
3185                }
3186        }
3187
3188        return 0;
3189}
3190
3191/*
3192 * Build a set of 'intermediate' watermark values that satisfy both the old
3193 * state and the new state.  These can be programmed to the hardware
3194 * immediately.
3195 */
3196static int ilk_compute_intermediate_wm(struct intel_crtc_state *newstate)
3197{
3198        struct intel_crtc *intel_crtc = to_intel_crtc(newstate->base.crtc);
3199        struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3200        struct intel_pipe_wm *a = &newstate->wm.ilk.intermediate;
3201        struct intel_atomic_state *intel_state =
3202                to_intel_atomic_state(newstate->base.state);
3203        const struct intel_crtc_state *oldstate =
3204                intel_atomic_get_old_crtc_state(intel_state, intel_crtc);
3205        const struct intel_pipe_wm *b = &oldstate->wm.ilk.optimal;
3206        int level, max_level = ilk_wm_max_level(dev_priv);
3207
3208        /*
3209         * Start with the final, target watermarks, then combine with the
3210         * currently active watermarks to get values that are safe both before
3211         * and after the vblank.
3212         */
3213        *a = newstate->wm.ilk.optimal;
3214        if (!newstate->base.active || drm_atomic_crtc_needs_modeset(&newstate->base) ||
3215            intel_state->skip_intermediate_wm)
3216                return 0;
3217
3218        a->pipe_enabled |= b->pipe_enabled;
3219        a->sprites_enabled |= b->sprites_enabled;
3220        a->sprites_scaled |= b->sprites_scaled;
3221
3222        for (level = 0; level <= max_level; level++) {
3223                struct intel_wm_level *a_wm = &a->wm[level];
3224                const struct intel_wm_level *b_wm = &b->wm[level];
3225
3226                a_wm->enable &= b_wm->enable;
3227                a_wm->pri_val = max(a_wm->pri_val, b_wm->pri_val);
3228                a_wm->spr_val = max(a_wm->spr_val, b_wm->spr_val);
3229                a_wm->cur_val = max(a_wm->cur_val, b_wm->cur_val);
3230                a_wm->fbc_val = max(a_wm->fbc_val, b_wm->fbc_val);
3231        }
3232
3233        /*
3234         * We need to make sure that these merged watermark values are
3235         * actually a valid configuration themselves.  If they're not,
3236         * there's no safe way to transition from the old state to
3237         * the new state, so we need to fail the atomic transaction.
3238         */
3239        if (!ilk_validate_pipe_wm(dev_priv, a))
3240                return -EINVAL;
3241
3242        /*
3243         * If our intermediate WM are identical to the final WM, then we can
3244         * omit the post-vblank programming; only update if it's different.
3245         */
3246        if (memcmp(a, &newstate->wm.ilk.optimal, sizeof(*a)) != 0)
3247                newstate->wm.need_postvbl_update = true;
3248
3249        return 0;
3250}
3251
3252/*
3253 * Merge the watermarks from all active pipes for a specific level.
3254 */
3255static void ilk_merge_wm_level(struct drm_i915_private *dev_priv,
3256                               int level,
3257                               struct intel_wm_level *ret_wm)
3258{
3259        const struct intel_crtc *intel_crtc;
3260
3261        ret_wm->enable = true;
3262
3263        for_each_intel_crtc(&dev_priv->drm, intel_crtc) {
3264                const struct intel_pipe_wm *active = &intel_crtc->wm.active.ilk;
3265                const struct intel_wm_level *wm = &active->wm[level];
3266
3267                if (!active->pipe_enabled)
3268                        continue;
3269
3270                /*
3271                 * The watermark values may have been used in the past,
3272                 * so we must maintain them in the registers for some
3273                 * time even if the level is now disabled.
3274                 */
3275                if (!wm->enable)
3276                        ret_wm->enable = false;
3277
3278                ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
3279                ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
3280                ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
3281                ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
3282        }
3283}
3284
3285/*
3286 * Merge all low power watermarks for all active pipes.
3287 */
3288static void ilk_wm_merge(struct drm_i915_private *dev_priv,
3289                         const struct intel_wm_config *config,
3290                         const struct ilk_wm_maximums *max,
3291                         struct intel_pipe_wm *merged)
3292{
3293        int level, max_level = ilk_wm_max_level(dev_priv);
3294        int last_enabled_level = max_level;
3295
3296        /* ILK/SNB/IVB: LP1+ watermarks only w/ single pipe */
3297        if ((INTEL_GEN(dev_priv) <= 6 || IS_IVYBRIDGE(dev_priv)) &&
3298            config->num_pipes_active > 1)
3299                last_enabled_level = 0;
3300
3301        /* ILK: FBC WM must be disabled always */
3302        merged->fbc_wm_enabled = INTEL_GEN(dev_priv) >= 6;
3303
3304        /* merge each WM1+ level */
3305        for (level = 1; level <= max_level; level++) {
3306                struct intel_wm_level *wm = &merged->wm[level];
3307
3308                ilk_merge_wm_level(dev_priv, level, wm);
3309
3310                if (level > last_enabled_level)
3311                        wm->enable = false;
3312                else if (!ilk_validate_wm_level(level, max, wm))
3313                        /* make sure all following levels get disabled */
3314                        last_enabled_level = level - 1;
3315
3316                /*
3317                 * The spec says it is preferred to disable
3318                 * FBC WMs instead of disabling a WM level.
3319                 */
3320                if (wm->fbc_val > max->fbc) {
3321                        if (wm->enable)
3322                                merged->fbc_wm_enabled = false;
3323                        wm->fbc_val = 0;
3324                }
3325        }
3326
3327        /* ILK: LP2+ must be disabled when FBC WM is disabled but FBC enabled */
3328        /*
3329         * FIXME this is racy. FBC might get enabled later.
3330         * What we should check here is whether FBC can be
3331         * enabled sometime later.
3332         */
3333        if (IS_GEN(dev_priv, 5) && !merged->fbc_wm_enabled &&
3334            intel_fbc_is_active(dev_priv)) {
3335                for (level = 2; level <= max_level; level++) {
3336                        struct intel_wm_level *wm = &merged->wm[level];
3337
3338                        wm->enable = false;
3339                }
3340        }
3341}
3342
3343static int ilk_wm_lp_to_level(int wm_lp, const struct intel_pipe_wm *pipe_wm)
3344{
3345        /* LP1,LP2,LP3 levels are either 1,2,3 or 1,3,4 */
3346        return wm_lp + (wm_lp >= 2 && pipe_wm->wm[4].enable);
3347}
3348
3349/* The value we need to program into the WM_LPx latency field */
3350static unsigned int ilk_wm_lp_latency(struct drm_i915_private *dev_priv,
3351                                      int level)
3352{
3353        if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3354                return 2 * level;
3355        else
3356                return dev_priv->wm.pri_latency[level];
3357}
3358
3359static void ilk_compute_wm_results(struct drm_i915_private *dev_priv,
3360                                   const struct intel_pipe_wm *merged,
3361                                   enum intel_ddb_partitioning partitioning,
3362                                   struct ilk_wm_values *results)
3363{
3364        struct intel_crtc *intel_crtc;
3365        int level, wm_lp;
3366
3367        results->enable_fbc_wm = merged->fbc_wm_enabled;
3368        results->partitioning = partitioning;
3369
3370        /* LP1+ register values */
3371        for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
3372                const struct intel_wm_level *r;
3373
3374                level = ilk_wm_lp_to_level(wm_lp, merged);
3375
3376                r = &merged->wm[level];
3377
3378                /*
3379                 * Maintain the watermark values even if the level is
3380                 * disabled. Doing otherwise could cause underruns.
3381                 */
3382                results->wm_lp[wm_lp - 1] =
3383                        (ilk_wm_lp_latency(dev_priv, level) << WM1_LP_LATENCY_SHIFT) |
3384                        (r->pri_val << WM1_LP_SR_SHIFT) |
3385                        r->cur_val;
3386
3387                if (r->enable)
3388                        results->wm_lp[wm_lp - 1] |= WM1_LP_SR_EN;
3389
3390                if (INTEL_GEN(dev_priv) >= 8)
3391                        results->wm_lp[wm_lp - 1] |=
3392                                r->fbc_val << WM1_LP_FBC_SHIFT_BDW;
3393                else
3394                        results->wm_lp[wm_lp - 1] |=
3395                                r->fbc_val << WM1_LP_FBC_SHIFT;
3396
3397                /*
3398                 * Always set WM1S_LP_EN when spr_val != 0, even if the
3399                 * level is disabled. Doing otherwise could cause underruns.
3400                 */
3401                if (INTEL_GEN(dev_priv) <= 6 && r->spr_val) {
3402                        WARN_ON(wm_lp != 1);
3403                        results->wm_lp_spr[wm_lp - 1] = WM1S_LP_EN | r->spr_val;
3404                } else
3405                        results->wm_lp_spr[wm_lp - 1] = r->spr_val;
3406        }
3407
3408        /* LP0 register values */
3409        for_each_intel_crtc(&dev_priv->drm, intel_crtc) {
3410                enum pipe pipe = intel_crtc->pipe;
3411                const struct intel_wm_level *r =
3412                        &intel_crtc->wm.active.ilk.wm[0];
3413
3414                if (WARN_ON(!r->enable))
3415                        continue;
3416
3417                results->wm_linetime[pipe] = intel_crtc->wm.active.ilk.linetime;
3418
3419                results->wm_pipe[pipe] =
3420                        (r->pri_val << WM0_PIPE_PLANE_SHIFT) |
3421                        (r->spr_val << WM0_PIPE_SPRITE_SHIFT) |
3422                        r->cur_val;
3423        }
3424}
3425
3426/* Find the result with the highest level enabled. Check for enable_fbc_wm in
3427 * case both are at the same level. Prefer r1 in case they're the same. */
3428static struct intel_pipe_wm *
3429ilk_find_best_result(struct drm_i915_private *dev_priv,
3430                     struct intel_pipe_wm *r1,
3431                     struct intel_pipe_wm *r2)
3432{
3433        int level, max_level = ilk_wm_max_level(dev_priv);
3434        int level1 = 0, level2 = 0;
3435
3436        for (level = 1; level <= max_level; level++) {
3437                if (r1->wm[level].enable)
3438                        level1 = level;
3439                if (r2->wm[level].enable)
3440                        level2 = level;
3441        }
3442
3443        if (level1 == level2) {
3444                if (r2->fbc_wm_enabled && !r1->fbc_wm_enabled)
3445                        return r2;
3446                else
3447                        return r1;
3448        } else if (level1 > level2) {
3449                return r1;
3450        } else {
3451                return r2;
3452        }
3453}
3454
3455/* dirty bits used to track which watermarks need changes */
3456#define WM_DIRTY_PIPE(pipe) (1 << (pipe))
3457#define WM_DIRTY_LINETIME(pipe) (1 << (8 + (pipe)))
3458#define WM_DIRTY_LP(wm_lp) (1 << (15 + (wm_lp)))
3459#define WM_DIRTY_LP_ALL (WM_DIRTY_LP(1) | WM_DIRTY_LP(2) | WM_DIRTY_LP(3))
3460#define WM_DIRTY_FBC (1 << 24)
3461#define WM_DIRTY_DDB (1 << 25)
3462
3463static unsigned int ilk_compute_wm_dirty(struct drm_i915_private *dev_priv,
3464                                         const struct ilk_wm_values *old,
3465                                         const struct ilk_wm_values *new)
3466{
3467        unsigned int dirty = 0;
3468        enum pipe pipe;
3469        int wm_lp;
3470
3471        for_each_pipe(dev_priv, pipe) {
3472                if (old->wm_linetime[pipe] != new->wm_linetime[pipe]) {
3473                        dirty |= WM_DIRTY_LINETIME(pipe);
3474                        /* Must disable LP1+ watermarks too */
3475                        dirty |= WM_DIRTY_LP_ALL;
3476                }
3477
3478                if (old->wm_pipe[pipe] != new->wm_pipe[pipe]) {
3479                        dirty |= WM_DIRTY_PIPE(pipe);
3480                        /* Must disable LP1+ watermarks too */
3481                        dirty |= WM_DIRTY_LP_ALL;
3482                }
3483        }
3484
3485        if (old->enable_fbc_wm != new->enable_fbc_wm) {
3486                dirty |= WM_DIRTY_FBC;
3487                /* Must disable LP1+ watermarks too */
3488                dirty |= WM_DIRTY_LP_ALL;
3489        }
3490
3491        if (old->partitioning != new->partitioning) {
3492                dirty |= WM_DIRTY_DDB;
3493                /* Must disable LP1+ watermarks too */
3494                dirty |= WM_DIRTY_LP_ALL;
3495        }
3496
3497        /* LP1+ watermarks already deemed dirty, no need to continue */
3498        if (dirty & WM_DIRTY_LP_ALL)
3499                return dirty;
3500
3501        /* Find the lowest numbered LP1+ watermark in need of an update... */
3502        for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
3503                if (old->wm_lp[wm_lp - 1] != new->wm_lp[wm_lp - 1] ||
3504                    old->wm_lp_spr[wm_lp - 1] != new->wm_lp_spr[wm_lp - 1])
3505                        break;
3506        }
3507
3508        /* ...and mark it and all higher numbered LP1+ watermarks as dirty */
3509        for (; wm_lp <= 3; wm_lp++)
3510                dirty |= WM_DIRTY_LP(wm_lp);
3511
3512        return dirty;
3513}
3514
3515static bool _ilk_disable_lp_wm(struct drm_i915_private *dev_priv,
3516                               unsigned int dirty)
3517{
3518        struct ilk_wm_values *previous = &dev_priv->wm.hw;
3519        bool changed = false;
3520
3521        if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] & WM1_LP_SR_EN) {
3522                previous->wm_lp[2] &= ~WM1_LP_SR_EN;
3523                I915_WRITE(WM3_LP_ILK, previous->wm_lp[2]);
3524                changed = true;
3525        }
3526        if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] & WM1_LP_SR_EN) {
3527                previous->wm_lp[1] &= ~WM1_LP_SR_EN;
3528                I915_WRITE(WM2_LP_ILK, previous->wm_lp[1]);
3529                changed = true;
3530        }
3531        if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] & WM1_LP_SR_EN) {
3532                previous->wm_lp[0] &= ~WM1_LP_SR_EN;
3533                I915_WRITE(WM1_LP_ILK, previous->wm_lp[0]);
3534                changed = true;
3535        }
3536
3537        /*
3538         * Don't touch WM1S_LP_EN here.
3539         * Doing so could cause underruns.
3540         */
3541
3542        return changed;
3543}
3544
3545/*
3546 * The spec says we shouldn't write when we don't need, because every write
3547 * causes WMs to be re-evaluated, expending some power.
3548 */
3549static void ilk_write_wm_values(struct drm_i915_private *dev_priv,
3550                                struct ilk_wm_values *results)
3551{
3552        struct ilk_wm_values *previous = &dev_priv->wm.hw;
3553        unsigned int dirty;
3554        u32 val;
3555
3556        dirty = ilk_compute_wm_dirty(dev_priv, previous, results);
3557        if (!dirty)
3558                return;
3559
3560        _ilk_disable_lp_wm(dev_priv, dirty);
3561
3562        if (dirty & WM_DIRTY_PIPE(PIPE_A))
3563                I915_WRITE(WM0_PIPEA_ILK, results->wm_pipe[0]);
3564        if (dirty & WM_DIRTY_PIPE(PIPE_B))
3565                I915_WRITE(WM0_PIPEB_ILK, results->wm_pipe[1]);
3566        if (dirty & WM_DIRTY_PIPE(PIPE_C))
3567                I915_WRITE(WM0_PIPEC_IVB, results->wm_pipe[2]);
3568
3569        if (dirty & WM_DIRTY_LINETIME(PIPE_A))
3570                I915_WRITE(PIPE_WM_LINETIME(PIPE_A), results->wm_linetime[0]);
3571        if (dirty & WM_DIRTY_LINETIME(PIPE_B))
3572                I915_WRITE(PIPE_WM_LINETIME(PIPE_B), results->wm_linetime[1]);
3573        if (dirty & WM_DIRTY_LINETIME(PIPE_C))
3574                I915_WRITE(PIPE_WM_LINETIME(PIPE_C), results->wm_linetime[2]);
3575
3576        if (dirty & WM_DIRTY_DDB) {
3577                if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3578                        val = I915_READ(WM_MISC);
3579                        if (results->partitioning == INTEL_DDB_PART_1_2)
3580                                val &= ~WM_MISC_DATA_PARTITION_5_6;
3581                        else
3582                                val |= WM_MISC_DATA_PARTITION_5_6;
3583                        I915_WRITE(WM_MISC, val);
3584                } else {
3585                        val = I915_READ(DISP_ARB_CTL2);
3586                        if (results->partitioning == INTEL_DDB_PART_1_2)
3587                                val &= ~DISP_DATA_PARTITION_5_6;
3588                        else
3589                                val |= DISP_DATA_PARTITION_5_6;
3590                        I915_WRITE(DISP_ARB_CTL2, val);
3591                }
3592        }
3593
3594        if (dirty & WM_DIRTY_FBC) {
3595                val = I915_READ(DISP_ARB_CTL);
3596                if (results->enable_fbc_wm)
3597                        val &= ~DISP_FBC_WM_DIS;
3598                else
3599                        val |= DISP_FBC_WM_DIS;
3600                I915_WRITE(DISP_ARB_CTL, val);
3601        }
3602
3603        if (dirty & WM_DIRTY_LP(1) &&
3604            previous->wm_lp_spr[0] != results->wm_lp_spr[0])
3605                I915_WRITE(WM1S_LP_ILK, results->wm_lp_spr[0]);
3606
3607        if (INTEL_GEN(dev_priv) >= 7) {
3608                if (dirty & WM_DIRTY_LP(2) && previous->wm_lp_spr[1] != results->wm_lp_spr[1])
3609                        I915_WRITE(WM2S_LP_IVB, results->wm_lp_spr[1]);
3610                if (dirty & WM_DIRTY_LP(3) && previous->wm_lp_spr[2] != results->wm_lp_spr[2])
3611                        I915_WRITE(WM3S_LP_IVB, results->wm_lp_spr[2]);
3612        }
3613
3614        if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] != results->wm_lp[0])
3615                I915_WRITE(WM1_LP_ILK, results->wm_lp[0]);
3616        if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] != results->wm_lp[1])
3617                I915_WRITE(WM2_LP_ILK, results->wm_lp[1]);
3618        if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] != results->wm_lp[2])
3619                I915_WRITE(WM3_LP_ILK, results->wm_lp[2]);
3620
3621        dev_priv->wm.hw = *results;
3622}
3623
3624bool ilk_disable_lp_wm(struct drm_device *dev)
3625{
3626        struct drm_i915_private *dev_priv = to_i915(dev);
3627
3628        return _ilk_disable_lp_wm(dev_priv, WM_DIRTY_LP_ALL);
3629}
3630
3631static u8 intel_enabled_dbuf_slices_num(struct drm_i915_private *dev_priv)
3632{
3633        u8 enabled_slices;
3634
3635        /* Slice 1 will always be enabled */
3636        enabled_slices = 1;
3637
3638        /* Gen prior to GEN11 have only one DBuf slice */
3639        if (INTEL_GEN(dev_priv) < 11)
3640                return enabled_slices;
3641
3642        /*
3643         * FIXME: for now we'll only ever use 1 slice; pretend that we have
3644         * only that 1 slice enabled until we have a proper way for on-demand
3645         * toggling of the second slice.
3646         */
3647        if (0 && I915_READ(DBUF_CTL_S2) & DBUF_POWER_STATE)
3648                enabled_slices++;
3649
3650        return enabled_slices;
3651}
3652
3653/*
3654 * FIXME: We still don't have the proper code detect if we need to apply the WA,
3655 * so assume we'll always need it in order to avoid underruns.
3656 */
3657static bool skl_needs_memory_bw_wa(struct drm_i915_private *dev_priv)
3658{
3659        return IS_GEN9_BC(dev_priv) || IS_BROXTON(dev_priv);
3660}
3661
3662static bool
3663intel_has_sagv(struct drm_i915_private *dev_priv)
3664{
3665        return (IS_GEN9_BC(dev_priv) || INTEL_GEN(dev_priv) >= 10) &&
3666                dev_priv->sagv_status != I915_SAGV_NOT_CONTROLLED;
3667}
3668
3669/*
3670 * SAGV dynamically adjusts the system agent voltage and clock frequencies
3671 * depending on power and performance requirements. The display engine access
3672 * to system memory is blocked during the adjustment time. Because of the
3673 * blocking time, having this enabled can cause full system hangs and/or pipe
3674 * underruns if we don't meet all of the following requirements:
3675 *
3676 *  - <= 1 pipe enabled
3677 *  - All planes can enable watermarks for latencies >= SAGV engine block time
3678 *  - We're not using an interlaced display configuration
3679 */
3680int
3681intel_enable_sagv(struct drm_i915_private *dev_priv)
3682{
3683        int ret;
3684
3685        if (!intel_has_sagv(dev_priv))
3686                return 0;
3687
3688        if (dev_priv->sagv_status == I915_SAGV_ENABLED)
3689                return 0;
3690
3691        DRM_DEBUG_KMS("Enabling SAGV\n");
3692        ret = sandybridge_pcode_write(dev_priv, GEN9_PCODE_SAGV_CONTROL,
3693                                      GEN9_SAGV_ENABLE);
3694
3695        /* We don't need to wait for SAGV when enabling */
3696
3697        /*
3698         * Some skl systems, pre-release machines in particular,
3699         * don't actually have SAGV.
3700         */
3701        if (IS_SKYLAKE(dev_priv) && ret == -ENXIO) {
3702                DRM_DEBUG_DRIVER("No SAGV found on system, ignoring\n");
3703                dev_priv->sagv_status = I915_SAGV_NOT_CONTROLLED;
3704                return 0;
3705        } else if (ret < 0) {
3706                DRM_ERROR("Failed to enable SAGV\n");
3707                return ret;
3708        }
3709
3710        dev_priv->sagv_status = I915_SAGV_ENABLED;
3711        return 0;
3712}
3713
3714int
3715intel_disable_sagv(struct drm_i915_private *dev_priv)
3716{
3717        int ret;
3718
3719        if (!intel_has_sagv(dev_priv))
3720                return 0;
3721
3722        if (dev_priv->sagv_status == I915_SAGV_DISABLED)
3723                return 0;
3724
3725        DRM_DEBUG_KMS("Disabling SAGV\n");
3726        /* bspec says to keep retrying for at least 1 ms */
3727        ret = skl_pcode_request(dev_priv, GEN9_PCODE_SAGV_CONTROL,
3728                                GEN9_SAGV_DISABLE,
3729                                GEN9_SAGV_IS_DISABLED, GEN9_SAGV_IS_DISABLED,
3730                                1);
3731        /*
3732         * Some skl systems, pre-release machines in particular,
3733         * don't actually have SAGV.
3734         */
3735        if (IS_SKYLAKE(dev_priv) && ret == -ENXIO) {
3736                DRM_DEBUG_DRIVER("No SAGV found on system, ignoring\n");
3737                dev_priv->sagv_status = I915_SAGV_NOT_CONTROLLED;
3738                return 0;
3739        } else if (ret < 0) {
3740                DRM_ERROR("Failed to disable SAGV (%d)\n", ret);
3741                return ret;
3742        }
3743
3744        dev_priv->sagv_status = I915_SAGV_DISABLED;
3745        return 0;
3746}
3747
3748bool intel_can_enable_sagv(struct intel_atomic_state *state)
3749{
3750        struct drm_device *dev = state->base.dev;
3751        struct drm_i915_private *dev_priv = to_i915(dev);
3752        struct intel_crtc *crtc;
3753        struct intel_plane *plane;
3754        struct intel_crtc_state *crtc_state;
3755        enum pipe pipe;
3756        int level, latency;
3757        int sagv_block_time_us;
3758
3759        if (!intel_has_sagv(dev_priv))
3760                return false;
3761
3762        if (IS_GEN(dev_priv, 9))
3763                sagv_block_time_us = 30;
3764        else if (IS_GEN(dev_priv, 10))
3765                sagv_block_time_us = 20;
3766        else
3767                sagv_block_time_us = 10;
3768
3769        /*
3770         * If there are no active CRTCs, no additional checks need be performed
3771         */
3772        if (hweight32(state->active_crtcs) == 0)
3773                return true;
3774
3775        /*
3776         * SKL+ workaround: bspec recommends we disable SAGV when we have
3777         * more then one pipe enabled
3778         */
3779        if (hweight32(state->active_crtcs) > 1)
3780                return false;
3781
3782        /* Since we're now guaranteed to only have one active CRTC... */
3783        pipe = ffs(state->active_crtcs) - 1;
3784        crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
3785        crtc_state = to_intel_crtc_state(crtc->base.state);
3786
3787        if (crtc->base.state->adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
3788                return false;
3789
3790        for_each_intel_plane_on_crtc(dev, crtc, plane) {
3791                struct skl_plane_wm *wm =
3792                        &crtc_state->wm.skl.optimal.planes[plane->id];
3793
3794                /* Skip this plane if it's not enabled */
3795                if (!wm->wm[0].plane_en)
3796                        continue;
3797
3798                /* Find the highest enabled wm level for this plane */
3799                for (level = ilk_wm_max_level(dev_priv);
3800                     !wm->wm[level].plane_en; --level)
3801                     { }
3802
3803                latency = dev_priv->wm.skl_latency[level];
3804
3805                if (skl_needs_memory_bw_wa(dev_priv) &&
3806                    plane->base.state->fb->modifier ==
3807                    I915_FORMAT_MOD_X_TILED)
3808                        latency += 15;
3809
3810                /*
3811                 * If any of the planes on this pipe don't enable wm levels that
3812                 * incur memory latencies higher than sagv_block_time_us we
3813                 * can't enable SAGV.
3814                 */
3815                if (latency < sagv_block_time_us)
3816                        return false;
3817        }
3818
3819        return true;
3820}
3821
3822static u16 intel_get_ddb_size(struct drm_i915_private *dev_priv,
3823                              const struct intel_crtc_state *crtc_state,
3824                              const u64 total_data_rate,
3825                              const int num_active,
3826                              struct skl_ddb_allocation *ddb)
3827{
3828        const struct drm_display_mode *adjusted_mode;
3829        u64 total_data_bw;
3830        u16 ddb_size = INTEL_INFO(dev_priv)->ddb_size;
3831
3832        WARN_ON(ddb_size == 0);
3833
3834        if (INTEL_GEN(dev_priv) < 11)
3835                return ddb_size - 4; /* 4 blocks for bypass path allocation */
3836
3837        adjusted_mode = &crtc_state->base.adjusted_mode;
3838        total_data_bw = total_data_rate * drm_mode_vrefresh(adjusted_mode);
3839
3840        /*
3841         * 12GB/s is maximum BW supported by single DBuf slice.
3842         *
3843         * FIXME dbuf slice code is broken:
3844         * - must wait for planes to stop using the slice before powering it off
3845         * - plane straddling both slices is illegal in multi-pipe scenarios
3846         * - should validate we stay within the hw bandwidth limits
3847         */
3848        if (0 && (num_active > 1 || total_data_bw >= GBps(12))) {
3849                ddb->enabled_slices = 2;
3850        } else {
3851                ddb->enabled_slices = 1;
3852                ddb_size /= 2;
3853        }
3854
3855        return ddb_size;
3856}
3857
3858static void
3859skl_ddb_get_pipe_allocation_limits(struct drm_i915_private *dev_priv,
3860                                   const struct intel_crtc_state *crtc_state,
3861                                   const u64 total_data_rate,
3862                                   struct skl_ddb_allocation *ddb,
3863                                   struct skl_ddb_entry *alloc, /* out */
3864                                   int *num_active /* out */)
3865{
3866        struct drm_atomic_state *state = crtc_state->base.state;
3867        struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
3868        struct drm_crtc *for_crtc = crtc_state->base.crtc;
3869        const struct intel_crtc *crtc;
3870        u32 pipe_width = 0, total_width = 0, width_before_pipe = 0;
3871        enum pipe for_pipe = to_intel_crtc(for_crtc)->pipe;
3872        u16 ddb_size;
3873        u32 i;
3874
3875        if (WARN_ON(!state) || !crtc_state->base.active) {
3876                alloc->start = 0;
3877                alloc->end = 0;
3878                *num_active = hweight32(dev_priv->active_crtcs);
3879                return;
3880        }
3881
3882        if (intel_state->active_pipe_changes)
3883                *num_active = hweight32(intel_state->active_crtcs);
3884        else
3885                *num_active = hweight32(dev_priv->active_crtcs);
3886
3887        ddb_size = intel_get_ddb_size(dev_priv, crtc_state, total_data_rate,
3888                                      *num_active, ddb);
3889
3890        /*
3891         * If the state doesn't change the active CRTC's or there is no
3892         * modeset request, then there's no need to recalculate;
3893         * the existing pipe allocation limits should remain unchanged.
3894         * Note that we're safe from racing commits since any racing commit
3895         * that changes the active CRTC list or do modeset would need to
3896         * grab _all_ crtc locks, including the one we currently hold.
3897         */
3898        if (!intel_state->active_pipe_changes && !intel_state->modeset) {
3899                /*
3900                 * alloc may be cleared by clear_intel_crtc_state,
3901                 * copy from old state to be sure
3902                 */
3903                *alloc = to_intel_crtc_state(for_crtc->state)->wm.skl.ddb;
3904                return;
3905        }
3906
3907        /*
3908         * Watermark/ddb requirement highly depends upon width of the
3909         * framebuffer, So instead of allocating DDB equally among pipes
3910         * distribute DDB based on resolution/width of the display.
3911         */
3912        for_each_new_intel_crtc_in_state(intel_state, crtc, crtc_state, i) {
3913                const struct drm_display_mode *adjusted_mode =
3914                        &crtc_state->base.adjusted_mode;
3915                enum pipe pipe = crtc->pipe;
3916                int hdisplay, vdisplay;
3917
3918                if (!crtc_state->base.enable)
3919                        continue;
3920
3921                drm_mode_get_hv_timing(adjusted_mode, &hdisplay, &vdisplay);
3922                total_width += hdisplay;
3923
3924                if (pipe < for_pipe)
3925                        width_before_pipe += hdisplay;
3926                else if (pipe == for_pipe)
3927                        pipe_width = hdisplay;
3928        }
3929
3930        alloc->start = ddb_size * width_before_pipe / total_width;
3931        alloc->end = ddb_size * (width_before_pipe + pipe_width) / total_width;
3932}
3933
3934static int skl_compute_wm_params(const struct intel_crtc_state *crtc_state,
3935                                 int width, const struct drm_format_info *format,
3936                                 u64 modifier, unsigned int rotation,
3937                                 u32 plane_pixel_rate, struct skl_wm_params *wp,
3938                                 int color_plane);
3939static void skl_compute_plane_wm(const struct intel_crtc_state *crtc_state,
3940                                 int level,
3941                                 const struct skl_wm_params *wp,
3942                                 const struct skl_wm_level *result_prev,
3943                                 struct skl_wm_level *result /* out */);
3944
3945static unsigned int
3946skl_cursor_allocation(const struct intel_crtc_state *crtc_state,
3947                      int num_active)
3948{
3949        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3950        int level, max_level = ilk_wm_max_level(dev_priv);
3951        struct skl_wm_level wm = {};
3952        int ret, min_ddb_alloc = 0;
3953        struct skl_wm_params wp;
3954
3955        ret = skl_compute_wm_params(crtc_state, 256,
3956                                    drm_format_info(DRM_FORMAT_ARGB8888),
3957                                    DRM_FORMAT_MOD_LINEAR,
3958                                    DRM_MODE_ROTATE_0,
3959                                    crtc_state->pixel_rate, &wp, 0);
3960        WARN_ON(ret);
3961
3962        for (level = 0; level <= max_level; level++) {
3963                skl_compute_plane_wm(crtc_state, level, &wp, &wm, &wm);
3964                if (wm.min_ddb_alloc == U16_MAX)
3965                        break;
3966
3967                min_ddb_alloc = wm.min_ddb_alloc;
3968        }
3969
3970        return max(num_active == 1 ? 32 : 8, min_ddb_alloc);
3971}
3972
3973static void skl_ddb_entry_init_from_hw(struct drm_i915_private *dev_priv,
3974                                       struct skl_ddb_entry *entry, u32 reg)
3975{
3976
3977        entry->start = reg & DDB_ENTRY_MASK;
3978        entry->end = (reg >> DDB_ENTRY_END_SHIFT) & DDB_ENTRY_MASK;
3979
3980        if (entry->end)
3981                entry->end += 1;
3982}
3983
3984static void
3985skl_ddb_get_hw_plane_state(struct drm_i915_private *dev_priv,
3986                           const enum pipe pipe,
3987                           const enum plane_id plane_id,
3988                           struct skl_ddb_entry *ddb_y,
3989                           struct skl_ddb_entry *ddb_uv)
3990{
3991        u32 val, val2;
3992        u32 fourcc = 0;
3993
3994        /* Cursor doesn't support NV12/planar, so no extra calculation needed */
3995        if (plane_id == PLANE_CURSOR) {
3996                val = I915_READ(CUR_BUF_CFG(pipe));
3997                skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
3998                return;
3999        }
4000
4001        val = I915_READ(PLANE_CTL(pipe, plane_id));
4002
4003        /* No DDB allocated for disabled planes */
4004        if (val & PLANE_CTL_ENABLE)
4005                fourcc = skl_format_to_fourcc(val & PLANE_CTL_FORMAT_MASK,
4006                                              val & PLANE_CTL_ORDER_RGBX,
4007                                              val & PLANE_CTL_ALPHA_MASK);
4008
4009        if (INTEL_GEN(dev_priv) >= 11) {
4010                val = I915_READ(PLANE_BUF_CFG(pipe, plane_id));
4011                skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
4012        } else {
4013                val = I915_READ(PLANE_BUF_CFG(pipe, plane_id));
4014                val2 = I915_READ(PLANE_NV12_BUF_CFG(pipe, plane_id));
4015
4016                if (is_planar_yuv_format(fourcc))
4017                        swap(val, val2);
4018
4019                skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
4020                skl_ddb_entry_init_from_hw(dev_priv, ddb_uv, val2);
4021        }
4022}
4023
4024void skl_pipe_ddb_get_hw_state(struct intel_crtc *crtc,
4025                               struct skl_ddb_entry *ddb_y,
4026                               struct skl_ddb_entry *ddb_uv)
4027{
4028        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4029        enum intel_display_power_domain power_domain;
4030        enum pipe pipe = crtc->pipe;
4031        intel_wakeref_t wakeref;
4032        enum plane_id plane_id;
4033
4034        power_domain = POWER_DOMAIN_PIPE(pipe);
4035        wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
4036        if (!wakeref)
4037                return;
4038
4039        for_each_plane_id_on_crtc(crtc, plane_id)
4040                skl_ddb_get_hw_plane_state(dev_priv, pipe,
4041                                           plane_id,
4042                                           &ddb_y[plane_id],
4043                                           &ddb_uv[plane_id]);
4044
4045        intel_display_power_put(dev_priv, power_domain, wakeref);
4046}
4047
4048void skl_ddb_get_hw_state(struct drm_i915_private *dev_priv,
4049                          struct skl_ddb_allocation *ddb /* out */)
4050{
4051        ddb->enabled_slices = intel_enabled_dbuf_slices_num(dev_priv);
4052}
4053
4054/*
4055 * Determines the downscale amount of a plane for the purposes of watermark calculations.
4056 * The bspec defines downscale amount as:
4057 *
4058 * """
4059 * Horizontal down scale amount = maximum[1, Horizontal source size /
4060 *                                           Horizontal destination size]
4061 * Vertical down scale amount = maximum[1, Vertical source size /
4062 *                                         Vertical destination size]
4063 * Total down scale amount = Horizontal down scale amount *
4064 *                           Vertical down scale amount
4065 * """
4066 *
4067 * Return value is provided in 16.16 fixed point form to retain fractional part.
4068 * Caller should take care of dividing & rounding off the value.
4069 */
4070static uint_fixed_16_16_t
4071skl_plane_downscale_amount(const struct intel_crtc_state *crtc_state,
4072                           const struct intel_plane_state *plane_state)
4073{
4074        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
4075        u32 src_w, src_h, dst_w, dst_h;
4076        uint_fixed_16_16_t fp_w_ratio, fp_h_ratio;
4077        uint_fixed_16_16_t downscale_h, downscale_w;
4078
4079        if (WARN_ON(!intel_wm_plane_visible(crtc_state, plane_state)))
4080                return u32_to_fixed16(0);
4081
4082        /* n.b., src is 16.16 fixed point, dst is whole integer */
4083        if (plane->id == PLANE_CURSOR) {
4084                /*
4085                 * Cursors only support 0/180 degree rotation,
4086                 * hence no need to account for rotation here.
4087                 */
4088                src_w = plane_state->base.src_w >> 16;
4089                src_h = plane_state->base.src_h >> 16;
4090                dst_w = plane_state->base.crtc_w;
4091                dst_h = plane_state->base.crtc_h;
4092        } else {
4093                /*
4094                 * Src coordinates are already rotated by 270 degrees for
4095                 * the 90/270 degree plane rotation cases (to match the
4096                 * GTT mapping), hence no need to account for rotation here.
4097                 */
4098                src_w = drm_rect_width(&plane_state->base.src) >> 16;
4099                src_h = drm_rect_height(&plane_state->base.src) >> 16;
4100                dst_w = drm_rect_width(&plane_state->base.dst);
4101                dst_h = drm_rect_height(&plane_state->base.dst);
4102        }
4103
4104        fp_w_ratio = div_fixed16(src_w, dst_w);
4105        fp_h_ratio = div_fixed16(src_h, dst_h);
4106        downscale_w = max_fixed16(fp_w_ratio, u32_to_fixed16(1));
4107        downscale_h = max_fixed16(fp_h_ratio, u32_to_fixed16(1));
4108
4109        return mul_fixed16(downscale_w, downscale_h);
4110}
4111
4112static uint_fixed_16_16_t
4113skl_pipe_downscale_amount(const struct intel_crtc_state *crtc_state)
4114{
4115        uint_fixed_16_16_t pipe_downscale = u32_to_fixed16(1);
4116
4117        if (!crtc_state->base.enable)
4118                return pipe_downscale;
4119
4120        if (crtc_state->pch_pfit.enabled) {
4121                u32 src_w, src_h, dst_w, dst_h;
4122                u32 pfit_size = crtc_state->pch_pfit.size;
4123                uint_fixed_16_16_t fp_w_ratio, fp_h_ratio;
4124                uint_fixed_16_16_t downscale_h, downscale_w;
4125
4126                src_w = crtc_state->pipe_src_w;
4127                src_h = crtc_state->pipe_src_h;
4128                dst_w = pfit_size >> 16;
4129                dst_h = pfit_size & 0xffff;
4130
4131                if (!dst_w || !dst_h)
4132                        return pipe_downscale;
4133
4134                fp_w_ratio = div_fixed16(src_w, dst_w);
4135                fp_h_ratio = div_fixed16(src_h, dst_h);
4136                downscale_w = max_fixed16(fp_w_ratio, u32_to_fixed16(1));
4137                downscale_h = max_fixed16(fp_h_ratio, u32_to_fixed16(1));
4138
4139                pipe_downscale = mul_fixed16(downscale_w, downscale_h);
4140        }
4141
4142        return pipe_downscale;
4143}
4144
4145int skl_check_pipe_max_pixel_rate(struct intel_crtc *intel_crtc,
4146                                  struct intel_crtc_state *crtc_state)
4147{
4148        struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4149        struct drm_atomic_state *state = crtc_state->base.state;
4150        struct drm_plane *plane;
4151        const struct drm_plane_state *drm_plane_state;
4152        int crtc_clock, dotclk;
4153        u32 pipe_max_pixel_rate;
4154        uint_fixed_16_16_t pipe_downscale;
4155        uint_fixed_16_16_t max_downscale = u32_to_fixed16(1);
4156
4157        if (!crtc_state->base.enable)
4158                return 0;
4159
4160        drm_atomic_crtc_state_for_each_plane_state(plane, drm_plane_state, &crtc_state->base) {
4161                uint_fixed_16_16_t plane_downscale;
4162                uint_fixed_16_16_t fp_9_div_8 = div_fixed16(9, 8);
4163                int bpp;
4164                const struct intel_plane_state *plane_state =
4165                        to_intel_plane_state(drm_plane_state);
4166
4167                if (!intel_wm_plane_visible(crtc_state, plane_state))
4168                        continue;
4169
4170                if (WARN_ON(!plane_state->base.fb))
4171                        return -EINVAL;
4172
4173                plane_downscale = skl_plane_downscale_amount(crtc_state, plane_state);
4174                bpp = plane_state->base.fb->format->cpp[0] * 8;
4175                if (bpp == 64)
4176                        plane_downscale = mul_fixed16(plane_downscale,
4177                                                      fp_9_div_8);
4178
4179                max_downscale = max_fixed16(plane_downscale, max_downscale);
4180        }
4181        pipe_downscale = skl_pipe_downscale_amount(crtc_state);
4182
4183        pipe_downscale = mul_fixed16(pipe_downscale, max_downscale);
4184
4185        crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
4186        dotclk = to_intel_atomic_state(state)->cdclk.logical.cdclk;
4187
4188        if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
4189                dotclk *= 2;
4190
4191        pipe_max_pixel_rate = div_round_up_u32_fixed16(dotclk, pipe_downscale);
4192
4193        if (pipe_max_pixel_rate < crtc_clock) {
4194                DRM_DEBUG_KMS("Max supported pixel clock with scaling exceeded\n");
4195                return -EINVAL;
4196        }
4197
4198        return 0;
4199}
4200
4201static u64
4202skl_plane_relative_data_rate(const struct intel_crtc_state *crtc_state,
4203                             const struct intel_plane_state *plane_state,
4204                             const int plane)
4205{
4206        struct intel_plane *intel_plane = to_intel_plane(plane_state->base.plane);
4207        u32 data_rate;
4208        u32 width = 0, height = 0;
4209        struct drm_framebuffer *fb;
4210        u32 format;
4211        uint_fixed_16_16_t down_scale_amount;
4212        u64 rate;
4213
4214        if (!plane_state->base.visible)
4215                return 0;
4216
4217        fb = plane_state->base.fb;
4218        format = fb->format->format;
4219
4220        if (intel_plane->id == PLANE_CURSOR)
4221                return 0;
4222        if (plane == 1 && !is_planar_yuv_format(format))
4223                return 0;
4224
4225        /*
4226         * Src coordinates are already rotated by 270 degrees for
4227         * the 90/270 degree plane rotation cases (to match the
4228         * GTT mapping), hence no need to account for rotation here.
4229         */
4230        width = drm_rect_width(&plane_state->base.src) >> 16;
4231        height = drm_rect_height(&plane_state->base.src) >> 16;
4232
4233        /* UV plane does 1/2 pixel sub-sampling */
4234        if (plane == 1 && is_planar_yuv_format(format)) {
4235                width /= 2;
4236                height /= 2;
4237        }
4238
4239        data_rate = width * height;
4240
4241        down_scale_amount = skl_plane_downscale_amount(crtc_state, plane_state);
4242
4243        rate = mul_round_up_u32_fixed16(data_rate, down_scale_amount);
4244
4245        rate *= fb->format->cpp[plane];
4246        return rate;
4247}
4248
4249static u64
4250skl_get_total_relative_data_rate(struct intel_crtc_state *crtc_state,
4251                                 u64 *plane_data_rate,
4252                                 u64 *uv_plane_data_rate)
4253{
4254        struct drm_atomic_state *state = crtc_state->base.state;
4255        struct drm_plane *plane;
4256        const struct drm_plane_state *drm_plane_state;
4257        u64 total_data_rate = 0;
4258
4259        if (WARN_ON(!state))
4260                return 0;
4261
4262        /* Calculate and cache data rate for each plane */
4263        drm_atomic_crtc_state_for_each_plane_state(plane, drm_plane_state, &crtc_state->base) {
4264                enum plane_id plane_id = to_intel_plane(plane)->id;
4265                const struct intel_plane_state *plane_state =
4266                        to_intel_plane_state(drm_plane_state);
4267                u64 rate;
4268
4269                /* packed/y */
4270                rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4271                plane_data_rate[plane_id] = rate;
4272                total_data_rate += rate;
4273
4274                /* uv-plane */
4275                rate = skl_plane_relative_data_rate(crtc_state, plane_state, 1);
4276                uv_plane_data_rate[plane_id] = rate;
4277                total_data_rate += rate;
4278        }
4279
4280        return total_data_rate;
4281}
4282
4283static u64
4284icl_get_total_relative_data_rate(struct intel_crtc_state *crtc_state,
4285                                 u64 *plane_data_rate)
4286{
4287        struct drm_plane *plane;
4288        const struct drm_plane_state *drm_plane_state;
4289        u64 total_data_rate = 0;
4290
4291        if (WARN_ON(!crtc_state->base.state))
4292                return 0;
4293
4294        /* Calculate and cache data rate for each plane */
4295        drm_atomic_crtc_state_for_each_plane_state(plane, drm_plane_state, &crtc_state->base) {
4296                const struct intel_plane_state *plane_state =
4297                        to_intel_plane_state(drm_plane_state);
4298                enum plane_id plane_id = to_intel_plane(plane)->id;
4299                u64 rate;
4300
4301                if (!plane_state->linked_plane) {
4302                        rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4303                        plane_data_rate[plane_id] = rate;
4304                        total_data_rate += rate;
4305                } else {
4306                        enum plane_id y_plane_id;
4307
4308                        /*
4309                         * The slave plane might not iterate in
4310                         * drm_atomic_crtc_state_for_each_plane_state(),
4311                         * and needs the master plane state which may be
4312                         * NULL if we try get_new_plane_state(), so we
4313                         * always calculate from the master.
4314                         */
4315                        if (plane_state->slave)
4316                                continue;
4317
4318                        /* Y plane rate is calculated on the slave */
4319                        rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4320                        y_plane_id = plane_state->linked_plane->id;
4321                        plane_data_rate[y_plane_id] = rate;
4322                        total_data_rate += rate;
4323
4324                        rate = skl_plane_relative_data_rate(crtc_state, plane_state, 1);
4325                        plane_data_rate[plane_id] = rate;
4326                        total_data_rate += rate;
4327                }
4328        }
4329
4330        return total_data_rate;
4331}
4332
4333static int
4334skl_allocate_pipe_ddb(struct intel_crtc_state *crtc_state,
4335                      struct skl_ddb_allocation *ddb /* out */)
4336{
4337        struct drm_atomic_state *state = crtc_state->base.state;
4338        struct drm_crtc *crtc = crtc_state->base.crtc;
4339        struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4340        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4341        struct skl_ddb_entry *alloc = &crtc_state->wm.skl.ddb;
4342        u16 alloc_size, start = 0;
4343        u16 total[I915_MAX_PLANES] = {};
4344        u16 uv_total[I915_MAX_PLANES] = {};
4345        u64 total_data_rate;
4346        enum plane_id plane_id;
4347        int num_active;
4348        u64 plane_data_rate[I915_MAX_PLANES] = {};
4349        u64 uv_plane_data_rate[I915_MAX_PLANES] = {};
4350        u32 blocks;
4351        int level;
4352
4353        /* Clear the partitioning for disabled planes. */
4354        memset(crtc_state->wm.skl.plane_ddb_y, 0, sizeof(crtc_state->wm.skl.plane_ddb_y));
4355        memset(crtc_state->wm.skl.plane_ddb_uv, 0, sizeof(crtc_state->wm.skl.plane_ddb_uv));
4356
4357        if (WARN_ON(!state))
4358                return 0;
4359
4360        if (!crtc_state->base.active) {
4361                alloc->start = alloc->end = 0;
4362                return 0;
4363        }
4364
4365        if (INTEL_GEN(dev_priv) >= 11)
4366                total_data_rate =
4367                        icl_get_total_relative_data_rate(crtc_state,
4368                                                         plane_data_rate);
4369        else
4370                total_data_rate =
4371                        skl_get_total_relative_data_rate(crtc_state,
4372                                                         plane_data_rate,
4373                                                         uv_plane_data_rate);
4374
4375
4376        skl_ddb_get_pipe_allocation_limits(dev_priv, crtc_state, total_data_rate,
4377                                           ddb, alloc, &num_active);
4378        alloc_size = skl_ddb_entry_size(alloc);
4379        if (alloc_size == 0)
4380                return 0;
4381
4382        /* Allocate fixed number of blocks for cursor. */
4383        total[PLANE_CURSOR] = skl_cursor_allocation(crtc_state, num_active);
4384        alloc_size -= total[PLANE_CURSOR];
4385        crtc_state->wm.skl.plane_ddb_y[PLANE_CURSOR].start =
4386                alloc->end - total[PLANE_CURSOR];
4387        crtc_state->wm.skl.plane_ddb_y[PLANE_CURSOR].end = alloc->end;
4388
4389        if (total_data_rate == 0)
4390                return 0;
4391
4392        /*
4393         * Find the highest watermark level for which we can satisfy the block
4394         * requirement of active planes.
4395         */
4396        for (level = ilk_wm_max_level(dev_priv); level >= 0; level--) {
4397                blocks = 0;
4398                for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4399                        const struct skl_plane_wm *wm =
4400                                &crtc_state->wm.skl.optimal.planes[plane_id];
4401
4402                        if (plane_id == PLANE_CURSOR) {
4403                                if (WARN_ON(wm->wm[level].min_ddb_alloc >
4404                                            total[PLANE_CURSOR])) {
4405                                        blocks = U32_MAX;
4406                                        break;
4407                                }
4408                                continue;
4409                        }
4410
4411                        blocks += wm->wm[level].min_ddb_alloc;
4412                        blocks += wm->uv_wm[level].min_ddb_alloc;
4413                }
4414
4415                if (blocks <= alloc_size) {
4416                        alloc_size -= blocks;
4417                        break;
4418                }
4419        }
4420
4421        if (level < 0) {
4422                DRM_DEBUG_KMS("Requested display configuration exceeds system DDB limitations");
4423                DRM_DEBUG_KMS("minimum required %d/%d\n", blocks,
4424                              alloc_size);
4425                return -EINVAL;
4426        }
4427
4428        /*
4429         * Grant each plane the blocks it requires at the highest achievable
4430         * watermark level, plus an extra share of the leftover blocks
4431         * proportional to its relative data rate.
4432         */
4433        for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4434                const struct skl_plane_wm *wm =
4435                        &crtc_state->wm.skl.optimal.planes[plane_id];
4436                u64 rate;
4437                u16 extra;
4438
4439                if (plane_id == PLANE_CURSOR)
4440                        continue;
4441
4442                /*
4443                 * We've accounted for all active planes; remaining planes are
4444                 * all disabled.
4445                 */
4446                if (total_data_rate == 0)
4447                        break;
4448
4449                rate = plane_data_rate[plane_id];
4450                extra = min_t(u16, alloc_size,
4451                              DIV64_U64_ROUND_UP(alloc_size * rate,
4452                                                 total_data_rate));
4453                total[plane_id] = wm->wm[level].min_ddb_alloc + extra;
4454                alloc_size -= extra;
4455                total_data_rate -= rate;
4456
4457                if (total_data_rate == 0)
4458                        break;
4459
4460                rate = uv_plane_data_rate[plane_id];
4461                extra = min_t(u16, alloc_size,
4462                              DIV64_U64_ROUND_UP(alloc_size * rate,
4463                                                 total_data_rate));
4464                uv_total[plane_id] = wm->uv_wm[level].min_ddb_alloc + extra;
4465                alloc_size -= extra;
4466                total_data_rate -= rate;
4467        }
4468        WARN_ON(alloc_size != 0 || total_data_rate != 0);
4469
4470        /* Set the actual DDB start/end points for each plane */
4471        start = alloc->start;
4472        for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4473                struct skl_ddb_entry *plane_alloc =
4474                        &crtc_state->wm.skl.plane_ddb_y[plane_id];
4475                struct skl_ddb_entry *uv_plane_alloc =
4476                        &crtc_state->wm.skl.plane_ddb_uv[plane_id];
4477
4478                if (plane_id == PLANE_CURSOR)
4479                        continue;
4480
4481                /* Gen11+ uses a separate plane for UV watermarks */
4482                WARN_ON(INTEL_GEN(dev_priv) >= 11 && uv_total[plane_id]);
4483
4484                /* Leave disabled planes at (0,0) */
4485                if (total[plane_id]) {
4486                        plane_alloc->start = start;
4487                        start += total[plane_id];
4488                        plane_alloc->end = start;
4489                }
4490
4491                if (uv_total[plane_id]) {
4492                        uv_plane_alloc->start = start;
4493                        start += uv_total[plane_id];
4494                        uv_plane_alloc->end = start;
4495                }
4496        }
4497
4498        /*
4499         * When we calculated watermark values we didn't know how high
4500         * of a level we'd actually be able to hit, so we just marked
4501         * all levels as "enabled."  Go back now and disable the ones
4502         * that aren't actually possible.
4503         */
4504        for (level++; level <= ilk_wm_max_level(dev_priv); level++) {
4505                for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4506                        struct skl_plane_wm *wm =
4507                                &crtc_state->wm.skl.optimal.planes[plane_id];
4508
4509                        /*
4510                         * We only disable the watermarks for each plane if
4511                         * they exceed the ddb allocation of said plane. This
4512                         * is done so that we don't end up touching cursor
4513                         * watermarks needlessly when some other plane reduces
4514                         * our max possible watermark level.
4515                         *
4516                         * Bspec has this to say about the PLANE_WM enable bit:
4517                         * "All the watermarks at this level for all enabled
4518                         *  planes must be enabled before the level will be used."
4519                         * So this is actually safe to do.
4520                         */
4521                        if (wm->wm[level].min_ddb_alloc > total[plane_id] ||
4522                            wm->uv_wm[level].min_ddb_alloc > uv_total[plane_id])
4523                                memset(&wm->wm[level], 0, sizeof(wm->wm[level]));
4524
4525                        /*
4526                         * Wa_1408961008:icl, ehl
4527                         * Underruns with WM1+ disabled
4528                         */
4529                        if (IS_GEN(dev_priv, 11) &&
4530                            level == 1 && wm->wm[0].plane_en) {
4531                                wm->wm[level].plane_res_b = wm->wm[0].plane_res_b;
4532                                wm->wm[level].plane_res_l = wm->wm[0].plane_res_l;
4533                                wm->wm[level].ignore_lines = wm->wm[0].ignore_lines;
4534                        }
4535                }
4536        }
4537
4538        /*
4539         * Go back and disable the transition watermark if it turns out we
4540         * don't have enough DDB blocks for it.
4541         */
4542        for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4543                struct skl_plane_wm *wm =
4544                        &crtc_state->wm.skl.optimal.planes[plane_id];
4545
4546                if (wm->trans_wm.plane_res_b >= total[plane_id])
4547                        memset(&wm->trans_wm, 0, sizeof(wm->trans_wm));
4548        }
4549
4550        return 0;
4551}
4552
4553/*
4554 * The max latency should be 257 (max the punit can code is 255 and we add 2us
4555 * for the read latency) and cpp should always be <= 8, so that
4556 * should allow pixel_rate up to ~2 GHz which seems sufficient since max
4557 * 2xcdclk is 1350 MHz and the pixel rate should never exceed that.
4558*/
4559static uint_fixed_16_16_t
4560skl_wm_method1(const struct drm_i915_private *dev_priv, u32 pixel_rate,
4561               u8 cpp, u32 latency, u32 dbuf_block_size)
4562{
4563        u32 wm_intermediate_val;
4564        uint_fixed_16_16_t ret;
4565
4566        if (latency == 0)
4567                return FP_16_16_MAX;
4568
4569        wm_intermediate_val = latency * pixel_rate * cpp;
4570        ret = div_fixed16(wm_intermediate_val, 1000 * dbuf_block_size);
4571
4572        if (INTEL_GEN(dev_priv) >= 10)
4573                ret = add_fixed16_u32(ret, 1);
4574
4575        return ret;
4576}
4577
4578static uint_fixed_16_16_t
4579skl_wm_method2(u32 pixel_rate, u32 pipe_htotal, u32 latency,
4580               uint_fixed_16_16_t plane_blocks_per_line)
4581{
4582        u32 wm_intermediate_val;
4583        uint_fixed_16_16_t ret;
4584
4585        if (latency == 0)
4586                return FP_16_16_MAX;
4587
4588        wm_intermediate_val = latency * pixel_rate;
4589        wm_intermediate_val = DIV_ROUND_UP(wm_intermediate_val,
4590                                           pipe_htotal * 1000);
4591        ret = mul_u32_fixed16(wm_intermediate_val, plane_blocks_per_line);
4592        return ret;
4593}
4594
4595static uint_fixed_16_16_t
4596intel_get_linetime_us(const struct intel_crtc_state *crtc_state)
4597{
4598        u32 pixel_rate;
4599        u32 crtc_htotal;
4600        uint_fixed_16_16_t linetime_us;
4601
4602        if (!crtc_state->base.active)
4603                return u32_to_fixed16(0);
4604
4605        pixel_rate = crtc_state->pixel_rate;
4606
4607        if (WARN_ON(pixel_rate == 0))
4608                return u32_to_fixed16(0);
4609
4610        crtc_htotal = crtc_state->base.adjusted_mode.crtc_htotal;
4611        linetime_us = div_fixed16(crtc_htotal * 1000, pixel_rate);
4612
4613        return linetime_us;
4614}
4615
4616static u32
4617skl_adjusted_plane_pixel_rate(const struct intel_crtc_state *crtc_state,
4618                              const struct intel_plane_state *plane_state)
4619{
4620        u64 adjusted_pixel_rate;
4621        uint_fixed_16_16_t downscale_amount;
4622
4623        /* Shouldn't reach here on disabled planes... */
4624        if (WARN_ON(!intel_wm_plane_visible(crtc_state, plane_state)))
4625                return 0;
4626
4627        /*
4628         * Adjusted plane pixel rate is just the pipe's adjusted pixel rate
4629         * with additional adjustments for plane-specific scaling.
4630         */
4631        adjusted_pixel_rate = crtc_state->pixel_rate;
4632        downscale_amount = skl_plane_downscale_amount(crtc_state, plane_state);
4633
4634        return mul_round_up_u32_fixed16(adjusted_pixel_rate,
4635                                            downscale_amount);
4636}
4637
4638static int
4639skl_compute_wm_params(const struct intel_crtc_state *crtc_state,
4640                      int width, const struct drm_format_info *format,
4641                      u64 modifier, unsigned int rotation,
4642                      u32 plane_pixel_rate, struct skl_wm_params *wp,
4643                      int color_plane)
4644{
4645        struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4646        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4647        u32 interm_pbpl;
4648
4649        /* only planar format has two planes */
4650        if (color_plane == 1 && !is_planar_yuv_format(format->format)) {
4651                DRM_DEBUG_KMS("Non planar format have single plane\n");
4652                return -EINVAL;
4653        }
4654
4655        wp->y_tiled = modifier == I915_FORMAT_MOD_Y_TILED ||
4656                      modifier == I915_FORMAT_MOD_Yf_TILED ||
4657                      modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
4658                      modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
4659        wp->x_tiled = modifier == I915_FORMAT_MOD_X_TILED;
4660        wp->rc_surface = modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
4661                         modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
4662        wp->is_planar = is_planar_yuv_format(format->format);
4663
4664        wp->width = width;
4665        if (color_plane == 1 && wp->is_planar)
4666                wp->width /= 2;
4667
4668        wp->cpp = format->cpp[color_plane];
4669        wp->plane_pixel_rate = plane_pixel_rate;
4670
4671        if (INTEL_GEN(dev_priv) >= 11 &&
4672            modifier == I915_FORMAT_MOD_Yf_TILED  && wp->cpp == 1)
4673                wp->dbuf_block_size = 256;
4674        else
4675                wp->dbuf_block_size = 512;
4676
4677        if (drm_rotation_90_or_270(rotation)) {
4678                switch (wp->cpp) {
4679                case 1:
4680                        wp->y_min_scanlines = 16;
4681                        break;
4682                case 2:
4683                        wp->y_min_scanlines = 8;
4684                        break;
4685                case 4:
4686                        wp->y_min_scanlines = 4;
4687                        break;
4688                default:
4689                        MISSING_CASE(wp->cpp);
4690                        return -EINVAL;
4691                }
4692        } else {
4693                wp->y_min_scanlines = 4;
4694        }
4695
4696        if (skl_needs_memory_bw_wa(dev_priv))
4697                wp->y_min_scanlines *= 2;
4698
4699        wp->plane_bytes_per_line = wp->width * wp->cpp;
4700        if (wp->y_tiled) {
4701                interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line *
4702                                           wp->y_min_scanlines,
4703                                           wp->dbuf_block_size);
4704
4705                if (INTEL_GEN(dev_priv) >= 10)
4706                        interm_pbpl++;
4707
4708                wp->plane_blocks_per_line = div_fixed16(interm_pbpl,
4709                                                        wp->y_min_scanlines);
4710        } else if (wp->x_tiled && IS_GEN(dev_priv, 9)) {
4711                interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line,
4712                                           wp->dbuf_block_size);
4713                wp->plane_blocks_per_line = u32_to_fixed16(interm_pbpl);
4714        } else {
4715                interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line,
4716                                           wp->dbuf_block_size) + 1;
4717                wp->plane_blocks_per_line = u32_to_fixed16(interm_pbpl);
4718        }
4719
4720        wp->y_tile_minimum = mul_u32_fixed16(wp->y_min_scanlines,
4721                                             wp->plane_blocks_per_line);
4722
4723        wp->linetime_us = fixed16_to_u32_round_up(
4724                                        intel_get_linetime_us(crtc_state));
4725
4726        return 0;
4727}
4728
4729static int
4730skl_compute_plane_wm_params(const struct intel_crtc_state *crtc_state,
4731                            const struct intel_plane_state *plane_state,
4732                            struct skl_wm_params *wp, int color_plane)
4733{
4734        struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
4735        const struct drm_framebuffer *fb = plane_state->base.fb;
4736        int width;
4737
4738        if (plane->id == PLANE_CURSOR) {
4739                width = plane_state->base.crtc_w;
4740        } else {
4741                /*
4742                 * Src coordinates are already rotated by 270 degrees for
4743                 * the 90/270 degree plane rotation cases (to match the
4744                 * GTT mapping), hence no need to account for rotation here.
4745                 */
4746                width = drm_rect_width(&plane_state->base.src) >> 16;
4747        }
4748
4749        return skl_compute_wm_params(crtc_state, width,
4750                                     fb->format, fb->modifier,
4751                                     plane_state->base.rotation,
4752                                     skl_adjusted_plane_pixel_rate(crtc_state, plane_state),
4753                                     wp, color_plane);
4754}
4755
4756static bool skl_wm_has_lines(struct drm_i915_private *dev_priv, int level)
4757{
4758        if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4759                return true;
4760
4761        /* The number of lines are ignored for the level 0 watermark. */
4762        return level > 0;
4763}
4764
4765static void skl_compute_plane_wm(const struct intel_crtc_state *crtc_state,
4766                                 int level,
4767                                 const struct skl_wm_params *wp,
4768                                 const struct skl_wm_level *result_prev,
4769                                 struct skl_wm_level *result /* out */)
4770{
4771        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4772        u32 latency = dev_priv->wm.skl_latency[level];
4773        uint_fixed_16_16_t method1, method2;
4774        uint_fixed_16_16_t selected_result;
4775        u32 res_blocks, res_lines, min_ddb_alloc = 0;
4776
4777        if (latency == 0) {
4778                /* reject it */
4779                result->min_ddb_alloc = U16_MAX;
4780                return;
4781        }
4782
4783        /*
4784         * WaIncreaseLatencyIPCEnabled: kbl,cfl
4785         * Display WA #1141: kbl,cfl
4786         */
4787        if ((IS_KABYLAKE(dev_priv) || IS_COFFEELAKE(dev_priv)) ||
4788            dev_priv->ipc_enabled)
4789                latency += 4;
4790
4791        if (skl_needs_memory_bw_wa(dev_priv) && wp->x_tiled)
4792                latency += 15;
4793
4794        method1 = skl_wm_method1(dev_priv, wp->plane_pixel_rate,
4795                                 wp->cpp, latency, wp->dbuf_block_size);
4796        method2 = skl_wm_method2(wp->plane_pixel_rate,
4797                                 crtc_state->base.adjusted_mode.crtc_htotal,
4798                                 latency,
4799                                 wp->plane_blocks_per_line);
4800
4801        if (wp->y_tiled) {
4802                selected_result = max_fixed16(method2, wp->y_tile_minimum);
4803        } else {
4804                if ((wp->cpp * crtc_state->base.adjusted_mode.crtc_htotal /
4805                     wp->dbuf_block_size < 1) &&
4806                     (wp->plane_bytes_per_line / wp->dbuf_block_size < 1)) {
4807                        selected_result = method2;
4808                } else if (latency >= wp->linetime_us) {
4809                        if (IS_GEN(dev_priv, 9) &&
4810                            !IS_GEMINILAKE(dev_priv))
4811                                selected_result = min_fixed16(method1, method2);
4812                        else
4813                                selected_result = method2;
4814                } else {
4815                        selected_result = method1;
4816                }
4817        }
4818
4819        res_blocks = fixed16_to_u32_round_up(selected_result) + 1;
4820        res_lines = div_round_up_fixed16(selected_result,
4821                                         wp->plane_blocks_per_line);
4822
4823        if (IS_GEN9_BC(dev_priv) || IS_BROXTON(dev_priv)) {
4824                /* Display WA #1125: skl,bxt,kbl */
4825                if (level == 0 && wp->rc_surface)
4826                        res_blocks +=
4827                                fixed16_to_u32_round_up(wp->y_tile_minimum);
4828
4829                /* Display WA #1126: skl,bxt,kbl */
4830                if (level >= 1 && level <= 7) {
4831                        if (wp->y_tiled) {
4832                                res_blocks +=
4833                                    fixed16_to_u32_round_up(wp->y_tile_minimum);
4834                                res_lines += wp->y_min_scanlines;
4835                        } else {
4836                                res_blocks++;
4837                        }
4838
4839                        /*
4840                         * Make sure result blocks for higher latency levels are
4841                         * atleast as high as level below the current level.
4842                         * Assumption in DDB algorithm optimization for special
4843                         * cases. Also covers Display WA #1125 for RC.
4844                         */
4845                        if (result_prev->plane_res_b > res_blocks)
4846                                res_blocks = result_prev->plane_res_b;
4847                }
4848        }
4849
4850        if (INTEL_GEN(dev_priv) >= 11) {
4851                if (wp->y_tiled) {
4852                        int extra_lines;
4853
4854                        if (res_lines % wp->y_min_scanlines == 0)
4855                                extra_lines = wp->y_min_scanlines;
4856                        else
4857                                extra_lines = wp->y_min_scanlines * 2 -
4858                                        res_lines % wp->y_min_scanlines;
4859
4860                        min_ddb_alloc = mul_round_up_u32_fixed16(res_lines + extra_lines,
4861                                                                 wp->plane_blocks_per_line);
4862                } else {
4863                        min_ddb_alloc = res_blocks +
4864                                DIV_ROUND_UP(res_blocks, 10);
4865                }
4866        }
4867
4868        if (!skl_wm_has_lines(dev_priv, level))
4869                res_lines = 0;
4870
4871        if (res_lines > 31) {
4872                /* reject it */
4873                result->min_ddb_alloc = U16_MAX;
4874                return;
4875        }
4876
4877        /*
4878         * If res_lines is valid, assume we can use this watermark level
4879         * for now.  We'll come back and disable it after we calculate the
4880         * DDB allocation if it turns out we don't actually have enough
4881         * blocks to satisfy it.
4882         */
4883        result->plane_res_b = res_blocks;
4884        result->plane_res_l = res_lines;
4885        /* Bspec says: value >= plane ddb allocation -> invalid, hence the +1 here */
4886        result->min_ddb_alloc = max(min_ddb_alloc, res_blocks) + 1;
4887        result->plane_en = true;
4888}
4889
4890static void
4891skl_compute_wm_levels(const struct intel_crtc_state *crtc_state,
4892                      const struct skl_wm_params *wm_params,
4893                      struct skl_wm_level *levels)
4894{
4895        struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4896        int level, max_level = ilk_wm_max_level(dev_priv);
4897        struct skl_wm_level *result_prev = &levels[0];
4898
4899        for (level = 0; level <= max_level; level++) {
4900                struct skl_wm_level *result = &levels[level];
4901
4902                skl_compute_plane_wm(crtc_state, level, wm_params,
4903                                     result_prev, result);
4904
4905                result_prev = result;
4906        }
4907}
4908
4909static u32
4910skl_compute_linetime_wm(const struct intel_crtc_state *crtc_state)
4911{
4912        struct drm_atomic_state *state = crtc_state->base.state;
4913        struct drm_i915_private *dev_priv = to_i915(state->dev);
4914        uint_fixed_16_16_t linetime_us;
4915        u32 linetime_wm;
4916
4917        linetime_us = intel_get_linetime_us(crtc_state);
4918        linetime_wm = fixed16_to_u32_round_up(mul_u32_fixed16(8, linetime_us));
4919
4920        /* Display WA #1135: BXT:ALL GLK:ALL */
4921        if (IS_GEN9_LP(dev_priv) && dev_priv->ipc_enabled)
4922                linetime_wm /= 2;
4923
4924        return linetime_wm;
4925}
4926
4927static void skl_compute_transition_wm(const struct intel_crtc_state *crtc_state,
4928                                      const struct skl_wm_params *wp,
4929                                      struct skl_plane_wm *wm)
4930{
4931        struct drm_device *dev = crtc_state->base.crtc->dev;
4932        const struct drm_i915_private *dev_priv = to_i915(dev);
4933        u16 trans_min, trans_y_tile_min;
4934        const u16 trans_amount = 10; /* This is configurable amount */
4935        u16 wm0_sel_res_b, trans_offset_b, res_blocks;
4936
4937        /* Transition WM are not recommended by HW team for GEN9 */
4938        if (INTEL_GEN(dev_priv) <= 9)
4939                return;
4940
4941        /* Transition WM don't make any sense if ipc is disabled */
4942        if (!dev_priv->ipc_enabled)
4943                return;
4944
4945        trans_min = 14;
4946        if (INTEL_GEN(dev_priv) >= 11)
4947                trans_min = 4;
4948
4949        trans_offset_b = trans_min + trans_amount;
4950
4951        /*
4952         * The spec asks for Selected Result Blocks for wm0 (the real value),
4953         * not Result Blocks (the integer value). Pay attention to the capital
4954         * letters. The value wm_l0->plane_res_b is actually Result Blocks, but
4955         * since Result Blocks is the ceiling of Selected Result Blocks plus 1,
4956         * and since we later will have to get the ceiling of the sum in the
4957         * transition watermarks calculation, we can just pretend Selected
4958         * Result Blocks is Result Blocks minus 1 and it should work for the
4959         * current platforms.
4960         */
4961        wm0_sel_res_b = wm->wm[0].plane_res_b - 1;
4962
4963        if (wp->y_tiled) {
4964                trans_y_tile_min =
4965                        (u16)mul_round_up_u32_fixed16(2, wp->y_tile_minimum);
4966                res_blocks = max(wm0_sel_res_b, trans_y_tile_min) +
4967                                trans_offset_b;
4968        } else {
4969                res_blocks = wm0_sel_res_b + trans_offset_b;
4970
4971                /* WA BUG:1938466 add one block for non y-tile