source: src/linux/universal/linux-4.4/drivers/gpu/drm/i915/intel_pm.c @ 31662

Last change on this file since 31662 was 31662, checked in by brainslayer, 2 weeks ago

use new squashfs in all kernels

File size: 206.9 KB
Line 
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 "i915_drv.h"
30#include "intel_drv.h"
31#include "../../../platform/x86/intel_ips.h"
32#include <linux/module.h>
33
34/**
35 * RC6 is a special power stage which allows the GPU to enter an very
36 * low-voltage mode when idle, using down to 0V while at this stage.  This
37 * stage is entered automatically when the GPU is idle when RC6 support is
38 * enabled, and as soon as new workload arises GPU wakes up automatically as well.
39 *
40 * There are different RC6 modes available in Intel GPU, which differentiate
41 * among each other with the latency required to enter and leave RC6 and
42 * voltage consumed by the GPU in different states.
43 *
44 * The combination of the following flags define which states GPU is allowed
45 * to enter, while RC6 is the normal RC6 state, RC6p is the deep RC6, and
46 * RC6pp is deepest RC6. Their support by hardware varies according to the
47 * GPU, BIOS, chipset and platform. RC6 is usually the safest one and the one
48 * which brings the most power savings; deeper states save more power, but
49 * require higher latency to switch to and wake up.
50 */
51#define INTEL_RC6_ENABLE                        (1<<0)
52#define INTEL_RC6p_ENABLE                       (1<<1)
53#define INTEL_RC6pp_ENABLE                      (1<<2)
54
55static void bxt_init_clock_gating(struct drm_device *dev)
56{
57        struct drm_i915_private *dev_priv = dev->dev_private;
58
59        /* WaDisableSDEUnitClockGating:bxt */
60        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
61                   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
62
63        /*
64         * FIXME:
65         * GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ applies on 3x6 GT SKUs only.
66         */
67        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
68                   GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ);
69}
70
71static void i915_pineview_get_mem_freq(struct drm_device *dev)
72{
73        struct drm_i915_private *dev_priv = dev->dev_private;
74        u32 tmp;
75
76        tmp = I915_READ(CLKCFG);
77
78        switch (tmp & CLKCFG_FSB_MASK) {
79        case CLKCFG_FSB_533:
80                dev_priv->fsb_freq = 533; /* 133*4 */
81                break;
82        case CLKCFG_FSB_800:
83                dev_priv->fsb_freq = 800; /* 200*4 */
84                break;
85        case CLKCFG_FSB_667:
86                dev_priv->fsb_freq =  667; /* 167*4 */
87                break;
88        case CLKCFG_FSB_400:
89                dev_priv->fsb_freq = 400; /* 100*4 */
90                break;
91        }
92
93        switch (tmp & CLKCFG_MEM_MASK) {
94        case CLKCFG_MEM_533:
95                dev_priv->mem_freq = 533;
96                break;
97        case CLKCFG_MEM_667:
98                dev_priv->mem_freq = 667;
99                break;
100        case CLKCFG_MEM_800:
101                dev_priv->mem_freq = 800;
102                break;
103        }
104
105        /* detect pineview DDR3 setting */
106        tmp = I915_READ(CSHRDDR3CTL);
107        dev_priv->is_ddr3 = (tmp & CSHRDDR3CTL_DDR3) ? 1 : 0;
108}
109
110static void i915_ironlake_get_mem_freq(struct drm_device *dev)
111{
112        struct drm_i915_private *dev_priv = dev->dev_private;
113        u16 ddrpll, csipll;
114
115        ddrpll = I915_READ16(DDRMPLL1);
116        csipll = I915_READ16(CSIPLL0);
117
118        switch (ddrpll & 0xff) {
119        case 0xc:
120                dev_priv->mem_freq = 800;
121                break;
122        case 0x10:
123                dev_priv->mem_freq = 1066;
124                break;
125        case 0x14:
126                dev_priv->mem_freq = 1333;
127                break;
128        case 0x18:
129                dev_priv->mem_freq = 1600;
130                break;
131        default:
132                DRM_DEBUG_DRIVER("unknown memory frequency 0x%02x\n",
133                                 ddrpll & 0xff);
134                dev_priv->mem_freq = 0;
135                break;
136        }
137
138        dev_priv->ips.r_t = dev_priv->mem_freq;
139
140        switch (csipll & 0x3ff) {
141        case 0x00c:
142                dev_priv->fsb_freq = 3200;
143                break;
144        case 0x00e:
145                dev_priv->fsb_freq = 3733;
146                break;
147        case 0x010:
148                dev_priv->fsb_freq = 4266;
149                break;
150        case 0x012:
151                dev_priv->fsb_freq = 4800;
152                break;
153        case 0x014:
154                dev_priv->fsb_freq = 5333;
155                break;
156        case 0x016:
157                dev_priv->fsb_freq = 5866;
158                break;
159        case 0x018:
160                dev_priv->fsb_freq = 6400;
161                break;
162        default:
163                DRM_DEBUG_DRIVER("unknown fsb frequency 0x%04x\n",
164                                 csipll & 0x3ff);
165                dev_priv->fsb_freq = 0;
166                break;
167        }
168
169        if (dev_priv->fsb_freq == 3200) {
170                dev_priv->ips.c_m = 0;
171        } else if (dev_priv->fsb_freq > 3200 && dev_priv->fsb_freq <= 4800) {
172                dev_priv->ips.c_m = 1;
173        } else {
174                dev_priv->ips.c_m = 2;
175        }
176}
177
178static const struct cxsr_latency cxsr_latency_table[] = {
179        {1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
180        {1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
181        {1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
182        {1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
183        {1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
184
185        {1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
186        {1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
187        {1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
188        {1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
189        {1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
190
191        {1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
192        {1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
193        {1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
194        {1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
195        {1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
196
197        {0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
198        {0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
199        {0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
200        {0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
201        {0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
202
203        {0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
204        {0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
205        {0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
206        {0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
207        {0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
208
209        {0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
210        {0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
211        {0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
212        {0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
213        {0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
214};
215
216static const struct cxsr_latency *intel_get_cxsr_latency(int is_desktop,
217                                                         int is_ddr3,
218                                                         int fsb,
219                                                         int mem)
220{
221        const struct cxsr_latency *latency;
222        int i;
223
224        if (fsb == 0 || mem == 0)
225                return NULL;
226
227        for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
228                latency = &cxsr_latency_table[i];
229                if (is_desktop == latency->is_desktop &&
230                    is_ddr3 == latency->is_ddr3 &&
231                    fsb == latency->fsb_freq && mem == latency->mem_freq)
232                        return latency;
233        }
234
235        DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
236
237        return NULL;
238}
239
240static void chv_set_memory_dvfs(struct drm_i915_private *dev_priv, bool enable)
241{
242        u32 val;
243
244        mutex_lock(&dev_priv->rps.hw_lock);
245
246        val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
247        if (enable)
248                val &= ~FORCE_DDR_HIGH_FREQ;
249        else
250                val |= FORCE_DDR_HIGH_FREQ;
251        val &= ~FORCE_DDR_LOW_FREQ;
252        val |= FORCE_DDR_FREQ_REQ_ACK;
253        vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
254
255        if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
256                      FORCE_DDR_FREQ_REQ_ACK) == 0, 3))
257                DRM_ERROR("timed out waiting for Punit DDR DVFS request\n");
258
259        mutex_unlock(&dev_priv->rps.hw_lock);
260}
261
262static void chv_set_memory_pm5(struct drm_i915_private *dev_priv, bool enable)
263{
264        u32 val;
265
266        mutex_lock(&dev_priv->rps.hw_lock);
267
268        val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
269        if (enable)
270                val |= DSP_MAXFIFO_PM5_ENABLE;
271        else
272                val &= ~DSP_MAXFIFO_PM5_ENABLE;
273        vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
274
275        mutex_unlock(&dev_priv->rps.hw_lock);
276}
277
278#define FW_WM(value, plane) \
279        (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK)
280
281void intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
282{
283        struct drm_device *dev = dev_priv->dev;
284        u32 val;
285
286        if (IS_VALLEYVIEW(dev)) {
287                I915_WRITE(FW_BLC_SELF_VLV, enable ? FW_CSPWRDWNEN : 0);
288                POSTING_READ(FW_BLC_SELF_VLV);
289                dev_priv->wm.vlv.cxsr = enable;
290        } else if (IS_G4X(dev) || IS_CRESTLINE(dev)) {
291                I915_WRITE(FW_BLC_SELF, enable ? FW_BLC_SELF_EN : 0);
292                POSTING_READ(FW_BLC_SELF);
293        } else if (IS_PINEVIEW(dev)) {
294                val = I915_READ(DSPFW3) & ~PINEVIEW_SELF_REFRESH_EN;
295                val |= enable ? PINEVIEW_SELF_REFRESH_EN : 0;
296                I915_WRITE(DSPFW3, val);
297                POSTING_READ(DSPFW3);
298        } else if (IS_I945G(dev) || IS_I945GM(dev)) {
299                val = enable ? _MASKED_BIT_ENABLE(FW_BLC_SELF_EN) :
300                               _MASKED_BIT_DISABLE(FW_BLC_SELF_EN);
301                I915_WRITE(FW_BLC_SELF, val);
302                POSTING_READ(FW_BLC_SELF);
303        } else if (IS_I915GM(dev)) {
304                val = enable ? _MASKED_BIT_ENABLE(INSTPM_SELF_EN) :
305                               _MASKED_BIT_DISABLE(INSTPM_SELF_EN);
306                I915_WRITE(INSTPM, val);
307                POSTING_READ(INSTPM);
308        } else {
309                return;
310        }
311
312        DRM_DEBUG_KMS("memory self-refresh is %s\n",
313                      enable ? "enabled" : "disabled");
314}
315
316
317/*
318 * Latency for FIFO fetches is dependent on several factors:
319 *   - memory configuration (speed, channels)
320 *   - chipset
321 *   - current MCH state
322 * It can be fairly high in some situations, so here we assume a fairly
323 * pessimal value.  It's a tradeoff between extra memory fetches (if we
324 * set this value too high, the FIFO will fetch frequently to stay full)
325 * and power consumption (set it too low to save power and we might see
326 * FIFO underruns and display "flicker").
327 *
328 * A value of 5us seems to be a good balance; safe for very low end
329 * platforms but not overly aggressive on lower latency configs.
330 */
331static const int pessimal_latency_ns = 5000;
332
333#define VLV_FIFO_START(dsparb, dsparb2, lo_shift, hi_shift) \
334        ((((dsparb) >> (lo_shift)) & 0xff) | ((((dsparb2) >> (hi_shift)) & 0x1) << 8))
335
336static int vlv_get_fifo_size(struct drm_device *dev,
337                              enum pipe pipe, int plane)
338{
339        struct drm_i915_private *dev_priv = dev->dev_private;
340        int sprite0_start, sprite1_start, size;
341
342        switch (pipe) {
343                uint32_t dsparb, dsparb2, dsparb3;
344        case PIPE_A:
345                dsparb = I915_READ(DSPARB);
346                dsparb2 = I915_READ(DSPARB2);
347                sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 0, 0);
348                sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 8, 4);
349                break;
350        case PIPE_B:
351                dsparb = I915_READ(DSPARB);
352                dsparb2 = I915_READ(DSPARB2);
353                sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 16, 8);
354                sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 24, 12);
355                break;
356        case PIPE_C:
357                dsparb2 = I915_READ(DSPARB2);
358                dsparb3 = I915_READ(DSPARB3);
359                sprite0_start = VLV_FIFO_START(dsparb3, dsparb2, 0, 16);
360                sprite1_start = VLV_FIFO_START(dsparb3, dsparb2, 8, 20);
361                break;
362        default:
363                return 0;
364        }
365
366        switch (plane) {
367        case 0:
368                size = sprite0_start;
369                break;
370        case 1:
371                size = sprite1_start - sprite0_start;
372                break;
373        case 2:
374                size = 512 - 1 - sprite1_start;
375                break;
376        default:
377                return 0;
378        }
379
380        DRM_DEBUG_KMS("Pipe %c %s %c FIFO size: %d\n",
381                      pipe_name(pipe), plane == 0 ? "primary" : "sprite",
382                      plane == 0 ? plane_name(pipe) : sprite_name(pipe, plane - 1),
383                      size);
384
385        return size;
386}
387
388static int i9xx_get_fifo_size(struct drm_device *dev, int plane)
389{
390        struct drm_i915_private *dev_priv = dev->dev_private;
391        uint32_t dsparb = I915_READ(DSPARB);
392        int size;
393
394        size = dsparb & 0x7f;
395        if (plane)
396                size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
397
398        DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
399                      plane ? "B" : "A", size);
400
401        return size;
402}
403
404static int i830_get_fifo_size(struct drm_device *dev, int plane)
405{
406        struct drm_i915_private *dev_priv = dev->dev_private;
407        uint32_t dsparb = I915_READ(DSPARB);
408        int size;
409
410        size = dsparb & 0x1ff;
411        if (plane)
412                size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
413        size >>= 1; /* Convert to cachelines */
414
415        DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
416                      plane ? "B" : "A", size);
417
418        return size;
419}
420
421static int i845_get_fifo_size(struct drm_device *dev, int plane)
422{
423        struct drm_i915_private *dev_priv = dev->dev_private;
424        uint32_t dsparb = I915_READ(DSPARB);
425        int size;
426
427        size = dsparb & 0x7f;
428        size >>= 2; /* Convert to cachelines */
429
430        DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
431                      plane ? "B" : "A",
432                      size);
433
434        return size;
435}
436
437/* Pineview has different values for various configs */
438static const struct intel_watermark_params pineview_display_wm = {
439        .fifo_size = PINEVIEW_DISPLAY_FIFO,
440        .max_wm = PINEVIEW_MAX_WM,
441        .default_wm = PINEVIEW_DFT_WM,
442        .guard_size = PINEVIEW_GUARD_WM,
443        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
444};
445static const struct intel_watermark_params pineview_display_hplloff_wm = {
446        .fifo_size = PINEVIEW_DISPLAY_FIFO,
447        .max_wm = PINEVIEW_MAX_WM,
448        .default_wm = PINEVIEW_DFT_HPLLOFF_WM,
449        .guard_size = PINEVIEW_GUARD_WM,
450        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
451};
452static const struct intel_watermark_params pineview_cursor_wm = {
453        .fifo_size = PINEVIEW_CURSOR_FIFO,
454        .max_wm = PINEVIEW_CURSOR_MAX_WM,
455        .default_wm = PINEVIEW_CURSOR_DFT_WM,
456        .guard_size = PINEVIEW_CURSOR_GUARD_WM,
457        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
458};
459static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
460        .fifo_size = PINEVIEW_CURSOR_FIFO,
461        .max_wm = PINEVIEW_CURSOR_MAX_WM,
462        .default_wm = PINEVIEW_CURSOR_DFT_WM,
463        .guard_size = PINEVIEW_CURSOR_GUARD_WM,
464        .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
465};
466static const struct intel_watermark_params g4x_wm_info = {
467        .fifo_size = G4X_FIFO_SIZE,
468        .max_wm = G4X_MAX_WM,
469        .default_wm = G4X_MAX_WM,
470        .guard_size = 2,
471        .cacheline_size = G4X_FIFO_LINE_SIZE,
472};
473static const struct intel_watermark_params g4x_cursor_wm_info = {
474        .fifo_size = I965_CURSOR_FIFO,
475        .max_wm = I965_CURSOR_MAX_WM,
476        .default_wm = I965_CURSOR_DFT_WM,
477        .guard_size = 2,
478        .cacheline_size = G4X_FIFO_LINE_SIZE,
479};
480static const struct intel_watermark_params valleyview_wm_info = {
481        .fifo_size = VALLEYVIEW_FIFO_SIZE,
482        .max_wm = VALLEYVIEW_MAX_WM,
483        .default_wm = VALLEYVIEW_MAX_WM,
484        .guard_size = 2,
485        .cacheline_size = G4X_FIFO_LINE_SIZE,
486};
487static const struct intel_watermark_params valleyview_cursor_wm_info = {
488        .fifo_size = I965_CURSOR_FIFO,
489        .max_wm = VALLEYVIEW_CURSOR_MAX_WM,
490        .default_wm = I965_CURSOR_DFT_WM,
491        .guard_size = 2,
492        .cacheline_size = G4X_FIFO_LINE_SIZE,
493};
494static const struct intel_watermark_params i965_cursor_wm_info = {
495        .fifo_size = I965_CURSOR_FIFO,
496        .max_wm = I965_CURSOR_MAX_WM,
497        .default_wm = I965_CURSOR_DFT_WM,
498        .guard_size = 2,
499        .cacheline_size = I915_FIFO_LINE_SIZE,
500};
501static const struct intel_watermark_params i945_wm_info = {
502        .fifo_size = I945_FIFO_SIZE,
503        .max_wm = I915_MAX_WM,
504        .default_wm = 1,
505        .guard_size = 2,
506        .cacheline_size = I915_FIFO_LINE_SIZE,
507};
508static const struct intel_watermark_params i915_wm_info = {
509        .fifo_size = I915_FIFO_SIZE,
510        .max_wm = I915_MAX_WM,
511        .default_wm = 1,
512        .guard_size = 2,
513        .cacheline_size = I915_FIFO_LINE_SIZE,
514};
515static const struct intel_watermark_params i830_a_wm_info = {
516        .fifo_size = I855GM_FIFO_SIZE,
517        .max_wm = I915_MAX_WM,
518        .default_wm = 1,
519        .guard_size = 2,
520        .cacheline_size = I830_FIFO_LINE_SIZE,
521};
522static const struct intel_watermark_params i830_bc_wm_info = {
523        .fifo_size = I855GM_FIFO_SIZE,
524        .max_wm = I915_MAX_WM/2,
525        .default_wm = 1,
526        .guard_size = 2,
527        .cacheline_size = I830_FIFO_LINE_SIZE,
528};
529static const struct intel_watermark_params i845_wm_info = {
530        .fifo_size = I830_FIFO_SIZE,
531        .max_wm = I915_MAX_WM,
532        .default_wm = 1,
533        .guard_size = 2,
534        .cacheline_size = I830_FIFO_LINE_SIZE,
535};
536
537/**
538 * intel_calculate_wm - calculate watermark level
539 * @clock_in_khz: pixel clock
540 * @wm: chip FIFO params
541 * @pixel_size: display pixel size
542 * @latency_ns: memory latency for the platform
543 *
544 * Calculate the watermark level (the level at which the display plane will
545 * start fetching from memory again).  Each chip has a different display
546 * FIFO size and allocation, so the caller needs to figure that out and pass
547 * in the correct intel_watermark_params structure.
548 *
549 * As the pixel clock runs, the FIFO will be drained at a rate that depends
550 * on the pixel size.  When it reaches the watermark level, it'll start
551 * fetching FIFO line sized based chunks from memory until the FIFO fills
552 * past the watermark point.  If the FIFO drains completely, a FIFO underrun
553 * will occur, and a display engine hang could result.
554 */
555static unsigned long intel_calculate_wm(unsigned long clock_in_khz,
556                                        const struct intel_watermark_params *wm,
557                                        int fifo_size,
558                                        int pixel_size,
559                                        unsigned long latency_ns)
560{
561        long entries_required, wm_size;
562
563        /*
564         * Note: we need to make sure we don't overflow for various clock &
565         * latency values.
566         * clocks go from a few thousand to several hundred thousand.
567         * latency is usually a few thousand
568         */
569        entries_required = ((clock_in_khz / 1000) * pixel_size * latency_ns) /
570                1000;
571        entries_required = DIV_ROUND_UP(entries_required, wm->cacheline_size);
572
573        DRM_DEBUG_KMS("FIFO entries required for mode: %ld\n", entries_required);
574
575        wm_size = fifo_size - (entries_required + wm->guard_size);
576
577        DRM_DEBUG_KMS("FIFO watermark level: %ld\n", wm_size);
578
579        /* Don't promote wm_size to unsigned... */
580        if (wm_size > (long)wm->max_wm)
581                wm_size = wm->max_wm;
582        if (wm_size <= 0)
583                wm_size = wm->default_wm;
584
585        /*
586         * Bspec seems to indicate that the value shouldn't be lower than
587         * 'burst size + 1'. Certainly 830 is quite unhappy with low values.
588         * Lets go for 8 which is the burst size since certain platforms
589         * already use a hardcoded 8 (which is what the spec says should be
590         * done).
591         */
592        if (wm_size <= 8)
593                wm_size = 8;
594
595        return wm_size;
596}
597
598static struct drm_crtc *single_enabled_crtc(struct drm_device *dev)
599{
600        struct drm_crtc *crtc, *enabled = NULL;
601
602        for_each_crtc(dev, crtc) {
603                if (intel_crtc_active(crtc)) {
604                        if (enabled)
605                                return NULL;
606                        enabled = crtc;
607                }
608        }
609
610        return enabled;
611}
612
613static void pineview_update_wm(struct drm_crtc *unused_crtc)
614{
615        struct drm_device *dev = unused_crtc->dev;
616        struct drm_i915_private *dev_priv = dev->dev_private;
617        struct drm_crtc *crtc;
618        const struct cxsr_latency *latency;
619        u32 reg;
620        unsigned long wm;
621
622        latency = intel_get_cxsr_latency(IS_PINEVIEW_G(dev), dev_priv->is_ddr3,
623                                         dev_priv->fsb_freq, dev_priv->mem_freq);
624        if (!latency) {
625                DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
626                intel_set_memory_cxsr(dev_priv, false);
627                return;
628        }
629
630        crtc = single_enabled_crtc(dev);
631        if (crtc) {
632                const struct drm_display_mode *adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
633                int pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
634                int clock = adjusted_mode->crtc_clock;
635
636                /* Display SR */
637                wm = intel_calculate_wm(clock, &pineview_display_wm,
638                                        pineview_display_wm.fifo_size,
639                                        pixel_size, latency->display_sr);
640                reg = I915_READ(DSPFW1);
641                reg &= ~DSPFW_SR_MASK;
642                reg |= FW_WM(wm, SR);
643                I915_WRITE(DSPFW1, reg);
644                DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
645
646                /* cursor SR */
647                wm = intel_calculate_wm(clock, &pineview_cursor_wm,
648                                        pineview_display_wm.fifo_size,
649                                        pixel_size, latency->cursor_sr);
650                reg = I915_READ(DSPFW3);
651                reg &= ~DSPFW_CURSOR_SR_MASK;
652                reg |= FW_WM(wm, CURSOR_SR);
653                I915_WRITE(DSPFW3, reg);
654
655                /* Display HPLL off SR */
656                wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
657                                        pineview_display_hplloff_wm.fifo_size,
658                                        pixel_size, latency->display_hpll_disable);
659                reg = I915_READ(DSPFW3);
660                reg &= ~DSPFW_HPLL_SR_MASK;
661                reg |= FW_WM(wm, HPLL_SR);
662                I915_WRITE(DSPFW3, reg);
663
664                /* cursor HPLL off SR */
665                wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
666                                        pineview_display_hplloff_wm.fifo_size,
667                                        pixel_size, latency->cursor_hpll_disable);
668                reg = I915_READ(DSPFW3);
669                reg &= ~DSPFW_HPLL_CURSOR_MASK;
670                reg |= FW_WM(wm, HPLL_CURSOR);
671                I915_WRITE(DSPFW3, reg);
672                DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
673
674                intel_set_memory_cxsr(dev_priv, true);
675        } else {
676                intel_set_memory_cxsr(dev_priv, false);
677        }
678}
679
680static bool g4x_compute_wm0(struct drm_device *dev,
681                            int plane,
682                            const struct intel_watermark_params *display,
683                            int display_latency_ns,
684                            const struct intel_watermark_params *cursor,
685                            int cursor_latency_ns,
686                            int *plane_wm,
687                            int *cursor_wm)
688{
689        struct drm_crtc *crtc;
690        const struct drm_display_mode *adjusted_mode;
691        int htotal, hdisplay, clock, pixel_size;
692        int line_time_us, line_count;
693        int entries, tlb_miss;
694
695        crtc = intel_get_crtc_for_plane(dev, plane);
696        if (!intel_crtc_active(crtc)) {
697                *cursor_wm = cursor->guard_size;
698                *plane_wm = display->guard_size;
699                return false;
700        }
701
702        adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
703        clock = adjusted_mode->crtc_clock;
704        htotal = adjusted_mode->crtc_htotal;
705        hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
706        pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
707
708        /* Use the small buffer method to calculate plane watermark */
709        entries = ((clock * pixel_size / 1000) * display_latency_ns) / 1000;
710        tlb_miss = display->fifo_size*display->cacheline_size - hdisplay * 8;
711        if (tlb_miss > 0)
712                entries += tlb_miss;
713        entries = DIV_ROUND_UP(entries, display->cacheline_size);
714        *plane_wm = entries + display->guard_size;
715        if (*plane_wm > (int)display->max_wm)
716                *plane_wm = display->max_wm;
717
718        /* Use the large buffer method to calculate cursor watermark */
719        line_time_us = max(htotal * 1000 / clock, 1);
720        line_count = (cursor_latency_ns / line_time_us + 1000) / 1000;
721        entries = line_count * crtc->cursor->state->crtc_w * pixel_size;
722        tlb_miss = cursor->fifo_size*cursor->cacheline_size - hdisplay * 8;
723        if (tlb_miss > 0)
724                entries += tlb_miss;
725        entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
726        *cursor_wm = entries + cursor->guard_size;
727        if (*cursor_wm > (int)cursor->max_wm)
728                *cursor_wm = (int)cursor->max_wm;
729
730        return true;
731}
732
733/*
734 * Check the wm result.
735 *
736 * If any calculated watermark values is larger than the maximum value that
737 * can be programmed into the associated watermark register, that watermark
738 * must be disabled.
739 */
740static bool g4x_check_srwm(struct drm_device *dev,
741                           int display_wm, int cursor_wm,
742                           const struct intel_watermark_params *display,
743                           const struct intel_watermark_params *cursor)
744{
745        DRM_DEBUG_KMS("SR watermark: display plane %d, cursor %d\n",
746                      display_wm, cursor_wm);
747
748        if (display_wm > display->max_wm) {
749                DRM_DEBUG_KMS("display watermark is too large(%d/%ld), disabling\n",
750                              display_wm, display->max_wm);
751                return false;
752        }
753
754        if (cursor_wm > cursor->max_wm) {
755                DRM_DEBUG_KMS("cursor watermark is too large(%d/%ld), disabling\n",
756                              cursor_wm, cursor->max_wm);
757                return false;
758        }
759
760        if (!(display_wm || cursor_wm)) {
761                DRM_DEBUG_KMS("SR latency is 0, disabling\n");
762                return false;
763        }
764
765        return true;
766}
767
768static bool g4x_compute_srwm(struct drm_device *dev,
769                             int plane,
770                             int latency_ns,
771                             const struct intel_watermark_params *display,
772                             const struct intel_watermark_params *cursor,
773                             int *display_wm, int *cursor_wm)
774{
775        struct drm_crtc *crtc;
776        const struct drm_display_mode *adjusted_mode;
777        int hdisplay, htotal, pixel_size, clock;
778        unsigned long line_time_us;
779        int line_count, line_size;
780        int small, large;
781        int entries;
782
783        if (!latency_ns) {
784                *display_wm = *cursor_wm = 0;
785                return false;
786        }
787
788        crtc = intel_get_crtc_for_plane(dev, plane);
789        adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
790        clock = adjusted_mode->crtc_clock;
791        htotal = adjusted_mode->crtc_htotal;
792        hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
793        pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
794
795        line_time_us = max(htotal * 1000 / clock, 1);
796        line_count = (latency_ns / line_time_us + 1000) / 1000;
797        line_size = hdisplay * pixel_size;
798
799        /* Use the minimum of the small and large buffer method for primary */
800        small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
801        large = line_count * line_size;
802
803        entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
804        *display_wm = entries + display->guard_size;
805
806        /* calculate the self-refresh watermark for display cursor */
807        entries = line_count * pixel_size * crtc->cursor->state->crtc_w;
808        entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
809        *cursor_wm = entries + cursor->guard_size;
810
811        return g4x_check_srwm(dev,
812                              *display_wm, *cursor_wm,
813                              display, cursor);
814}
815
816#define FW_WM_VLV(value, plane) \
817        (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK_VLV)
818
819static void vlv_write_wm_values(struct intel_crtc *crtc,
820                                const struct vlv_wm_values *wm)
821{
822        struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
823        enum pipe pipe = crtc->pipe;
824
825        I915_WRITE(VLV_DDL(pipe),
826                   (wm->ddl[pipe].cursor << DDL_CURSOR_SHIFT) |
827                   (wm->ddl[pipe].sprite[1] << DDL_SPRITE_SHIFT(1)) |
828                   (wm->ddl[pipe].sprite[0] << DDL_SPRITE_SHIFT(0)) |
829                   (wm->ddl[pipe].primary << DDL_PLANE_SHIFT));
830
831        I915_WRITE(DSPFW1,
832                   FW_WM(wm->sr.plane, SR) |
833                   FW_WM(wm->pipe[PIPE_B].cursor, CURSORB) |
834                   FW_WM_VLV(wm->pipe[PIPE_B].primary, PLANEB) |
835                   FW_WM_VLV(wm->pipe[PIPE_A].primary, PLANEA));
836        I915_WRITE(DSPFW2,
837                   FW_WM_VLV(wm->pipe[PIPE_A].sprite[1], SPRITEB) |
838                   FW_WM(wm->pipe[PIPE_A].cursor, CURSORA) |
839                   FW_WM_VLV(wm->pipe[PIPE_A].sprite[0], SPRITEA));
840        I915_WRITE(DSPFW3,
841                   FW_WM(wm->sr.cursor, CURSOR_SR));
842
843        if (IS_CHERRYVIEW(dev_priv)) {
844                I915_WRITE(DSPFW7_CHV,
845                           FW_WM_VLV(wm->pipe[PIPE_B].sprite[1], SPRITED) |
846                           FW_WM_VLV(wm->pipe[PIPE_B].sprite[0], SPRITEC));
847                I915_WRITE(DSPFW8_CHV,
848                           FW_WM_VLV(wm->pipe[PIPE_C].sprite[1], SPRITEF) |
849                           FW_WM_VLV(wm->pipe[PIPE_C].sprite[0], SPRITEE));
850                I915_WRITE(DSPFW9_CHV,
851                           FW_WM_VLV(wm->pipe[PIPE_C].primary, PLANEC) |
852                           FW_WM(wm->pipe[PIPE_C].cursor, CURSORC));
853                I915_WRITE(DSPHOWM,
854                           FW_WM(wm->sr.plane >> 9, SR_HI) |
855                           FW_WM(wm->pipe[PIPE_C].sprite[1] >> 8, SPRITEF_HI) |
856                           FW_WM(wm->pipe[PIPE_C].sprite[0] >> 8, SPRITEE_HI) |
857                           FW_WM(wm->pipe[PIPE_C].primary >> 8, PLANEC_HI) |
858                           FW_WM(wm->pipe[PIPE_B].sprite[1] >> 8, SPRITED_HI) |
859                           FW_WM(wm->pipe[PIPE_B].sprite[0] >> 8, SPRITEC_HI) |
860                           FW_WM(wm->pipe[PIPE_B].primary >> 8, PLANEB_HI) |
861                           FW_WM(wm->pipe[PIPE_A].sprite[1] >> 8, SPRITEB_HI) |
862                           FW_WM(wm->pipe[PIPE_A].sprite[0] >> 8, SPRITEA_HI) |
863                           FW_WM(wm->pipe[PIPE_A].primary >> 8, PLANEA_HI));
864        } else {
865                I915_WRITE(DSPFW7,
866                           FW_WM_VLV(wm->pipe[PIPE_B].sprite[1], SPRITED) |
867                           FW_WM_VLV(wm->pipe[PIPE_B].sprite[0], SPRITEC));
868                I915_WRITE(DSPHOWM,
869                           FW_WM(wm->sr.plane >> 9, SR_HI) |
870                           FW_WM(wm->pipe[PIPE_B].sprite[1] >> 8, SPRITED_HI) |
871                           FW_WM(wm->pipe[PIPE_B].sprite[0] >> 8, SPRITEC_HI) |
872                           FW_WM(wm->pipe[PIPE_B].primary >> 8, PLANEB_HI) |
873                           FW_WM(wm->pipe[PIPE_A].sprite[1] >> 8, SPRITEB_HI) |
874                           FW_WM(wm->pipe[PIPE_A].sprite[0] >> 8, SPRITEA_HI) |
875                           FW_WM(wm->pipe[PIPE_A].primary >> 8, PLANEA_HI));
876        }
877
878        /* zero (unused) WM1 watermarks */
879        I915_WRITE(DSPFW4, 0);
880        I915_WRITE(DSPFW5, 0);
881        I915_WRITE(DSPFW6, 0);
882        I915_WRITE(DSPHOWM1, 0);
883
884        POSTING_READ(DSPFW1);
885}
886
887#undef FW_WM_VLV
888
889enum vlv_wm_level {
890        VLV_WM_LEVEL_PM2,
891        VLV_WM_LEVEL_PM5,
892        VLV_WM_LEVEL_DDR_DVFS,
893};
894
895/* latency must be in 0.1us units. */
896static unsigned int vlv_wm_method2(unsigned int pixel_rate,
897                                   unsigned int pipe_htotal,
898                                   unsigned int horiz_pixels,
899                                   unsigned int bytes_per_pixel,
900                                   unsigned int latency)
901{
902        unsigned int ret;
903
904        ret = (latency * pixel_rate) / (pipe_htotal * 10000);
905        ret = (ret + 1) * horiz_pixels * bytes_per_pixel;
906        ret = DIV_ROUND_UP(ret, 64);
907
908        return ret;
909}
910
911static void vlv_setup_wm_latency(struct drm_device *dev)
912{
913        struct drm_i915_private *dev_priv = dev->dev_private;
914
915        /* all latencies in usec */
916        dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM2] = 3;
917
918        dev_priv->wm.max_level = VLV_WM_LEVEL_PM2;
919
920        if (IS_CHERRYVIEW(dev_priv)) {
921                dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM5] = 12;
922                dev_priv->wm.pri_latency[VLV_WM_LEVEL_DDR_DVFS] = 33;
923
924                dev_priv->wm.max_level = VLV_WM_LEVEL_DDR_DVFS;
925        }
926}
927
928static uint16_t vlv_compute_wm_level(struct intel_plane *plane,
929                                     struct intel_crtc *crtc,
930                                     const struct intel_plane_state *state,
931                                     int level)
932{
933        struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
934        int clock, htotal, pixel_size, width, wm;
935
936        if (dev_priv->wm.pri_latency[level] == 0)
937                return USHRT_MAX;
938
939        if (!state->visible)
940                return 0;
941
942        pixel_size = drm_format_plane_cpp(state->base.fb->pixel_format, 0);
943        clock = crtc->config->base.adjusted_mode.crtc_clock;
944        htotal = crtc->config->base.adjusted_mode.crtc_htotal;
945        width = crtc->config->pipe_src_w;
946        if (WARN_ON(htotal == 0))
947                htotal = 1;
948
949        if (plane->base.type == DRM_PLANE_TYPE_CURSOR) {
950                /*
951                 * FIXME the formula gives values that are
952                 * too big for the cursor FIFO, and hence we
953                 * would never be able to use cursors. For
954                 * now just hardcode the watermark.
955                 */
956                wm = 63;
957        } else {
958                wm = vlv_wm_method2(clock, htotal, width, pixel_size,
959                                    dev_priv->wm.pri_latency[level] * 10);
960        }
961
962        return min_t(int, wm, USHRT_MAX);
963}
964
965static void vlv_compute_fifo(struct intel_crtc *crtc)
966{
967        struct drm_device *dev = crtc->base.dev;
968        struct vlv_wm_state *wm_state = &crtc->wm_state;
969        struct intel_plane *plane;
970        unsigned int total_rate = 0;
971        const int fifo_size = 512 - 1;
972        int fifo_extra, fifo_left = fifo_size;
973
974        for_each_intel_plane_on_crtc(dev, crtc, plane) {
975                struct intel_plane_state *state =
976                        to_intel_plane_state(plane->base.state);
977
978                if (plane->base.type == DRM_PLANE_TYPE_CURSOR)
979                        continue;
980
981                if (state->visible) {
982                        wm_state->num_active_planes++;
983                        total_rate += drm_format_plane_cpp(state->base.fb->pixel_format, 0);
984                }
985        }
986
987        for_each_intel_plane_on_crtc(dev, crtc, plane) {
988                struct intel_plane_state *state =
989                        to_intel_plane_state(plane->base.state);
990                unsigned int rate;
991
992                if (plane->base.type == DRM_PLANE_TYPE_CURSOR) {
993                        plane->wm.fifo_size = 63;
994                        continue;
995                }
996
997                if (!state->visible) {
998                        plane->wm.fifo_size = 0;
999                        continue;
1000                }
1001
1002                rate = drm_format_plane_cpp(state->base.fb->pixel_format, 0);
1003                plane->wm.fifo_size = fifo_size * rate / total_rate;
1004                fifo_left -= plane->wm.fifo_size;
1005        }
1006
1007        fifo_extra = DIV_ROUND_UP(fifo_left, wm_state->num_active_planes ?: 1);
1008
1009        /* spread the remainder evenly */
1010        for_each_intel_plane_on_crtc(dev, crtc, plane) {
1011                int plane_extra;
1012
1013                if (fifo_left == 0)
1014                        break;
1015
1016                if (plane->base.type == DRM_PLANE_TYPE_CURSOR)
1017                        continue;
1018
1019                /* give it all to the first plane if none are active */
1020                if (plane->wm.fifo_size == 0 &&
1021                    wm_state->num_active_planes)
1022                        continue;
1023
1024                plane_extra = min(fifo_extra, fifo_left);
1025                plane->wm.fifo_size += plane_extra;
1026                fifo_left -= plane_extra;
1027        }
1028
1029        WARN_ON(fifo_left != 0);
1030}
1031
1032static void vlv_invert_wms(struct intel_crtc *crtc)
1033{
1034        struct vlv_wm_state *wm_state = &crtc->wm_state;
1035        int level;
1036
1037        for (level = 0; level < wm_state->num_levels; level++) {
1038                struct drm_device *dev = crtc->base.dev;
1039                const int sr_fifo_size = INTEL_INFO(dev)->num_pipes * 512 - 1;
1040                struct intel_plane *plane;
1041
1042                wm_state->sr[level].plane = sr_fifo_size - wm_state->sr[level].plane;
1043                wm_state->sr[level].cursor = 63 - wm_state->sr[level].cursor;
1044
1045                for_each_intel_plane_on_crtc(dev, crtc, plane) {
1046                        switch (plane->base.type) {
1047                                int sprite;
1048                        case DRM_PLANE_TYPE_CURSOR:
1049                                wm_state->wm[level].cursor = plane->wm.fifo_size -
1050                                        wm_state->wm[level].cursor;
1051                                break;
1052                        case DRM_PLANE_TYPE_PRIMARY:
1053                                wm_state->wm[level].primary = plane->wm.fifo_size -
1054                                        wm_state->wm[level].primary;
1055                                break;
1056                        case DRM_PLANE_TYPE_OVERLAY:
1057                                sprite = plane->plane;
1058                                wm_state->wm[level].sprite[sprite] = plane->wm.fifo_size -
1059                                        wm_state->wm[level].sprite[sprite];
1060                                break;
1061                        }
1062                }
1063        }
1064}
1065
1066static void vlv_compute_wm(struct intel_crtc *crtc)
1067{
1068        struct drm_device *dev = crtc->base.dev;
1069        struct vlv_wm_state *wm_state = &crtc->wm_state;
1070        struct intel_plane *plane;
1071        int sr_fifo_size = INTEL_INFO(dev)->num_pipes * 512 - 1;
1072        int level;
1073
1074        memset(wm_state, 0, sizeof(*wm_state));
1075
1076        wm_state->cxsr = crtc->pipe != PIPE_C && crtc->wm.cxsr_allowed;
1077        wm_state->num_levels = to_i915(dev)->wm.max_level + 1;
1078
1079        wm_state->num_active_planes = 0;
1080
1081        vlv_compute_fifo(crtc);
1082
1083        if (wm_state->num_active_planes != 1)
1084                wm_state->cxsr = false;
1085
1086        if (wm_state->cxsr) {
1087                for (level = 0; level < wm_state->num_levels; level++) {
1088                        wm_state->sr[level].plane = sr_fifo_size;
1089                        wm_state->sr[level].cursor = 63;
1090                }
1091        }
1092
1093        for_each_intel_plane_on_crtc(dev, crtc, plane) {
1094                struct intel_plane_state *state =
1095                        to_intel_plane_state(plane->base.state);
1096
1097                if (!state->visible)
1098                        continue;
1099
1100                /* normal watermarks */
1101                for (level = 0; level < wm_state->num_levels; level++) {
1102                        int wm = vlv_compute_wm_level(plane, crtc, state, level);
1103                        int max_wm = plane->base.type == DRM_PLANE_TYPE_CURSOR ? 63 : 511;
1104
1105                        /* hack */
1106                        if (WARN_ON(level == 0 && wm > max_wm))
1107                                wm = max_wm;
1108
1109                        if (wm > plane->wm.fifo_size)
1110                                break;
1111
1112                        switch (plane->base.type) {
1113                                int sprite;
1114                        case DRM_PLANE_TYPE_CURSOR:
1115                                wm_state->wm[level].cursor = wm;
1116                                break;
1117                        case DRM_PLANE_TYPE_PRIMARY:
1118                                wm_state->wm[level].primary = wm;
1119                                break;
1120                        case DRM_PLANE_TYPE_OVERLAY:
1121                                sprite = plane->plane;
1122                                wm_state->wm[level].sprite[sprite] = wm;
1123                                break;
1124                        }
1125                }
1126
1127                wm_state->num_levels = level;
1128
1129                if (!wm_state->cxsr)
1130                        continue;
1131
1132                /* maxfifo watermarks */
1133                switch (plane->base.type) {
1134                        int sprite, level;
1135                case DRM_PLANE_TYPE_CURSOR:
1136                        for (level = 0; level < wm_state->num_levels; level++)
1137                                wm_state->sr[level].cursor =
1138                                        wm_state->wm[level].cursor;
1139                        break;
1140                case DRM_PLANE_TYPE_PRIMARY:
1141                        for (level = 0; level < wm_state->num_levels; level++)
1142                                wm_state->sr[level].plane =
1143                                        min(wm_state->sr[level].plane,
1144                                            wm_state->wm[level].primary);
1145                        break;
1146                case DRM_PLANE_TYPE_OVERLAY:
1147                        sprite = plane->plane;
1148                        for (level = 0; level < wm_state->num_levels; level++)
1149                                wm_state->sr[level].plane =
1150                                        min(wm_state->sr[level].plane,
1151                                            wm_state->wm[level].sprite[sprite]);
1152                        break;
1153                }
1154        }
1155
1156        /* clear any (partially) filled invalid levels */
1157        for (level = wm_state->num_levels; level < to_i915(dev)->wm.max_level + 1; level++) {
1158                memset(&wm_state->wm[level], 0, sizeof(wm_state->wm[level]));
1159                memset(&wm_state->sr[level], 0, sizeof(wm_state->sr[level]));
1160        }
1161
1162        vlv_invert_wms(crtc);
1163}
1164
1165#define VLV_FIFO(plane, value) \
1166        (((value) << DSPARB_ ## plane ## _SHIFT_VLV) & DSPARB_ ## plane ## _MASK_VLV)
1167
1168static void vlv_pipe_set_fifo_size(struct intel_crtc *crtc)
1169{
1170        struct drm_device *dev = crtc->base.dev;
1171        struct drm_i915_private *dev_priv = to_i915(dev);
1172        struct intel_plane *plane;
1173        int sprite0_start = 0, sprite1_start = 0, fifo_size = 0;
1174
1175        for_each_intel_plane_on_crtc(dev, crtc, plane) {
1176                if (plane->base.type == DRM_PLANE_TYPE_CURSOR) {
1177                        WARN_ON(plane->wm.fifo_size != 63);
1178                        continue;
1179                }
1180
1181                if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
1182                        sprite0_start = plane->wm.fifo_size;
1183                else if (plane->plane == 0)
1184                        sprite1_start = sprite0_start + plane->wm.fifo_size;
1185                else
1186                        fifo_size = sprite1_start + plane->wm.fifo_size;
1187        }
1188
1189        WARN_ON(fifo_size != 512 - 1);
1190
1191        DRM_DEBUG_KMS("Pipe %c FIFO split %d / %d / %d\n",
1192                      pipe_name(crtc->pipe), sprite0_start,
1193                      sprite1_start, fifo_size);
1194
1195        switch (crtc->pipe) {
1196                uint32_t dsparb, dsparb2, dsparb3;
1197        case PIPE_A:
1198                dsparb = I915_READ(DSPARB);
1199                dsparb2 = I915_READ(DSPARB2);
1200
1201                dsparb &= ~(VLV_FIFO(SPRITEA, 0xff) |
1202                            VLV_FIFO(SPRITEB, 0xff));
1203                dsparb |= (VLV_FIFO(SPRITEA, sprite0_start) |
1204                           VLV_FIFO(SPRITEB, sprite1_start));
1205
1206                dsparb2 &= ~(VLV_FIFO(SPRITEA_HI, 0x1) |
1207                             VLV_FIFO(SPRITEB_HI, 0x1));
1208                dsparb2 |= (VLV_FIFO(SPRITEA_HI, sprite0_start >> 8) |
1209                           VLV_FIFO(SPRITEB_HI, sprite1_start >> 8));
1210
1211                I915_WRITE(DSPARB, dsparb);
1212                I915_WRITE(DSPARB2, dsparb2);
1213                break;
1214        case PIPE_B:
1215                dsparb = I915_READ(DSPARB);
1216                dsparb2 = I915_READ(DSPARB2);
1217
1218                dsparb &= ~(VLV_FIFO(SPRITEC, 0xff) |
1219                            VLV_FIFO(SPRITED, 0xff));
1220                dsparb |= (VLV_FIFO(SPRITEC, sprite0_start) |
1221                           VLV_FIFO(SPRITED, sprite1_start));
1222
1223                dsparb2 &= ~(VLV_FIFO(SPRITEC_HI, 0xff) |
1224                             VLV_FIFO(SPRITED_HI, 0xff));
1225                dsparb2 |= (VLV_FIFO(SPRITEC_HI, sprite0_start >> 8) |
1226                           VLV_FIFO(SPRITED_HI, sprite1_start >> 8));
1227
1228                I915_WRITE(DSPARB, dsparb);
1229                I915_WRITE(DSPARB2, dsparb2);
1230                break;
1231        case PIPE_C:
1232                dsparb3 = I915_READ(DSPARB3);
1233                dsparb2 = I915_READ(DSPARB2);
1234
1235                dsparb3 &= ~(VLV_FIFO(SPRITEE, 0xff) |
1236                             VLV_FIFO(SPRITEF, 0xff));
1237                dsparb3 |= (VLV_FIFO(SPRITEE, sprite0_start) |
1238                            VLV_FIFO(SPRITEF, sprite1_start));
1239
1240                dsparb2 &= ~(VLV_FIFO(SPRITEE_HI, 0xff) |
1241                             VLV_FIFO(SPRITEF_HI, 0xff));
1242                dsparb2 |= (VLV_FIFO(SPRITEE_HI, sprite0_start >> 8) |
1243                           VLV_FIFO(SPRITEF_HI, sprite1_start >> 8));
1244
1245                I915_WRITE(DSPARB3, dsparb3);
1246                I915_WRITE(DSPARB2, dsparb2);
1247                break;
1248        default:
1249                break;
1250        }
1251}
1252
1253#undef VLV_FIFO
1254
1255static void vlv_merge_wm(struct drm_device *dev,
1256                         struct vlv_wm_values *wm)
1257{
1258        struct intel_crtc *crtc;
1259        int num_active_crtcs = 0;
1260
1261        wm->level = to_i915(dev)->wm.max_level;
1262        wm->cxsr = true;
1263
1264        for_each_intel_crtc(dev, crtc) {
1265                const struct vlv_wm_state *wm_state = &crtc->wm_state;
1266
1267                if (!crtc->active)
1268                        continue;
1269
1270                if (!wm_state->cxsr)
1271                        wm->cxsr = false;
1272
1273                num_active_crtcs++;
1274                wm->level = min_t(int, wm->level, wm_state->num_levels - 1);
1275        }
1276
1277        if (num_active_crtcs != 1)
1278                wm->cxsr = false;
1279
1280        if (num_active_crtcs > 1)
1281                wm->level = VLV_WM_LEVEL_PM2;
1282
1283        for_each_intel_crtc(dev, crtc) {
1284                struct vlv_wm_state *wm_state = &crtc->wm_state;
1285                enum pipe pipe = crtc->pipe;
1286
1287                if (!crtc->active)
1288                        continue;
1289
1290                wm->pipe[pipe] = wm_state->wm[wm->level];
1291                if (wm->cxsr)
1292                        wm->sr = wm_state->sr[wm->level];
1293
1294                wm->ddl[pipe].primary = DDL_PRECISION_HIGH | 2;
1295                wm->ddl[pipe].sprite[0] = DDL_PRECISION_HIGH | 2;
1296                wm->ddl[pipe].sprite[1] = DDL_PRECISION_HIGH | 2;
1297                wm->ddl[pipe].cursor = DDL_PRECISION_HIGH | 2;
1298        }
1299}
1300
1301static void vlv_update_wm(struct drm_crtc *crtc)
1302{
1303        struct drm_device *dev = crtc->dev;
1304        struct drm_i915_private *dev_priv = dev->dev_private;
1305        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1306        enum pipe pipe = intel_crtc->pipe;
1307        struct vlv_wm_values wm = {};
1308
1309        vlv_compute_wm(intel_crtc);
1310        vlv_merge_wm(dev, &wm);
1311
1312        if (memcmp(&dev_priv->wm.vlv, &wm, sizeof(wm)) == 0) {
1313                /* FIXME should be part of crtc atomic commit */
1314                vlv_pipe_set_fifo_size(intel_crtc);
1315                return;
1316        }
1317
1318        if (wm.level < VLV_WM_LEVEL_DDR_DVFS &&
1319            dev_priv->wm.vlv.level >= VLV_WM_LEVEL_DDR_DVFS)
1320                chv_set_memory_dvfs(dev_priv, false);
1321
1322        if (wm.level < VLV_WM_LEVEL_PM5 &&
1323            dev_priv->wm.vlv.level >= VLV_WM_LEVEL_PM5)
1324                chv_set_memory_pm5(dev_priv, false);
1325
1326        if (!wm.cxsr && dev_priv->wm.vlv.cxsr)
1327                intel_set_memory_cxsr(dev_priv, false);
1328
1329        /* FIXME should be part of crtc atomic commit */
1330        vlv_pipe_set_fifo_size(intel_crtc);
1331
1332        vlv_write_wm_values(intel_crtc, &wm);
1333
1334        DRM_DEBUG_KMS("Setting FIFO watermarks - %c: plane=%d, cursor=%d, "
1335                      "sprite0=%d, sprite1=%d, SR: plane=%d, cursor=%d level=%d cxsr=%d\n",
1336                      pipe_name(pipe), wm.pipe[pipe].primary, wm.pipe[pipe].cursor,
1337                      wm.pipe[pipe].sprite[0], wm.pipe[pipe].sprite[1],
1338                      wm.sr.plane, wm.sr.cursor, wm.level, wm.cxsr);
1339
1340        if (wm.cxsr && !dev_priv->wm.vlv.cxsr)
1341                intel_set_memory_cxsr(dev_priv, true);
1342
1343        if (wm.level >= VLV_WM_LEVEL_PM5 &&
1344            dev_priv->wm.vlv.level < VLV_WM_LEVEL_PM5)
1345                chv_set_memory_pm5(dev_priv, true);
1346
1347        if (wm.level >= VLV_WM_LEVEL_DDR_DVFS &&
1348            dev_priv->wm.vlv.level < VLV_WM_LEVEL_DDR_DVFS)
1349                chv_set_memory_dvfs(dev_priv, true);
1350
1351        dev_priv->wm.vlv = wm;
1352}
1353
1354#define single_plane_enabled(mask) is_power_of_2(mask)
1355
1356static void g4x_update_wm(struct drm_crtc *crtc)
1357{
1358        struct drm_device *dev = crtc->dev;
1359        static const int sr_latency_ns = 12000;
1360        struct drm_i915_private *dev_priv = dev->dev_private;
1361        int planea_wm, planeb_wm, cursora_wm, cursorb_wm;
1362        int plane_sr, cursor_sr;
1363        unsigned int enabled = 0;
1364        bool cxsr_enabled;
1365
1366        if (g4x_compute_wm0(dev, PIPE_A,
1367                            &g4x_wm_info, pessimal_latency_ns,
1368                            &g4x_cursor_wm_info, pessimal_latency_ns,
1369                            &planea_wm, &cursora_wm))
1370                enabled |= 1 << PIPE_A;
1371
1372        if (g4x_compute_wm0(dev, PIPE_B,
1373                            &g4x_wm_info, pessimal_latency_ns,
1374                            &g4x_cursor_wm_info, pessimal_latency_ns,
1375                            &planeb_wm, &cursorb_wm))
1376                enabled |= 1 << PIPE_B;
1377
1378        if (single_plane_enabled(enabled) &&
1379            g4x_compute_srwm(dev, ffs(enabled) - 1,
1380                             sr_latency_ns,
1381                             &g4x_wm_info,
1382                             &g4x_cursor_wm_info,
1383                             &plane_sr, &cursor_sr)) {
1384                cxsr_enabled = true;
1385        } else {
1386                cxsr_enabled = false;
1387                intel_set_memory_cxsr(dev_priv, false);
1388                plane_sr = cursor_sr = 0;
1389        }
1390
1391        DRM_DEBUG_KMS("Setting FIFO watermarks - A: plane=%d, cursor=%d, "
1392                      "B: plane=%d, cursor=%d, SR: plane=%d, cursor=%d\n",
1393                      planea_wm, cursora_wm,
1394                      planeb_wm, cursorb_wm,
1395                      plane_sr, cursor_sr);
1396
1397        I915_WRITE(DSPFW1,
1398                   FW_WM(plane_sr, SR) |
1399                   FW_WM(cursorb_wm, CURSORB) |
1400                   FW_WM(planeb_wm, PLANEB) |
1401                   FW_WM(planea_wm, PLANEA));
1402        I915_WRITE(DSPFW2,
1403                   (I915_READ(DSPFW2) & ~DSPFW_CURSORA_MASK) |
1404                   FW_WM(cursora_wm, CURSORA));
1405        /* HPLL off in SR has some issues on G4x... disable it */
1406        I915_WRITE(DSPFW3,
1407                   (I915_READ(DSPFW3) & ~(DSPFW_HPLL_SR_EN | DSPFW_CURSOR_SR_MASK)) |
1408                   FW_WM(cursor_sr, CURSOR_SR));
1409
1410        if (cxsr_enabled)
1411                intel_set_memory_cxsr(dev_priv, true);
1412}
1413
1414static void i965_update_wm(struct drm_crtc *unused_crtc)
1415{
1416        struct drm_device *dev = unused_crtc->dev;
1417        struct drm_i915_private *dev_priv = dev->dev_private;
1418        struct drm_crtc *crtc;
1419        int srwm = 1;
1420        int cursor_sr = 16;
1421        bool cxsr_enabled;
1422
1423        /* Calc sr entries for one plane configs */
1424        crtc = single_enabled_crtc(dev);
1425        if (crtc) {
1426                /* self-refresh has much higher latency */
1427                static const int sr_latency_ns = 12000;
1428                const struct drm_display_mode *adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1429                int clock = adjusted_mode->crtc_clock;
1430                int htotal = adjusted_mode->crtc_htotal;
1431                int hdisplay = to_intel_crtc(crtc)->config->pipe_src_w;
1432                int pixel_size = crtc->primary->state->fb->bits_per_pixel / 8;
1433                unsigned long line_time_us;
1434                int entries;
1435
1436                line_time_us = max(htotal * 1000 / clock, 1);
1437
1438                /* Use ns/us then divide to preserve precision */
1439                entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1440                        pixel_size * hdisplay;
1441                entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
1442                srwm = I965_FIFO_SIZE - entries;
1443                if (srwm < 0)
1444                        srwm = 1;
1445                srwm &= 0x1ff;
1446                DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
1447                              entries, srwm);
1448
1449                entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1450                        pixel_size * crtc->cursor->state->crtc_w;
1451                entries = DIV_ROUND_UP(entries,
1452                                          i965_cursor_wm_info.cacheline_size);
1453                cursor_sr = i965_cursor_wm_info.fifo_size -
1454                        (entries + i965_cursor_wm_info.guard_size);
1455
1456                if (cursor_sr > i965_cursor_wm_info.max_wm)
1457                        cursor_sr = i965_cursor_wm_info.max_wm;
1458
1459                DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
1460                              "cursor %d\n", srwm, cursor_sr);
1461
1462                cxsr_enabled = true;
1463        } else {
1464                cxsr_enabled = false;
1465                /* Turn off self refresh if both pipes are enabled */
1466                intel_set_memory_cxsr(dev_priv, false);
1467        }
1468
1469        DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
1470                      srwm);
1471
1472        /* 965 has limitations... */
1473        I915_WRITE(DSPFW1, FW_WM(srwm, SR) |
1474                   FW_WM(8, CURSORB) |
1475                   FW_WM(8, PLANEB) |
1476                   FW_WM(8, PLANEA));
1477        I915_WRITE(DSPFW2, FW_WM(8, CURSORA) |
1478                   FW_WM(8, PLANEC_OLD));
1479        /* update cursor SR watermark */
1480        I915_WRITE(DSPFW3, FW_WM(cursor_sr, CURSOR_SR));
1481
1482        if (cxsr_enabled)
1483                intel_set_memory_cxsr(dev_priv, true);
1484}
1485
1486#undef FW_WM
1487
1488static void i9xx_update_wm(struct drm_crtc *unused_crtc)
1489{
1490        struct drm_device *dev = unused_crtc->dev;
1491        struct drm_i915_private *dev_priv = dev->dev_private;
1492        const struct intel_watermark_params *wm_info;
1493        uint32_t fwater_lo;
1494        uint32_t fwater_hi;
1495        int cwm, srwm = 1;
1496        int fifo_size;
1497        int planea_wm, planeb_wm;
1498        struct drm_crtc *crtc, *enabled = NULL;
1499
1500        if (IS_I945GM(dev))
1501                wm_info = &i945_wm_info;
1502        else if (!IS_GEN2(dev))
1503                wm_info = &i915_wm_info;
1504        else
1505                wm_info = &i830_a_wm_info;
1506
1507        fifo_size = dev_priv->display.get_fifo_size(dev, 0);
1508        crtc = intel_get_crtc_for_plane(dev, 0);
1509        if (intel_crtc_active(crtc)) {
1510                const struct drm_display_mode *adjusted_mode;
1511                int cpp = crtc->primary->state->fb->bits_per_pixel / 8;
1512                if (IS_GEN2(dev))
1513                        cpp = 4;
1514
1515                adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1516                planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1517                                               wm_info, fifo_size, cpp,
1518                                               pessimal_latency_ns);
1519                enabled = crtc;
1520        } else {
1521                planea_wm = fifo_size - wm_info->guard_size;
1522                if (planea_wm > (long)wm_info->max_wm)
1523                        planea_wm = wm_info->max_wm;
1524        }
1525
1526        if (IS_GEN2(dev))
1527                wm_info = &i830_bc_wm_info;
1528
1529        fifo_size = dev_priv->display.get_fifo_size(dev, 1);
1530        crtc = intel_get_crtc_for_plane(dev, 1);
1531        if (intel_crtc_active(crtc)) {
1532                const struct drm_display_mode *adjusted_mode;
1533                int cpp = crtc->primary->state->fb->bits_per_pixel / 8;
1534                if (IS_GEN2(dev))
1535                        cpp = 4;
1536
1537                adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1538                planeb_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1539                                               wm_info, fifo_size, cpp,
1540                                               pessimal_latency_ns);
1541                if (enabled == NULL)
1542                        enabled = crtc;
1543                else
1544                        enabled = NULL;
1545        } else {
1546                planeb_wm = fifo_size - wm_info->guard_size;
1547                if (planeb_wm > (long)wm_info->max_wm)
1548                        planeb_wm = wm_info->max_wm;
1549        }
1550
1551        DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
1552
1553        if (IS_I915GM(dev) && enabled) {
1554                struct drm_i915_gem_object *obj;
1555
1556                obj = intel_fb_obj(enabled->primary->state->fb);
1557
1558                /* self-refresh seems busted with untiled */
1559                if (obj->tiling_mode == I915_TILING_NONE)
1560                        enabled = NULL;
1561        }
1562
1563        /*
1564         * Overlay gets an aggressive default since video jitter is bad.
1565         */
1566        cwm = 2;
1567
1568        /* Play safe and disable self-refresh before adjusting watermarks. */
1569        intel_set_memory_cxsr(dev_priv, false);
1570
1571        /* Calc sr entries for one plane configs */
1572        if (HAS_FW_BLC(dev) && enabled) {
1573                /* self-refresh has much higher latency */
1574                static const int sr_latency_ns = 6000;
1575                const struct drm_display_mode *adjusted_mode = &to_intel_crtc(enabled)->config->base.adjusted_mode;
1576                int clock = adjusted_mode->crtc_clock;
1577                int htotal = adjusted_mode->crtc_htotal;
1578                int hdisplay = to_intel_crtc(enabled)->config->pipe_src_w;
1579                int pixel_size = enabled->primary->state->fb->bits_per_pixel / 8;
1580                unsigned long line_time_us;
1581                int entries;
1582
1583                line_time_us = max(htotal * 1000 / clock, 1);
1584
1585                /* Use ns/us then divide to preserve precision */
1586                entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1587                        pixel_size * hdisplay;
1588                entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
1589                DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
1590                srwm = wm_info->fifo_size - entries;
1591                if (srwm < 0)
1592                        srwm = 1;
1593
1594                if (IS_I945G(dev) || IS_I945GM(dev))
1595                        I915_WRITE(FW_BLC_SELF,
1596                                   FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
1597                else if (IS_I915GM(dev))
1598                        I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
1599        }
1600
1601        DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
1602                      planea_wm, planeb_wm, cwm, srwm);
1603
1604        fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
1605        fwater_hi = (cwm & 0x1f);
1606
1607        /* Set request length to 8 cachelines per fetch */
1608        fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
1609        fwater_hi = fwater_hi | (1 << 8);
1610
1611        I915_WRITE(FW_BLC, fwater_lo);
1612        I915_WRITE(FW_BLC2, fwater_hi);
1613
1614        if (enabled)
1615                intel_set_memory_cxsr(dev_priv, true);
1616}
1617
1618static void i845_update_wm(struct drm_crtc *unused_crtc)
1619{
1620        struct drm_device *dev = unused_crtc->dev;
1621        struct drm_i915_private *dev_priv = dev->dev_private;
1622        struct drm_crtc *crtc;
1623        const struct drm_display_mode *adjusted_mode;
1624        uint32_t fwater_lo;
1625        int planea_wm;
1626
1627        crtc = single_enabled_crtc(dev);
1628        if (crtc == NULL)
1629                return;
1630
1631        adjusted_mode = &to_intel_crtc(crtc)->config->base.adjusted_mode;
1632        planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1633                                       &i845_wm_info,
1634                                       dev_priv->display.get_fifo_size(dev, 0),
1635                                       4, pessimal_latency_ns);
1636        fwater_lo = I915_READ(FW_BLC) & ~0xfff;
1637        fwater_lo |= (3<<8) | planea_wm;
1638
1639        DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
1640
1641        I915_WRITE(FW_BLC, fwater_lo);
1642}
1643
1644uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
1645{
1646        uint32_t pixel_rate;
1647
1648        pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
1649
1650        /* We only use IF-ID interlacing. If we ever use PF-ID we'll need to
1651         * adjust the pixel_rate here. */
1652
1653        if (pipe_config->pch_pfit.enabled) {
1654                uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
1655                uint32_t pfit_size = pipe_config->pch_pfit.size;
1656
1657                pipe_w = pipe_config->pipe_src_w;
1658                pipe_h = pipe_config->pipe_src_h;
1659
1660                pfit_w = (pfit_size >> 16) & 0xFFFF;
1661                pfit_h = pfit_size & 0xFFFF;
1662                if (pipe_w < pfit_w)
1663                        pipe_w = pfit_w;
1664                if (pipe_h < pfit_h)
1665                        pipe_h = pfit_h;
1666
1667                pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
1668                                     pfit_w * pfit_h);
1669        }
1670
1671        return pixel_rate;
1672}
1673
1674/* latency must be in 0.1us units. */
1675static uint32_t ilk_wm_method1(uint32_t pixel_rate, uint8_t bytes_per_pixel,
1676                               uint32_t latency)
1677{
1678        uint64_t ret;
1679
1680        if (WARN(latency == 0, "Latency value missing\n"))
1681                return UINT_MAX;
1682
1683        ret = (uint64_t) pixel_rate * bytes_per_pixel * latency;
1684        ret = DIV_ROUND_UP_ULL(ret, 64 * 10000) + 2;
1685
1686        return ret;
1687}
1688
1689/* latency must be in 0.1us units. */
1690static uint32_t ilk_wm_method2(uint32_t pixel_rate, uint32_t pipe_htotal,
1691                               uint32_t horiz_pixels, uint8_t bytes_per_pixel,
1692                               uint32_t latency)
1693{
1694        uint32_t ret;
1695
1696        if (WARN(latency == 0, "Latency value missing\n"))
1697                return UINT_MAX;
1698
1699        ret = (latency * pixel_rate) / (pipe_htotal * 10000);
1700        ret = (ret + 1) * horiz_pixels * bytes_per_pixel;
1701        ret = DIV_ROUND_UP(ret, 64) + 2;
1702        return ret;
1703}
1704
1705static uint32_t ilk_wm_fbc(uint32_t pri_val, uint32_t horiz_pixels,
1706                           uint8_t bytes_per_pixel)
1707{
1708        return DIV_ROUND_UP(pri_val * 64, horiz_pixels * bytes_per_pixel) + 2;
1709}
1710
1711struct skl_pipe_wm_parameters {
1712        bool active;
1713        uint32_t pipe_htotal;
1714        uint32_t pixel_rate; /* in KHz */
1715        struct intel_plane_wm_parameters plane[I915_MAX_PLANES];
1716};
1717
1718struct ilk_wm_maximums {
1719        uint16_t pri;
1720        uint16_t spr;
1721        uint16_t cur;
1722        uint16_t fbc;
1723};
1724
1725/* used in computing the new watermarks state */
1726struct intel_wm_config {
1727        unsigned int num_pipes_active;
1728        bool sprites_enabled;
1729        bool sprites_scaled;
1730};
1731
1732/*
1733 * For both WM_PIPE and WM_LP.
1734 * mem_value must be in 0.1us units.
1735 */
1736static uint32_t ilk_compute_pri_wm(const struct intel_crtc_state *cstate,
1737                                   const struct intel_plane_state *pstate,
1738                                   uint32_t mem_value,
1739                                   bool is_lp)
1740{
1741        int bpp = pstate->base.fb ? pstate->base.fb->bits_per_pixel / 8 : 0;
1742        uint32_t method1, method2;
1743
1744        if (!cstate->base.active || !pstate->visible)
1745                return 0;
1746
1747        method1 = ilk_wm_method1(ilk_pipe_pixel_rate(cstate), bpp, mem_value);
1748
1749        if (!is_lp)
1750                return method1;
1751
1752        method2 = ilk_wm_method2(ilk_pipe_pixel_rate(cstate),
1753                                 cstate->base.adjusted_mode.crtc_htotal,
1754                                 drm_rect_width(&pstate->dst),
1755                                 bpp,
1756                                 mem_value);
1757
1758        return min(method1, method2);
1759}
1760
1761/*
1762 * For both WM_PIPE and WM_LP.
1763 * mem_value must be in 0.1us units.
1764 */
1765static uint32_t ilk_compute_spr_wm(const struct intel_crtc_state *cstate,
1766                                   const struct intel_plane_state *pstate,
1767                                   uint32_t mem_value)
1768{
1769        int bpp = pstate->base.fb ? pstate->base.fb->bits_per_pixel / 8 : 0;
1770        uint32_t method1, method2;
1771
1772        if (!cstate->base.active || !pstate->visible)
1773                return 0;
1774
1775        method1 = ilk_wm_method1(ilk_pipe_pixel_rate(cstate), bpp, mem_value);
1776        method2 = ilk_wm_method2(ilk_pipe_pixel_rate(cstate),
1777                                 cstate->base.adjusted_mode.crtc_htotal,
1778                                 drm_rect_width(&pstate->dst),
1779                                 bpp,
1780                                 mem_value);
1781        return min(method1, method2);
1782}
1783
1784/*
1785 * For both WM_PIPE and WM_LP.
1786 * mem_value must be in 0.1us units.
1787 */
1788static uint32_t ilk_compute_cur_wm(const struct intel_crtc_state *cstate,
1789                                   const struct intel_plane_state *pstate,
1790                                   uint32_t mem_value)
1791{
1792        /*
1793         * We treat the cursor plane as always-on for the purposes of watermark
1794         * calculation.  Until we have two-stage watermark programming merged,
1795         * this is necessary to avoid flickering.
1796         */
1797        int cpp = 4;
1798        int width = pstate->visible ? pstate->base.crtc_w : 64;
1799
1800        if (!cstate->base.active)
1801                return 0;
1802
1803        return ilk_wm_method2(ilk_pipe_pixel_rate(cstate),
1804                              cstate->base.adjusted_mode.crtc_htotal,
1805                              width, cpp, mem_value);
1806}
1807
1808/* Only for WM_LP. */
1809static uint32_t ilk_compute_fbc_wm(const struct intel_crtc_state *cstate,
1810                                   const struct intel_plane_state *pstate,
1811                                   uint32_t pri_val)
1812{
1813        int bpp = pstate->base.fb ? pstate->base.fb->bits_per_pixel / 8 : 0;
1814
1815        if (!cstate->base.active || !pstate->visible)
1816                return 0;
1817
1818        return ilk_wm_fbc(pri_val, drm_rect_width(&pstate->dst), bpp);
1819}
1820
1821static unsigned int ilk_display_fifo_size(const struct drm_device *dev)
1822{
1823        if (INTEL_INFO(dev)->gen >= 8)
1824                return 3072;
1825        else if (INTEL_INFO(dev)->gen >= 7)
1826                return 768;
1827        else
1828                return 512;
1829}
1830
1831static unsigned int ilk_plane_wm_reg_max(const struct drm_device *dev,
1832                                         int level, bool is_sprite)
1833{
1834        if (INTEL_INFO(dev)->gen >= 8)
1835                /* BDW primary/sprite plane watermarks */
1836                return level == 0 ? 255 : 2047;
1837        else if (INTEL_INFO(dev)->gen >= 7)
1838                /* IVB/HSW primary/sprite plane watermarks */
1839                return level == 0 ? 127 : 1023;
1840        else if (!is_sprite)
1841                /* ILK/SNB primary plane watermarks */
1842                return level == 0 ? 127 : 511;
1843        else
1844                /* ILK/SNB sprite plane watermarks */
1845                return level == 0 ? 63 : 255;
1846}
1847
1848static unsigned int ilk_cursor_wm_reg_max(const struct drm_device *dev,
1849                                          int level)
1850{
1851        if (INTEL_INFO(dev)->gen >= 7)
1852                return level == 0 ? 63 : 255;
1853        else
1854                return level == 0 ? 31 : 63;
1855}
1856
1857static unsigned int ilk_fbc_wm_reg_max(const struct drm_device *dev)
1858{
1859        if (INTEL_INFO(dev)->gen >= 8)
1860                return 31;
1861        else
1862                return 15;
1863}
1864
1865/* Calculate the maximum primary/sprite plane watermark */
1866static unsigned int ilk_plane_wm_max(const struct drm_device *dev,
1867                                     int level,
1868                                     const struct intel_wm_config *config,
1869                                     enum intel_ddb_partitioning ddb_partitioning,
1870                                     bool is_sprite)
1871{
1872        unsigned int fifo_size = ilk_display_fifo_size(dev);
1873
1874        /* if sprites aren't enabled, sprites get nothing */
1875        if (is_sprite && !config->sprites_enabled)
1876                return 0;
1877
1878        /* HSW allows LP1+ watermarks even with multiple pipes */
1879        if (level == 0 || config->num_pipes_active > 1) {
1880                fifo_size /= INTEL_INFO(dev)->num_pipes;
1881
1882                /*
1883                 * For some reason the non self refresh
1884                 * FIFO size is only half of the self
1885                 * refresh FIFO size on ILK/SNB.
1886                 */
1887                if (INTEL_INFO(dev)->gen <= 6)
1888                        fifo_size /= 2;
1889        }
1890
1891        if (config->sprites_enabled) {
1892                /* level 0 is always calculated with 1:1 split */
1893                if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
1894                        if (is_sprite)
1895                                fifo_size *= 5;
1896                        fifo_size /= 6;
1897                } else {
1898                        fifo_size /= 2;
1899                }
1900        }
1901
1902        /* clamp to max that the registers can hold */
1903        return min(fifo_size, ilk_plane_wm_reg_max(dev, level, is_sprite));
1904}
1905
1906/* Calculate the maximum cursor plane watermark */
1907static unsigned int ilk_cursor_wm_max(const struct drm_device *dev,
1908                                      int level,
1909                                      const struct intel_wm_config *config)
1910{
1911        /* HSW LP1+ watermarks w/ multiple pipes */
1912        if (level > 0 && config->num_pipes_active > 1)
1913                return 64;
1914
1915        /* otherwise just report max that registers can hold */
1916        return ilk_cursor_wm_reg_max(dev, level);
1917}
1918
1919static void ilk_compute_wm_maximums(const struct drm_device *dev,
1920                                    int level,
1921                                    const struct intel_wm_config *config,
1922                                    enum intel_ddb_partitioning ddb_partitioning,
1923                                    struct ilk_wm_maximums *max)
1924{
1925        max->pri = ilk_plane_wm_max(dev, level, config, ddb_partitioning, false);
1926        max->spr = ilk_plane_wm_max(dev, level, config, ddb_partitioning, true);
1927        max->cur = ilk_cursor_wm_max(dev, level, config);
1928        max->fbc = ilk_fbc_wm_reg_max(dev);
1929}
1930
1931static void ilk_compute_wm_reg_maximums(struct drm_device *dev,
1932                                        int level,
1933                                        struct ilk_wm_maximums *max)
1934{
1935        max->pri = ilk_plane_wm_reg_max(dev, level, false);
1936        max->spr = ilk_plane_wm_reg_max(dev, level, true);
1937        max->cur = ilk_cursor_wm_reg_max(dev, level);
1938        max->fbc = ilk_fbc_wm_reg_max(dev);
1939}
1940
1941static bool ilk_validate_wm_level(int level,
1942                                  const struct ilk_wm_maximums *max,
1943                                  struct intel_wm_level *result)
1944{
1945        bool ret;
1946
1947        /* already determined to be invalid? */
1948        if (!result->enable)
1949                return false;
1950
1951        result->enable = result->pri_val <= max->pri &&
1952                         result->spr_val <= max->spr &&
1953                         result->cur_val <= max->cur;
1954
1955        ret = result->enable;
1956
1957        /*
1958         * HACK until we can pre-compute everything,
1959         * and thus fail gracefully if LP0 watermarks
1960         * are exceeded...
1961         */
1962        if (level == 0 && !result->enable) {
1963                if (result->pri_val > max->pri)
1964                        DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
1965                                      level, result->pri_val, max->pri);
1966                if (result->spr_val > max->spr)
1967                        DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
1968                                      level, result->spr_val, max->spr);
1969                if (result->cur_val > max->cur)
1970                        DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
1971                                      level, result->cur_val, max->cur);
1972
1973                result->pri_val = min_t(uint32_t, result->pri_val, max->pri);
1974                result->spr_val = min_t(uint32_t, result->spr_val, max->spr);
1975                result->cur_val = min_t(uint32_t, result->cur_val, max->cur);
1976                result->enable = true;
1977        }
1978
1979        return ret;
1980}
1981
1982static void ilk_compute_wm_level(const struct drm_i915_private *dev_priv,
1983                                 const struct intel_crtc *intel_crtc,
1984                                 int level,
1985                                 struct intel_crtc_state *cstate,
1986                                 struct intel_wm_level *result)
1987{
1988        struct intel_plane *intel_plane;
1989        uint16_t pri_latency = dev_priv->wm.pri_latency[level];
1990        uint16_t spr_latency = dev_priv->wm.spr_latency[level];
1991        uint16_t cur_latency = dev_priv->wm.cur_latency[level];
1992
1993        /* WM1+ latency values stored in 0.5us units */
1994        if (level > 0) {
1995                pri_latency *= 5;
1996                spr_latency *= 5;
1997                cur_latency *= 5;
1998        }
1999
2000        for_each_intel_plane_on_crtc(dev_priv->dev, intel_crtc, intel_plane) {
2001                struct intel_plane_state *pstate =
2002                        to_intel_plane_state(intel_plane->base.state);
2003
2004                switch (intel_plane->base.type) {
2005                case DRM_PLANE_TYPE_PRIMARY:
2006                        result->pri_val = ilk_compute_pri_wm(cstate, pstate,
2007                                                             pri_latency,
2008                                                             level);
2009                        result->fbc_val = ilk_compute_fbc_wm(cstate, pstate,
2010                                                             result->pri_val);
2011                        break;
2012                case DRM_PLANE_TYPE_OVERLAY:
2013                        result->spr_val = ilk_compute_spr_wm(cstate, pstate,
2014                                                             spr_latency);
2015                        break;
2016                case DRM_PLANE_TYPE_CURSOR:
2017                        result->cur_val = ilk_compute_cur_wm(cstate, pstate,
2018                                                             cur_latency);
2019                        break;
2020                }
2021        }
2022
2023        result->enable = true;
2024}
2025
2026static uint32_t
2027hsw_compute_linetime_wm(struct drm_device *dev, struct drm_crtc *crtc)
2028{
2029        struct drm_i915_private *dev_priv = dev->dev_private;
2030        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2031        const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
2032        u32 linetime, ips_linetime;
2033
2034        if (!intel_crtc->active)
2035                return 0;
2036
2037        /* The WM are computed with base on how long it takes to fill a single
2038         * row at the given clock rate, multiplied by 8.
2039         * */
2040        linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2041                                     adjusted_mode->crtc_clock);
2042        ips_linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2043                                         dev_priv->cdclk_freq);
2044
2045        return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
2046               PIPE_WM_LINETIME_TIME(linetime);
2047}
2048
2049static void intel_read_wm_latency(struct drm_device *dev, uint16_t wm[8])
2050{
2051        struct drm_i915_private *dev_priv = dev->dev_private;
2052
2053        if (IS_GEN9(dev)) {
2054                uint32_t val;
2055                int ret, i;
2056                int level, max_level = ilk_wm_max_level(dev);
2057
2058                /* read the first set of memory latencies[0:3] */
2059                val = 0; /* data0 to be programmed to 0 for first set */
2060                mutex_lock(&dev_priv->rps.hw_lock);
2061                ret = sandybridge_pcode_read(dev_priv,
2062                                             GEN9_PCODE_READ_MEM_LATENCY,
2063                                             &val);
2064                mutex_unlock(&dev_priv->rps.hw_lock);
2065
2066                if (ret) {
2067                        DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2068                        return;
2069                }
2070
2071                wm[0] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2072                wm[1] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2073                                GEN9_MEM_LATENCY_LEVEL_MASK;
2074                wm[2] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2075                                GEN9_MEM_LATENCY_LEVEL_MASK;
2076                wm[3] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2077                                GEN9_MEM_LATENCY_LEVEL_MASK;
2078
2079                /* read the second set of memory latencies[4:7] */
2080                val = 1; /* data0 to be programmed to 1 for second set */
2081                mutex_lock(&dev_priv->rps.hw_lock);
2082                ret = sandybridge_pcode_read(dev_priv,
2083                                             GEN9_PCODE_READ_MEM_LATENCY,
2084                                             &val);
2085                mutex_unlock(&dev_priv->rps.hw_lock);
2086                if (ret) {
2087                        DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2088                        return;
2089                }
2090
2091                wm[4] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2092                wm[5] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2093                                GEN9_MEM_LATENCY_LEVEL_MASK;
2094                wm[6] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2095                                GEN9_MEM_LATENCY_LEVEL_MASK;
2096                wm[7] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2097                                GEN9_MEM_LATENCY_LEVEL_MASK;
2098
2099                /*
2100                 * If a level n (n > 1) has a 0us latency, all levels m (m >= n)
2101                 * need to be disabled. We make sure to sanitize the values out
2102                 * of the punit to satisfy this requirement.
2103                 */
2104                for (level = 1; level <= max_level; level++) {
2105                        if (wm[level] == 0) {
2106                                for (i = level + 1; i <= max_level; i++)
2107                                        wm[i] = 0;
2108                                break;
2109                        }
2110                }
2111
2112                /*
2113                 * WaWmMemoryReadLatency:skl
2114                 *
2115                 * punit doesn't take into account the read latency so we need
2116                 * to add 2us to the various latency levels we retrieve from the
2117                 * punit when level 0 response data us 0us.
2118                 */
2119                if (wm[0] == 0) {
2120                        wm[0] += 2;
2121                        for (level = 1; level <= max_level; level++) {
2122                                if (wm[level] == 0)
2123                                        break;
2124                                wm[level] += 2;
2125                        }
2126                }
2127
2128        } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2129                uint64_t sskpd = I915_READ64(MCH_SSKPD);
2130
2131                wm[0] = (sskpd >> 56) & 0xFF;
2132                if (wm[0] == 0)
2133                        wm[0] = sskpd & 0xF;
2134                wm[1] = (sskpd >> 4) & 0xFF;
2135                wm[2] = (sskpd >> 12) & 0xFF;
2136                wm[3] = (sskpd >> 20) & 0x1FF;
2137                wm[4] = (sskpd >> 32) & 0x1FF;
2138        } else if (INTEL_INFO(dev)->gen >= 6) {
2139                uint32_t sskpd = I915_READ(MCH_SSKPD);
2140
2141                wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
2142                wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
2143                wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
2144                wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
2145        } else if (INTEL_INFO(dev)->gen >= 5) {
2146                uint32_t mltr = I915_READ(MLTR_ILK);
2147
2148                /* ILK primary LP0 latency is 700 ns */
2149                wm[0] = 7;
2150                wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
2151                wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
2152        }
2153}
2154
2155static void intel_fixup_spr_wm_latency(struct drm_device *dev, uint16_t wm[5])
2156{
2157        /* ILK sprite LP0 latency is 1300 ns */
2158        if (INTEL_INFO(dev)->gen == 5)
2159                wm[0] = 13;
2160}
2161
2162static void intel_fixup_cur_wm_latency(struct drm_device *dev, uint16_t wm[5])
2163{
2164        /* ILK cursor LP0 latency is 1300 ns */
2165        if (INTEL_INFO(dev)->gen == 5)
2166                wm[0] = 13;
2167
2168        /* WaDoubleCursorLP3Latency:ivb */
2169        if (IS_IVYBRIDGE(dev))
2170                wm[3] *= 2;
2171}
2172
2173int ilk_wm_max_level(const struct drm_device *dev)
2174{
2175        /* how many WM levels are we expecting */
2176        if (INTEL_INFO(dev)->gen >= 9)
2177                return 7;
2178        else if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2179                return 4;
2180        else if (INTEL_INFO(dev)->gen >= 6)
2181                return 3;
2182        else
2183                return 2;
2184}
2185
2186static void intel_print_wm_latency(struct drm_device *dev,
2187                                   const char *name,
2188                                   const uint16_t wm[8])
2189{
2190        int level, max_level = ilk_wm_max_level(dev);
2191
2192        for (level = 0; level <= max_level; level++) {
2193                unsigned int latency = wm[level];
2194
2195                if (latency == 0) {
2196                        DRM_ERROR("%s WM%d latency not provided\n",
2197                                  name, level);
2198                        continue;
2199                }
2200
2201                /*
2202                 * - latencies are in us on gen9.
2203                 * - before then, WM1+ latency values are in 0.5us units
2204                 */
2205                if (IS_GEN9(dev))
2206                        latency *= 10;
2207                else if (level > 0)
2208                        latency *= 5;
2209
2210                DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
2211                              name, level, wm[level],
2212                              latency / 10, latency % 10);
2213        }
2214}
2215
2216static bool ilk_increase_wm_latency(struct drm_i915_private *dev_priv,
2217                                    uint16_t wm[5], uint16_t min)
2218{
2219        int level, max_level = ilk_wm_max_level(dev_priv->dev);
2220
2221        if (wm[0] >= min)
2222                return false;
2223
2224        wm[0] = max(wm[0], min);
2225        for (level = 1; level <= max_level; level++)
2226                wm[level] = max_t(uint16_t, wm[level], DIV_ROUND_UP(min, 5));
2227
2228        return true;
2229}
2230
2231static void snb_wm_latency_quirk(struct drm_device *dev)
2232{
2233        struct drm_i915_private *dev_priv = dev->dev_private;
2234        bool changed;
2235
2236        /*
2237         * The BIOS provided WM memory latency values are often
2238         * inadequate for high resolution displays. Adjust them.
2239         */
2240        changed = ilk_increase_wm_latency(dev_priv, dev_priv->wm.pri_latency, 12) |
2241                ilk_increase_wm_latency(dev_priv, dev_priv->wm.spr_latency, 12) |
2242                ilk_increase_wm_latency(dev_priv, dev_priv->wm.cur_latency, 12);
2243
2244        if (!changed)
2245                return;
2246
2247        DRM_DEBUG_KMS("WM latency values increased to avoid potential underruns\n");
2248        intel_print_wm_latency(dev, "Primary", dev_priv->wm.pri_latency);
2249        intel_print_wm_latency(dev, "Sprite", dev_priv->wm.spr_latency);
2250        intel_print_wm_latency(dev, "Cursor", dev_priv->wm.cur_latency);
2251}
2252
2253static void ilk_setup_wm_latency(struct drm_device *dev)
2254{
2255        struct drm_i915_private *dev_priv = dev->dev_private;
2256
2257        intel_read_wm_latency(dev, dev_priv->wm.pri_latency);
2258
2259        memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
2260               sizeof(dev_priv->wm.pri_latency));
2261        memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
2262               sizeof(dev_priv->wm.pri_latency));
2263
2264        intel_fixup_spr_wm_latency(dev, dev_priv->wm.spr_latency);
2265        intel_fixup_cur_wm_latency(dev, dev_priv->wm.cur_latency);
2266
2267        intel_print_wm_latency(dev, "Primary", dev_priv->wm.pri_latency);
2268        intel_print_wm_latency(dev, "Sprite", dev_priv->wm.spr_latency);
2269        intel_print_wm_latency(dev, "Cursor", dev_priv->wm.cur_latency);
2270
2271        if (IS_GEN6(dev))
2272                snb_wm_latency_quirk(dev);
2273}
2274
2275static void skl_setup_wm_latency(struct drm_device *dev)
2276{
2277        struct drm_i915_private *dev_priv = dev->dev_private;
2278
2279        intel_read_wm_latency(dev, dev_priv->wm.skl_latency);
2280        intel_print_wm_latency(dev, "Gen9 Plane", dev_priv->wm.skl_latency);
2281}
2282
2283static void ilk_compute_wm_config(struct drm_device *dev,
2284                                  struct intel_wm_config *config)
2285{
2286        struct intel_crtc *intel_crtc;
2287
2288        /* Compute the currently _active_ config */
2289        for_each_intel_crtc(dev, intel_crtc) {
2290                const struct intel_pipe_wm *wm = &intel_crtc->wm.active;
2291
2292                if (!wm->pipe_enabled)
2293                        continue;
2294
2295                config->sprites_enabled |= wm->sprites_enabled;
2296                config->sprites_scaled |= wm->sprites_scaled;
2297                config->num_pipes_active++;
2298        }
2299}
2300
2301/* Compute new watermarks for the pipe */
2302static bool intel_compute_pipe_wm(struct intel_crtc_state *cstate,
2303                                  struct intel_pipe_wm *pipe_wm)
2304{
2305        struct drm_crtc *crtc = cstate->base.crtc;
2306        struct drm_device *dev = crtc->dev;
2307        const struct drm_i915_private *dev_priv = dev->dev_private;
2308        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2309        struct intel_plane *intel_plane;
2310        struct intel_plane_state *sprstate = NULL;
2311        int level, max_level = ilk_wm_max_level(dev);
2312        /* LP0 watermark maximums depend on this pipe alone */
2313        struct intel_wm_config config = {
2314                .num_pipes_active = 1,
2315        };
2316        struct ilk_wm_maximums max;
2317
2318        for_each_intel_plane_on_crtc(dev, intel_crtc, intel_plane) {
2319                if (intel_plane->base.type == DRM_PLANE_TYPE_OVERLAY) {
2320                        sprstate = to_intel_plane_state(intel_plane->base.state);
2321                        break;
2322                }
2323        }
2324
2325        config.sprites_enabled = sprstate->visible;
2326        config.sprites_scaled = sprstate->visible &&
2327                (drm_rect_width(&sprstate->dst) != drm_rect_width(&sprstate->src) >> 16 ||
2328                drm_rect_height(&sprstate->dst) != drm_rect_height(&sprstate->src) >> 16);
2329
2330        pipe_wm->pipe_enabled = cstate->base.active;
2331        pipe_wm->sprites_enabled = sprstate->visible;
2332        pipe_wm->sprites_scaled = config.sprites_scaled;
2333
2334        /* ILK/SNB: LP2+ watermarks only w/o sprites */
2335        if (INTEL_INFO(dev)->gen <= 6 && sprstate->visible)
2336                max_level = 1;
2337
2338        /* ILK/SNB/IVB: LP1+ watermarks only w/o scaling */
2339        if (config.sprites_scaled)
2340                max_level = 0;
2341
2342        ilk_compute_wm_level(dev_priv, intel_crtc, 0, cstate, &pipe_wm->wm[0]);
2343
2344        if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2345                pipe_wm->linetime = hsw_compute_linetime_wm(dev, crtc);
2346
2347        /* LP0 watermarks always use 1/2 DDB partitioning */
2348        ilk_compute_wm_maximums(dev, 0, &config, INTEL_DDB_PART_1_2, &max);
2349
2350        /* At least LP0 must be valid */
2351        if (!ilk_validate_wm_level(0, &max, &pipe_wm->wm[0]))
2352                return false;
2353
2354        ilk_compute_wm_reg_maximums(dev, 1, &max);
2355
2356        for (level = 1; level <= max_level; level++) {
2357                struct intel_wm_level wm = {};
2358
2359                ilk_compute_wm_level(dev_priv, intel_crtc, level, cstate, &wm);
2360
2361                /*
2362                 * Disable any watermark level that exceeds the
2363                 * register maximums since such watermarks are
2364                 * always invalid.
2365                 */
2366                if (!ilk_validate_wm_level(level, &max, &wm))
2367                        break;
2368
2369                pipe_wm->wm[level] = wm;
2370        }
2371
2372        return true;
2373}
2374
2375/*
2376 * Merge the watermarks from all active pipes for a specific level.
2377 */
2378static void ilk_merge_wm_level(struct drm_device *dev,
2379                               int level,
2380                               struct intel_wm_level *ret_wm)
2381{
2382        const struct intel_crtc *intel_crtc;
2383
2384        ret_wm->enable = true;
2385
2386        for_each_intel_crtc(dev, intel_crtc) {
2387                const struct intel_pipe_wm *active = &intel_crtc->wm.active;
2388                const struct intel_wm_level *wm = &active->wm[level];
2389
2390                if (!active->pipe_enabled)
2391                        continue;
2392
2393                /*
2394                 * The watermark values may have been used in the past,
2395                 * so we must maintain them in the registers for some
2396                 * time even if the level is now disabled.
2397                 */
2398                if (!wm->enable)
2399                        ret_wm->enable = false;
2400
2401                ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
2402                ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
2403                ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
2404                ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
2405        }
2406}
2407
2408/*
2409 * Merge all low power watermarks for all active pipes.
2410 */
2411static void ilk_wm_merge(struct drm_device *dev,
2412                         const struct intel_wm_config *config,
2413                         const struct ilk_wm_maximums *max,
2414                         struct intel_pipe_wm *merged)
2415{
2416        struct drm_i915_private *dev_priv = dev->dev_private;
2417        int level, max_level = ilk_wm_max_level(dev);
2418        int last_enabled_level = max_level;
2419
2420        /* ILK/SNB/IVB: LP1+ watermarks only w/ single pipe */
2421        if ((INTEL_INFO(dev)->gen <= 6 || IS_IVYBRIDGE(dev)) &&
2422            config->num_pipes_active > 1)
2423                return;
2424
2425        /* ILK: FBC WM must be disabled always */
2426        merged->fbc_wm_enabled = INTEL_INFO(dev)->gen >= 6;
2427
2428        /* merge each WM1+ level */
2429        for (level = 1; level <= max_level; level++) {
2430                struct intel_wm_level *wm = &merged->wm[level];
2431
2432                ilk_merge_wm_level(dev, level, wm);
2433
2434                if (level > last_enabled_level)
2435                        wm->enable = false;
2436                else if (!ilk_validate_wm_level(level, max, wm))
2437                        /* make sure all following levels get disabled */
2438                        last_enabled_level = level - 1;
2439
2440                /*
2441                 * The spec says it is preferred to disable
2442                 * FBC WMs instead of disabling a WM level.
2443                 */
2444                if (wm->fbc_val > max->fbc) {
2445                        if (wm->enable)
2446                                merged->fbc_wm_enabled = false;
2447                        wm->fbc_val = 0;
2448                }
2449        }
2450
2451        /* ILK: LP2+ must be disabled when FBC WM is disabled but FBC enabled */
2452        /*
2453         * FIXME this is racy. FBC might get enabled later.
2454         * What we should check here is whether FBC can be
2455         * enabled sometime later.
2456         */
2457        if (IS_GEN5(dev) && !merged->fbc_wm_enabled &&
2458            intel_fbc_enabled(dev_priv)) {
2459                for (level = 2; level <= max_level; level++) {
2460                        struct intel_wm_level *wm = &merged->wm[level];
2461
2462                        wm->enable = false;
2463                }
2464        }
2465}
2466
2467static int ilk_wm_lp_to_level(int wm_lp, const struct intel_pipe_wm *pipe_wm)
2468{
2469        /* LP1,LP2,LP3 levels are either 1,2,3 or 1,3,4 */
2470        return wm_lp + (wm_lp >= 2 && pipe_wm->wm[4].enable);
2471}
2472
2473/* The value we need to program into the WM_LPx latency field */
2474static unsigned int ilk_wm_lp_latency(struct drm_device *dev, int level)
2475{
2476        struct drm_i915_private *dev_priv = dev->dev_private;
2477
2478        if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2479                return 2 * level;
2480        else
2481                return dev_priv->wm.pri_latency[level];
2482}
2483
2484static void ilk_compute_wm_results(struct drm_device *dev,
2485                                   const struct intel_pipe_wm *merged,
2486                                   enum intel_ddb_partitioning partitioning,
2487                                   struct ilk_wm_values *results)
2488{
2489        struct intel_crtc *intel_crtc;
2490        int level, wm_lp;
2491
2492        results->enable_fbc_wm = merged->fbc_wm_enabled;
2493        results->partitioning = partitioning;
2494
2495        /* LP1+ register values */
2496        for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
2497                const struct intel_wm_level *r;
2498
2499                level = ilk_wm_lp_to_level(wm_lp, merged);
2500
2501                r = &merged->wm[level];
2502
2503                /*
2504                 * Maintain the watermark values even if the level is
2505                 * disabled. Doing otherwise could cause underruns.
2506                 */
2507                results->wm_lp[wm_lp - 1] =
2508                        (ilk_wm_lp_latency(dev, level) << WM1_LP_LATENCY_SHIFT) |
2509                        (r->pri_val << WM1_LP_SR_SHIFT) |
2510                        r->cur_val;
2511
2512                if (r->enable)
2513                        results->wm_lp[wm_lp - 1] |= WM1_LP_SR_EN;
2514
2515                if (INTEL_INFO(dev)->gen >= 8)
2516                        results->wm_lp[wm_lp - 1] |=
2517                                r->fbc_val << WM1_LP_FBC_SHIFT_BDW;
2518                else
2519                        results->wm_lp[wm_lp - 1] |=
2520                                r->fbc_val << WM1_LP_FBC_SHIFT;
2521
2522                /*
2523                 * Always set WM1S_LP_EN when spr_val != 0, even if the
2524                 * level is disabled. Doing otherwise could cause underruns.
2525                 */
2526                if (INTEL_INFO(dev)->gen <= 6 && r->spr_val) {
2527                        WARN_ON(wm_lp != 1);
2528                        results->wm_lp_spr[wm_lp - 1] = WM1S_LP_EN | r->spr_val;
2529                } else
2530                        results->wm_lp_spr[wm_lp - 1] = r->spr_val;
2531        }
2532
2533        /* LP0 register values */
2534        for_each_intel_crtc(dev, intel_crtc) {
2535                enum pipe pipe = intel_crtc->pipe;
2536                const struct intel_wm_level *r =
2537                        &intel_crtc->wm.active.wm[0];
2538
2539                if (WARN_ON(!r->enable))
2540                        continue;
2541
2542                results->wm_linetime[pipe] = intel_crtc->wm.active.linetime;
2543
2544                results->wm_pipe[pipe] =
2545                        (r->pri_val << WM0_PIPE_PLANE_SHIFT) |
2546                        (r->spr_val << WM0_PIPE_SPRITE_SHIFT) |
2547                        r->cur_val;
2548        }
2549}
2550
2551/* Find the result with the highest level enabled. Check for enable_fbc_wm in
2552 * case both are at the same level. Prefer r1 in case they're the same. */
2553static struct intel_pipe_wm *ilk_find_best_result(struct drm_device *dev,
2554                                                  struct intel_pipe_wm *r1,
2555                                                  struct intel_pipe_wm *r2)
2556{
2557        int level, max_level = ilk_wm_max_level(dev);
2558        int level1 = 0, level2 = 0;
2559
2560        for (level = 1; level <= max_level; level++) {
2561                if (r1->wm[level].enable)
2562                        level1 = level;
2563                if (r2->wm[level].enable)
2564                        level2 = level;
2565        }
2566
2567        if (level1 == level2) {
2568                if (r2->fbc_wm_enabled && !r1->fbc_wm_enabled)
2569                        return r2;
2570                else
2571                        return r1;
2572        } else if (level1 > level2) {
2573                return r1;
2574        } else {
2575                return r2;
2576        }
2577}
2578
2579/* dirty bits used to track which watermarks need changes */
2580#define WM_DIRTY_PIPE(pipe) (1 << (pipe))
2581#define WM_DIRTY_LINETIME(pipe) (1 << (8 + (pipe)))
2582#define WM_DIRTY_LP(wm_lp) (1 << (15 + (wm_lp)))
2583#define WM_DIRTY_LP_ALL (WM_DIRTY_LP(1) | WM_DIRTY_LP(2) | WM_DIRTY_LP(3))
2584#define WM_DIRTY_FBC (1 << 24)
2585#define WM_DIRTY_DDB (1 << 25)
2586
2587static unsigned int ilk_compute_wm_dirty(struct drm_i915_private *dev_priv,
2588                                         const struct ilk_wm_values *old,
2589                                         const struct ilk_wm_values *new)
2590{
2591        unsigned int dirty = 0;
2592        enum pipe pipe;
2593        int wm_lp;
2594
2595        for_each_pipe(dev_priv, pipe) {
2596                if (old->wm_linetime[pipe] != new->wm_linetime[pipe]) {
2597                        dirty |= WM_DIRTY_LINETIME(pipe);
2598                        /* Must disable LP1+ watermarks too */
2599                        dirty |= WM_DIRTY_LP_ALL;
2600                }
2601
2602                if (old->wm_pipe[pipe] != new->wm_pipe[pipe]) {
2603                        dirty |= WM_DIRTY_PIPE(pipe);
2604                        /* Must disable LP1+ watermarks too */
2605                        dirty |= WM_DIRTY_LP_ALL;
2606                }
2607        }
2608
2609        if (old->enable_fbc_wm != new->enable_fbc_wm) {
2610                dirty |= WM_DIRTY_FBC;
2611                /* Must disable LP1+ watermarks too */
2612                dirty |= WM_DIRTY_LP_ALL;
2613        }
2614
2615        if (old->partitioning != new->partitioning) {
2616                dirty |= WM_DIRTY_DDB;
2617                /* Must disable LP1+ watermarks too */
2618                dirty |= WM_DIRTY_LP_ALL;
2619        }
2620
2621        /* LP1+ watermarks already deemed dirty, no need to continue */
2622        if (dirty & WM_DIRTY_LP_ALL)
2623                return dirty;
2624
2625        /* Find the lowest numbered LP1+ watermark in need of an update... */
2626        for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
2627                if (old->wm_lp[wm_lp - 1] != new->wm_lp[wm_lp - 1] ||
2628                    old->wm_lp_spr[wm_lp - 1] != new->wm_lp_spr[wm_lp - 1])
2629                        break;
2630        }
2631
2632        /* ...and mark it and all higher numbered LP1+ watermarks as dirty */
2633        for (; wm_lp <= 3; wm_lp++)
2634                dirty |= WM_DIRTY_LP(wm_lp);
2635
2636        return dirty;
2637}
2638
2639static bool _ilk_disable_lp_wm(struct drm_i915_private *dev_priv,
2640                               unsigned int dirty)
2641{
2642        struct ilk_wm_values *previous = &dev_priv->wm.hw;
2643        bool changed = false;
2644
2645        if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] & WM1_LP_SR_EN) {
2646                previous->wm_lp[2] &= ~WM1_LP_SR_EN;
2647                I915_WRITE(WM3_LP_ILK, previous->wm_lp[2]);
2648                changed = true;
2649        }
2650        if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] & WM1_LP_SR_EN) {
2651                previous->wm_lp[1] &= ~WM1_LP_SR_EN;
2652                I915_WRITE(WM2_LP_ILK, previous->wm_lp[1]);
2653                changed = true;
2654        }
2655        if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] & WM1_LP_SR_EN) {
2656                previous->wm_lp[0] &= ~WM1_LP_SR_EN;
2657                I915_WRITE(WM1_LP_ILK, previous->wm_lp[0]);
2658                changed = true;
2659        }
2660
2661        /*
2662         * Don't touch WM1S_LP_EN here.
2663         * Doing so could cause underruns.
2664         */
2665
2666        return changed;
2667}
2668
2669/*
2670 * The spec says we shouldn't write when we don't need, because every write
2671 * causes WMs to be re-evaluated, expending some power.
2672 */
2673static void ilk_write_wm_values(struct drm_i915_private *dev_priv,
2674                                struct ilk_wm_values *results)
2675{
2676        struct drm_device *dev = dev_priv->dev;
2677        struct ilk_wm_values *previous = &dev_priv->wm.hw;
2678        unsigned int dirty;
2679        uint32_t val;
2680
2681        dirty = ilk_compute_wm_dirty(dev_priv, previous, results);
2682        if (!dirty)
2683                return;
2684
2685        _ilk_disable_lp_wm(dev_priv, dirty);
2686
2687        if (dirty & WM_DIRTY_PIPE(PIPE_A))
2688                I915_WRITE(WM0_PIPEA_ILK, results->wm_pipe[0]);
2689        if (dirty & WM_DIRTY_PIPE(PIPE_B))
2690                I915_WRITE(WM0_PIPEB_ILK, results->wm_pipe[1]);
2691        if (dirty & WM_DIRTY_PIPE(PIPE_C))
2692                I915_WRITE(WM0_PIPEC_IVB, results->wm_pipe[2]);
2693
2694        if (dirty & WM_DIRTY_LINETIME(PIPE_A))
2695                I915_WRITE(PIPE_WM_LINETIME(PIPE_A), results->wm_linetime[0]);
2696        if (dirty & WM_DIRTY_LINETIME(PIPE_B))
2697                I915_WRITE(PIPE_WM_LINETIME(PIPE_B), results->wm_linetime[1]);
2698        if (dirty & WM_DIRTY_LINETIME(PIPE_C))
2699                I915_WRITE(PIPE_WM_LINETIME(PIPE_C), results->wm_linetime[2]);
2700
2701        if (dirty & WM_DIRTY_DDB) {
2702                if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2703                        val = I915_READ(WM_MISC);
2704                        if (results->partitioning == INTEL_DDB_PART_1_2)
2705                                val &= ~WM_MISC_DATA_PARTITION_5_6;
2706                        else
2707                                val |= WM_MISC_DATA_PARTITION_5_6;
2708                        I915_WRITE(WM_MISC, val);
2709                } else {
2710                        val = I915_READ(DISP_ARB_CTL2);
2711                        if (results->partitioning == INTEL_DDB_PART_1_2)
2712                                val &= ~DISP_DATA_PARTITION_5_6;
2713                        else
2714                                val |= DISP_DATA_PARTITION_5_6;
2715                        I915_WRITE(DISP_ARB_CTL2, val);
2716                }
2717        }
2718
2719        if (dirty & WM_DIRTY_FBC) {
2720                val = I915_READ(DISP_ARB_CTL);
2721                if (results->enable_fbc_wm)
2722                        val &= ~DISP_FBC_WM_DIS;
2723                else
2724                        val |= DISP_FBC_WM_DIS;
2725                I915_WRITE(DISP_ARB_CTL, val);
2726        }
2727
2728        if (dirty & WM_DIRTY_LP(1) &&
2729            previous->wm_lp_spr[0] != results->wm_lp_spr[0])
2730                I915_WRITE(WM1S_LP_ILK, results->wm_lp_spr[0]);
2731
2732        if (INTEL_INFO(dev)->gen >= 7) {
2733                if (dirty & WM_DIRTY_LP(2) && previous->wm_lp_spr[1] != results->wm_lp_spr[1])
2734                        I915_WRITE(WM2S_LP_IVB, results->wm_lp_spr[1]);
2735                if (dirty & WM_DIRTY_LP(3) && previous->wm_lp_spr[2] != results->wm_lp_spr[2])
2736                        I915_WRITE(WM3S_LP_IVB, results->wm_lp_spr[2]);
2737        }
2738
2739        if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] != results->wm_lp[0])
2740                I915_WRITE(WM1_LP_ILK, results->wm_lp[0]);
2741        if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] != results->wm_lp[1])
2742                I915_WRITE(WM2_LP_ILK, results->wm_lp[1]);
2743        if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] != results->wm_lp[2])
2744                I915_WRITE(WM3_LP_ILK, results->wm_lp[2]);
2745
2746        dev_priv->wm.hw = *results;
2747}
2748
2749static bool ilk_disable_lp_wm(struct drm_device *dev)
2750{
2751        struct drm_i915_private *dev_priv = dev->dev_private;
2752
2753        return _ilk_disable_lp_wm(dev_priv, WM_DIRTY_LP_ALL);
2754}
2755
2756/*
2757 * On gen9, we need to allocate Display Data Buffer (DDB) portions to the
2758 * different active planes.
2759 */
2760
2761#define SKL_DDB_SIZE            896     /* in blocks */
2762#define BXT_DDB_SIZE            512
2763
2764static void
2765skl_ddb_get_pipe_allocation_limits(struct drm_device *dev,
2766                                   struct drm_crtc *for_crtc,
2767                                   const struct intel_wm_config *config,
2768                                   const struct skl_pipe_wm_parameters *params,
2769                                   struct skl_ddb_entry *alloc /* out */)
2770{
2771        struct drm_crtc *crtc;
2772        unsigned int pipe_size, ddb_size;
2773        int nth_active_pipe;
2774
2775        if (!params->active) {
2776                alloc->start = 0;
2777                alloc->end = 0;
2778                return;
2779        }
2780
2781        if (IS_BROXTON(dev))
2782                ddb_size = BXT_DDB_SIZE;
2783        else
2784                ddb_size = SKL_DDB_SIZE;
2785
2786        ddb_size -= 4; /* 4 blocks for bypass path allocation */
2787
2788        nth_active_pipe = 0;
2789        for_each_crtc(dev, crtc) {
2790                if (!to_intel_crtc(crtc)->active)
2791                        continue;
2792
2793                if (crtc == for_crtc)
2794                        break;
2795
2796                nth_active_pipe++;
2797        }
2798
2799        pipe_size = ddb_size / config->num_pipes_active;
2800        alloc->start = nth_active_pipe * ddb_size / config->num_pipes_active;
2801        alloc->end = alloc->start + pipe_size;
2802}
2803
2804static unsigned int skl_cursor_allocation(const struct intel_wm_config *config)
2805{
2806        if (config->num_pipes_active == 1)
2807                return 32;
2808
2809        return 8;
2810}
2811
2812static void skl_ddb_entry_init_from_hw(struct skl_ddb_entry *entry, u32 reg)
2813{
2814        entry->start = reg & 0x3ff;
2815        entry->end = (reg >> 16) & 0x3ff;
2816        if (entry->end)
2817                entry->end += 1;
2818}
2819
2820void skl_ddb_get_hw_state(struct drm_i915_private *dev_priv,
2821                          struct skl_ddb_allocation *ddb /* out */)
2822{
2823        enum pipe pipe;
2824        int plane;
2825        u32 val;
2826
2827        memset(ddb, 0, sizeof(*ddb));
2828
2829        for_each_pipe(dev_priv, pipe) {
2830                if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PIPE(pipe)))
2831                        continue;
2832
2833                for_each_plane(dev_priv, pipe, plane) {
2834                        val = I915_READ(PLANE_BUF_CFG(pipe, plane));
2835                        skl_ddb_entry_init_from_hw(&ddb->plane[pipe][plane],
2836                                                   val);
2837                }
2838
2839                val = I915_READ(CUR_BUF_CFG(pipe));
2840                skl_ddb_entry_init_from_hw(&ddb->plane[pipe][PLANE_CURSOR],
2841                                           val);
2842        }
2843}
2844
2845static unsigned int
2846skl_plane_relative_data_rate(const struct intel_plane_wm_parameters *p, int y)
2847{
2848
2849        /* for planar format */
2850        if (p->y_bytes_per_pixel) {
2851                if (y)  /* y-plane data rate */
2852                        return p->horiz_pixels * p->vert_pixels * p->y_bytes_per_pixel;
2853                else    /* uv-plane data rate */
2854                        return (p->horiz_pixels/2) * (p->vert_pixels/2) * p->bytes_per_pixel;
2855        }
2856
2857        /* for packed formats */
2858        return p->horiz_pixels * p->vert_pixels * p->bytes_per_pixel;
2859}
2860
2861/*
2862 * We don't overflow 32 bits. Worst case is 3 planes enabled, each fetching
2863 * a 8192x4096@32bpp framebuffer:
2864 *   3 * 4096 * 8192  * 4 < 2^32
2865 */
2866static unsigned int
2867skl_get_total_relative_data_rate(struct intel_crtc *intel_crtc,
2868                                 const struct skl_pipe_wm_parameters *params)
2869{
2870        unsigned int total_data_rate = 0;
2871        int plane;
2872
2873        for (plane = 0; plane < intel_num_planes(intel_crtc); plane++) {
2874                const struct intel_plane_wm_parameters *p;
2875
2876                p = &params->plane[plane];
2877                if (!p->enabled)
2878                        continue;
2879
2880                total_data_rate += skl_plane_relative_data_rate(p, 0); /* packed/uv */
2881                if (p->y_bytes_per_pixel) {
2882                        total_data_rate += skl_plane_relative_data_rate(p, 1); /* y-plane */
2883                }
2884        }
2885
2886        return total_data_rate;
2887}
2888
2889static void
2890skl_allocate_pipe_ddb(struct drm_crtc *crtc,
2891                      const struct intel_wm_config *config,
2892                      const struct skl_pipe_wm_parameters *params,
2893                      struct skl_ddb_allocation *ddb /* out */)
2894{
2895        struct drm_device *dev = crtc->dev;
2896        struct drm_i915_private *dev_priv = dev->dev_private;
2897        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2898        enum pipe pipe = intel_crtc->pipe;
2899        struct skl_ddb_entry *alloc = &ddb->pipe[pipe];
2900        uint16_t alloc_size, start, cursor_blocks;
2901        uint16_t minimum[I915_MAX_PLANES];
2902        uint16_t y_minimum[I915_MAX_PLANES];
2903        unsigned int total_data_rate;
2904        int plane;
2905
2906        skl_ddb_get_pipe_allocation_limits(dev, crtc, config, params, alloc);
2907        alloc_size = skl_ddb_entry_size(alloc);
2908        if (alloc_size == 0) {
2909                memset(ddb->plane[pipe], 0, sizeof(ddb->plane[pipe]));
2910                memset(&ddb->plane[pipe][PLANE_CURSOR], 0,
2911                       sizeof(ddb->plane[pipe][PLANE_CURSOR]));
2912                return;
2913        }
2914
2915        cursor_blocks = skl_cursor_allocation(config);
2916        ddb->plane[pipe][PLANE_CURSOR].start = alloc->end - cursor_blocks;
2917        ddb->plane[pipe][PLANE_CURSOR].end = alloc->end;
2918
2919        alloc_size -= cursor_blocks;
2920        alloc->end -= cursor_blocks;
2921
2922        /* 1. Allocate the mininum required blocks for each active plane */
2923        for_each_plane(dev_priv, pipe, plane) {
2924                const struct intel_plane_wm_parameters *p;
2925
2926                p = &params->plane[plane];
2927                if (!p->enabled)
2928                        continue;
2929
2930                minimum[plane] = 8;
2931                alloc_size -= minimum[plane];
2932                y_minimum[plane] = p->y_bytes_per_pixel ? 8 : 0;
2933                alloc_size -= y_minimum[plane];
2934        }
2935
2936        /*
2937         * 2. Distribute the remaining space in proportion to the amount of
2938         * data each plane needs to fetch from memory.
2939         *
2940         * FIXME: we may not allocate every single block here.
2941         */
2942        total_data_rate = skl_get_total_relative_data_rate(intel_crtc, params);
2943
2944        start = alloc->start;
2945        for (plane = 0; plane < intel_num_planes(intel_crtc); plane++) {
2946                const struct intel_plane_wm_parameters *p;
2947                unsigned int data_rate, y_data_rate;
2948                uint16_t plane_blocks, y_plane_blocks = 0;
2949
2950                p = &params->plane[plane];
2951                if (!p->enabled)
2952                        continue;
2953
2954                data_rate = skl_plane_relative_data_rate(p, 0);
2955
2956                /*
2957                 * allocation for (packed formats) or (uv-plane part of planar format):
2958                 * promote the expression to 64 bits to avoid overflowing, the
2959                 * result is < available as data_rate / total_data_rate < 1
2960                 */
2961                plane_blocks = minimum[plane];
2962                plane_blocks += div_u64((uint64_t)alloc_size * data_rate,
2963                                        total_data_rate);
2964
2965                ddb->plane[pipe][plane].start = start;
2966                ddb->plane[pipe][plane].end = start + plane_blocks;
2967
2968                start += plane_blocks;
2969
2970                /*
2971                 * allocation for y_plane part of planar format:
2972                 */
2973                if (p->y_bytes_per_pixel) {
2974                        y_data_rate = skl_plane_relative_data_rate(p, 1);
2975                        y_plane_blocks = y_minimum[plane];
2976                        y_plane_blocks += div_u64((uint64_t)alloc_size * y_data_rate,
2977                                                total_data_rate);
2978
2979                        ddb->y_plane[pipe][plane].start = start;
2980                        ddb->y_plane[pipe][plane].end = start + y_plane_blocks;
2981
2982                        start += y_plane_blocks;
2983                }
2984
2985        }
2986
2987}
2988
2989static uint32_t skl_pipe_pixel_rate(const struct intel_crtc_state *config)
2990{
2991        /* TODO: Take into account the scalers once we support them */
2992        return config->base.adjusted_mode.crtc_clock;
2993}
2994
2995/*
2996 * The max latency should be 257 (max the punit can code is 255 and we add 2us
2997 * for the read latency) and bytes_per_pixel should always be <= 8, so that
2998 * should allow pixel_rate up to ~2 GHz which seems sufficient since max
2999 * 2xcdclk is 1350 MHz and the pixel rate should never exceed that.
3000*/
3001static uint32_t skl_wm_method1(uint32_t pixel_rate, uint8_t bytes_per_pixel,
3002                               uint32_t latency)
3003{
3004        uint32_t wm_intermediate_val, ret;
3005
3006        if (latency == 0)
3007                return UINT_MAX;
3008
3009        wm_intermediate_val = latency * pixel_rate * bytes_per_pixel / 512;
3010        ret = DIV_ROUND_UP(wm_intermediate_val, 1000);
3011
3012        return ret;
3013}
3014
3015static uint32_t skl_wm_method2(uint32_t pixel_rate, uint32_t pipe_htotal,
3016                               uint32_t horiz_pixels, uint8_t bytes_per_pixel,
3017                               uint64_t tiling, uint32_t latency)
3018{
3019        uint32_t ret;
3020        uint32_t plane_bytes_per_line, plane_blocks_per_line;
3021        uint32_t wm_intermediate_val;
3022
3023        if (latency == 0)
3024                return UINT_MAX;
3025
3026        plane_bytes_per_line = horiz_pixels * bytes_per_pixel;
3027
3028        if (tiling == I915_FORMAT_MOD_Y_TILED ||
3029            tiling == I915_FORMAT_MOD_Yf_TILED) {
3030                plane_bytes_per_line *= 4;
3031                plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
3032                plane_blocks_per_line /= 4;
3033        } else {
3034                plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
3035        }
3036
3037        wm_intermediate_val = latency * pixel_rate;
3038        ret = DIV_ROUND_UP(wm_intermediate_val, pipe_htotal * 1000) *
3039                                plane_blocks_per_line;
3040
3041        return ret;
3042}
3043
3044static bool skl_ddb_allocation_changed(const struct skl_ddb_allocation *new_ddb,
3045                                       const struct intel_crtc *intel_crtc)
3046{
3047        struct drm_device *dev = intel_crtc->base.dev;
3048        struct drm_i915_private *dev_priv = dev->dev_private;
3049        const struct skl_ddb_allocation *cur_ddb = &dev_priv->wm.skl_hw.ddb;
3050        enum pipe pipe = intel_crtc->pipe;
3051
3052        if (memcmp(new_ddb->plane[pipe], cur_ddb->plane[pipe],
3053                   sizeof(new_ddb->plane[pipe])))
3054                return true;
3055
3056        if (memcmp(&new_ddb->plane[pipe][PLANE_CURSOR], &cur_ddb->plane[pipe][PLANE_CURSOR],
3057                    sizeof(new_ddb->plane[pipe][PLANE_CURSOR])))
3058                return true;
3059
3060        return false;
3061}
3062
3063static void skl_compute_wm_global_parameters(struct drm_device *dev,
3064                                             struct intel_wm_config *config)
3065{
3066        struct drm_crtc *crtc;
3067        struct drm_plane *plane;
3068
3069        list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
3070                config->num_pipes_active += to_intel_crtc(crtc)->active;
3071
3072        /* FIXME: I don't think we need those two global parameters on SKL */
3073        list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
3074                struct intel_plane *intel_plane = to_intel_plane(plane);
3075
3076                config->sprites_enabled |= intel_plane->wm.enabled;
3077                config->sprites_scaled |= intel_plane->wm.scaled;
3078        }
3079}
3080
3081static void skl_compute_wm_pipe_parameters(struct drm_crtc *crtc,
3082                                           struct skl_pipe_wm_parameters *p)
3083{
3084        struct drm_device *dev = crtc->dev;
3085        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3086        enum pipe pipe = intel_crtc->pipe;
3087        struct drm_plane *plane;
3088        struct drm_framebuffer *fb;
3089        int i = 1; /* Index for sprite planes start */
3090
3091        p->active = intel_crtc->active;
3092        if (p->active) {
3093                p->pipe_htotal = intel_crtc->config->base.adjusted_mode.crtc_htotal;
3094                p->pixel_rate = skl_pipe_pixel_rate(intel_crtc->config);
3095
3096                fb = crtc->primary->state->fb;
3097                /* For planar: Bpp is for uv plane, y_Bpp is for y plane */
3098                if (fb) {
3099                        p->plane[0].enabled = true;
3100                        p->plane[0].bytes_per_pixel = fb->pixel_format == DRM_FORMAT_NV12 ?
3101                                drm_format_plane_cpp(fb->pixel_format, 1) :
3102                                drm_format_plane_cpp(fb->pixel_format, 0);
3103                        p->plane[0].y_bytes_per_pixel = fb->pixel_format == DRM_FORMAT_NV12 ?
3104                                drm_format_plane_cpp(fb->pixel_format, 0) : 0;
3105                        p->plane[0].tiling = fb->modifier[0];
3106                } else {
3107                        p->plane[0].enabled = false;
3108                        p->plane[0].bytes_per_pixel = 0;
3109                        p->plane[0].y_bytes_per_pixel = 0;
3110                        p->plane[0].tiling = DRM_FORMAT_MOD_NONE;
3111                }
3112                p->plane[0].horiz_pixels = intel_crtc->config->pipe_src_w;
3113                p->plane[0].vert_pixels = intel_crtc->config->pipe_src_h;
3114                p->plane[0].rotation = crtc->primary->state->rotation;
3115
3116                fb = crtc->cursor->state->fb;
3117                p->plane[PLANE_CURSOR].y_bytes_per_pixel = 0;
3118                if (fb) {
3119                        p->plane[PLANE_CURSOR].enabled = true;
3120                        p->plane[PLANE_CURSOR].bytes_per_pixel = fb->bits_per_pixel / 8;
3121                        p->plane[PLANE_CURSOR].horiz_pixels = crtc->cursor->state->crtc_w;
3122                        p->plane[PLANE_CURSOR].vert_pixels = crtc->cursor->state->crtc_h;
3123                } else {
3124                        p->plane[PLANE_CURSOR].enabled = false;
3125                        p->plane[PLANE_CURSOR].bytes_per_pixel = 0;
3126                        p->plane[PLANE_CURSOR].horiz_pixels = 64;
3127                        p->plane[PLANE_CURSOR].vert_pixels = 64;
3128                }
3129        }
3130
3131        list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
3132                struct intel_plane *intel_plane = to_intel_plane(plane);
3133
3134                if (intel_plane->pipe == pipe &&
3135                        plane->type == DRM_PLANE_TYPE_OVERLAY)
3136                        p->plane[i++] = intel_plane->wm;
3137        }
3138}
3139
3140static bool skl_compute_plane_wm(const struct drm_i915_private *dev_priv,
3141                                 struct skl_pipe_wm_parameters *p,
3142                                 struct intel_plane_wm_parameters *p_params,
3143                                 uint16_t ddb_allocation,
3144                                 int level,
3145                                 uint16_t *out_blocks, /* out */
3146                                 uint8_t *out_lines /* out */)
3147{
3148        uint32_t latency = dev_priv->wm.skl_latency[level];
3149        uint32_t method1, method2;
3150        uint32_t plane_bytes_per_line, plane_blocks_per_line;
3151        uint32_t res_blocks, res_lines;
3152        uint32_t selected_result;
3153        uint8_t bytes_per_pixel;
3154
3155        if (latency == 0 || !p->active || !p_params->enabled)
3156                return false;
3157
3158        bytes_per_pixel = p_params->y_bytes_per_pixel ?
3159                p_params->y_bytes_per_pixel :
3160                p_params->bytes_per_pixel;
3161        method1 = skl_wm_method1(p->pixel_rate,
3162                                 bytes_per_pixel,
3163                                 latency);
3164        method2 = skl_wm_method2(p->pixel_rate,
3165                                 p->pipe_htotal,
3166                                 p_params->horiz_pixels,
3167                                 bytes_per_pixel,
3168                                 p_params->tiling,
3169                                 latency);
3170
3171        plane_bytes_per_line = p_params->horiz_pixels * bytes_per_pixel;
3172        plane_blocks_per_line = DIV_ROUND_UP(plane_bytes_per_line, 512);
3173
3174        if (p_params->tiling == I915_FORMAT_MOD_Y_TILED ||
3175            p_params->tiling == I915_FORMAT_MOD_Yf_TILED) {
3176                uint32_t min_scanlines = 4;
3177                uint32_t y_tile_minimum;
3178                if (intel_rotation_90_or_270(p_params->rotation)) {
3179                        switch (p_params->bytes_per_pixel) {
3180                        case 1:
3181                                min_scanlines = 16;
3182                                break;
3183                        case 2:
3184                                min_scanlines = 8;
3185                                break;
3186                        case 8:
3187                                WARN(1, "Unsupported pixel depth for rotation");
3188                        }
3189                }
3190                y_tile_minimum = plane_blocks_per_line * min_scanlines;
3191                selected_result = max(method2, y_tile_minimum);
3192        } else {
3193                if ((ddb_allocation / plane_blocks_per_line) >= 1)
3194                        selected_result = min(method1, method2);
3195                else
3196                        selected_result = method1;
3197        }
3198
3199        res_blocks = selected_result + 1;
3200        res_lines = DIV_ROUND_UP(selected_result, plane_blocks_per_line);
3201
3202        if (level >= 1 && level <= 7) {
3203                if (p_params->tiling == I915_FORMAT_MOD_Y_TILED ||
3204                    p_params->tiling == I915_FORMAT_MOD_Yf_TILED)
3205                        res_lines += 4;
3206                else
3207                        res_blocks++;
3208        }
3209
3210        if (res_blocks >= ddb_allocation || res_lines > 31)
3211                return false;
3212
3213        *out_blocks = res_blocks;
3214        *out_lines = res_lines;
3215
3216        return true;
3217}
3218
3219static void skl_compute_wm_level(const struct drm_i915_private *dev_priv,
3220                                 struct skl_ddb_allocation *ddb,
3221                                 struct skl_pipe_wm_parameters *p,
3222                                 enum pipe pipe,
3223                                 int level,
3224                                 int num_planes,
3225                                 struct skl_wm_level *result)
3226{
3227        uint16_t ddb_blocks;
3228        int i;
3229
3230        for (i = 0; i < num_planes; i++) {
3231                ddb_blocks = skl_ddb_entry_size(&ddb->plane[pipe][i]);
3232
3233                result->plane_en[i] = skl_compute_plane_wm(dev_priv,
3234                                                p, &p->plane[i],
3235                                                ddb_blocks,
3236                                                level,
3237                                                &result->plane_res_b[i],
3238                                                &result->plane_res_l[i]);
3239        }
3240
3241        ddb_blocks = skl_ddb_entry_size(&ddb->plane[pipe][PLANE_CURSOR]);
3242        result->plane_en[PLANE_CURSOR] = skl_compute_plane_wm(dev_priv, p,
3243                                                 &p->plane[PLANE_CURSOR],
3244                                                 ddb_blocks, level,
3245                                                 &result->plane_res_b[PLANE_CURSOR],
3246                                                 &result->plane_res_l[PLANE_CURSOR]);
3247}
3248
3249static uint32_t
3250skl_compute_linetime_wm(struct drm_crtc *crtc, struct skl_pipe_wm_parameters *p)
3251{
3252        if (!to_intel_crtc(crtc)->active)
3253                return 0;
3254
3255        if (WARN_ON(p->pixel_rate == 0))
3256                return 0;
3257
3258        return DIV_ROUND_UP(8 * p->pipe_htotal * 1000, p->pixel_rate);
3259}
3260
3261static void skl_compute_transition_wm(struct drm_crtc *crtc,
3262                                      struct skl_pipe_wm_parameters *params,
3263                                      struct skl_wm_level *trans_wm /* out */)
3264{
3265        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3266        int i;
3267
3268        if (!params->active)
3269                return;
3270
3271        /* Until we know more, just disable transition WMs */
3272        for (i = 0; i < intel_num_planes(intel_crtc); i++)
3273                trans_wm->plane_en[i] = false;
3274        trans_wm->plane_en[PLANE_CURSOR] = false;
3275}
3276
3277static void skl_compute_pipe_wm(struct drm_crtc *crtc,
3278                                struct skl_ddb_allocation *ddb,
3279                                struct skl_pipe_wm_parameters *params,
3280                                struct skl_pipe_wm *pipe_wm)
3281{
3282        struct drm_device *dev = crtc->dev;
3283        const struct drm_i915_private *dev_priv = dev->dev_private;
3284        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3285        int level, max_level = ilk_wm_max_level(dev);
3286
3287        for (level = 0; level <= max_level; level++) {
3288                skl_compute_wm_level(dev_priv, ddb, params, intel_crtc->pipe,
3289                                     level, intel_num_planes(intel_crtc),
3290                                     &pipe_wm->wm[level]);
3291        }
3292        pipe_wm->linetime = skl_compute_linetime_wm(crtc, params);
3293
3294        skl_compute_transition_wm(crtc, params, &pipe_wm->trans_wm);
3295}
3296
3297static void skl_compute_wm_results(struct drm_device *dev,
3298                                   struct skl_pipe_wm_parameters *p,
3299                                   struct skl_pipe_wm *p_wm,
3300                                   struct skl_wm_values *r,
3301                                   struct intel_crtc *intel_crtc)
3302{
3303        int level, max_level = ilk_wm_max_level(dev);
3304        enum pipe pipe = intel_crtc->pipe;
3305        uint32_t temp;
3306        int i;
3307
3308        for (level = 0; level <= max_level; level++) {
3309                for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3310                        temp = 0;
3311
3312                        temp |= p_wm->wm[level].plane_res_l[i] <<
3313                                        PLANE_WM_LINES_SHIFT;
3314                        temp |= p_wm->wm[level].plane_res_b[i];
3315                        if (p_wm->wm[level].plane_en[i])
3316                                temp |= PLANE_WM_EN;
3317
3318                        r->plane[pipe][i][level] = temp;
3319                }
3320
3321                temp = 0;
3322
3323                temp |= p_wm->wm[level].plane_res_l[PLANE_CURSOR] << PLANE_WM_LINES_SHIFT;
3324                temp |= p_wm->wm[level].plane_res_b[PLANE_CURSOR];
3325
3326                if (p_wm->wm[level].plane_en[PLANE_CURSOR])
3327                        temp |= PLANE_WM_EN;
3328
3329                r->plane[pipe][PLANE_CURSOR][level] = temp;
3330
3331        }
3332
3333        /* transition WMs */
3334        for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3335                temp = 0;
3336                temp |= p_wm->trans_wm.plane_res_l[i] << PLANE_WM_LINES_SHIFT;
3337                temp |= p_wm->trans_wm.plane_res_b[i];
3338                if (p_wm->trans_wm.plane_en[i])
3339                        temp |= PLANE_WM_EN;
3340
3341                r->plane_trans[pipe][i] = temp;
3342        }
3343
3344        temp = 0;
3345        temp |= p_wm->trans_wm.plane_res_l[PLANE_CURSOR] << PLANE_WM_LINES_SHIFT;
3346        temp |= p_wm->trans_wm.plane_res_b[PLANE_CURSOR];
3347        if (p_wm->trans_wm.plane_en[PLANE_CURSOR])
3348                temp |= PLANE_WM_EN;
3349
3350        r->plane_trans[pipe][PLANE_CURSOR] = temp;
3351
3352        r->wm_linetime[pipe] = p_wm->linetime;
3353}
3354
3355static void skl_ddb_entry_write(struct drm_i915_private *dev_priv, uint32_t reg,
3356                                const struct skl_ddb_entry *entry)
3357{
3358        if (entry->end)
3359                I915_WRITE(reg, (entry->end - 1) << 16 | entry->start);
3360        else
3361                I915_WRITE(reg, 0);
3362}
3363
3364static void skl_write_wm_values(struct drm_i915_private *dev_priv,
3365                                const struct skl_wm_values *new)
3366{
3367        struct drm_device *dev = dev_priv->dev;
3368        struct intel_crtc *crtc;
3369
3370        list_for_each_entry(crtc, &dev->mode_config.crtc_list, base.head) {
3371                int i, level, max_level = ilk_wm_max_level(dev);
3372                enum pipe pipe = crtc->pipe;
3373
3374                if (!new->dirty[pipe])
3375                        continue;
3376
3377                I915_WRITE(PIPE_WM_LINETIME(pipe), new->wm_linetime[pipe]);
3378
3379                for (level = 0; level <= max_level; level++) {
3380                        for (i = 0; i < intel_num_planes(crtc); i++)
3381                                I915_WRITE(PLANE_WM(pipe, i, level),
3382                                           new->plane[pipe][i][level]);
3383                        I915_WRITE(CUR_WM(pipe, level),
3384                                   new->plane[pipe][PLANE_CURSOR][level]);
3385                }
3386                for (i = 0; i < intel_num_planes(crtc); i++)
3387                        I915_WRITE(PLANE_WM_TRANS(pipe, i),
3388                                   new->plane_trans[pipe][i]);
3389                I915_WRITE(CUR_WM_TRANS(pipe),
3390                           new->plane_trans[pipe][PLANE_CURSOR]);
3391
3392                for (i = 0; i < intel_num_planes(crtc); i++) {
3393                        skl_ddb_entry_write(dev_priv,
3394                                            PLANE_BUF_CFG(pipe, i),
3395                                            &new->ddb.plane[pipe][i]);
3396                        skl_ddb_entry_write(dev_priv,
3397                                            PLANE_NV12_BUF_CFG(pipe, i),
3398                                            &new->ddb.y_plane[pipe][i]);
3399                }
3400
3401                skl_ddb_entry_write(dev_priv, CUR_BUF_CFG(pipe),
3402                                    &new->ddb.plane[pipe][PLANE_CURSOR]);
3403        }
3404}
3405
3406/*
3407 * When setting up a new DDB allocation arrangement, we need to correctly
3408 * sequence the times at which the new allocations for the pipes are taken into
3409 * account or we'll have pipes fetching from space previously allocated to
3410 * another pipe.
3411 *
3412 * Roughly the sequence looks like:
3413 *  1. re-allocate the pipe(s) with the allocation being reduced and not
3414 *     overlapping with a previous light-up pipe (another way to put it is:
3415 *     pipes with their new allocation strickly included into their old ones).
3416 *  2. re-allocate the other pipes that get their allocation reduced
3417 *  3. allocate the pipes having their allocation increased
3418 *
3419 * Steps 1. and 2. are here to take care of the following case:
3420 * - Initially DDB looks like this:
3421 *     |   B    |   C    |
3422 * - enable pipe A.
3423 * - pipe B has a reduced DDB allocation that overlaps with the old pipe C
3424 *   allocation
3425 *     |  A  |  B  |  C  |
3426 *
3427 * We need to sequence the re-allocation: C, B, A (and not B, C, A).
3428 */
3429
3430static void
3431skl_wm_flush_pipe(struct drm_i915_private *dev_priv, enum pipe pipe, int pass)
3432{
3433        int plane;
3434
3435        DRM_DEBUG_KMS("flush pipe %c (pass %d)\n", pipe_name(pipe), pass);
3436
3437        for_each_plane(dev_priv, pipe, plane) {
3438                I915_WRITE(PLANE_SURF(pipe, plane),
3439                           I915_READ(PLANE_SURF(pipe, plane)));
3440        }
3441        I915_WRITE(CURBASE(pipe), I915_READ(CURBASE(pipe)));
3442}
3443
3444static bool
3445skl_ddb_allocation_included(const struct skl_ddb_allocation *old,
3446                            const struct skl_ddb_allocation *new,
3447                            enum pipe pipe)
3448{
3449        uint16_t old_size, new_size;
3450
3451        old_size = skl_ddb_entry_size(&old->pipe[pipe]);
3452        new_size = skl_ddb_entry_size(&new->pipe[pipe]);
3453
3454        return old_size != new_size &&
3455               new->pipe[pipe].start >= old->pipe[pipe].start &&
3456               new->pipe[pipe].end <= old->pipe[pipe].end;
3457}
3458
3459static void skl_flush_wm_values(struct drm_i915_private *dev_priv,
3460                                struct skl_wm_values *new_values)
3461{
3462        struct drm_device *dev = dev_priv->dev;
3463        struct skl_ddb_allocation *cur_ddb, *new_ddb;
3464        bool reallocated[I915_MAX_PIPES] = {};
3465        struct intel_crtc *crtc;
3466        enum pipe pipe;
3467
3468        new_ddb = &new_values->ddb;
3469        cur_ddb = &dev_priv->wm.skl_hw.ddb;
3470
3471        /*
3472         * First pass: flush the pipes with the new allocation contained into
3473         * the old space.
3474         *
3475         * We'll wait for the vblank on those pipes to ensure we can safely
3476         * re-allocate the freed space without this pipe fetching from it.
3477         */
3478        for_each_intel_crtc(dev, crtc) {
3479                if (!crtc->active)
3480                        continue;
3481
3482                pipe = crtc->pipe;
3483
3484                if (!skl_ddb_allocation_included(cur_ddb, new_ddb, pipe))
3485                        continue;
3486
3487                skl_wm_flush_pipe(dev_priv, pipe, 1);
3488                intel_wait_for_vblank(dev, pipe);
3489
3490                reallocated[pipe] = true;
3491        }
3492
3493
3494        /*
3495         * Second pass: flush the pipes that are having their allocation
3496         * reduced, but overlapping with a previous allocation.
3497         *
3498         * Here as well we need to wait for the vblank to make sure the freed
3499         * space is not used anymore.
3500         */
3501        for_each_intel_crtc(dev, crtc) {
3502                if (!crtc->active)
3503                        continue;
3504
3505                pipe = crtc->pipe;
3506
3507                if (reallocated[pipe])
3508                        continue;
3509
3510                if (skl_ddb_entry_size(&new_ddb->pipe[pipe]) <
3511                    skl_ddb_entry_size(&cur_ddb->pipe[pipe])) {
3512                        skl_wm_flush_pipe(dev_priv, pipe, 2);
3513                        intel_wait_for_vblank(dev, pipe);
3514                        reallocated[pipe] = true;
3515                }
3516        }
3517
3518        /*
3519         * Third pass: flush the pipes that got more space allocated.
3520         *
3521         * We don't need to actively wait for the update here, next vblank
3522         * will just get more DDB space with the correct WM values.
3523         */
3524        for_each_intel_crtc(dev, crtc) {
3525                if (!crtc->active)
3526                        continue;
3527
3528                pipe = crtc->pipe;
3529
3530                /*
3531                 * At this point, only the pipes more space than before are
3532                 * left to re-allocate.
3533                 */
3534                if (reallocated[pipe])
3535                        continue;
3536
3537                skl_wm_flush_pipe(dev_priv, pipe, 3);
3538        }
3539}
3540
3541static bool skl_update_pipe_wm(struct drm_crtc *crtc,
3542                               struct skl_pipe_wm_parameters *params,
3543                               struct intel_wm_config *config,
3544                               struct skl_ddb_allocation *ddb, /* out */
3545                               struct skl_pipe_wm *pipe_wm /* out */)
3546{
3547        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3548
3549        skl_compute_wm_pipe_parameters(crtc, params);
3550        skl_allocate_pipe_ddb(crtc, config, params, ddb);
3551        skl_compute_pipe_wm(crtc, ddb, params, pipe_wm);
3552
3553        if (!memcmp(&intel_crtc->wm.skl_active, pipe_wm, sizeof(*pipe_wm)))
3554                return false;
3555
3556        intel_crtc->wm.skl_active = *pipe_wm;
3557
3558        return true;
3559}
3560
3561static void skl_update_other_pipe_wm(struct drm_device *dev,
3562                                     struct drm_crtc *crtc,
3563                                     struct intel_wm_config *config,
3564                                     struct skl_wm_values *r)
3565{
3566        struct intel_crtc *intel_crtc;
3567        struct intel_crtc *this_crtc = to_intel_crtc(crtc);
3568
3569        /*
3570         * If the WM update hasn't changed the allocation for this_crtc (the
3571         * crtc we are currently computing the new WM values for), other
3572         * enabled crtcs will keep the same allocation and we don't need to
3573         * recompute anything for them.
3574         */
3575        if (!skl_ddb_allocation_changed(&r->ddb, this_crtc))
3576                return;
3577
3578        /*
3579         * Otherwise, because of this_crtc being freshly enabled/disabled, the
3580         * other active pipes need new DDB allocation and WM values.
3581         */
3582        list_for_each_entry(intel_crtc, &dev->mode_config.crtc_list,
3583                                base.head) {
3584                struct skl_pipe_wm_parameters params = {};
3585                struct skl_pipe_wm pipe_wm = {};
3586                bool wm_changed;
3587
3588                if (this_crtc->pipe == intel_crtc->pipe)
3589                        continue;
3590
3591                if (!intel_crtc->active)
3592                        continue;
3593
3594                wm_changed = skl_update_pipe_wm(&intel_crtc->base,
3595                                                &params, config,
3596                                                &r->ddb, &pipe_wm);
3597
3598                /*
3599                 * If we end up re-computing the other pipe WM values, it's
3600                 * because it was really needed, so we expect the WM values to
3601                 * be different.
3602                 */
3603                WARN_ON(!wm_changed);
3604
3605                skl_compute_wm_results(dev, &params, &pipe_wm, r, intel_crtc);
3606                r->dirty[intel_crtc->pipe] = true;
3607        }
3608}
3609
3610static void skl_clear_wm(struct skl_wm_values *watermarks, enum pipe pipe)
3611{
3612        watermarks->wm_linetime[pipe] = 0;
3613        memset(watermarks->plane[pipe], 0,
3614               sizeof(uint32_t) * 8 * I915_MAX_PLANES);
3615        memset(watermarks->plane_trans[pipe],
3616               0, sizeof(uint32_t) * I915_MAX_PLANES);
3617        watermarks->plane_trans[pipe][PLANE_CURSOR] = 0;
3618
3619        /* Clear ddb entries for pipe */
3620        memset(&watermarks->ddb.pipe[pipe], 0, sizeof(struct skl_ddb_entry));
3621        memset(&watermarks->ddb.plane[pipe], 0,
3622               sizeof(struct skl_ddb_entry) * I915_MAX_PLANES);
3623        memset(&watermarks->ddb.y_plane[pipe], 0,
3624               sizeof(struct skl_ddb_entry) * I915_MAX_PLANES);
3625        memset(&watermarks->ddb.plane[pipe][PLANE_CURSOR], 0,
3626               sizeof(struct skl_ddb_entry));
3627
3628}
3629
3630static void skl_update_wm(struct drm_crtc *crtc)
3631{
3632        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3633        struct drm_device *dev = crtc->dev;
3634        struct drm_i915_private *dev_priv = dev->dev_private;
3635        struct skl_pipe_wm_parameters params = {};
3636        struct skl_wm_values *results = &dev_priv->wm.skl_results;
3637        struct skl_pipe_wm pipe_wm = {};
3638        struct intel_wm_config config = {};
3639
3640
3641        /* Clear all dirty flags */
3642        memset(results->dirty, 0, sizeof(bool) * I915_MAX_PIPES);
3643
3644        skl_clear_wm(results, intel_crtc->pipe);
3645
3646        skl_compute_wm_global_parameters(dev, &config);
3647
3648        if (!skl_update_pipe_wm(crtc, &params, &config,
3649                                &results->ddb, &pipe_wm))
3650                return;
3651
3652        skl_compute_wm_results(dev, &params, &pipe_wm, results, intel_crtc);
3653        results->dirty[intel_crtc->pipe] = true;
3654
3655        skl_update_other_pipe_wm(dev, crtc, &config, results);
3656        skl_write_wm_values(dev_priv, results);
3657        skl_flush_wm_values(dev_priv, results);
3658
3659        /* store the new configuration */
3660        dev_priv->wm.skl_hw = *results;
3661}
3662
3663static void
3664skl_update_sprite_wm(struct drm_plane *plane, struct drm_crtc *crtc,
3665                     uint32_t sprite_width, uint32_t sprite_height,
3666                     int pixel_size, bool enabled, bool scaled)
3667{
3668        struct intel_plane *intel_plane = to_intel_plane(plane);
3669        struct drm_framebuffer *fb = plane->state->fb;
3670
3671        intel_plane->wm.enabled = enabled;
3672        intel_plane->wm.scaled = scaled;
3673        intel_plane->wm.horiz_pixels = sprite_width;
3674        intel_plane->wm.vert_pixels = sprite_height;
3675        intel_plane->wm.tiling = DRM_FORMAT_MOD_NONE;
3676
3677        /* For planar: Bpp is for UV plane, y_Bpp is for Y plane */
3678        intel_plane->wm.bytes_per_pixel =
3679                (fb && fb->pixel_format == DRM_FORMAT_NV12) ?
3680                drm_format_plane_cpp(plane->state->fb->pixel_format, 1) : pixel_size;
3681        intel_plane->wm.y_bytes_per_pixel =
3682                (fb && fb->pixel_format == DRM_FORMAT_NV12) ?
3683                drm_format_plane_cpp(plane->state->fb->pixel_format, 0) : 0;
3684
3685        /*
3686         * Framebuffer can be NULL on plane disable, but it does not
3687         * matter for watermarks if we assume no tiling in that case.
3688         */
3689        if (fb)
3690                intel_plane->wm.tiling = fb->modifier[0];
3691        intel_plane->wm.rotation = plane->state->rotation;
3692
3693        skl_update_wm(crtc);
3694}
3695
3696static void ilk_update_wm(struct drm_crtc *crtc)
3697{
3698        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3699        struct intel_crtc_state *cstate = to_intel_crtc_state(crtc->state);
3700        struct drm_device *dev = crtc->dev;
3701        struct drm_i915_private *dev_priv = dev->dev_private;
3702        struct ilk_wm_maximums max;
3703        struct ilk_wm_values results = {};
3704        enum intel_ddb_partitioning partitioning;
3705        struct intel_pipe_wm pipe_wm = {};
3706        struct intel_pipe_wm lp_wm_1_2 = {}, lp_wm_5_6 = {}, *best_lp_wm;
3707        struct intel_wm_config config = {};
3708
3709        WARN_ON(cstate->base.active != intel_crtc->active);
3710
3711        intel_compute_pipe_wm(cstate, &pipe_wm);
3712
3713        if (!memcmp(&intel_crtc->wm.active, &pipe_wm, sizeof(pipe_wm)))
3714                return;
3715
3716        intel_crtc->wm.active = pipe_wm;
3717
3718        ilk_compute_wm_config(dev, &config);
3719
3720        ilk_compute_wm_maximums(dev, 1, &config, INTEL_DDB_PART_1_2, &max);
3721        ilk_wm_merge(dev, &config, &max, &lp_wm_1_2);
3722
3723        /* 5/6 split only in single pipe config on IVB+ */
3724        if (INTEL_INFO(dev)->gen >= 7 &&
3725            config.num_pipes_active == 1 && config.sprites_enabled) {
3726                ilk_compute_wm_maximums(dev, 1, &config, INTEL_DDB_PART_5_6, &max);
3727                ilk_wm_merge(dev, &config, &max, &lp_wm_5_6);
3728
3729                best_lp_wm = ilk_find_best_result(dev, &lp_wm_1_2, &lp_wm_5_6);
3730        } else {
3731                best_lp_wm = &lp_wm_1_2;
3732        }
3733
3734        partitioning = (best_lp_wm == &lp_wm_1_2) ?
3735                       INTEL_DDB_PART_1_2 : INTEL_DDB_PART_5_6;
3736
3737        ilk_compute_wm_results(dev, best_lp_wm, partitioning, &results);
3738
3739        ilk_write_wm_values(dev_priv, &results);
3740}
3741
3742static void
3743ilk_update_sprite_wm(struct drm_plane *plane,
3744                     struct drm_crtc *crtc,
3745                     uint32_t sprite_width, uint32_t sprite_height,
3746                     int pixel_size, bool enabled, bool scaled)
3747{
3748        struct drm_device *dev = plane->dev;
3749        struct intel_plane *intel_plane = to_intel_plane(plane);
3750
3751        /*
3752         * IVB workaround: must disable low power watermarks for at least
3753         * one frame before enabling scaling.  LP watermarks can be re-enabled
3754         * when scaling is disabled.
3755         *
3756         * WaCxSRDisabledForSpriteScaling:ivb
3757         */
3758        if (IS_IVYBRIDGE(dev) && scaled && ilk_disable_lp_wm(dev))
3759                intel_wait_for_vblank(dev, intel_plane->pipe);
3760
3761        ilk_update_wm(crtc);
3762}
3763
3764static void skl_pipe_wm_active_state(uint32_t val,
3765                                     struct skl_pipe_wm *active,
3766                                     bool is_transwm,
3767                                     bool is_cursor,
3768                                     int i,
3769                                     int level)
3770{
3771        bool is_enabled = (val & PLANE_WM_EN) != 0;
3772
3773        if (!is_transwm) {
3774                if (!is_cursor) {
3775                        active->wm[level].plane_en[i] = is_enabled;
3776                        active->wm[level].plane_res_b[i] =
3777                                        val & PLANE_WM_BLOCKS_MASK;
3778                        active->wm[level].plane_res_l[i] =
3779                                        (val >> PLANE_WM_LINES_SHIFT) &
3780                                                PLANE_WM_LINES_MASK;
3781                } else {
3782                        active->wm[level].plane_en[PLANE_CURSOR] = is_enabled;
3783                        active->wm[level].plane_res_b[PLANE_CURSOR] =
3784                                        val & PLANE_WM_BLOCKS_MASK;
3785                        active->wm[level].plane_res_l[PLANE_CURSOR] =
3786                                        (val >> PLANE_WM_LINES_SHIFT) &
3787                                                PLANE_WM_LINES_MASK;
3788                }
3789        } else {
3790                if (!is_cursor) {
3791                        active->trans_wm.plane_en[i] = is_enabled;
3792                        active->trans_wm.plane_res_b[i] =
3793                                        val & PLANE_WM_BLOCKS_MASK;
3794                        active->trans_wm.plane_res_l[i] =
3795                                        (val >> PLANE_WM_LINES_SHIFT) &
3796                                                PLANE_WM_LINES_MASK;
3797                } else {
3798                        active->trans_wm.plane_en[PLANE_CURSOR] = is_enabled;
3799                        active->trans_wm.plane_res_b[PLANE_CURSOR] =
3800                                        val & PLANE_WM_BLOCKS_MASK;
3801                        active->trans_wm.plane_res_l[PLANE_CURSOR] =
3802                                        (val >> PLANE_WM_LINES_SHIFT) &
3803                                                PLANE_WM_LINES_MASK;
3804                }
3805        }
3806}
3807
3808static void skl_pipe_wm_get_hw_state(struct drm_crtc *crtc)
3809{
3810        struct drm_device *dev = crtc->dev;
3811        struct drm_i915_private *dev_priv = dev->dev_private;
3812        struct skl_wm_values *hw = &dev_priv->wm.skl_hw;
3813        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3814        struct skl_pipe_wm *active = &intel_crtc->wm.skl_active;
3815        enum pipe pipe = intel_crtc->pipe;
3816        int level, i, max_level;
3817        uint32_t temp;
3818
3819        max_level = ilk_wm_max_level(dev);
3820
3821        hw->wm_linetime[pipe] = I915_READ(PIPE_WM_LINETIME(pipe));
3822
3823        for (level = 0; level <= max_level; level++) {
3824                for (i = 0; i < intel_num_planes(intel_crtc); i++)
3825                        hw->plane[pipe][i][level] =
3826                                        I915_READ(PLANE_WM(pipe, i, level));
3827                hw->plane[pipe][PLANE_CURSOR][level] = I915_READ(CUR_WM(pipe, level));
3828        }
3829
3830        for (i = 0; i < intel_num_planes(intel_crtc); i++)
3831                hw->plane_trans[pipe][i] = I915_READ(PLANE_WM_TRANS(pipe, i));
3832        hw->plane_trans[pipe][PLANE_CURSOR] = I915_READ(CUR_WM_TRANS(pipe));
3833
3834        if (!intel_crtc->active)
3835                return;
3836
3837        hw->dirty[pipe] = true;
3838
3839        active->linetime = hw->wm_linetime[pipe];
3840
3841        for (level = 0; level <= max_level; level++) {
3842                for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3843                        temp = hw->plane[pipe][i][level];
3844                        skl_pipe_wm_active_state(temp, active, false,
3845                                                false, i, level);
3846                }
3847                temp = hw->plane[pipe][PLANE_CURSOR][level];
3848                skl_pipe_wm_active_state(temp, active, false, true, i, level);
3849        }
3850
3851        for (i = 0; i < intel_num_planes(intel_crtc); i++) {
3852                temp = hw->plane_trans[pipe][i];
3853                skl_pipe_wm_active_state(temp, active, true, false, i, 0);
3854        }
3855
3856        temp = hw->plane_trans[pipe][PLANE_CURSOR];
3857        skl_pipe_wm_active_state(temp, active, true, true, i, 0);
3858}
3859
3860void skl_wm_get_hw_state(struct drm_device *dev)
3861{
3862        struct drm_i915_private *dev_priv = dev->dev_private;
3863        struct skl_ddb_allocation *ddb = &dev_priv->wm.skl_hw.ddb;
3864        struct drm_crtc *crtc;
3865
3866        skl_ddb_get_hw_state(dev_priv, ddb);
3867        list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
3868                skl_pipe_wm_get_hw_state(crtc);
3869}
3870
3871static void ilk_pipe_wm_get_hw_state(struct drm_crtc *crtc)
3872{
3873        struct drm_device *dev = crtc->dev;
3874        struct drm_i915_private *dev_priv = dev->dev_private;
3875        struct ilk_wm_values *hw = &dev_priv->wm.hw;
3876        struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3877        struct intel_pipe_wm *active = &intel_crtc->wm.active;
3878        enum pipe pipe = intel_crtc->pipe;
3879        static const unsigned int wm0_pipe_reg[] = {
3880                [PIPE_A] = WM0_PIPEA_ILK,
3881                [PIPE_B] = WM0_PIPEB_ILK,
3882                [PIPE_C] = WM0_PIPEC_IVB,
3883        };
3884
3885        hw->wm_pipe[pipe] = I915_READ(wm0_pipe_reg[pipe]);
3886        if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3887                hw->wm_linetime[pipe] = I915_READ(PIPE_WM_LINETIME(pipe));
3888
3889        memset(active, 0, sizeof(*active));
3890
3891        active->pipe_enabled = intel_crtc->active;
3892
3893        if (active->pipe_enabled) {
3894                u32 tmp = hw->wm_pipe[pipe];
3895
3896                /*
3897                 * For active pipes LP0 watermark is marked as
3898                 * enabled, and LP1+ watermaks as disabled since
3899                 * we can't really reverse compute them in case
3900                 * multiple pipes are active.
3901                 */
3902                active->wm[0].enable = true;
3903                active->wm[0].pri_val = (tmp & WM0_PIPE_PLANE_MASK) >> WM0_PIPE_PLANE_SHIFT;
3904                active->wm[0].spr_val = (tmp & WM0_PIPE_SPRITE_MASK) >> WM0_PIPE_SPRITE_SHIFT;
3905                active->wm[0].cur_val = tmp & WM0_PIPE_CURSOR_MASK;
3906                active->linetime = hw->wm_linetime[pipe];
3907        } else {
3908                int level, max_level = ilk_wm_max_level(dev);
3909
3910                /*
3911                 * For inactive pipes, all watermark levels
3912                 * should be marked as enabled but zeroed,
3913                 * which is what we'd compute them to.
3914                 */
3915                for (level = 0; level <= max_level; level++)
3916                        active->wm[level].enable = true;
3917        }
3918}
3919
3920#define _FW_WM(value, plane) \
3921        (((value) & DSPFW_ ## plane ## _MASK) >> DSPFW_ ## plane ## _SHIFT)
3922#define _FW_WM_VLV(value, plane) \
3923        (((value) & DSPFW_ ## plane ## _MASK_VLV) >> DSPFW_ ## plane ## _SHIFT)
3924
3925static void vlv_read_wm_values(struct drm_i915_private *dev_priv,
3926                               struct vlv_wm_values *wm)
3927{
3928        enum pipe pipe;
3929        uint32_t tmp;
3930
3931        for_each_pipe(dev_priv, pipe) {
3932                tmp = I915_READ(VLV_DDL(pipe));
3933
3934                wm->ddl[pipe].primary =
3935                        (tmp >> DDL_PLANE_SHIFT) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
3936                wm->ddl[pipe].cursor =
3937                        (tmp >> DDL_CURSOR_SHIFT) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
3938                wm->ddl[pipe].sprite[0] =
3939                        (tmp >> DDL_SPRITE_SHIFT(0)) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
3940                wm->ddl[pipe].sprite[1] =
3941                        (tmp >> DDL_SPRITE_SHIFT(1)) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
3942        }
3943
3944        tmp = I915_READ(DSPFW1);
3945        wm->sr.plane = _FW_WM(tmp, SR);
3946        wm->pipe[PIPE_B].cursor = _FW_WM(tmp, CURSORB);
3947        wm->pipe[PIPE_B].primary = _FW_WM_VLV(tmp, PLANEB);
3948        wm->pipe[PIPE_A].primary = _FW_WM_VLV(tmp, PLANEA);
3949
3950        tmp = I915_READ(DSPFW2);
3951        wm->pipe[PIPE_A].sprite[1] = _FW_WM_VLV(tmp, SPRITEB);
3952        wm->pipe[PIPE_A].cursor = _FW_WM(tmp, CURSORA);
3953        wm->pipe[PIPE_A].sprite[0] = _FW_WM_VLV(tmp, SPRITEA);
3954
3955        tmp = I915_READ(DSPFW3);
3956        wm->sr.cursor = _FW_WM(tmp, CURSOR_SR);
3957
3958        if (IS_CHERRYVIEW(dev_priv)) {
3959                tmp = I915_READ(DSPFW7_CHV);
3960                wm->pipe[PIPE_B].sprite[1] = _FW_WM_VLV(tmp, SPRITED);
3961                wm->pipe[PIPE_B].sprite[0] = _FW_WM_VLV(tmp, SPRITEC);
3962
3963                tmp = I915_READ(DSPFW8_CHV);
3964                wm->pipe[PIPE_C].sprite[1] = _FW_WM_VLV(tmp, SPRITEF);
3965                wm->pipe[PIPE_C].sprite[0] = _FW_WM_VLV(tmp, SPRITEE);
3966
3967                tmp = I915_READ(DSPFW9_CHV);
3968                wm->pipe[PIPE_C].primary = _FW_WM_VLV(tmp, PLANEC);
3969                wm->pipe[PIPE_C].cursor = _FW_WM(tmp, CURSORC);
3970
3971                tmp = I915_READ(DSPHOWM);
3972                wm->sr.plane |= _FW_WM(tmp, SR_HI) << 9;
3973                wm->pipe[PIPE_C].sprite[1] |= _FW_WM(tmp, SPRITEF_HI) << 8;
3974                wm->pipe[PIPE_C].sprite[0] |= _FW_WM(tmp, SPRITEE_HI) << 8;
3975                wm->pipe[PIPE_C].primary |= _FW_WM(tmp, PLANEC_HI) << 8;
3976                wm->pipe[PIPE_B].sprite[1] |= _FW_WM(tmp, SPRITED_HI) << 8;
3977                wm->pipe[PIPE_B].sprite[0] |= _FW_WM(tmp, SPRITEC_HI) << 8;
3978                wm->pipe[PIPE_B].primary |= _FW_WM(tmp, PLANEB_HI) << 8;
3979                wm->pipe[PIPE_A].sprite[1] |= _FW_WM(tmp, SPRITEB_HI) << 8;
3980                wm->pipe[PIPE_A].sprite[0] |= _FW_WM(tmp, SPRITEA_HI) << 8;
3981                wm->pipe[PIPE_A].primary |= _FW_WM(tmp, PLANEA_HI) << 8;
3982        } else {
3983                tmp = I915_READ(DSPFW7);
3984                wm->pipe[PIPE_B].sprite[1] = _FW_WM_VLV(tmp, SPRITED);
3985                wm->pipe[PIPE_B].sprite[0] = _FW_WM_VLV(tmp, SPRITEC);
3986
3987                tmp = I915_READ(DSPHOWM);
3988                wm->sr.plane |= _FW_WM(tmp, SR_HI) << 9;
3989                wm->pipe[PIPE_B].sprite[1] |= _FW_WM(tmp, SPRITED_HI) << 8;
3990                wm->pipe[PIPE_B].sprite[0] |= _FW_WM(tmp, SPRITEC_HI) << 8;
3991                wm->pipe[PIPE_B].primary |= _FW_WM(tmp, PLANEB_HI) << 8;
3992                wm->pipe[PIPE_A].sprite[1] |= _FW_WM(tmp, SPRITEB_HI) << 8;
3993                wm->pipe[PIPE_A].sprite[0] |= _FW_WM(tmp, SPRITEA_HI) << 8;
3994                wm->pipe[PIPE_A].primary |= _FW_WM(tmp, PLANEA_HI) << 8;
3995        }
3996}
3997
3998#undef _FW_WM
3999#undef _FW_WM_VLV
4000
4001void vlv_wm_get_hw_state(struct drm_device *dev)
4002{
4003        struct drm_i915_private *dev_priv = to_i915(dev);
4004        struct vlv_wm_values *wm = &dev_priv->wm.vlv;
4005        struct intel_plane *plane;
4006        enum pipe pipe;
4007        u32 val;
4008
4009        vlv_read_wm_values(dev_priv, wm);
4010
4011        for_each_intel_plane(dev, plane) {
4012                switch (plane->base.type) {
4013                        int sprite;
4014                case DRM_PLANE_TYPE_CURSOR:
4015                        plane->wm.fifo_size = 63;
4016                        break;
4017                case DRM_PLANE_TYPE_PRIMARY:
4018                        plane->wm.fifo_size = vlv_get_fifo_size(dev, plane->pipe, 0);
4019                        break;
4020                case DRM_PLANE_TYPE_OVERLAY:
4021                        sprite = plane->plane;
4022                        plane->wm.fifo_size = vlv_get_fifo_size(dev, plane->pipe, sprite + 1);
4023                        break;
4024                }
4025        }
4026
4027        wm->cxsr = I915_READ(FW_BLC_SELF_VLV) & FW_CSPWRDWNEN;
4028        wm->level = VLV_WM_LEVEL_PM2;
4029
4030        if (IS_CHERRYVIEW(dev_priv)) {
4031                mutex_lock(&dev_priv->rps.hw_lock);
4032
4033                val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4034                if (val & DSP_MAXFIFO_PM5_ENABLE)
4035                        wm->level = VLV_WM_LEVEL_PM5;
4036
4037                /*
4038                 * If DDR DVFS is disabled in the BIOS, Punit
4039                 * will never ack the request. So if that happens
4040                 * assume we don't have to enable/disable DDR DVFS
4041                 * dynamically. To test that just set the REQ_ACK
4042                 * bit to poke the Punit, but don't change the
4043                 * HIGH/LOW bits so that we don't actually change
4044                 * the current state.
4045                 */
4046                val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
4047                val |= FORCE_DDR_FREQ_REQ_ACK;
4048                vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
4049
4050                if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
4051                              FORCE_DDR_FREQ_REQ_ACK) == 0, 3)) {
4052                        DRM_DEBUG_KMS("Punit not acking DDR DVFS request, "
4053                                      "assuming DDR DVFS is disabled\n");
4054                        dev_priv->wm.max_level = VLV_WM_LEVEL_PM5;
4055                } else {
4056                        val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
4057                        if ((val & FORCE_DDR_HIGH_FREQ) == 0)
4058                                wm->level = VLV_WM_LEVEL_DDR_DVFS;
4059                }
4060
4061                mutex_unlock(&dev_priv->rps.hw_lock);
4062        }
4063
4064        for_each_pipe(dev_priv, pipe)
4065                DRM_DEBUG_KMS("Initial watermarks: pipe %c, plane=%d, cursor=%d, sprite0=%d, sprite1=%d\n",
4066                              pipe_name(pipe), wm->pipe[pipe].primary, wm->pipe[pipe].cursor,
4067                              wm->pipe[pipe].sprite[0], wm->pipe[pipe].sprite[1]);
4068
4069        DRM_DEBUG_KMS("Initial watermarks: SR plane=%d, SR cursor=%d level=%d cxsr=%d\n",
4070                      wm->sr.plane, wm->sr.cursor, wm->level, wm->cxsr);
4071}
4072
4073void ilk_wm_get_hw_state(struct drm_device *dev)
4074{
4075        struct drm_i915_private *dev_priv = dev->dev_private;
4076        struct ilk_wm_values *hw = &dev_priv->wm.hw;
4077        struct drm_crtc *crtc;
4078
4079        for_each_crtc(dev, crtc)
4080                ilk_pipe_wm_get_hw_state(crtc);
4081
4082        hw->wm_lp[0] = I915_READ(WM1_LP_ILK);
4083        hw->wm_lp[1] = I915_READ(WM2_LP_ILK);
4084        hw->wm_lp[2] = I915_READ(WM3_LP_ILK);
4085
4086        hw->wm_lp_spr[0] = I915_READ(WM1S_LP_ILK);
4087        if (INTEL_INFO(dev)->gen >= 7) {
4088                hw->wm_lp_spr[1] = I915_READ(WM2S_LP_IVB);
4089                hw->wm_lp_spr[2] = I915_READ(WM3S_LP_IVB);
4090        }
4091
4092        if (IS_HASWELL(dev) || IS_BROADWELL(dev))
4093                hw->partitioning = (I915_READ(WM_MISC) & WM_MISC_DATA_PARTITION_5_6) ?
4094                        INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
4095        else if (IS_IVYBRIDGE(dev))
4096                hw->partitioning = (I915_READ(DISP_ARB_CTL2) & DISP_DATA_PARTITION_5_6) ?
4097                        INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
4098
4099        hw->enable_fbc_wm =
4100                !(I915_READ(DISP_ARB_CTL) & DISP_FBC_WM_DIS);
4101}
4102
4103/**
4104 * intel_update_watermarks - update FIFO watermark values based on current modes
4105 *
4106 * Calculate watermark values for the various WM regs based on current mode
4107 * and plane configuration.
4108 *
4109 * There are several cases to deal with here:
4110 *   - normal (i.e. non-self-refresh)
4111 *   - self-refresh (SR) mode
4112 *   - lines are large relative to FIFO size (buffer can hold up to 2)
4113 *   - lines are small relative to FIFO size (buffer can hold more than 2
4114 *     lines), so need to account for TLB latency
4115 *
4116 *   The normal calculation is:
4117 *     watermark = dotclock * bytes per pixel * latency
4118 *   where latency is platform & configuration dependent (we assume pessimal
4119 *   values here).
4120 *
4121 *   The SR calculation is:
4122 *     watermark = (trunc(latency/line time)+1) * surface width *
4123 *       bytes per pixel
4124 *   where
4125 *     line time = htotal / dotclock
4126 *     surface width = hdisplay for normal plane and 64 for cursor
4127 *   and latency is assumed to be high, as above.
4128 *
4129 * The final value programmed to the register should always be rounded up,
4130 * and include an extra 2 entries to account for clock crossings.
4131 *
4132 * We don't use the sprite, so we can ignore that.  And on Crestline we have
4133 * to set the non-SR watermarks to 8.
4134 */
4135void intel_update_watermarks(struct drm_crtc *crtc)
4136{
4137        struct drm_i915_private *dev_priv = crtc->dev->dev_private;
4138
4139        if (dev_priv->display.update_wm)
4140                dev_priv->display.update_wm(crtc);
4141}
4142
4143void intel_update_sprite_watermarks(struct drm_plane *plane,
4144                                    struct drm_crtc *crtc,
4145                                    uint32_t sprite_width,
4146                                    uint32_t sprite_height,
4147                                    int pixel_size,
4148                                    bool enabled, bool scaled)
4149{
4150        struct drm_i915_private *dev_priv = plane->dev->dev_private;
4151
4152        if (dev_priv->display.update_sprite_wm)
4153                dev_priv->display.update_sprite_wm(plane, crtc,
4154                                                   sprite_width, sprite_height,
4155                                                   pixel_size, enabled, scaled);
4156}
4157
4158/**
4159 * Lock protecting IPS related data structures
4160 */
4161DEFINE_SPINLOCK(mchdev_lock);
4162
4163/* Global for IPS driver to get at the current i915 device. Protected by
4164 * mchdev_lock. */
4165static struct drm_i915_private *i915_mch_dev;
4166
4167bool ironlake_set_drps(struct drm_device *dev, u8 val)
4168{
4169        struct drm_i915_private *dev_priv = dev->dev_private;
4170        u16 rgvswctl;
4171
4172        assert_spin_locked(&mchdev_lock);
4173
4174        rgvswctl = I915_READ16(MEMSWCTL);
4175        if (rgvswctl & MEMCTL_CMD_STS) {
4176                DRM_DEBUG("gpu busy, RCS change rejected\n");
4177                return false; /* still busy with another command */
4178        }
4179
4180        rgvswctl = (MEMCTL_CMD_CHFREQ << MEMCTL_CMD_SHIFT) |
4181                (val << MEMCTL_FREQ_SHIFT) | MEMCTL_SFCAVM;
4182        I915_WRITE16(MEMSWCTL, rgvswctl);
4183        POSTING_READ16(MEMSWCTL);
4184
4185        rgvswctl |= MEMCTL_CMD_STS;
4186        I915_WRITE16(MEMSWCTL, rgvswctl);
4187
4188        return true;
4189}
4190
4191static void ironlake_enable_drps(struct drm_device *dev)
4192{
4193        struct drm_i915_private *dev_priv = dev->dev_private;
4194        u32 rgvmodectl = I915_READ(MEMMODECTL);
4195        u8 fmax, fmin, fstart, vstart;
4196
4197        spin_lock_irq(&mchdev_lock);
4198
4199        /* Enable temp reporting */
4200        I915_WRITE16(PMMISC, I915_READ(PMMISC) | MCPPCE_EN);
4201        I915_WRITE16(TSC1, I915_READ(TSC1) | TSE);
4202
4203        /* 100ms RC evaluation intervals */
4204        I915_WRITE(RCUPEI, 100000);
4205        I915_WRITE(RCDNEI, 100000);
4206
4207        /* Set max/min thresholds to 90ms and 80ms respectively */
4208        I915_WRITE(RCBMAXAVG, 90000);
4209        I915_WRITE(RCBMINAVG, 80000);
4210
4211        I915_WRITE(MEMIHYST, 1);
4212
4213        /* Set up min, max, and cur for interrupt handling */
4214        fmax = (rgvmodectl & MEMMODE_FMAX_MASK) >> MEMMODE_FMAX_SHIFT;
4215        fmin = (rgvmodectl & MEMMODE_FMIN_MASK);
4216        fstart = (rgvmodectl & MEMMODE_FSTART_MASK) >>
4217                MEMMODE_FSTART_SHIFT;
4218
4219        vstart = (I915_READ(PXVFREQ(fstart)) & PXVFREQ_PX_MASK) >>
4220                PXVFREQ_PX_SHIFT;
4221
4222        dev_priv->ips.fmax = fmax; /* IPS callback will increase this */
4223        dev_priv->ips.fstart = fstart;
4224
4225        dev_priv->ips.max_delay = fstart;
4226        dev_priv->ips.min_delay = fmin;
4227        dev_priv->ips.cur_delay = fstart;
4228
4229        DRM_DEBUG_DRIVER("fmax: %d, fmin: %d, fstart: %d\n",
4230                         fmax, fmin, fstart);
4231
4232        I915_WRITE(MEMINTREN, MEMINT_CX_SUPR_EN | MEMINT_EVAL_CHG_EN);
4233
4234        /*
4235         * Interrupts will be enabled in ironlake_irq_postinstall
4236         */
4237
4238        I915_WRITE(VIDSTART, vstart);
4239        POSTING_READ(VIDSTART);
4240
4241        rgvmodectl |= MEMMODE_SWMODE_EN;
4242        I915_WRITE(MEMMODECTL, rgvmodectl);
4243
4244        if (wait_for_atomic((I915_READ(MEMSWCTL) & MEMCTL_CMD_STS) == 0, 10))
4245                DRM_ERROR("stuck trying to change perf mode\n");
4246        mdelay(1);
4247
4248        ironlake_set_drps(dev, fstart);
4249
4250        dev_priv->ips.last_count1 = I915_READ(DMIEC) +
4251                I915_READ(DDREC) + I915_READ(CSIEC);
4252        dev_priv->ips.last_time1 = jiffies_to_msecs(jiffies);
4253        dev_priv->ips.last_count2 = I915_READ(GFXEC);
4254        dev_priv->ips.last_time2 = ktime_get_raw_ns();
4255
4256        spin_unlock_irq(&mchdev_lock);
4257}
4258
4259static void ironlake_disable_drps(struct drm_device *dev)
4260{
4261        struct drm_i915_private *dev_priv = dev->dev_private;
4262        u16 rgvswctl;
4263
4264        spin_lock_irq(&mchdev_lock);
4265
4266        rgvswctl = I915_READ16(MEMSWCTL);
4267
4268        /* Ack interrupts, disable EFC interrupt */
4269        I915_WRITE(MEMINTREN, I915_READ(MEMINTREN) & ~MEMINT_EVAL_CHG_EN);
4270        I915_WRITE(MEMINTRSTS, MEMINT_EVAL_CHG);
4271        I915_WRITE(DEIER, I915_READ(DEIER) & ~DE_PCU_EVENT);
4272        I915_WRITE(DEIIR, DE_PCU_EVENT);
4273        I915_WRITE(DEIMR, I915_READ(DEIMR) | DE_PCU_EVENT);
4274
4275        /* Go back to the starting frequency */
4276        ironlake_set_drps(dev, dev_priv->ips.fstart);
4277        mdelay(1);
4278        rgvswctl |= MEMCTL_CMD_STS;
4279        I915_WRITE(MEMSWCTL, rgvswctl);
4280        mdelay(1);
4281
4282        spin_unlock_irq(&mchdev_lock);
4283}
4284
4285/* There's a funny hw issue where the hw returns all 0 when reading from
4286 * GEN6_RP_INTERRUPT_LIMITS. Hence we always need to compute the desired value
4287 * ourselves, instead of doing a rmw cycle (which might result in us clearing
4288 * all limits and the gpu stuck at whatever frequency it is at atm).
4289 */
4290static u32 intel_rps_limits(struct drm_i915_private *dev_priv, u8 val)
4291{
4292        u32 limits;
4293
4294        /* Only set the down limit when we've reached the lowest level to avoid
4295         * getting more interrupts, otherwise leave this clear. This prevents a
4296         * race in the hw when coming out of rc6: There's a tiny window where
4297         * the hw runs at the minimal clock before selecting the desired
4298         * frequency, if the down threshold expires in that window we will not
4299         * receive a down interrupt. */
4300        if (IS_GEN9(dev_priv->dev)) {
4301                limits = (dev_priv->rps.max_freq_softlimit) << 23;
4302                if (val <= dev_priv->rps.min_freq_softlimit)
4303                        limits |= (dev_priv->rps.min_freq_softlimit) << 14;
4304        } else {
4305                limits = dev_priv->rps.max_freq_softlimit << 24;
4306                if (val <= dev_priv->rps.min_freq_softlimit)
4307                        limits |= dev_priv->rps.min_freq_softlimit << 16;
4308        }
4309
4310        return limits;
4311}
4312
4313static void gen6_set_rps_thresholds(struct drm_i915_private *dev_priv, u8 val)
4314{
4315        int new_power;
4316        u32 threshold_up = 0, threshold_down = 0; /* in % */
4317        u32 ei_up = 0, ei_down = 0;
4318
4319        new_power = dev_priv->rps.power;
4320        switch (dev_priv->rps.power) {
4321        case LOW_POWER:
4322                if (val > dev_priv->rps.efficient_freq + 1 && val > dev_priv->rps.cur_freq)
4323                        new_power = BETWEEN;
4324                break;
4325
4326        case BETWEEN:
4327                if (val <= dev_priv->rps.efficient_freq && val < dev_priv->rps.cur_freq)
4328                        new_power = LOW_POWER;
4329                else if (val >= dev_priv->rps.rp0_freq && val > dev_priv->rps.cur_freq)
4330                        new_power = HIGH_POWER;
4331                break;
4332
4333        case HIGH_POWER:
4334                if (val < (dev_priv->rps.rp1_freq + dev_priv->rps.rp0_freq) >> 1 && val < dev_priv->rps.cur_freq)
4335                        new_power = BETWEEN;
4336                break;
4337        }
4338        /* Max/min bins are special */
4339        if (val <= dev_priv->rps.min_freq_softlimit)
4340                new_power = LOW_POWER;
4341        if (val >= dev_priv->rps.max_freq_softlimit)
4342                new_power = HIGH_POWER;
4343        if (new_power == dev_priv->rps.power)
4344                return;
4345
4346        /* Note the units here are not exactly 1us, but 1280ns. */
4347        switch (new_power) {
4348        case LOW_POWER:
4349                /* Upclock if more than 95% busy over 16ms */
4350                ei_up = 16000;
4351                threshold_up = 95;
4352
4353                /* Downclock if less than 85% busy over 32ms */
4354                ei_down = 32000;
4355                threshold_down = 85;
4356                break;
4357
4358        case BETWEEN:
4359                /* Upclock if more than 90% busy over 13ms */
4360                ei_up = 13000;
4361                threshold_up = 90;
4362
4363                /* Downclock if less than 75% busy over 32ms */
4364                ei_down = 32000;
4365                threshold_down = 75;
4366                break;
4367
4368        case HIGH_POWER:
4369                /* Upclock if more than 85% busy over 10ms */
4370                ei_up = 10000;
4371                threshold_up = 85;
4372
4373                /* Downclock if less than 60% busy over 32ms */
4374                ei_down = 32000;
4375                threshold_down = 60;
4376                break;
4377        }
4378
4379        I915_WRITE(GEN6_RP_UP_EI,
4380                GT_INTERVAL_FROM_US(dev_priv, ei_up));
4381        I915_WRITE(GEN6_RP_UP_THRESHOLD,
4382                GT_INTERVAL_FROM_US(dev_priv, (ei_up * threshold_up / 100)));
4383
4384        I915_WRITE(GEN6_RP_DOWN_EI,
4385                GT_INTERVAL_FROM_US(dev_priv, ei_down));
4386        I915_WRITE(GEN6_RP_DOWN_THRESHOLD,
4387                GT_INTERVAL_FROM_US(dev_priv, (ei_down * threshold_down / 100)));
4388
4389         I915_WRITE(GEN6_RP_CONTROL,
4390                    GEN6_RP_MEDIA_TURBO |
4391                    GEN6_RP_MEDIA_HW_NORMAL_MODE |
4392                    GEN6_RP_MEDIA_IS_GFX |
4393                    GEN6_RP_ENABLE |
4394                    GEN6_RP_UP_BUSY_AVG |
4395                    GEN6_RP_DOWN_IDLE_AVG);
4396
4397        dev_priv->rps.power = new_power;
4398        dev_priv->rps.up_threshold = threshold_up;
4399        dev_priv->rps.down_threshold = threshold_down;
4400        dev_priv->rps.last_adj = 0;
4401}
4402
4403static u32 gen6_rps_pm_mask(struct drm_i915_private *dev_priv, u8 val)
4404{
4405        u32 mask = 0;
4406
4407        if (val > dev_priv->rps.min_freq_softlimit)
4408                mask |= GEN6_PM_RP_DOWN_EI_EXPIRED | GEN6_PM_RP_DOWN_THRESHOLD | GEN6_PM_RP_DOWN_TIMEOUT;
4409        if (val < dev_priv->rps.max_freq_softlimit)
4410                mask |= GEN6_PM_RP_UP_EI_EXPIRED | GEN6_PM_RP_UP_THRESHOLD;
4411
4412        mask &= dev_priv->pm_rps_events;
4413
4414        return gen6_sanitize_rps_pm_mask(dev_priv, ~mask);
4415}
4416
4417/* gen6_set_rps is called to update the frequency request, but should also be
4418 * called when the range (min_delay and max_delay) is modified so that we can
4419 * update the GEN6_RP_INTERRUPT_LIMITS register accordingly. */
4420static void gen6_set_rps(struct drm_device *dev, u8 val)
4421{
4422        struct drm_i915_private *dev_priv = dev->dev_private;
4423
4424        /* WaGsvDisableTurbo: Workaround to disable turbo on BXT A* */
4425        if (IS_BROXTON(dev) && (INTEL_REVID(dev) < BXT_REVID_B0))
4426                return;
4427
4428        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4429        WARN_ON(val > dev_priv->rps.max_freq);
4430        WARN_ON(val < dev_priv->rps.min_freq);
4431
4432        /* min/max delay may still have been modified so be sure to
4433         * write the limits value.
4434         */
4435        if (val != dev_priv->rps.cur_freq) {
4436                gen6_set_rps_thresholds(dev_priv, val);
4437
4438                if (IS_GEN9(dev))
4439                        I915_WRITE(GEN6_RPNSWREQ,
4440                                   GEN9_FREQUENCY(val));
4441                else if (IS_HASWELL(dev) || IS_BROADWELL(dev))
4442                        I915_WRITE(GEN6_RPNSWREQ,
4443                                   HSW_FREQUENCY(val));
4444                else
4445                        I915_WRITE(GEN6_RPNSWREQ,
4446                                   GEN6_FREQUENCY(val) |
4447                                   GEN6_OFFSET(0) |
4448                                   GEN6_AGGRESSIVE_TURBO);
4449        }
4450
4451        /* Make sure we continue to get interrupts
4452         * until we hit the minimum or maximum frequencies.
4453         */
4454        I915_WRITE(GEN6_RP_INTERRUPT_LIMITS, intel_rps_limits(dev_priv, val));
4455        I915_WRITE(GEN6_PMINTRMSK, gen6_rps_pm_mask(dev_priv, val));
4456
4457        POSTING_READ(GEN6_RPNSWREQ);
4458
4459        dev_priv->rps.cur_freq = val;
4460        trace_intel_gpu_freq_change(intel_gpu_freq(dev_priv, val));
4461}
4462
4463static void valleyview_set_rps(struct drm_device *dev, u8 val)
4464{
4465        struct drm_i915_private *dev_priv = dev->dev_private;
4466
4467        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4468        WARN_ON(val > dev_priv->rps.max_freq);
4469        WARN_ON(val < dev_priv->rps.min_freq);
4470
4471        if (WARN_ONCE(IS_CHERRYVIEW(dev) && (val & 1),
4472                      "Odd GPU freq value\n"))
4473                val &= ~1;
4474
4475        I915_WRITE(GEN6_PMINTRMSK, gen6_rps_pm_mask(dev_priv, val));
4476
4477        if (val != dev_priv->rps.cur_freq) {
4478                vlv_punit_write(dev_priv, PUNIT_REG_GPU_FREQ_REQ, val);
4479                if (!IS_CHERRYVIEW(dev_priv))
4480                        gen6_set_rps_thresholds(dev_priv, val);
4481        }
4482
4483        dev_priv->rps.cur_freq = val;
4484        trace_intel_gpu_freq_change(intel_gpu_freq(dev_priv, val));
4485}
4486
4487/* vlv_set_rps_idle: Set the frequency to idle, if Gfx clocks are down
4488 *
4489 * * If Gfx is Idle, then
4490 * 1. Forcewake Media well.
4491 * 2. Request idle freq.
4492 * 3. Release Forcewake of Media well.
4493*/
4494static void vlv_set_rps_idle(struct drm_i915_private *dev_priv)
4495{
4496        u32 val = dev_priv->rps.idle_freq;
4497
4498        if (dev_priv->rps.cur_freq <= val)
4499                return;
4500
4501        /* Wake up the media well, as that takes a lot less
4502         * power than the Render well. */
4503        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_MEDIA);
4504        valleyview_set_rps(dev_priv->dev, val);
4505        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_MEDIA);
4506}
4507
4508void gen6_rps_busy(struct drm_i915_private *dev_priv)
4509{
4510        mutex_lock(&dev_priv->rps.hw_lock);
4511        if (dev_priv->rps.enabled) {
4512                if (dev_priv->pm_rps_events & (GEN6_PM_RP_DOWN_EI_EXPIRED | GEN6_PM_RP_UP_EI_EXPIRED))
4513                        gen6_rps_reset_ei(dev_priv);
4514                I915_WRITE(GEN6_PMINTRMSK,
4515                           gen6_rps_pm_mask(dev_priv, dev_priv->rps.cur_freq));
4516        }
4517        mutex_unlock(&dev_priv->rps.hw_lock);
4518}
4519
4520void gen6_rps_idle(struct drm_i915_private *dev_priv)
4521{
4522        struct drm_device *dev = dev_priv->dev;
4523
4524        mutex_lock(&dev_priv->rps.hw_lock);
4525        if (dev_priv->rps.enabled) {
4526                if (IS_VALLEYVIEW(dev))
4527                        vlv_set_rps_idle(dev_priv);
4528                else
4529                        gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
4530                dev_priv->rps.last_adj = 0;
4531                I915_WRITE(GEN6_PMINTRMSK,
4532                           gen6_sanitize_rps_pm_mask(dev_priv, ~0));
4533        }
4534        mutex_unlock(&dev_priv->rps.hw_lock);
4535
4536        spin_lock(&dev_priv->rps.client_lock);
4537        while (!list_empty(&dev_priv->rps.clients))
4538                list_del_init(dev_priv->rps.clients.next);
4539        spin_unlock(&dev_priv->rps.client_lock);
4540}
4541
4542void gen6_rps_boost(struct drm_i915_private *dev_priv,
4543                    struct intel_rps_client *rps,
4544                    unsigned long submitted)
4545{
4546        /* This is intentionally racy! We peek at the state here, then
4547         * validate inside the RPS worker.
4548         */
4549        if (!(dev_priv->mm.busy &&
4550              dev_priv->rps.enabled &&
4551              dev_priv->rps.cur_freq < dev_priv->rps.max_freq_softlimit))
4552                return;
4553
4554        /* Force a RPS boost (and don't count it against the client) if
4555         * the GPU is severely congested.
4556         */
4557        if (rps && time_after(jiffies, submitted + DRM_I915_THROTTLE_JIFFIES))
4558                rps = NULL;
4559
4560        spin_lock(&dev_priv->rps.client_lock);
4561        if (rps == NULL || list_empty(&rps->link)) {
4562                spin_lock_irq(&dev_priv->irq_lock);
4563                if (dev_priv->rps.interrupts_enabled) {
4564                        dev_priv->rps.client_boost = true;
4565                        queue_work(dev_priv->wq, &dev_priv->rps.work);
4566                }
4567                spin_unlock_irq(&dev_priv->irq_lock);
4568
4569                if (rps != NULL) {
4570                        list_add(&rps->link, &dev_priv->rps.clients);
4571                        rps->boosts++;
4572                } else
4573                        dev_priv->rps.boosts++;
4574        }
4575        spin_unlock(&dev_priv->rps.client_lock);
4576}
4577
4578void intel_set_rps(struct drm_device *dev, u8 val)
4579{
4580        if (IS_VALLEYVIEW(dev))
4581                valleyview_set_rps(dev, val);
4582        else
4583                gen6_set_rps(dev, val);
4584}
4585
4586static void gen9_disable_rps(struct drm_device *dev)
4587{
4588        struct drm_i915_private *dev_priv = dev->dev_private;
4589
4590        I915_WRITE(GEN6_RC_CONTROL, 0);
4591        I915_WRITE(GEN9_PG_ENABLE, 0);
4592}
4593
4594static void gen6_disable_rps(struct drm_device *dev)
4595{
4596        struct drm_i915_private *dev_priv = dev->dev_private;
4597
4598        I915_WRITE(GEN6_RC_CONTROL, 0);
4599        I915_WRITE(GEN6_RPNSWREQ, 1 << 31);
4600}
4601
4602static void cherryview_disable_rps(struct drm_device *dev)
4603{
4604        struct drm_i915_private *dev_priv = dev->dev_private;
4605
4606        I915_WRITE(GEN6_RC_CONTROL, 0);
4607}
4608
4609static void valleyview_disable_rps(struct drm_device *dev)
4610{
4611        struct drm_i915_private *dev_priv = dev->dev_private;
4612
4613        /* we're doing forcewake before Disabling RC6,
4614         * This what the BIOS expects when going into suspend */
4615        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4616
4617        I915_WRITE(GEN6_RC_CONTROL, 0);
4618
4619        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4620}
4621
4622static void intel_print_rc6_info(struct drm_device *dev, u32 mode)
4623{
4624        if (IS_VALLEYVIEW(dev)) {
4625                if (mode & (GEN7_RC_CTL_TO_MODE | GEN6_RC_CTL_EI_MODE(1)))
4626                        mode = GEN6_RC_CTL_RC6_ENABLE;
4627                else
4628                        mode = 0;
4629        }
4630        if (HAS_RC6p(dev))
4631                DRM_DEBUG_KMS("Enabling RC6 states: RC6 %s RC6p %s RC6pp %s\n",
4632                              (mode & GEN6_RC_CTL_RC6_ENABLE) ? "on" : "off",
4633                              (mode & GEN6_RC_CTL_RC6p_ENABLE) ? "on" : "off",
4634                              (mode & GEN6_RC_CTL_RC6pp_ENABLE) ? "on" : "off");
4635
4636        else
4637                DRM_DEBUG_KMS("Enabling RC6 states: RC6 %s\n",
4638                              (mode & GEN6_RC_CTL_RC6_ENABLE) ? "on" : "off");
4639}
4640
4641static int sanitize_rc6_option(const struct drm_device *dev, int enable_rc6)
4642{
4643        /* No RC6 before Ironlake and code is gone for ilk. */
4644        if (INTEL_INFO(dev)->gen < 6)
4645                return 0;
4646
4647        /* Respect the kernel parameter if it is set */
4648        if (enable_rc6 >= 0) {
4649                int mask;
4650
4651                if (HAS_RC6p(dev))
4652                        mask = INTEL_RC6_ENABLE | INTEL_RC6p_ENABLE |
4653                               INTEL_RC6pp_ENABLE;
4654                else
4655                        mask = INTEL_RC6_ENABLE;
4656
4657                if ((enable_rc6 & mask) != enable_rc6)
4658                        DRM_DEBUG_KMS("Adjusting RC6 mask to %d (requested %d, valid %d)\n",
4659                                      enable_rc6 & mask, enable_rc6, mask);
4660
4661                return enable_rc6 & mask;
4662        }
4663
4664        if (IS_IVYBRIDGE(dev))
4665                return (INTEL_RC6_ENABLE | INTEL_RC6p_ENABLE);
4666
4667        return INTEL_RC6_ENABLE;
4668}
4669
4670int intel_enable_rc6(const struct drm_device *dev)
4671{
4672        return i915.enable_rc6;
4673}
4674
4675static void gen6_init_rps_frequencies(struct drm_device *dev)
4676{
4677        struct drm_i915_private *dev_priv = dev->dev_private;
4678        uint32_t rp_state_cap;
4679        u32 ddcc_status = 0;
4680        int ret;
4681
4682        /* All of these values are in units of 50MHz */
4683        dev_priv->rps.cur_freq          = 0;
4684        /* static values from HW: RP0 > RP1 > RPn (min_freq) */
4685        if (IS_BROXTON(dev)) {
4686                rp_state_cap = I915_READ(BXT_RP_STATE_CAP);
4687                dev_priv->rps.rp0_freq = (rp_state_cap >> 16) & 0xff;
4688                dev_priv->rps.rp1_freq = (rp_state_cap >>  8) & 0xff;
4689                dev_priv->rps.min_freq = (rp_state_cap >>  0) & 0xff;
4690        } else {
4691                rp_state_cap = I915_READ(GEN6_RP_STATE_CAP);
4692                dev_priv->rps.rp0_freq = (rp_state_cap >>  0) & 0xff;
4693                dev_priv->rps.rp1_freq = (rp_state_cap >>  8) & 0xff;
4694                dev_priv->rps.min_freq = (rp_state_cap >> 16) & 0xff;
4695        }
4696
4697        /* hw_max = RP0 until we check for overclocking */
4698        dev_priv->rps.max_freq          = dev_priv->rps.rp0_freq;
4699
4700        dev_priv->rps.efficient_freq = dev_priv->rps.rp1_freq;
4701        if (IS_HASWELL(dev) || IS_BROADWELL(dev) || IS_SKYLAKE(dev)) {
4702                ret = sandybridge_pcode_read(dev_priv,
4703                                        HSW_PCODE_DYNAMIC_DUTY_CYCLE_CONTROL,
4704                                        &ddcc_status);
4705                if (0 == ret)
4706                        dev_priv->rps.efficient_freq =
4707                                clamp_t(u8,
4708                                        ((ddcc_status >> 8) & 0xff),
4709                                        dev_priv->rps.min_freq,
4710                                        dev_priv->rps.max_freq);
4711        }
4712
4713        if (IS_SKYLAKE(dev)) {
4714                /* Store the frequency values in 16.66 MHZ units, which is
4715                   the natural hardware unit for SKL */
4716                dev_priv->rps.rp0_freq *= GEN9_FREQ_SCALER;
4717                dev_priv->rps.rp1_freq *= GEN9_FREQ_SCALER;
4718                dev_priv->rps.min_freq *= GEN9_FREQ_SCALER;
4719                dev_priv->rps.max_freq *= GEN9_FREQ_SCALER;
4720                dev_priv->rps.efficient_freq *= GEN9_FREQ_SCALER;
4721        }
4722
4723        dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
4724
4725        /* Preserve min/max settings in case of re-init */
4726        if (dev_priv->rps.max_freq_softlimit == 0)
4727                dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
4728
4729        if (dev_priv->rps.min_freq_softlimit == 0) {
4730                if (IS_HASWELL(dev) || IS_BROADWELL(dev))
4731                        dev_priv->rps.min_freq_softlimit =
4732                                max_t(int, dev_priv->rps.efficient_freq,
4733                                      intel_freq_opcode(dev_priv, 450));
4734                else
4735                        dev_priv->rps.min_freq_softlimit =
4736                                dev_priv->rps.min_freq;
4737        }
4738}
4739
4740/* See the Gen9_GT_PM_Programming_Guide doc for the below */
4741static void gen9_enable_rps(struct drm_device *dev)
4742{
4743        struct drm_i915_private *dev_priv = dev->dev_private;
4744
4745        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4746
4747        gen6_init_rps_frequencies(dev);
4748
4749        /* WaGsvDisableTurbo: Workaround to disable turbo on BXT A* */
4750        if (IS_BROXTON(dev) && (INTEL_REVID(dev) < BXT_REVID_B0)) {
4751                intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4752                return;
4753        }
4754
4755        /* Program defaults and thresholds for RPS*/
4756        I915_WRITE(GEN6_RC_VIDEO_FREQ,
4757                GEN9_FREQUENCY(dev_priv->rps.rp1_freq));
4758
4759        /* 1 second timeout*/
4760        I915_WRITE(GEN6_RP_DOWN_TIMEOUT,
4761                GT_INTERVAL_FROM_US(dev_priv, 1000000));
4762
4763        I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 0xa);
4764
4765        /* Leaning on the below call to gen6_set_rps to program/setup the
4766         * Up/Down EI & threshold registers, as well as the RP_CONTROL,
4767         * RP_INTERRUPT_LIMITS & RPNSWREQ registers */
4768        dev_priv->rps.power = HIGH_POWER; /* force a reset */
4769        gen6_set_rps(dev_priv->dev, dev_priv->rps.min_freq_softlimit);
4770
4771        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4772}
4773
4774static void gen9_enable_rc6(struct drm_device *dev)
4775{
4776        struct drm_i915_private *dev_priv = dev->dev_private;
4777        struct intel_engine_cs *ring;
4778        uint32_t rc6_mask = 0;
4779        int unused;
4780
4781        /* 1a: Software RC state - RC0 */
4782        I915_WRITE(GEN6_RC_STATE, 0);
4783
4784        /* 1b: Get forcewake during program sequence. Although the driver
4785         * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
4786        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4787
4788        /* 2a: Disable RC states. */
4789        I915_WRITE(GEN6_RC_CONTROL, 0);
4790
4791        /* 2b: Program RC6 thresholds.*/
4792
4793        /* WaRsDoubleRc6WrlWithCoarsePowerGating: Doubling WRL only when CPG is enabled */
4794        if (IS_SKYLAKE(dev))
4795                I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 108 << 16);
4796        else
4797                I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 54 << 16);
4798        I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
4799        I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
4800        for_each_ring(ring, dev_priv, unused)
4801                I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4802
4803        if (HAS_GUC_UCODE(dev))
4804                I915_WRITE(GUC_MAX_IDLE_COUNT, 0xA);
4805
4806        I915_WRITE(GEN6_RC_SLEEP, 0);
4807
4808        /* 2c: Program Coarse Power Gating Policies. */
4809        I915_WRITE(GEN9_MEDIA_PG_IDLE_HYSTERESIS, 25);
4810        I915_WRITE(GEN9_RENDER_PG_IDLE_HYSTERESIS, 25);
4811
4812        /* 3a: Enable RC6 */
4813        if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
4814                rc6_mask = GEN6_RC_CTL_RC6_ENABLE;
4815        DRM_INFO("RC6 %s\n", (rc6_mask & GEN6_RC_CTL_RC6_ENABLE) ?
4816                        "on" : "off");
4817        /* WaRsUseTimeoutMode */
4818        if ((IS_SKYLAKE(dev) && INTEL_REVID(dev) <= SKL_REVID_D0) ||
4819            (IS_BROXTON(dev) && INTEL_REVID(dev) <= BXT_REVID_A0)) {
4820                I915_WRITE(GEN6_RC6_THRESHOLD, 625); /* 800us */
4821                I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4822                           GEN7_RC_CTL_TO_MODE |
4823                           rc6_mask);
4824        } else {
4825                I915_WRITE(GEN6_RC6_THRESHOLD, 37500); /* 37.5/125ms per EI */
4826                I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4827                           GEN6_RC_CTL_EI_MODE(1) |
4828                           rc6_mask);
4829        }
4830
4831        /*
4832         * 3b: Enable Coarse Power Gating only when RC6 is enabled.
4833         * WaRsDisableCoarsePowerGating:skl,bxt - Render/Media PG need to be disabled with RC6.
4834         */
4835        if ((IS_BROXTON(dev) && (INTEL_REVID(dev) < BXT_REVID_B0)) ||
4836            ((IS_SKL_GT3(dev) || IS_SKL_GT4(dev)) && (INTEL_REVID(dev) <= SKL_REVID_F0)))
4837                I915_WRITE(GEN9_PG_ENABLE, 0);
4838        else
4839                I915_WRITE(GEN9_PG_ENABLE, (rc6_mask & GEN6_RC_CTL_RC6_ENABLE) ?
4840                                (GEN9_RENDER_PG_ENABLE | GEN9_MEDIA_PG_ENABLE) : 0);
4841
4842        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4843
4844}
4845
4846static void gen8_enable_rps(struct drm_device *dev)
4847{
4848        struct drm_i915_private *dev_priv = dev->dev_private;
4849        struct intel_engine_cs *ring;
4850        uint32_t rc6_mask = 0;
4851        int unused;
4852
4853        /* 1a: Software RC state - RC0 */
4854        I915_WRITE(GEN6_RC_STATE, 0);
4855
4856        /* 1c & 1d: Get forcewake during program sequence. Although the driver
4857         * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
4858        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4859
4860        /* 2a: Disable RC states. */
4861        I915_WRITE(GEN6_RC_CONTROL, 0);
4862
4863        /* Initialize rps frequencies */
4864        gen6_init_rps_frequencies(dev);
4865
4866        /* 2b: Program RC6 thresholds.*/
4867        I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16);
4868        I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
4869        I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
4870        for_each_ring(ring, dev_priv, unused)
4871                I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4872        I915_WRITE(GEN6_RC_SLEEP, 0);
4873        if (IS_BROADWELL(dev))
4874                I915_WRITE(GEN6_RC6_THRESHOLD, 625); /* 800us/1.28 for TO */
4875        else
4876                I915_WRITE(GEN6_RC6_THRESHOLD, 50000); /* 50/125ms per EI */
4877
4878        /* 3: Enable RC6 */
4879        if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
4880                rc6_mask = GEN6_RC_CTL_RC6_ENABLE;
4881        intel_print_rc6_info(dev, rc6_mask);
4882        if (IS_BROADWELL(dev))
4883                I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4884                                GEN7_RC_CTL_TO_MODE |
4885                                rc6_mask);
4886        else
4887                I915_WRITE(GEN6_RC_CONTROL, GEN6_RC_CTL_HW_ENABLE |
4888                                GEN6_RC_CTL_EI_MODE(1) |
4889                                rc6_mask);
4890
4891        /* 4 Program defaults and thresholds for RPS*/
4892        I915_WRITE(GEN6_RPNSWREQ,
4893                   HSW_FREQUENCY(dev_priv->rps.rp1_freq));
4894        I915_WRITE(GEN6_RC_VIDEO_FREQ,
4895                   HSW_FREQUENCY(dev_priv->rps.rp1_freq));
4896        /* NB: Docs say 1s, and 1000000 - which aren't equivalent */
4897        I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 100000000 / 128); /* 1 second timeout */
4898
4899        /* Docs recommend 900MHz, and 300 MHz respectively */
4900        I915_WRITE(GEN6_RP_INTERRUPT_LIMITS,
4901                   dev_priv->rps.max_freq_softlimit << 24 |
4902                   dev_priv->rps.min_freq_softlimit << 16);
4903
4904        I915_WRITE(GEN6_RP_UP_THRESHOLD, 7600000 / 128); /* 76ms busyness per EI, 90% */
4905        I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 31300000 / 128); /* 313ms busyness per EI, 70%*/
4906        I915_WRITE(GEN6_RP_UP_EI, 66000); /* 84.48ms, XXX: random? */
4907        I915_WRITE(GEN6_RP_DOWN_EI, 350000); /* 448ms, XXX: random? */
4908
4909        I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
4910
4911        /* 5: Enable RPS */
4912        I915_WRITE(GEN6_RP_CONTROL,
4913                   GEN6_RP_MEDIA_TURBO |
4914                   GEN6_RP_MEDIA_HW_NORMAL_MODE |
4915                   GEN6_RP_MEDIA_IS_GFX |
4916                   GEN6_RP_ENABLE |
4917                   GEN6_RP_UP_BUSY_AVG |
4918                   GEN6_RP_DOWN_IDLE_AVG);
4919
4920        /* 6: Ring frequency + overclocking (our driver does this later */
4921
4922        dev_priv->rps.power = HIGH_POWER; /* force a reset */
4923        gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
4924
4925        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4926}
4927
4928static void gen6_enable_rps(struct drm_device *dev)
4929{
4930        struct drm_i915_private *dev_priv = dev->dev_private;
4931        struct intel_engine_cs *ring;
4932        u32 rc6vids, pcu_mbox = 0, rc6_mask = 0;
4933        u32 gtfifodbg;
4934        int rc6_mode;
4935        int i, ret;
4936
4937        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
4938
4939        /* Here begins a magic sequence of register writes to enable
4940         * auto-downclocking.
4941         *
4942         * Perhaps there might be some value in exposing these to
4943         * userspace...
4944         */
4945        I915_WRITE(GEN6_RC_STATE, 0);
4946
4947        /* Clear the DBG now so we don't confuse earlier errors */
4948        if ((gtfifodbg = I915_READ(GTFIFODBG))) {
4949                DRM_ERROR("GT fifo had a previous error %x\n", gtfifodbg);
4950                I915_WRITE(GTFIFODBG, gtfifodbg);
4951        }
4952
4953        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4954
4955        /* Initialize rps frequencies */
4956        gen6_init_rps_frequencies(dev);
4957
4958        /* disable the counters and set deterministic thresholds */
4959        I915_WRITE(GEN6_RC_CONTROL, 0);
4960
4961        I915_WRITE(GEN6_RC1_WAKE_RATE_LIMIT, 1000 << 16);
4962        I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16 | 30);
4963        I915_WRITE(GEN6_RC6pp_WAKE_RATE_LIMIT, 30);
4964        I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
4965        I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
4966
4967        for_each_ring(ring, dev_priv, i)
4968                I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
4969
4970        I915_WRITE(GEN6_RC_SLEEP, 0);
4971        I915_WRITE(GEN6_RC1e_THRESHOLD, 1000);
4972        if (IS_IVYBRIDGE(dev))
4973                I915_WRITE(GEN6_RC6_THRESHOLD, 125000);
4974        else
4975                I915_WRITE(GEN6_RC6_THRESHOLD, 50000);
4976        I915_WRITE(GEN6_RC6p_THRESHOLD, 150000);
4977        I915_WRITE(GEN6_RC6pp_THRESHOLD, 64000); /* unused */
4978
4979        /* Check if we are enabling RC6 */
4980        rc6_mode = intel_enable_rc6(dev_priv->dev);
4981        if (rc6_mode & INTEL_RC6_ENABLE)
4982                rc6_mask |= GEN6_RC_CTL_RC6_ENABLE;
4983
4984        /* We don't use those on Haswell */
4985        if (!IS_HASWELL(dev)) {
4986                if (rc6_mode & INTEL_RC6p_ENABLE)
4987                        rc6_mask |= GEN6_RC_CTL_RC6p_ENABLE;
4988
4989                if (rc6_mode & INTEL_RC6pp_ENABLE)
4990                        rc6_mask |= GEN6_RC_CTL_RC6pp_ENABLE;
4991        }
4992
4993        intel_print_rc6_info(dev, rc6_mask);
4994
4995        I915_WRITE(GEN6_RC_CONTROL,
4996                   rc6_mask |
4997                   GEN6_RC_CTL_EI_MODE(1) |
4998                   GEN6_RC_CTL_HW_ENABLE);
4999
5000        /* Power down if completely idle for over 50ms */
5001        I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 50000);
5002        I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
5003
5004        ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_MIN_FREQ_TABLE, 0);
5005        if (ret)
5006                DRM_DEBUG_DRIVER("Failed to set the min frequency\n");
5007
5008        ret = sandybridge_pcode_read(dev_priv, GEN6_READ_OC_PARAMS, &pcu_mbox);
5009        if (!ret && (pcu_mbox & (1<<31))) { /* OC supported */
5010                DRM_DEBUG_DRIVER("Overclocking supported. Max: %dMHz, Overclock max: %dMHz\n",
5011                                 (dev_priv->rps.max_freq_softlimit & 0xff) * 50,
5012                                 (pcu_mbox & 0xff) * 50);
5013                dev_priv->rps.max_freq = pcu_mbox & 0xff;
5014        }
5015
5016        dev_priv->rps.power = HIGH_POWER; /* force a reset */
5017        gen6_set_rps(dev_priv->dev, dev_priv->rps.idle_freq);
5018
5019        rc6vids = 0;
5020        ret = sandybridge_pcode_read(dev_priv, GEN6_PCODE_READ_RC6VIDS, &rc6vids);
5021        if (IS_GEN6(dev) && ret) {
5022                DRM_DEBUG_DRIVER("Couldn't check for BIOS workaround\n");
5023        } else if (IS_GEN6(dev) && (GEN6_DECODE_RC6_VID(rc6vids & 0xff) < 450)) {
5024                DRM_DEBUG_DRIVER("You should update your BIOS. Correcting minimum rc6 voltage (%dmV->%dmV)\n",
5025                          GEN6_DECODE_RC6_VID(rc6vids & 0xff), 450);
5026                rc6vids &= 0xffff00;
5027                rc6vids |= GEN6_ENCODE_RC6_VID(450);
5028                ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_RC6VIDS, rc6vids);
5029                if (ret)
5030                        DRM_ERROR("Couldn't fix incorrect rc6 voltage\n");
5031        }
5032
5033        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5034}
5035
5036static void __gen6_update_ring_freq(struct drm_device *dev)
5037{
5038        struct drm_i915_private *dev_priv = dev->dev_private;
5039        int min_freq = 15;
5040        unsigned int gpu_freq;
5041        unsigned int max_ia_freq, min_ring_freq;
5042        unsigned int max_gpu_freq, min_gpu_freq;
5043        int scaling_factor = 180;
5044        struct cpufreq_policy *policy;
5045
5046        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5047
5048        policy = cpufreq_cpu_get(0);
5049        if (policy) {
5050                max_ia_freq = policy->cpuinfo.max_freq;
5051                cpufreq_cpu_put(policy);
5052        } else {
5053                /*
5054                 * Default to measured freq if none found, PCU will ensure we
5055                 * don't go over
5056                 */
5057                max_ia_freq = tsc_khz;
5058        }
5059
5060        /* Convert from kHz to MHz */
5061        max_ia_freq /= 1000;
5062
5063        min_ring_freq = I915_READ(DCLK) & 0xf;
5064        /* convert DDR frequency from units of 266.6MHz to bandwidth */
5065        min_ring_freq = mult_frac(min_ring_freq, 8, 3);
5066
5067        if (IS_SKYLAKE(dev)) {
5068                /* Convert GT frequency to 50 HZ units */
5069                min_gpu_freq = dev_priv->rps.min_freq / GEN9_FREQ_SCALER;
5070                max_gpu_freq = dev_priv->rps.max_freq / GEN9_FREQ_SCALER;
5071        } else {
5072                min_gpu_freq = dev_priv->rps.min_freq;
5073                max_gpu_freq = dev_priv->rps.max_freq;
5074        }
5075
5076        /*
5077         * For each potential GPU frequency, load a ring frequency we'd like
5078         * to use for memory access.  We do this by specifying the IA frequency
5079         * the PCU should use as a reference to determine the ring frequency.
5080         */
5081        for (gpu_freq = max_gpu_freq; gpu_freq >= min_gpu_freq; gpu_freq--) {
5082                int diff = max_gpu_freq - gpu_freq;
5083                unsigned int ia_freq = 0, ring_freq = 0;
5084
5085                if (IS_SKYLAKE(dev)) {
5086                        /*
5087                         * ring_freq = 2 * GT. ring_freq is in 100MHz units
5088                         * No floor required for ring frequency on SKL.
5089                         */
5090                        ring_freq = gpu_freq;
5091                } else if (INTEL_INFO(dev)->gen >= 8) {
5092                        /* max(2 * GT, DDR). NB: GT is 50MHz units */
5093                        ring_freq = max(min_ring_freq, gpu_freq);
5094                } else if (IS_HASWELL(dev)) {
5095                        ring_freq = mult_frac(gpu_freq, 5, 4);
5096                        ring_freq = max(min_ring_freq, ring_freq);
5097                        /* leave ia_freq as the default, chosen by cpufreq */
5098                } else {
5099                        /* On older processors, there is no separate ring
5100                         * clock domain, so in order to boost the bandwidth
5101                         * of the ring, we need to upclock the CPU (ia_freq).
5102                         *
5103                         * For GPU frequencies less than 750MHz,
5104                         * just use the lowest ring freq.
5105                         */
5106                        if (gpu_freq < min_freq)
5107                                ia_freq = 800;
5108                        else
5109                                ia_freq = max_ia_freq - ((diff * scaling_factor) / 2);
5110                        ia_freq = DIV_ROUND_CLOSEST(ia_freq, 100);
5111                }
5112
5113                sandybridge_pcode_write(dev_priv,
5114                                        GEN6_PCODE_WRITE_MIN_FREQ_TABLE,
5115                                        ia_freq << GEN6_PCODE_FREQ_IA_RATIO_SHIFT |
5116                                        ring_freq << GEN6_PCODE_FREQ_RING_RATIO_SHIFT |
5117                                        gpu_freq);
5118        }
5119}
5120
5121void gen6_update_ring_freq(struct drm_device *dev)
5122{
5123        struct drm_i915_private *dev_priv = dev->dev_private;
5124
5125        if (!HAS_CORE_RING_FREQ(dev))
5126                return;
5127
5128        mutex_lock(&dev_priv->rps.hw_lock);
5129        __gen6_update_ring_freq(dev);
5130        mutex_unlock(&dev_priv->rps.hw_lock);
5131}
5132
5133static int cherryview_rps_max_freq(struct drm_i915_private *dev_priv)
5134{
5135        struct drm_device *dev = dev_priv->dev;
5136        u32 val, rp0;
5137
5138        val = vlv_punit_read(dev_priv, FB_GFX_FMAX_AT_VMAX_FUSE);
5139
5140        switch (INTEL_INFO(dev)->eu_total) {
5141        case 8:
5142                /* (2 * 4) config */
5143                rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS4EU_FUSE_SHIFT);
5144                break;
5145        case 12:
5146                /* (2 * 6) config */
5147                rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS6EU_FUSE_SHIFT);
5148                break;
5149        case 16:
5150                /* (2 * 8) config */
5151        default:
5152                /* Setting (2 * 8) Min RP0 for any other combination */
5153                rp0 = (val >> FB_GFX_FMAX_AT_VMAX_2SS8EU_FUSE_SHIFT);
5154                break;
5155        }
5156
5157        rp0 = (rp0 & FB_GFX_FREQ_FUSE_MASK);
5158
5159        return rp0;
5160}
5161
5162static int cherryview_rps_rpe_freq(struct drm_i915_private *dev_priv)
5163{
5164        u32 val, rpe;
5165
5166        val = vlv_punit_read(dev_priv, PUNIT_GPU_DUTYCYCLE_REG);
5167        rpe = (val >> PUNIT_GPU_DUTYCYCLE_RPE_FREQ_SHIFT) & PUNIT_GPU_DUTYCYCLE_RPE_FREQ_MASK;
5168
5169        return rpe;
5170}
5171
5172static int cherryview_rps_guar_freq(struct drm_i915_private *dev_priv)
5173{
5174        u32 val, rp1;
5175
5176        val = vlv_punit_read(dev_priv, FB_GFX_FMAX_AT_VMAX_FUSE);
5177        rp1 = (val & FB_GFX_FREQ_FUSE_MASK);
5178
5179        return rp1;
5180}
5181
5182static int valleyview_rps_guar_freq(struct drm_i915_private *dev_priv)
5183{
5184        u32 val, rp1;
5185
5186        val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FREQ_FUSE);
5187
5188        rp1 = (val & FB_GFX_FGUARANTEED_FREQ_FUSE_MASK) >> FB_GFX_FGUARANTEED_FREQ_FUSE_SHIFT;
5189
5190        return rp1;
5191}
5192
5193static int valleyview_rps_max_freq(struct drm_i915_private *dev_priv)
5194{
5195        u32 val, rp0;
5196
5197        val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FREQ_FUSE);
5198
5199        rp0 = (val & FB_GFX_MAX_FREQ_FUSE_MASK) >> FB_GFX_MAX_FREQ_FUSE_SHIFT;
5200        /* Clamp to max */
5201        rp0 = min_t(u32, rp0, 0xea);
5202
5203        return rp0;
5204}
5205
5206static int valleyview_rps_rpe_freq(struct drm_i915_private *dev_priv)
5207{
5208        u32 val, rpe;
5209
5210        val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_LO);
5211        rpe = (val & FB_FMAX_VMIN_FREQ_LO_MASK) >> FB_FMAX_VMIN_FREQ_LO_SHIFT;
5212        val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_HI);
5213        rpe |= (val & FB_FMAX_VMIN_FREQ_HI_MASK) << 5;
5214
5215        return rpe;
5216}
5217
5218static int valleyview_rps_min_freq(struct drm_i915_private *dev_priv)
5219{
5220        return vlv_punit_read(dev_priv, PUNIT_REG_GPU_LFM) & 0xff;
5221}
5222
5223/* Check that the pctx buffer wasn't move under us. */
5224static void valleyview_check_pctx(struct drm_i915_private *dev_priv)
5225{
5226        unsigned long pctx_addr = I915_READ(VLV_PCBR) & ~4095;
5227
5228        WARN_ON(pctx_addr != dev_priv->mm.stolen_base +
5229                             dev_priv->vlv_pctx->stolen->start);
5230}
5231
5232
5233/* Check that the pcbr address is not empty. */
5234static void cherryview_check_pctx(struct drm_i915_private *dev_priv)
5235{
5236        unsigned long pctx_addr = I915_READ(VLV_PCBR) & ~4095;
5237
5238        WARN_ON((pctx_addr >> VLV_PCBR_ADDR_SHIFT) == 0);
5239}
5240
5241static void cherryview_setup_pctx(struct drm_device *dev)
5242{
5243        struct drm_i915_private *dev_priv = dev->dev_private;
5244        unsigned long pctx_paddr, paddr;
5245        struct i915_gtt *gtt = &dev_priv->gtt;
5246        u32 pcbr;
5247        int pctx_size = 32*1024;
5248
5249        WARN_ON(!mutex_is_locked(&dev->struct_mutex));
5250
5251        pcbr = I915_READ(VLV_PCBR);
5252        if ((pcbr >> VLV_PCBR_ADDR_SHIFT) == 0) {
5253                DRM_DEBUG_DRIVER("BIOS didn't set up PCBR, fixing up\n");
5254                paddr = (dev_priv->mm.stolen_base +
5255                         (gtt->stolen_size - pctx_size));
5256
5257                pctx_paddr = (paddr & (~4095));
5258                I915_WRITE(VLV_PCBR, pctx_paddr);
5259        }
5260
5261        DRM_DEBUG_DRIVER("PCBR: 0x%08x\n", I915_READ(VLV_PCBR));
5262}
5263
5264static void valleyview_setup_pctx(struct drm_device *dev)
5265{
5266        struct drm_i915_private *dev_priv = dev->dev_private;
5267        struct drm_i915_gem_object *pctx;
5268        unsigned long pctx_paddr;
5269        u32 pcbr;
5270        int pctx_size = 24*1024;
5271
5272        WARN_ON(!mutex_is_locked(&dev->struct_mutex));
5273
5274        pcbr = I915_READ(VLV_PCBR);
5275        if (pcbr) {
5276                /* BIOS set it up already, grab the pre-alloc'd space */
5277                int pcbr_offset;
5278
5279                pcbr_offset = (pcbr & (~4095)) - dev_priv->mm.stolen_base;
5280                pctx = i915_gem_object_create_stolen_for_preallocated(dev_priv->dev,
5281                                                                      pcbr_offset,
5282                                                                      I915_GTT_OFFSET_NONE,
5283                                                                      pctx_size);
5284                goto out;
5285        }
5286
5287        DRM_DEBUG_DRIVER("BIOS didn't set up PCBR, fixing up\n");
5288
5289        /*
5290         * From the Gunit register HAS:
5291         * The Gfx driver is expected to program this register and ensure
5292         * proper allocation within Gfx stolen memory.  For example, this
5293         * register should be programmed such than the PCBR range does not
5294         * overlap with other ranges, such as the frame buffer, protected
5295         * memory, or any other relevant ranges.
5296         */
5297        pctx = i915_gem_object_create_stolen(dev, pctx_size);
5298        if (!pctx) {
5299                DRM_DEBUG("not enough stolen space for PCTX, disabling\n");
5300                return;
5301        }
5302
5303        pctx_paddr = dev_priv->mm.stolen_base + pctx->stolen->start;
5304        I915_WRITE(VLV_PCBR, pctx_paddr);
5305
5306out:
5307        DRM_DEBUG_DRIVER("PCBR: 0x%08x\n", I915_READ(VLV_PCBR));
5308        dev_priv->vlv_pctx = pctx;
5309}
5310
5311static void valleyview_cleanup_pctx(struct drm_device *dev)
5312{
5313        struct drm_i915_private *dev_priv = dev->dev_private;
5314
5315        if (WARN_ON(!dev_priv->vlv_pctx))
5316                return;
5317
5318        drm_gem_object_unreference(&dev_priv->vlv_pctx->base);
5319        dev_priv->vlv_pctx = NULL;
5320}
5321
5322static void valleyview_init_gt_powersave(struct drm_device *dev)
5323{
5324        struct drm_i915_private *dev_priv = dev->dev_private;
5325        u32 val;
5326
5327        valleyview_setup_pctx(dev);
5328
5329        mutex_lock(&dev_priv->rps.hw_lock);
5330
5331        val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
5332        switch ((val >> 6) & 3) {
5333        case 0:
5334        case 1:
5335                dev_priv->mem_freq = 800;
5336                break;
5337        case 2:
5338                dev_priv->mem_freq = 1066;
5339                break;
5340        case 3:
5341                dev_priv->mem_freq = 1333;
5342                break;
5343        }
5344        DRM_DEBUG_DRIVER("DDR speed: %d MHz\n", dev_priv->mem_freq);
5345
5346        dev_priv->rps.max_freq = valleyview_rps_max_freq(dev_priv);
5347        dev_priv->rps.rp0_freq = dev_priv->rps.max_freq;
5348        DRM_DEBUG_DRIVER("max GPU freq: %d MHz (%u)\n",
5349                         intel_gpu_freq(dev_priv, dev_priv->rps.max_freq),
5350                         dev_priv->rps.max_freq);
5351
5352        dev_priv->rps.efficient_freq = valleyview_rps_rpe_freq(dev_priv);
5353        DRM_DEBUG_DRIVER("RPe GPU freq: %d MHz (%u)\n",
5354                         intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5355                         dev_priv->rps.efficient_freq);
5356
5357        dev_priv->rps.rp1_freq = valleyview_rps_guar_freq(dev_priv);
5358        DRM_DEBUG_DRIVER("RP1(Guar Freq) GPU freq: %d MHz (%u)\n",
5359                         intel_gpu_freq(dev_priv, dev_priv->rps.rp1_freq),
5360                         dev_priv->rps.rp1_freq);
5361
5362        dev_priv->rps.min_freq = valleyview_rps_min_freq(dev_priv);
5363        DRM_DEBUG_DRIVER("min GPU freq: %d MHz (%u)\n",
5364                         intel_gpu_freq(dev_priv, dev_priv->rps.min_freq),
5365                         dev_priv->rps.min_freq);
5366
5367        dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
5368
5369        /* Preserve min/max settings in case of re-init */
5370        if (dev_priv->rps.max_freq_softlimit == 0)
5371                dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
5372
5373        if (dev_priv->rps.min_freq_softlimit == 0)
5374                dev_priv->rps.min_freq_softlimit = dev_priv->rps.min_freq;
5375
5376        mutex_unlock(&dev_priv->rps.hw_lock);
5377}
5378
5379static void cherryview_init_gt_powersave(struct drm_device *dev)
5380{
5381        struct drm_i915_private *dev_priv = dev->dev_private;
5382        u32 val;
5383
5384        cherryview_setup_pctx(dev);
5385
5386        mutex_lock(&dev_priv->rps.hw_lock);
5387
5388        mutex_lock(&dev_priv->sb_lock);
5389        val = vlv_cck_read(dev_priv, CCK_FUSE_REG);
5390        mutex_unlock(&dev_priv->sb_lock);
5391
5392        switch ((val >> 2) & 0x7) {
5393        case 3:
5394                dev_priv->mem_freq = 2000;
5395                break;
5396        default:
5397                dev_priv->mem_freq = 1600;
5398                break;
5399        }
5400        DRM_DEBUG_DRIVER("DDR speed: %d MHz\n", dev_priv->mem_freq);
5401
5402        dev_priv->rps.max_freq = cherryview_rps_max_freq(dev_priv);
5403        dev_priv->rps.rp0_freq = dev_priv->rps.max_freq;
5404        DRM_DEBUG_DRIVER("max GPU freq: %d MHz (%u)\n",
5405                         intel_gpu_freq(dev_priv, dev_priv->rps.max_freq),
5406                         dev_priv->rps.max_freq);
5407
5408        dev_priv->rps.efficient_freq = cherryview_rps_rpe_freq(dev_priv);
5409        DRM_DEBUG_DRIVER("RPe GPU freq: %d MHz (%u)\n",
5410                         intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5411                         dev_priv->rps.efficient_freq);
5412
5413        dev_priv->rps.rp1_freq = cherryview_rps_guar_freq(dev_priv);
5414        DRM_DEBUG_DRIVER("RP1(Guar) GPU freq: %d MHz (%u)\n",
5415                         intel_gpu_freq(dev_priv, dev_priv->rps.rp1_freq),
5416                         dev_priv->rps.rp1_freq);
5417
5418        /* PUnit validated range is only [RPe, RP0] */
5419        dev_priv->rps.min_freq = dev_priv->rps.efficient_freq;
5420        DRM_DEBUG_DRIVER("min GPU freq: %d MHz (%u)\n",
5421                         intel_gpu_freq(dev_priv, dev_priv->rps.min_freq),
5422                         dev_priv->rps.min_freq);
5423
5424        WARN_ONCE((dev_priv->rps.max_freq |
5425                   dev_priv->rps.efficient_freq |
5426                   dev_priv->rps.rp1_freq |
5427                   dev_priv->rps.min_freq) & 1,
5428                  "Odd GPU freq values\n");
5429
5430        dev_priv->rps.idle_freq = dev_priv->rps.min_freq;
5431
5432        /* Preserve min/max settings in case of re-init */
5433        if (dev_priv->rps.max_freq_softlimit == 0)
5434                dev_priv->rps.max_freq_softlimit = dev_priv->rps.max_freq;
5435
5436        if (dev_priv->rps.min_freq_softlimit == 0)
5437                dev_priv->rps.min_freq_softlimit = dev_priv->rps.min_freq;
5438
5439        mutex_unlock(&dev_priv->rps.hw_lock);
5440}
5441
5442static void valleyview_cleanup_gt_powersave(struct drm_device *dev)
5443{
5444        valleyview_cleanup_pctx(dev);
5445}
5446
5447static void cherryview_enable_rps(struct drm_device *dev)
5448{
5449        struct drm_i915_private *dev_priv = dev->dev_private;
5450        struct intel_engine_cs *ring;
5451        u32 gtfifodbg, val, rc6_mode = 0, pcbr;
5452        int i;
5453
5454        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5455
5456        gtfifodbg = I915_READ(GTFIFODBG);
5457        if (gtfifodbg) {
5458                DRM_DEBUG_DRIVER("GT fifo had a previous error %x\n",
5459                                 gtfifodbg);
5460                I915_WRITE(GTFIFODBG, gtfifodbg);
5461        }
5462
5463        cherryview_check_pctx(dev_priv);
5464
5465        /* 1a & 1b: Get forcewake during program sequence. Although the driver
5466         * hasn't enabled a state yet where we need forcewake, BIOS may have.*/
5467        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5468
5469        /*  Disable RC states. */
5470        I915_WRITE(GEN6_RC_CONTROL, 0);
5471
5472        /* 2a: Program RC6 thresholds.*/
5473        I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16);
5474        I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000); /* 12500 * 1280ns */
5475        I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25); /* 25 * 1280ns */
5476
5477        for_each_ring(ring, dev_priv, i)
5478                I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
5479        I915_WRITE(GEN6_RC_SLEEP, 0);
5480
5481        /* TO threshold set to 500 us ( 0x186 * 1.28 us) */
5482        I915_WRITE(GEN6_RC6_THRESHOLD, 0x186);
5483
5484        /* allows RC6 residency counter to work */
5485        I915_WRITE(VLV_COUNTER_CONTROL,
5486                   _MASKED_BIT_ENABLE(VLV_COUNT_RANGE_HIGH |
5487                                      VLV_MEDIA_RC6_COUNT_EN |
5488                                      VLV_RENDER_RC6_COUNT_EN));
5489
5490        /* For now we assume BIOS is allocating and populating the PCBR  */
5491        pcbr = I915_READ(VLV_PCBR);
5492
5493        /* 3: Enable RC6 */
5494        if ((intel_enable_rc6(dev) & INTEL_RC6_ENABLE) &&
5495                                                (pcbr >> VLV_PCBR_ADDR_SHIFT))
5496                rc6_mode = GEN7_RC_CTL_TO_MODE;
5497
5498        I915_WRITE(GEN6_RC_CONTROL, rc6_mode);
5499
5500        /* 4 Program defaults and thresholds for RPS*/
5501        I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 1000000);
5502        I915_WRITE(GEN6_RP_UP_THRESHOLD, 59400);
5503        I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 245000);
5504        I915_WRITE(GEN6_RP_UP_EI, 66000);
5505        I915_WRITE(GEN6_RP_DOWN_EI, 350000);
5506
5507        I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
5508
5509        /* 5: Enable RPS */
5510        I915_WRITE(GEN6_RP_CONTROL,
5511                   GEN6_RP_MEDIA_HW_NORMAL_MODE |
5512                   GEN6_RP_MEDIA_IS_GFX |
5513                   GEN6_RP_ENABLE |
5514                   GEN6_RP_UP_BUSY_AVG |
5515                   GEN6_RP_DOWN_IDLE_AVG);
5516
5517        /* Setting Fixed Bias */
5518        val = VLV_OVERRIDE_EN |
5519                  VLV_SOC_TDP_EN |
5520                  CHV_BIAS_CPU_50_SOC_50;
5521        vlv_punit_write(dev_priv, VLV_TURBO_SOC_OVERRIDE, val);
5522
5523        val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
5524
5525        /* RPS code assumes GPLL is used */
5526        WARN_ONCE((val & GPLLENABLE) == 0, "GPLL not enabled\n");
5527
5528        DRM_DEBUG_DRIVER("GPLL enabled? %s\n", yesno(val & GPLLENABLE));
5529        DRM_DEBUG_DRIVER("GPU status: 0x%08x\n", val);
5530
5531        dev_priv->rps.cur_freq = (val >> 8) & 0xff;
5532        DRM_DEBUG_DRIVER("current GPU freq: %d MHz (%u)\n",
5533                         intel_gpu_freq(dev_priv, dev_priv->rps.cur_freq),
5534                         dev_priv->rps.cur_freq);
5535
5536        DRM_DEBUG_DRIVER("setting GPU freq to %d MHz (%u)\n",
5537                         intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5538                         dev_priv->rps.efficient_freq);
5539
5540        valleyview_set_rps(dev_priv->dev, dev_priv->rps.efficient_freq);
5541
5542        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5543}
5544
5545static void valleyview_enable_rps(struct drm_device *dev)
5546{
5547        struct drm_i915_private *dev_priv = dev->dev_private;
5548        struct intel_engine_cs *ring;
5549        u32 gtfifodbg, val, rc6_mode = 0;
5550        int i;
5551
5552        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5553
5554        valleyview_check_pctx(dev_priv);
5555
5556        if ((gtfifodbg = I915_READ(GTFIFODBG))) {
5557                DRM_DEBUG_DRIVER("GT fifo had a previous error %x\n",
5558                                 gtfifodbg);
5559                I915_WRITE(GTFIFODBG, gtfifodbg);
5560        }
5561
5562        /* If VLV, Forcewake all wells, else re-direct to regular path */
5563        intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5564
5565        /*  Disable RC states. */
5566        I915_WRITE(GEN6_RC_CONTROL, 0);
5567
5568        I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 1000000);
5569        I915_WRITE(GEN6_RP_UP_THRESHOLD, 59400);
5570        I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 245000);
5571        I915_WRITE(GEN6_RP_UP_EI, 66000);
5572        I915_WRITE(GEN6_RP_DOWN_EI, 350000);
5573
5574        I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
5575
5576        I915_WRITE(GEN6_RP_CONTROL,
5577                   GEN6_RP_MEDIA_TURBO |
5578                   GEN6_RP_MEDIA_HW_NORMAL_MODE |
5579                   GEN6_RP_MEDIA_IS_GFX |
5580                   GEN6_RP_ENABLE |
5581                   GEN6_RP_UP_BUSY_AVG |
5582                   GEN6_RP_DOWN_IDLE_CONT);
5583
5584        I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 0x00280000);
5585        I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
5586        I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
5587
5588        for_each_ring(ring, dev_priv, i)
5589                I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
5590
5591        I915_WRITE(GEN6_RC6_THRESHOLD, 0x557);
5592
5593        /* allows RC6 residency counter to work */
5594        I915_WRITE(VLV_COUNTER_CONTROL,
5595                   _MASKED_BIT_ENABLE(VLV_MEDIA_RC0_COUNT_EN |
5596                                      VLV_RENDER_RC0_COUNT_EN |
5597                                      VLV_MEDIA_RC6_COUNT_EN |
5598                                      VLV_RENDER_RC6_COUNT_EN));
5599
5600        if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
5601                rc6_mode = GEN7_RC_CTL_TO_MODE | VLV_RC_CTL_CTX_RST_PARALLEL;
5602
5603        intel_print_rc6_info(dev, rc6_mode);
5604
5605        I915_WRITE(GEN6_RC_CONTROL, rc6_mode);
5606
5607        /* Setting Fixed Bias */
5608        val = VLV_OVERRIDE_EN |
5609                  VLV_SOC_TDP_EN |
5610                  VLV_BIAS_CPU_125_SOC_875;
5611        vlv_punit_write(dev_priv, VLV_TURBO_SOC_OVERRIDE, val);
5612
5613        val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
5614
5615        /* RPS code assumes GPLL is used */
5616        WARN_ONCE((val & GPLLENABLE) == 0, "GPLL not enabled\n");
5617
5618        DRM_DEBUG_DRIVER("GPLL enabled? %s\n", yesno(val & GPLLENABLE));
5619        DRM_DEBUG_DRIVER("GPU status: 0x%08x\n", val);
5620
5621        dev_priv->rps.cur_freq = (val >> 8) & 0xff;
5622        DRM_DEBUG_DRIVER("current GPU freq: %d MHz (%u)\n",
5623                         intel_gpu_freq(dev_priv, dev_priv->rps.cur_freq),
5624                         dev_priv->rps.cur_freq);
5625
5626        DRM_DEBUG_DRIVER("setting GPU freq to %d MHz (%u)\n",
5627                         intel_gpu_freq(dev_priv, dev_priv->rps.efficient_freq),
5628                         dev_priv->rps.efficient_freq);
5629
5630        valleyview_set_rps(dev_priv->dev, dev_priv->rps.efficient_freq);
5631
5632        intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5633}
5634
5635static unsigned long intel_pxfreq(u32 vidfreq)
5636{
5637        unsigned long freq;
5638        int div = (vidfreq & 0x3f0000) >> 16;
5639        int post = (vidfreq & 0x3000) >> 12;
5640        int pre = (vidfreq & 0x7);
5641
5642        if (!pre)
5643                return 0;
5644
5645        freq = ((div * 133333) / ((1<<post) * pre));
5646
5647        return freq;
5648}
5649
5650static const struct cparams {
5651        u16 i;
5652        u16 t;
5653        u16 m;
5654        u16 c;
5655} cparams[] = {
5656        { 1, 1333, 301, 28664 },
5657        { 1, 1066, 294, 24460 },
5658        { 1, 800, 294, 25192 },
5659        { 0, 1333, 276, 27605 },
5660        { 0, 1066, 276, 27605 },
5661        { 0, 800, 231, 23784 },
5662};
5663
5664static unsigned long __i915_chipset_val(struct drm_i915_private *dev_priv)
5665{
5666        u64 total_count, diff, ret;
5667        u32 count1, count2, count3, m = 0, c = 0;
5668        unsigned long now = jiffies_to_msecs(jiffies), diff1;
5669        int i;
5670
5671        assert_spin_locked(&mchdev_lock);
5672
5673        diff1 = now - dev_priv->ips.last_time1;
5674
5675        /* Prevent division-by-zero if we are asking too fast.
5676         * Also, we don't get interesting results if we are polling
5677         * faster than once in 10ms, so just return the saved value
5678         * in such cases.
5679         */
5680        if (diff1 <= 10)
5681                return dev_priv->ips.chipset_power;
5682
5683        count1 = I915_READ(DMIEC);
5684        count2 = I915_READ(DDREC);
5685        count3 = I915_READ(CSIEC);
5686
5687        total_count = count1 + count2 + count3;
5688
5689        /* FIXME: handle per-counter overflow */
5690        if (total_count < dev_priv->ips.last_count1) {
5691                diff = ~0UL - dev_priv->ips.last_count1;
5692                diff += total_count;
5693        } else {
5694                diff = total_count - dev_priv->ips.last_count1;
5695        }
5696
5697        for (i = 0; i < ARRAY_SIZE(cparams); i++) {
5698                if (cparams[i].i == dev_priv->ips.c_m &&
5699                    cparams[i].t == dev_priv->ips.r_t) {
5700                        m = cparams[i].m;
5701                        c = cparams[i].c;
5702                        break;
5703                }
5704        }
5705
5706        diff = div_u64(diff, diff1);
5707        ret = ((m * diff) + c);
5708        ret = div_u64(ret, 10);
5709
5710        dev_priv->ips.last_count1 = total_count;
5711        dev_priv->ips.last_time1 = now;
5712
5713        dev_priv->ips.chipset_power = ret;
5714
5715        return ret;
5716}
5717
5718unsigned long i915_chipset_val(struct drm_i915_private *dev_priv)
5719{
5720        struct drm_device *dev = dev_priv->dev;
5721        unsigned long val;
5722
5723        if (INTEL_INFO(dev)->gen != 5)
5724                return 0;
5725
5726        spin_lock_irq(&mchdev_lock);
5727
5728        val = __i915_chipset_val(dev_priv);
5729
5730        spin_unlock_irq(&mchdev_lock);
5731
5732        return val;
5733}
5734
5735unsigned long i915_mch_val(struct drm_i915_private *dev_priv)
5736{
5737        unsigned long m, x, b;
5738        u32 tsfs;
5739
5740        tsfs = I915_READ(TSFS);
5741
5742        m = ((tsfs & TSFS_SLOPE_MASK) >> TSFS_SLOPE_SHIFT);
5743        x = I915_READ8(TR1);
5744
5745        b = tsfs & TSFS_INTR_MASK;
5746
5747        return ((m * x) / 127) - b;
5748}
5749
5750static int _pxvid_to_vd(u8 pxvid)
5751{
5752        if (pxvid == 0)
5753                return 0;
5754
5755        if (pxvid >= 8 && pxvid < 31)
5756                pxvid = 31;
5757
5758        return (pxvid + 2) * 125;
5759}
5760
5761static u32 pvid_to_extvid(struct drm_i915_private *dev_priv, u8 pxvid)
5762{
5763        struct drm_device *dev = dev_priv->dev;
5764        const int vd = _pxvid_to_vd(pxvid);
5765        const int vm = vd - 1125;
5766
5767        if (INTEL_INFO(dev)->is_mobile)
5768                return vm > 0 ? vm : 0;
5769
5770        return vd;
5771}
5772
5773static void __i915_update_gfx_val(struct drm_i915_private *dev_priv)
5774{
5775        u64 now, diff, diffms;
5776        u32 count;
5777
5778        assert_spin_locked(&mchdev_lock);
5779
5780        now = ktime_get_raw_ns();
5781        diffms = now - dev_priv->ips.last_time2;
5782        do_div(diffms, NSEC_PER_MSEC);
5783
5784        /* Don't divide by 0 */
5785        if (!diffms)
5786                return;
5787
5788        count = I915_READ(GFXEC);
5789
5790        if (count < dev_priv->ips.last_count2) {
5791                diff = ~0UL - dev_priv->ips.last_count2;
5792                diff += count;
5793        } else {
5794                diff = count - dev_priv->ips.last_count2;
5795        }
5796
5797        dev_priv->ips.last_count2 = count;
5798        dev_priv->ips.last_time2 = now;
5799
5800        /* More magic constants... */
5801        diff = diff * 1181;
5802        diff = div_u64(diff, diffms * 10);
5803        dev_priv->ips.gfx_power = diff;
5804}
5805
5806void i915_update_gfx_val(struct drm_i915_private *dev_priv)
5807{
5808        struct drm_device *dev = dev_priv->dev;
5809
5810        if (INTEL_INFO(dev)->gen != 5)
5811                return;
5812
5813        spin_lock_irq(&mchdev_lock);
5814
5815        __i915_update_gfx_val(dev_priv);
5816
5817        spin_unlock_irq(&mchdev_lock);
5818}
5819
5820static unsigned long __i915_gfx_val(struct drm_i915_private *dev_priv)
5821{
5822        unsigned long t, corr, state1, corr2, state2;
5823        u32 pxvid, ext_v;
5824
5825        assert_spin_locked(&mchdev_lock);
5826
5827        pxvid = I915_READ(PXVFREQ(dev_priv->rps.cur_freq));
5828        pxvid = (pxvid >> 24) & 0x7f;
5829        ext_v = pvid_to_extvid(dev_priv, pxvid);
5830
5831        state1 = ext_v;
5832
5833        t = i915_mch_val(dev_priv);
5834
5835        /* Revel in the empirically derived constants */
5836
5837        /* Correction factor in 1/100000 units */
5838        if (t > 80)
5839                corr = ((t * 2349) + 135940);
5840        else if (t >= 50)
5841                corr = ((t * 964) + 29317);
5842        else /* < 50 */
5843                corr = ((t * 301) + 1004);
5844
5845        corr = corr * ((150142 * state1) / 10000 - 78642);
5846        corr /= 100000;
5847        corr2 = (corr * dev_priv->ips.corr);
5848
5849        state2 = (corr2 * state1) / 10000;
5850        state2 /= 100; /* convert to mW */
5851
5852        __i915_update_gfx_val(dev_priv);
5853
5854        return dev_priv->ips.gfx_power + state2;
5855}
5856
5857unsigned long i915_gfx_val(struct drm_i915_private *dev_priv)
5858{
5859        struct drm_device *dev = dev_priv->dev;
5860        unsigned long val;
5861
5862        if (INTEL_INFO(dev)->gen != 5)
5863                return 0;
5864
5865        spin_lock_irq(&mchdev_lock);
5866
5867        val = __i915_gfx_val(dev_priv);
5868
5869        spin_unlock_irq(&mchdev_lock);
5870
5871        return val;
5872}
5873
5874/**
5875 * i915_read_mch_val - return value for IPS use
5876 *
5877 * Calculate and return a value for the IPS driver to use when deciding whether
5878 * we have thermal and power headroom to increase CPU or GPU power budget.
5879 */
5880unsigned long i915_read_mch_val(void)
5881{
5882        struct drm_i915_private *dev_priv;
5883        unsigned long chipset_val, graphics_val, ret = 0;
5884
5885        spin_lock_irq(&mchdev_lock);
5886        if (!i915_mch_dev)
5887                goto out_unlock;
5888        dev_priv = i915_mch_dev;
5889
5890        chipset_val = __i915_chipset_val(dev_priv);
5891        graphics_val = __i915_gfx_val(dev_priv);
5892
5893        ret = chipset_val + graphics_val;
5894
5895out_unlock:
5896        spin_unlock_irq(&mchdev_lock);
5897
5898        return ret;
5899}
5900EXPORT_SYMBOL_GPL(i915_read_mch_val);
5901
5902/**
5903 * i915_gpu_raise - raise GPU frequency limit
5904 *
5905 * Raise the limit; IPS indicates we have thermal headroom.
5906 */
5907bool i915_gpu_raise(void)
5908{
5909        struct drm_i915_private *dev_priv;
5910        bool ret = true;
5911
5912        spin_lock_irq(&mchdev_lock);
5913        if (!i915_mch_dev) {
5914                ret = false;
5915                goto out_unlock;
5916        }
5917        dev_priv = i915_mch_dev;
5918
5919        if (dev_priv->ips.max_delay > dev_priv->ips.fmax)
5920                dev_priv->ips.max_delay--;
5921
5922out_unlock:
5923        spin_unlock_irq(&mchdev_lock);
5924
5925        return ret;
5926}
5927EXPORT_SYMBOL_GPL(i915_gpu_raise);
5928
5929/**
5930 * i915_gpu_lower - lower GPU frequency limit
5931 *
5932 * IPS indicates we're close to a thermal limit, so throttle back the GPU
5933 * frequency maximum.
5934 */
5935bool i915_gpu_lower(void)
5936{
5937        struct drm_i915_private *dev_priv;
5938        bool ret = true;
5939
5940        spin_lock_irq(&mchdev_lock);
5941        if (!i915_mch_dev) {
5942                ret = false;
5943                goto out_unlock;
5944        }
5945        dev_priv = i915_mch_dev;
5946
5947        if (dev_priv->ips.max_delay < dev_priv->ips.min_delay)
5948                dev_priv->ips.max_delay++;
5949
5950out_unlock:
5951        spin_unlock_irq(&mchdev_lock);
5952
5953        return ret;
5954}
5955EXPORT_SYMBOL_GPL(i915_gpu_lower);
5956
5957/**
5958 * i915_gpu_busy - indicate GPU business to IPS
5959 *
5960 * Tell the IPS driver whether or not the GPU is busy.
5961 */
5962bool i915_gpu_busy(void)
5963{
5964        struct drm_i915_private *dev_priv;
5965        struct intel_engine_cs *ring;
5966        bool ret = false;
5967        int i;
5968
5969        spin_lock_irq(&mchdev_lock);
5970        if (!i915_mch_dev)
5971                goto out_unlock;
5972        dev_priv = i915_mch_dev;
5973
5974        for_each_ring(ring, dev_priv, i)
5975                ret |= !list_empty(&ring->request_list);
5976
5977out_unlock:
5978        spin_unlock_irq(&mchdev_lock);
5979
5980        return ret;
5981}
5982EXPORT_SYMBOL_GPL(i915_gpu_busy);
5983
5984/**
5985 * i915_gpu_turbo_disable - disable graphics turbo
5986 *
5987 * Disable graphics turbo by resetting the max frequency and setting the
5988 * current frequency to the default.
5989 */
5990bool i915_gpu_turbo_disable(void)
5991{
5992        struct drm_i915_private *dev_priv;
5993        bool ret = true;
5994
5995        spin_lock_irq(&mchdev_lock);
5996        if (!i915_mch_dev) {
5997                ret = false;
5998                goto out_unlock;
5999        }
6000        dev_priv = i915_mch_dev;
6001
6002        dev_priv->ips.max_delay = dev_priv->ips.fstart;
6003
6004        if (!ironlake_set_drps(dev_priv->dev, dev_priv->ips.fstart))
6005                ret = false;
6006
6007out_unlock:
6008        spin_unlock_irq(&mchdev_lock);
6009
6010        return ret;
6011}
6012EXPORT_SYMBOL_GPL(i915_gpu_turbo_disable);
6013
6014/**
6015 * Tells the intel_ips driver that the i915 driver is now loaded, if
6016 * IPS got loaded first.
6017 *
6018 * This awkward dance is so that neither module has to depend on the
6019 * other in order for IPS to do the appropriate communication of
6020 * GPU turbo limits to i915.
6021 */
6022static void
6023ips_ping_for_i915_load(void)
6024{
6025        void (*link)(void);
6026
6027        link = symbol_get(ips_link_to_i915_driver);
6028        if (link) {
6029                link();
6030                symbol_put(ips_link_to_i915_driver);
6031        }
6032}
6033
6034void intel_gpu_ips_init(struct drm_i915_private *dev_priv)
6035{
6036        /* We only register the i915 ips part with intel-ips once everything is
6037         * set up, to avoid intel-ips sneaking in and reading bogus values. */
6038        spin_lock_irq(&mchdev_lock);
6039        i915_mch_dev = dev_priv;
6040        spin_unlock_irq(&mchdev_lock);
6041
6042        ips_ping_for_i915_load();
6043}
6044
6045void intel_gpu_ips_teardown(void)
6046{
6047        spin_lock_irq(&mchdev_lock);
6048        i915_mch_dev = NULL;
6049        spin_unlock_irq(&mchdev_lock);
6050}
6051
6052static void intel_init_emon(struct drm_device *dev)
6053{
6054        struct drm_i915_private *dev_priv = dev->dev_private;
6055        u32 lcfuse;
6056        u8 pxw[16];
6057        int i;
6058
6059        /* Disable to program */
6060        I915_WRITE(ECR, 0);
6061        POSTING_READ(ECR);
6062
6063        /* Program energy weights for various events */
6064        I915_WRITE(SDEW, 0x15040d00);
6065        I915_WRITE(CSIEW0, 0x007f0000);
6066        I915_WRITE(CSIEW1, 0x1e220004);
6067        I915_WRITE(CSIEW2, 0x04000004);
6068
6069        for (i = 0; i < 5; i++)
6070                I915_WRITE(PEW(i), 0);
6071        for (i = 0; i < 3; i++)
6072                I915_WRITE(DEW(i), 0);
6073
6074        /* Program P-state weights to account for frequency power adjustment */
6075        for (i = 0; i < 16; i++) {
6076                u32 pxvidfreq = I915_READ(PXVFREQ(i));
6077                unsigned long freq = intel_pxfreq(pxvidfreq);
6078                unsigned long vid = (pxvidfreq & PXVFREQ_PX_MASK) >>
6079                        PXVFREQ_PX_SHIFT;
6080                unsigned long val;
6081
6082                val = vid * vid;
6083                val *= (freq / 1000);
6084                val *= 255;
6085                val /= (127*127*900);
6086                if (val > 0xff)
6087                        DRM_ERROR("bad pxval: %ld\n", val);
6088                pxw[i] = val;
6089        }
6090        /* Render standby states get 0 weight */
6091        pxw[14] = 0;
6092        pxw[15] = 0;
6093
6094        for (i = 0; i < 4; i++) {
6095                u32 val = (pxw[i*4] << 24) | (pxw[(i*4)+1] << 16) |
6096                        (pxw[(i*4)+2] << 8) | (pxw[(i*4)+3]);
6097                I915_WRITE(PXW(i), val);
6098        }
6099
6100        /* Adjust magic regs to magic values (more experimental results) */
6101        I915_WRITE(OGW0, 0);
6102        I915_WRITE(OGW1, 0);
6103        I915_WRITE(EG0, 0x00007f00);
6104        I915_WRITE(EG1, 0x0000000e);
6105        I915_WRITE(EG2, 0x000e0000);
6106        I915_WRITE(EG3, 0x68000300);
6107        I915_WRITE(EG4, 0x42000000);
6108        I915_WRITE(EG5, 0x00140031);
6109        I915_WRITE(EG6, 0);
6110        I915_WRITE(EG7, 0);
6111
6112        for (i = 0; i < 8; i++)
6113                I915_WRITE(PXWL(i), 0);
6114
6115        /* Enable PMON + select events */
6116        I915_WRITE(ECR, 0x80000019);
6117
6118        lcfuse = I915_READ(LCFUSE02);
6119
6120        dev_priv->ips.corr = (lcfuse & LCFUSE_HIV_MASK);
6121}
6122
6123void intel_init_gt_powersave(struct drm_device *dev)
6124{
6125        i915.enable_rc6 = sanitize_rc6_option(dev, i915.enable_rc6);
6126
6127        if (IS_CHERRYVIEW(dev))
6128                cherryview_init_gt_powersave(dev);
6129        else if (IS_VALLEYVIEW(dev))
6130                valleyview_init_gt_powersave(dev);
6131}
6132
6133void intel_cleanup_gt_powersave(struct drm_device *dev)
6134{
6135        if (IS_CHERRYVIEW(dev))
6136                return;
6137        else if (IS_VALLEYVIEW(dev))
6138                valleyview_cleanup_gt_powersave(dev);
6139}
6140
6141static void gen6_suspend_rps(struct drm_device *dev)
6142{
6143        struct drm_i915_private *dev_priv = dev->dev_private;
6144
6145        flush_delayed_work(&dev_priv->rps.delayed_resume_work);
6146
6147        gen6_disable_rps_interrupts(dev);
6148}
6149
6150/**
6151 * intel_suspend_gt_powersave - suspend PM work and helper threads
6152 * @dev: drm device
6153 *
6154 * We don't want to disable RC6 or other features here, we just want
6155 * to make sure any work we've queued has finished and won't bother
6156 * us while we're suspended.
6157 */
6158void intel_suspend_gt_powersave(struct drm_device *dev)
6159{
6160        struct drm_i915_private *dev_priv = dev->dev_private;
6161
6162        if (INTEL_INFO(dev)->gen < 6)
6163                return;
6164
6165        gen6_suspend_rps(dev);
6166
6167        /* Force GPU to min freq during suspend */
6168        gen6_rps_idle(dev_priv);
6169}
6170
6171void intel_disable_gt_powersave(struct drm_device *dev)
6172{
6173        struct drm_i915_private *dev_priv = dev->dev_private;
6174
6175        if (IS_IRONLAKE_M(dev)) {
6176                ironlake_disable_drps(dev);
6177        } else if (INTEL_INFO(dev)->gen >= 6) {
6178                intel_suspend_gt_powersave(dev);
6179
6180                mutex_lock(&dev_priv->rps.hw_lock);
6181                if (INTEL_INFO(dev)->gen >= 9)
6182                        gen9_disable_rps(dev);
6183                else if (IS_CHERRYVIEW(dev))
6184                        cherryview_disable_rps(dev);
6185                else if (IS_VALLEYVIEW(dev))
6186                        valleyview_disable_rps(dev);
6187                else
6188                        gen6_disable_rps(dev);
6189
6190                dev_priv->rps.enabled = false;
6191                mutex_unlock(&dev_priv->rps.hw_lock);
6192        }
6193}
6194
6195static void intel_gen6_powersave_work(struct work_struct *work)
6196{
6197        struct drm_i915_private *dev_priv =
6198                container_of(work, struct drm_i915_private,
6199                             rps.delayed_resume_work.work);
6200        struct drm_device *dev = dev_priv->dev;
6201
6202        mutex_lock(&dev_priv->rps.hw_lock);
6203
6204        gen6_reset_rps_interrupts(dev);
6205
6206        if (IS_CHERRYVIEW(dev)) {
6207                cherryview_enable_rps(dev);
6208        } else if (IS_VALLEYVIEW(dev)) {
6209                valleyview_enable_rps(dev);
6210        } else if (INTEL_INFO(dev)->gen >= 9) {
6211                gen9_enable_rc6(dev);
6212                gen9_enable_rps(dev);
6213                if (IS_SKYLAKE(dev))
6214                        __gen6_update_ring_freq(dev);
6215        } else if (IS_BROADWELL(dev)) {
6216                gen8_enable_rps(dev);
6217                __gen6_update_ring_freq(dev);
6218        } else {
6219                gen6_enable_rps(dev);
6220                __gen6_update_ring_freq(dev);
6221        }
6222
6223        WARN_ON(dev_priv->rps.max_freq < dev_priv->rps.min_freq);
6224        WARN_ON(dev_priv->rps.idle_freq > dev_priv->rps.max_freq);
6225
6226        WARN_ON(dev_priv->rps.efficient_freq < dev_priv->rps.min_freq);
6227        WARN_ON(dev_priv->rps.efficient_freq > dev_priv->rps.max_freq);
6228
6229        dev_priv->rps.enabled = true;
6230
6231        gen6_enable_rps_interrupts(dev);
6232
6233        mutex_unlock(&dev_priv->rps.hw_lock);
6234
6235        intel_runtime_pm_put(dev_priv);
6236}
6237
6238void intel_enable_gt_powersave(struct drm_device *dev)
6239{
6240        struct drm_i915_private *dev_priv = dev->dev_private;
6241
6242        /* Powersaving is controlled by the host when inside a VM */
6243        if (intel_vgpu_active(dev))
6244                return;
6245
6246        if (IS_IRONLAKE_M(dev)) {
6247                mutex_lock(&dev->struct_mutex);
6248                ironlake_enable_drps(dev);
6249                intel_init_emon(dev);
6250                mutex_unlock(&dev->struct_mutex);
6251        } else if (INTEL_INFO(dev)->gen >= 6) {
6252                /*
6253                 * PCU communication is slow and this doesn't need to be
6254                 * done at any specific time, so do this out of our fast path
6255                 * to make resume and init faster.
6256                 *
6257                 * We depend on the HW RC6 power context save/restore
6258                 * mechanism when entering D3 through runtime PM suspend. So
6259                 * disable RPM until RPS/RC6 is properly setup. We can only
6260                 * get here via the driver load/system resume/runtime resume
6261                 * paths, so the _noresume version is enough (and in case of
6262                 * runtime resume it's necessary).
6263                 */
6264                if (schedule_delayed_work(&dev_priv->rps.delayed_resume_work,
6265                                           round_jiffies_up_relative(HZ)))
6266                        intel_runtime_pm_get_noresume(dev_priv);
6267        }
6268}
6269
6270void intel_reset_gt_powersave(struct drm_device *dev)
6271{
6272        struct drm_i915_private *dev_priv = dev->dev_private;
6273
6274        if (INTEL_INFO(dev)->gen < 6)
6275                return;
6276
6277        gen6_suspend_rps(dev);
6278        dev_priv->rps.enabled = false;
6279}
6280
6281static void ibx_init_clock_gating(struct drm_device *dev)
6282{
6283        struct drm_i915_private *dev_priv = dev->dev_private;
6284
6285        /*
6286         * On Ibex Peak and Cougar Point, we need to disable clock
6287         * gating for the panel power sequencer or it will fail to
6288         * start up when no ports are active.
6289         */
6290        I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
6291}
6292
6293static void g4x_disable_trickle_feed(struct drm_device *dev)
6294{
6295        struct drm_i915_private *dev_priv = dev->dev_private;
6296        enum pipe pipe;
6297
6298        for_each_pipe(dev_priv, pipe) {
6299                I915_WRITE(DSPCNTR(pipe),
6300                           I915_READ(DSPCNTR(pipe)) |
6301                           DISPPLANE_TRICKLE_FEED_DISABLE);
6302
6303                I915_WRITE(DSPSURF(pipe), I915_READ(DSPSURF(pipe)));
6304                POSTING_READ(DSPSURF(pipe));
6305        }
6306}
6307
6308static void ilk_init_lp_watermarks(struct drm_device *dev)
6309{
6310        struct drm_i915_private *dev_priv = dev->dev_private;
6311
6312        I915_WRITE(WM3_LP_ILK, I915_READ(WM3_LP_ILK) & ~WM1_LP_SR_EN);
6313        I915_WRITE(WM2_LP_ILK, I915_READ(WM2_LP_ILK) & ~WM1_LP_SR_EN);
6314        I915_WRITE(WM1_LP_ILK, I915_READ(WM1_LP_ILK) & ~WM1_LP_SR_EN);
6315
6316        /*
6317         * Don't touch WM1S_LP_EN here.
6318         * Doing so could cause underruns.
6319         */
6320}
6321
6322static void ironlake_init_clock_gating(struct drm_device *dev)
6323{
6324        struct drm_i915_private *dev_priv = dev->dev_private;
6325        uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
6326
6327        /*
6328         * Required for FBC
6329         * WaFbcDisableDpfcClockGating:ilk
6330         */
6331        dspclk_gate |= ILK_DPFCRUNIT_CLOCK_GATE_DISABLE |
6332                   ILK_DPFCUNIT_CLOCK_GATE_DISABLE |
6333                   ILK_DPFDUNIT_CLOCK_GATE_ENABLE;
6334
6335        I915_WRITE(PCH_3DCGDIS0,
6336                   MARIUNIT_CLOCK_GATE_DISABLE |
6337                   SVSMUNIT_CLOCK_GATE_DISABLE);
6338        I915_WRITE(PCH_3DCGDIS1,
6339                   VFMUNIT_CLOCK_GATE_DISABLE);
6340
6341        /*
6342         * According to the spec the following bits should be set in
6343         * order to enable memory self-refresh
6344         * The bit 22/21 of 0x42004
6345         * The bit 5 of 0x42020
6346         * The bit 15 of 0x45000
6347         */
6348        I915_WRITE(ILK_DISPLAY_CHICKEN2,
6349                   (I915_READ(ILK_DISPLAY_CHICKEN2) |
6350                    ILK_DPARB_GATE | ILK_VSDPFD_FULL));
6351        dspclk_gate |= ILK_DPARBUNIT_CLOCK_GATE_ENABLE;
6352        I915_WRITE(DISP_ARB_CTL,
6353                   (I915_READ(DISP_ARB_CTL) |
6354                    DISP_FBC_WM_DIS));
6355
6356        ilk_init_lp_watermarks(dev);
6357
6358        /*
6359         * Based on the document from hardware guys the following bits
6360         * should be set unconditionally in order to enable FBC.
6361         * The bit 22 of 0x42000
6362         * The bit 22 of 0x42004
6363         * The bit 7,8,9 of 0x42020.
6364         */
6365        if (IS_IRONLAKE_M(dev)) {
6366                /* WaFbcAsynchFlipDisableFbcQueue:ilk */
6367                I915_WRITE(ILK_DISPLAY_CHICKEN1,
6368                           I915_READ(ILK_DISPLAY_CHICKEN1) |
6369                           ILK_FBCQ_DIS);
6370                I915_WRITE(ILK_DISPLAY_CHICKEN2,
6371                           I915_READ(ILK_DISPLAY_CHICKEN2) |
6372                           ILK_DPARB_GATE);
6373        }
6374
6375        I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
6376
6377        I915_WRITE(ILK_DISPLAY_CHICKEN2,
6378                   I915_READ(ILK_DISPLAY_CHICKEN2) |
6379                   ILK_ELPIN_409_SELECT);
6380        I915_WRITE(_3D_CHICKEN2,
6381                   _3D_CHICKEN2_WM_READ_PIPELINED << 16 |
6382                   _3D_CHICKEN2_WM_READ_PIPELINED);
6383
6384        /* WaDisableRenderCachePipelinedFlush:ilk */
6385        I915_WRITE(CACHE_MODE_0,
6386                   _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
6387
6388        /* WaDisable_RenderCache_OperationalFlush:ilk */
6389        I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6390
6391        g4x_disable_trickle_feed(dev);
6392
6393        ibx_init_clock_gating(dev);
6394}
6395
6396static void cpt_init_clock_gating(struct drm_device *dev)
6397{
6398        struct drm_i915_private *dev_priv = dev->dev_private;
6399        int pipe;
6400        uint32_t val;
6401
6402        /*
6403         * On Ibex Peak and Cougar Point, we need to disable clock
6404         * gating for the panel power sequencer or it will fail to
6405         * start up when no ports are active.
6406         */
6407        I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE |
6408                   PCH_DPLUNIT_CLOCK_GATE_DISABLE |
6409                   PCH_CPUNIT_CLOCK_GATE_DISABLE);
6410        I915_WRITE(SOUTH_CHICKEN2, I915_READ(SOUTH_CHICKEN2) |
6411                   DPLS_EDP_PPS_FIX_DIS);
6412        /* The below fixes the weird display corruption, a few pixels shifted
6413         * downward, on (only) LVDS of some HP laptops with IVY.
6414         */
6415        for_each_pipe(dev_priv, pipe) {
6416                val = I915_READ(TRANS_CHICKEN2(pipe));
6417                val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
6418                val &= ~TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
6419                if (dev_priv->vbt.fdi_rx_polarity_inverted)
6420                        val |= TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
6421                val &= ~TRANS_CHICKEN2_FRAME_START_DELAY_MASK;
6422                val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_COUNTER;
6423                val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_MODESWITCH;
6424                I915_WRITE(TRANS_CHICKEN2(pipe), val);
6425        }
6426        /* WADP0ClockGatingDisable */
6427        for_each_pipe(dev_priv, pipe) {
6428                I915_WRITE(TRANS_CHICKEN1(pipe),
6429                           TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
6430        }
6431}
6432
6433static void gen6_check_mch_setup(struct drm_device *dev)
6434{
6435        struct drm_i915_private *dev_priv = dev->dev_private;
6436        uint32_t tmp;
6437
6438        tmp = I915_READ(MCH_SSKPD);
6439        if ((tmp & MCH_SSKPD_WM0_MASK) != MCH_SSKPD_WM0_VAL)
6440                DRM_DEBUG_KMS("Wrong MCH_SSKPD value: 0x%08x This can cause underruns.\n",
6441                              tmp);
6442}
6443
6444static void gen6_init_clock_gating(struct drm_device *dev)
6445{
6446        struct drm_i915_private *dev_priv = dev->dev_private;
6447        uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
6448
6449        I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
6450
6451        I915_WRITE(ILK_DISPLAY_CHICKEN2,
6452                   I915_READ(ILK_DISPLAY_CHICKEN2) |
6453                   ILK_ELPIN_409_SELECT);
6454
6455        /* WaDisableHiZPlanesWhenMSAAEnabled:snb */
6456        I915_WRITE(_3D_CHICKEN,
6457                   _MASKED_BIT_ENABLE(_3D_CHICKEN_HIZ_PLANE_DISABLE_MSAA_4X_SNB));
6458
6459        /* WaDisable_RenderCache_OperationalFlush:snb */
6460        I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6461
6462        /*
6463         * BSpec recoomends 8x4 when MSAA is used,
6464         * however in practice 16x4 seems fastest.
6465         *
6466         * Note that PS/WM thread counts depend on the WIZ hashing
6467         * disable bit, which we don't touch here, but it's good
6468         * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6469         */
6470        I915_WRITE(GEN6_GT_MODE,
6471                   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6472
6473        ilk_init_lp_watermarks(dev);
6474
6475        I915_WRITE(CACHE_MODE_0,
6476                   _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
6477
6478        I915_WRITE(GEN6_UCGCTL1,
6479                   I915_READ(GEN6_UCGCTL1) |
6480                   GEN6_BLBUNIT_CLOCK_GATE_DISABLE |
6481                   GEN6_CSUNIT_CLOCK_GATE_DISABLE);
6482
6483        /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
6484         * gating disable must be set.  Failure to set it results in
6485         * flickering pixels due to Z write ordering failures after
6486         * some amount of runtime in the Mesa "fire" demo, and Unigine
6487         * Sanctuary and Tropics, and apparently anything else with
6488         * alpha test or pixel discard.
6489         *
6490         * According to the spec, bit 11 (RCCUNIT) must also be set,
6491         * but we didn't debug actual testcases to find it out.
6492         *
6493         * WaDisableRCCUnitClockGating:snb
6494         * WaDisableRCPBUnitClockGating:snb
6495         */
6496        I915_WRITE(GEN6_UCGCTL2,
6497                   GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
6498                   GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
6499
6500        /* WaStripsFansDisableFastClipPerformanceFix:snb */
6501        I915_WRITE(_3D_CHICKEN3,
6502                   _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_FASTCLIP_CULL));
6503
6504        /*
6505         * Bspec says:
6506         * "This bit must be set if 3DSTATE_CLIP clip mode is set to normal and
6507         * 3DSTATE_SF number of SF output attributes is more than 16."
6508         */
6509        I915_WRITE(_3D_CHICKEN3,
6510                   _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_PIPELINED_ATTR_FETCH));
6511
6512        /*
6513         * According to the spec the following bits should be
6514         * set in order to enable memory self-refresh and fbc:
6515         * The bit21 and bit22 of 0x42000
6516         * The bit21 and bit22 of 0x42004
6517         * The bit5 and bit7 of 0x42020
6518         * The bit14 of 0x70180
6519         * The bit14 of 0x71180
6520         *
6521         * WaFbcAsynchFlipDisableFbcQueue:snb
6522         */
6523        I915_WRITE(ILK_DISPLAY_CHICKEN1,
6524                   I915_READ(ILK_DISPLAY_CHICKEN1) |
6525                   ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
6526        I915_WRITE(ILK_DISPLAY_CHICKEN2,
6527                   I915_READ(ILK_DISPLAY_CHICKEN2) |
6528                   ILK_DPARB_GATE | ILK_VSDPFD_FULL);
6529        I915_WRITE(ILK_DSPCLK_GATE_D,
6530                   I915_READ(ILK_DSPCLK_GATE_D) |
6531                   ILK_DPARBUNIT_CLOCK_GATE_ENABLE  |
6532                   ILK_DPFDUNIT_CLOCK_GATE_ENABLE);
6533
6534        g4x_disable_trickle_feed(dev);
6535
6536        cpt_init_clock_gating(dev);
6537
6538        gen6_check_mch_setup(dev);
6539}
6540
6541static void gen7_setup_fixed_func_scheduler(struct drm_i915_private *dev_priv)
6542{
6543        uint32_t reg = I915_READ(GEN7_FF_THREAD_MODE);
6544
6545        /*
6546         * WaVSThreadDispatchOverride:ivb,vlv
6547         *
6548         * This actually overrides the dispatch
6549         * mode for all thread types.
6550         */
6551        reg &= ~GEN7_FF_SCHED_MASK;
6552        reg |= GEN7_FF_TS_SCHED_HW;
6553        reg |= GEN7_FF_VS_SCHED_HW;
6554        reg |= GEN7_FF_DS_SCHED_HW;
6555
6556        I915_WRITE(GEN7_FF_THREAD_MODE, reg);
6557}
6558
6559static void lpt_init_clock_gating(struct drm_device *dev)
6560{
6561        struct drm_i915_private *dev_priv = dev->dev_private;
6562
6563        /*
6564         * TODO: this bit should only be enabled when really needed, then
6565         * disabled when not needed anymore in order to save power.
6566         */
6567        if (HAS_PCH_LPT_LP(dev))
6568                I915_WRITE(SOUTH_DSPCLK_GATE_D,
6569                           I915_READ(SOUTH_DSPCLK_GATE_D) |
6570                           PCH_LP_PARTITION_LEVEL_DISABLE);
6571
6572        /* WADPOClockGatingDisable:hsw */
6573        I915_WRITE(TRANS_CHICKEN1(PIPE_A),
6574                   I915_READ(TRANS_CHICKEN1(PIPE_A)) |
6575                   TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
6576}
6577
6578static void lpt_suspend_hw(struct drm_device *dev)
6579{
6580        struct drm_i915_private *dev_priv = dev->dev_private;
6581
6582        if (HAS_PCH_LPT_LP(dev)) {
6583                uint32_t val = I915_READ(SOUTH_DSPCLK_GATE_D);
6584
6585                val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
6586                I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
6587        }
6588}
6589
6590static void broadwell_init_clock_gating(struct drm_device *dev)
6591{
6592        struct drm_i915_private *dev_priv = dev->dev_private;
6593        enum pipe pipe;
6594        uint32_t misccpctl;
6595
6596        ilk_init_lp_watermarks(dev);
6597
6598        /* WaSwitchSolVfFArbitrationPriority:bdw */
6599        I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6600
6601        /* WaPsrDPAMaskVBlankInSRD:bdw */
6602        I915_WRITE(CHICKEN_PAR1_1,
6603                   I915_READ(CHICKEN_PAR1_1) | DPA_MASK_VBLANK_SRD);
6604
6605        /* WaPsrDPRSUnmaskVBlankInSRD:bdw */
6606        for_each_pipe(dev_priv, pipe) {
6607                I915_WRITE(CHICKEN_PIPESL_1(pipe),
6608                           I915_READ(CHICKEN_PIPESL_1(pipe)) |
6609                           BDW_DPRS_MASK_VBLANK_SRD);
6610        }
6611
6612        /* WaVSRefCountFullforceMissDisable:bdw */
6613        /* WaDSRefCountFullforceMissDisable:bdw */
6614        I915_WRITE(GEN7_FF_THREAD_MODE,
6615                   I915_READ(GEN7_FF_THREAD_MODE) &
6616                   ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6617
6618        I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6619                   _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6620
6621        /* WaDisableSDEUnitClockGating:bdw */
6622        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6623                   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6624
6625        /*
6626         * WaProgramL3SqcReg1Default:bdw
6627         * WaTempDisableDOPClkGating:bdw
6628         */
6629        misccpctl = I915_READ(GEN7_MISCCPCTL);
6630        I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
6631        I915_WRITE(GEN8_L3SQCREG1, BDW_WA_L3SQCREG1_DEFAULT);
6632        /*
6633         * Wait at least 100 clocks before re-enabling clock gating. See
6634         * the definition of L3SQCREG1 in BSpec.
6635         */
6636        POSTING_READ(GEN8_L3SQCREG1);
6637        udelay(1);
6638        I915_WRITE(GEN7_MISCCPCTL, misccpctl);
6639
6640        /*
6641         * WaGttCachingOffByDefault:bdw
6642         * GTT cache may not work with big pages, so if those
6643         * are ever enabled GTT cache may need to be disabled.
6644         */
6645        I915_WRITE(HSW_GTT_CACHE_EN, GTT_CACHE_EN_ALL);
6646
6647        lpt_init_clock_gating(dev);
6648}
6649
6650static void haswell_init_clock_gating(struct drm_device *dev)
6651{
6652        struct drm_i915_private *dev_priv = dev->dev_private;
6653
6654        ilk_init_lp_watermarks(dev);
6655
6656        /* L3 caching of data atomics doesn't work -- disable it. */
6657        I915_WRITE(HSW_SCRATCH1, HSW_SCRATCH1_L3_DATA_ATOMICS_DISABLE);
6658        I915_WRITE(HSW_ROW_CHICKEN3,
6659                   _MASKED_BIT_ENABLE(HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE));
6660
6661        /* This is required by WaCatErrorRejectionIssue:hsw */
6662        I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6663                        I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6664                        GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6665
6666        /* WaVSRefCountFullforceMissDisable:hsw */
6667        I915_WRITE(GEN7_FF_THREAD_MODE,
6668                   I915_READ(GEN7_FF_THREAD_MODE) & ~GEN7_FF_VS_REF_CNT_FFME);
6669
6670        /* WaDisable_RenderCache_OperationalFlush:hsw */
6671        I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6672
6673        /* enable HiZ Raw Stall Optimization */
6674        I915_WRITE(CACHE_MODE_0_GEN7,
6675                   _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6676
6677        /* WaDisable4x2SubspanOptimization:hsw */
6678        I915_WRITE(CACHE_MODE_1,
6679                   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6680
6681        /*
6682         * BSpec recommends 8x4 when MSAA is used,
6683         * however in practice 16x4 seems fastest.
6684         *
6685         * Note that PS/WM thread counts depend on the WIZ hashing
6686         * disable bit, which we don't touch here, but it's good
6687         * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6688         */
6689        I915_WRITE(GEN7_GT_MODE,
6690                   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6691
6692        /* WaSampleCChickenBitEnable:hsw */
6693        I915_WRITE(HALF_SLICE_CHICKEN3,
6694                   _MASKED_BIT_ENABLE(HSW_SAMPLE_C_PERFORMANCE));
6695
6696        /* WaSwitchSolVfFArbitrationPriority:hsw */
6697        I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6698
6699        /* WaRsPkgCStateDisplayPMReq:hsw */
6700        I915_WRITE(CHICKEN_PAR1_1,
6701                   I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
6702
6703        lpt_init_clock_gating(dev);
6704}
6705
6706static void ivybridge_init_clock_gating(struct drm_device *dev)
6707{
6708        struct drm_i915_private *dev_priv = dev->dev_private;
6709        uint32_t snpcr;
6710
6711        ilk_init_lp_watermarks(dev);
6712
6713        I915_WRITE(ILK_DSPCLK_GATE_D, ILK_VRHUNIT_CLOCK_GATE_DISABLE);
6714
6715        /* WaDisableEarlyCull:ivb */
6716        I915_WRITE(_3D_CHICKEN3,
6717                   _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6718
6719        /* WaDisableBackToBackFlipFix:ivb */
6720        I915_WRITE(IVB_CHICKEN3,
6721                   CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6722                   CHICKEN3_DGMG_DONE_FIX_DISABLE);
6723
6724        /* WaDisablePSDDualDispatchEnable:ivb */
6725        if (IS_IVB_GT1(dev))
6726                I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6727                           _MASKED_BIT_ENABLE(GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6728
6729        /* WaDisable_RenderCache_OperationalFlush:ivb */
6730        I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6731
6732        /* Apply the WaDisableRHWOOptimizationForRenderHang:ivb workaround. */
6733        I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
6734                   GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
6735
6736        /* WaApplyL3ControlAndL3ChickenMode:ivb */
6737        I915_WRITE(GEN7_L3CNTLREG1,
6738                        GEN7_WA_FOR_GEN7_L3_CONTROL);
6739        I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
6740                   GEN7_WA_L3_CHICKEN_MODE);
6741        if (IS_IVB_GT1(dev))
6742                I915_WRITE(GEN7_ROW_CHICKEN2,
6743                           _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6744        else {
6745                /* must write both registers */
6746                I915_WRITE(GEN7_ROW_CHICKEN2,
6747                           _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6748                I915_WRITE(GEN7_ROW_CHICKEN2_GT2,
6749                           _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6750        }
6751
6752        /* WaForceL3Serialization:ivb */
6753        I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6754                   ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6755
6756        /*
6757         * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6758         * This implements the WaDisableRCZUnitClockGating:ivb workaround.
6759         */
6760        I915_WRITE(GEN6_UCGCTL2,
6761                   GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6762
6763        /* This is required by WaCatErrorRejectionIssue:ivb */
6764        I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6765                        I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6766                        GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6767
6768        g4x_disable_trickle_feed(dev);
6769
6770        gen7_setup_fixed_func_scheduler(dev_priv);
6771
6772        if (0) { /* causes HiZ corruption on ivb:gt1 */
6773                /* enable HiZ Raw Stall Optimization */
6774                I915_WRITE(CACHE_MODE_0_GEN7,
6775                           _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6776        }
6777
6778        /* WaDisable4x2SubspanOptimization:ivb */
6779        I915_WRITE(CACHE_MODE_1,
6780                   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6781
6782        /*
6783         * BSpec recommends 8x4 when MSAA is used,
6784         * however in practice 16x4 seems fastest.
6785         *
6786         * Note that PS/WM thread counts depend on the WIZ hashing
6787         * disable bit, which we don't touch here, but it's good
6788         * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6789         */
6790        I915_WRITE(GEN7_GT_MODE,
6791                   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6792
6793        snpcr = I915_READ(GEN6_MBCUNIT_SNPCR);
6794        snpcr &= ~GEN6_MBC_SNPCR_MASK;
6795        snpcr |= GEN6_MBC_SNPCR_MED;
6796        I915_WRITE(GEN6_MBCUNIT_SNPCR, snpcr);
6797
6798        if (!HAS_PCH_NOP(dev))
6799                cpt_init_clock_gating(dev);
6800
6801        gen6_check_mch_setup(dev);
6802}
6803
6804static void vlv_init_display_clock_gating(struct drm_i915_private *dev_priv)
6805{
6806        u32 val;
6807
6808        /*
6809        * On driver load, a pipe may be active and driving a DSI display.
6810        * Preserve DPOUNIT_CLOCK_GATE_DISABLE to avoid the pipe getting stuck
6811        * (and never recovering) in this case. intel_dsi_post_disable() will
6812        * clear it when we turn off the display.
6813        */
6814        val = I915_READ(DSPCLK_GATE_D);
6815        val &= DPOUNIT_CLOCK_GATE_DISABLE;
6816        val |= VRHUNIT_CLOCK_GATE_DISABLE;
6817        I915_WRITE(DSPCLK_GATE_D, val);
6818
6819        /*
6820         * Disable trickle feed and enable pnd deadline calculation
6821         */
6822        I915_WRITE(MI_ARB_VLV, MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE);
6823        I915_WRITE(CBR1_VLV, 0);
6824}
6825
6826static void valleyview_init_clock_gating(struct drm_device *dev)
6827{
6828        struct drm_i915_private *dev_priv = dev->dev_private;
6829
6830        vlv_init_display_clock_gating(dev_priv);
6831
6832        /* WaDisableEarlyCull:vlv */
6833        I915_WRITE(_3D_CHICKEN3,
6834                   _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6835
6836        /* WaDisableBackToBackFlipFix:vlv */
6837        I915_WRITE(IVB_CHICKEN3,
6838                   CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6839                   CHICKEN3_DGMG_DONE_FIX_DISABLE);
6840
6841        /* WaPsdDispatchEnable:vlv */
6842        /* WaDisablePSDDualDispatchEnable:vlv */
6843        I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6844                   _MASKED_BIT_ENABLE(GEN7_MAX_PS_THREAD_DEP |
6845                                      GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6846
6847        /* WaDisable_RenderCache_OperationalFlush:vlv */
6848        I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6849
6850        /* WaForceL3Serialization:vlv */
6851        I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6852                   ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6853
6854        /* WaDisableDopClockGating:vlv */
6855        I915_WRITE(GEN7_ROW_CHICKEN2,
6856                   _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6857
6858        /* This is required by WaCatErrorRejectionIssue:vlv */
6859        I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6860                   I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6861                   GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6862
6863        gen7_setup_fixed_func_scheduler(dev_priv);
6864
6865        /*
6866         * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6867         * This implements the WaDisableRCZUnitClockGating:vlv workaround.
6868         */
6869        I915_WRITE(GEN6_UCGCTL2,
6870                   GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6871
6872        /* WaDisableL3Bank2xClockGate:vlv
6873         * Disabling L3 clock gating- MMIO 940c[25] = 1
6874         * Set bit 25, to disable L3_BANK_2x_CLK_GATING */
6875        I915_WRITE(GEN7_UCGCTL4,
6876                   I915_READ(GEN7_UCGCTL4) | GEN7_L3BANK2X_CLOCK_GATE_DISABLE);
6877
6878        /*
6879         * BSpec says this must be set, even though
6880         * WaDisable4x2SubspanOptimization isn't listed for VLV.
6881         */
6882        I915_WRITE(CACHE_MODE_1,
6883                   _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6884
6885        /*
6886         * BSpec recommends 8x4 when MSAA is used,
6887         * however in practice 16x4 seems fastest.
6888         *
6889         * Note that PS/WM thread counts depend on the WIZ hashing
6890         * disable bit, which we don't touch here, but it's good
6891         * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6892         */
6893        I915_WRITE(GEN7_GT_MODE,
6894                   _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6895
6896        /*
6897         * WaIncreaseL3CreditsForVLVB0:vlv
6898         * This is the hardware default actually.
6899         */
6900        I915_WRITE(GEN7_L3SQCREG1, VLV_B0_WA_L3SQCREG1_VALUE);
6901
6902        /*
6903         * WaDisableVLVClockGating_VBIIssue:vlv
6904         * Disable clock gating on th GCFG unit to prevent a delay
6905         * in the reporting of vblank events.
6906         */
6907        I915_WRITE(VLV_GUNIT_CLOCK_GATE, GCFG_DIS);
6908}
6909
6910static void cherryview_init_clock_gating(struct drm_device *dev)
6911{
6912        struct drm_i915_private *dev_priv = dev->dev_private;
6913
6914        vlv_init_display_clock_gating(dev_priv);
6915
6916        /* WaVSRefCountFullforceMissDisable:chv */
6917        /* WaDSRefCountFullforceMissDisable:chv */
6918        I915_WRITE(GEN7_FF_THREAD_MODE,
6919                   I915_READ(GEN7_FF_THREAD_MODE) &
6920                   ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6921
6922        /* WaDisableSemaphoreAndSyncFlipWait:chv */
6923        I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6924                   _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6925
6926        /* WaDisableCSUnitClockGating:chv */
6927        I915_WRITE(GEN6_UCGCTL1, I915_READ(GEN6_UCGCTL1) |
6928                   GEN6_CSUNIT_CLOCK_GATE_DISABLE);
6929
6930        /* WaDisableSDEUnitClockGating:chv */
6931        I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6932                   GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6933
6934        /*
6935         * GTT cache may not work with big pages, so if those
6936         * are ever enabled GTT cache may need to be disabled.
6937         */
6938        I915_WRITE(HSW_GTT_CACHE_EN, GTT_CACHE_EN_ALL);
6939}
6940
6941static void g4x_init_clock_gating(struct drm_device *dev)
6942{
6943        struct drm_i915_private *dev_priv = dev->dev_private;
6944        uint32_t dspclk_gate;
6945
6946        I915_WRITE(RENCLK_GATE_D1, 0);
6947        I915_WRITE(RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
6948                   GS_UNIT_CLOCK_GATE_DISABLE |
6949                   CL_UNIT_CLOCK_GATE_DISABLE);
6950        I915_WRITE(RAMCLK_GATE_D, 0);
6951        dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
6952                OVRUNIT_CLOCK_GATE_DISABLE |
6953                OVCUNIT_CLOCK_GATE_DISABLE;
6954        if (IS_GM45(dev))
6955                dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
6956        I915_WRITE(DSPCLK_GATE_D, dspclk_gate);
6957
6958        /* WaDisableRenderCachePipelinedFlush */
6959        I915_WRITE(CACHE_MODE_0,
6960                   _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
6961
6962        /* WaDisable_RenderCache_OperationalFlush:g4x */
6963        I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6964
6965        g4x_disable_trickle_feed(dev);
6966}
6967
6968static void crestline_init_clock_gating(struct drm_device *dev)
6969{
6970        struct drm_i915_private *dev_priv = dev->dev_private;
6971
6972        I915_WRITE(RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
6973        I915_WRITE(RENCLK_GATE_D2, 0);
6974        I915_WRITE(DSPCLK_GATE_D, 0);
6975        I915_WRITE(RAMCLK_GATE_D, 0);
6976        I915_WRITE16(DEUC, 0);
6977        I915_WRITE(MI_ARB_STATE,
6978                   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
6979
6980        /* WaDisable_RenderCache_OperationalFlush:gen4 */
6981        I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6982}
6983
6984static void broadwater_init_clock_gating(struct drm_device *dev)
6985{
6986        struct drm_i915_private *dev_priv = dev->dev_private;
6987
6988        I915_WRITE(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
6989                   I965_RCC_CLOCK_GATE_DISABLE |
6990                   I965_RCPB_CLOCK_GATE_DISABLE |
6991                   I965_ISC_CLOCK_GATE_DISABLE |
6992                   I965_FBC_CLOCK_GATE_DISABLE);
6993        I915_WRITE(RENCLK_GATE_D2, 0);
6994        I915_WRITE(MI_ARB_STATE,
6995                   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
6996
6997        /* WaDisable_RenderCache_OperationalFlush:gen4 */
6998        I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6999}
7000
7001static void gen3_init_clock_gating(struct drm_device *dev)
7002{
7003        struct drm_i915_private *dev_priv = dev->dev_private;
7004        u32 dstate = I915_READ(D_STATE);
7005
7006        dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
7007                DSTATE_DOT_CLOCK_GATING;
7008        I915_WRITE(D_STATE, dstate);
7009
7010        if (IS_PINEVIEW(dev))
7011                I915_WRITE(ECOSKPD, _MASKED_BIT_ENABLE(ECO_GATING_CX_ONLY));
7012
7013        /* IIR "flip pending" means done if this bit is set */
7014        I915_WRITE(ECOSKPD, _MASKED_BIT_DISABLE(ECO_FLIP_DONE));
7015
7016        /* interrupts should cause a wake up from C3 */
7017        I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_AGPBUSY_INT_EN));
7018
7019        /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
7020        I915_WRITE(MI_ARB_STATE, _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
7021
7022        I915_WRITE(MI_ARB_STATE,
7023                   _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
7024}
7025
7026static void i85x_init_clock_gating(struct drm_device *dev)
7027{
7028        struct drm_i915_private *dev_priv = dev->dev_private;
7029
7030        I915_WRITE(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
7031
7032        /* interrupts should cause a wake up from C3 */
7033        I915_WRITE(MI_STATE, _MASKED_BIT_ENABLE(MI_AGPBUSY_INT_EN) |
7034                   _MASKED_BIT_DISABLE(MI_AGPBUSY_830_MODE));
7035
7036        I915_WRITE(MEM_MODE,
7037                   _MASKED_BIT_ENABLE(MEM_DISPLAY_TRICKLE_FEED_DISABLE));
7038}
7039
7040static void i830_init_clock_gating(struct drm_device *dev)
7041{
7042        struct drm_i915_private *dev_priv = dev->dev_private;
7043
7044        I915_WRITE(DSPCLK_GATE_D, OVRUNIT_CLOCK_GATE_DISABLE);
7045
7046        I915_WRITE(MEM_MODE,
7047                   _MASKED_BIT_ENABLE(MEM_DISPLAY_A_TRICKLE_FEED_DISABLE) |
7048                   _MASKED_BIT_ENABLE(MEM_DISPLAY_B_TRICKLE_FEED_DISABLE));
7049}
7050
7051void intel_init_clock_gating(struct drm_device *dev)
7052{
7053        struct drm_i915_private *dev_priv = dev->dev_private;
7054
7055        if (dev_priv->display.init_clock_gating)
7056                dev_priv->display.init_clock_gating(dev);
7057}
7058
7059void intel_suspend_hw(struct drm_device *dev)
7060{
7061        if (HAS_PCH_LPT(dev))
7062                lpt_suspend_hw(dev);
7063}
7064
7065/* Set up chip specific power management-related functions */
7066void intel_init_pm(struct drm_device *dev)
7067{
7068        struct drm_i915_private *dev_priv = dev->dev_private;
7069
7070        intel_fbc_init(dev_priv);
7071
7072        /* For cxsr */
7073        if (IS_PINEVIEW(dev))
7074                i915_pineview_get_mem_freq(dev);
7075        else if (IS_GEN5(dev))
7076                i915_ironlake_get_mem_freq(dev);
7077
7078        /* For FIFO watermark updates */
7079        if (INTEL_INFO(dev)->gen >= 9) {
7080                skl_setup_wm_latency(dev);
7081
7082                if (IS_BROXTON(dev))
7083                        dev_priv->display.init_clock_gating =
7084                                bxt_init_clock_gating;
7085                dev_priv->display.update_wm = skl_update_wm;
7086                dev_priv->display.update_sprite_wm = skl_update_sprite_wm;
7087        } else if (HAS_PCH_SPLIT(dev)) {
7088                ilk_setup_wm_latency(dev);
7089
7090                if ((IS_GEN5(dev) && dev_priv->wm.pri_latency[1] &&
7091                     dev_priv->wm.spr_latency[1] && dev_priv->wm.cur_latency[1]) ||
7092                    (!IS_GEN5(dev) && dev_priv->wm.pri_latency[0] &&
7093                     dev_priv->wm.spr_latency[0] && dev_priv->wm.cur_latency[0])) {
7094                        dev_priv->display.update_wm = ilk_update_wm;
7095                        dev_priv->display.update_sprite_wm = ilk_update_sprite_wm;
7096                } else {
7097                        DRM_DEBUG_KMS("Failed to read display plane latency. "
7098                                      "Disable CxSR\n");
7099                }
7100
7101                if (IS_GEN5(dev))
7102                        dev_priv->display.init_clock_gating = ironlake_init_clock_gating;
7103                else if (IS_GEN6(dev))
7104                        dev_priv->display.init_clock_gating = gen6_init_clock_gating;
7105                else if (IS_IVYBRIDGE(dev))
7106                        dev_priv->display.init_clock_gating = ivybridge_init_clock_gating;
7107                else if (IS_HASWELL(dev))
7108                        dev_priv->display.init_clock_gating = haswell_init_clock_gating;
7109                else if (INTEL_INFO(dev)->gen == 8)
7110                        dev_priv->display.init_clock_gating = broadwell_init_clock_gating;
7111        } else if (IS_CHERRYVIEW(dev)) {
7112                vlv_setup_wm_latency(dev);
7113
7114                dev_priv->display.update_wm = vlv_update_wm;
7115                dev_priv->display.init_clock_gating =
7116                        cherryview_init_clock_gating;
7117        } else if (IS_VALLEYVIEW(dev)) {
7118                vlv_setup_wm_latency(dev);
7119
7120                dev_priv->display.update_wm = vlv_update_wm;
7121                dev_priv->display.init_clock_gating =
7122                        valleyview_init_clock_gating;
7123        } else if (IS_PINEVIEW(dev)) {
7124                if (!intel_get_cxsr_latency(IS_PINEVIEW_G(dev),
7125                                            dev_priv->is_ddr3,
7126                                            dev_priv->fsb_freq,
7127                                            dev_priv->mem_freq)) {
7128                        DRM_INFO("failed to find known CxSR latency "
7129                                 "(found ddr%s fsb freq %d, mem freq %d), "
7130                                 "disabling CxSR\n",
7131                                 (dev_priv->is_ddr3 == 1) ? "3" : "2",
7132                                 dev_priv->fsb_freq, dev_priv->mem_freq);
7133                        /* Disable CxSR and never update its watermark again */
7134                        intel_set_memory_cxsr(dev_priv, false);
7135                        dev_priv->display.update_wm = NULL;
7136                } else
7137                        dev_priv->display.update_wm = pineview_update_wm;
7138                dev_priv->display.init_clock_gating = gen3_init_clock_gating;
7139        } else if (IS_G4X(dev)) {
7140                dev_priv->display.update_wm = g4x_update_wm;
7141                dev_priv->display.init_clock_gating = g4x_init_clock_gating;
7142        } else if (IS_GEN4(dev)) {
7143                dev_priv->display.update_wm = i965_update_wm;
7144                if (IS_CRESTLINE(dev))
7145                        dev_priv->display.init_clock_gating = crestline_init_clock_gating;
7146                else if (IS_BROADWATER(dev))
7147                        dev_priv->display.init_clock_gating = broadwater_init_clock_gating;
7148        } else if (IS_GEN3(dev)) {
7149                dev_priv->display.update_wm = i9xx_update_wm;
7150                dev_priv->display.get_fifo_size = i9xx_get_fifo_size;
7151                dev_priv->display.init_clock_gating = gen3_init_clock_gating;
7152        } else if (IS_GEN2(dev)) {
7153                if (INTEL_INFO(dev)->num_pipes == 1) {
7154                        dev_priv->display.update_wm = i845_update_wm;
7155                        dev_priv->display.get_fifo_size = i845_get_fifo_size;
7156                } else {
7157                        dev_priv->display.update_wm = i9xx_update_wm;
7158                        dev_priv->display.get_fifo_size = i830_get_fifo_size;
7159                }
7160
7161                if (IS_I85X(dev) || IS_I865G(dev))
7162                        dev_priv->display.init_clock_gating = i85x_init_clock_gating;
7163                else
7164                        dev_priv->display.init_clock_gating = i830_init_clock_gating;
7165        } else {
7166                DRM_ERROR("unexpected fall-through in intel_init_pm\n");
7167        }
7168}
7169
7170int sandybridge_pcode_read(struct drm_i915_private *dev_priv, u32 mbox, u32 *val)
7171{
7172        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
7173
7174        if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
7175                DRM_DEBUG_DRIVER("warning: pcode (read) mailbox access failed\n");
7176                return -EAGAIN;
7177        }
7178
7179        I915_WRITE(GEN6_PCODE_DATA, *val);
7180        I915_WRITE(GEN6_PCODE_DATA1, 0);
7181        I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
7182
7183        if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
7184                     500)) {
7185                DRM_ERROR("timeout waiting for pcode read (%d) to finish\n", mbox);
7186                return -ETIMEDOUT;
7187        }
7188
7189        *val = I915_READ(GEN6_PCODE_DATA);
7190        I915_WRITE(GEN6_PCODE_DATA, 0);
7191
7192        return 0;
7193}
7194
7195int sandybridge_pcode_write(struct drm_i915_private *dev_priv, u32 mbox, u32 val)
7196{
7197        WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
7198
7199        if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
7200                DRM_DEBUG_DRIVER("warning: pcode (write) mailbox access failed\n");
7201                return -EAGAIN;
7202        }
7203
7204        I915_WRITE(GEN6_PCODE_DATA, val);
7205        I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
7206
7207        if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
7208                     500)) {
7209                DRM_ERROR("timeout waiting for pcode write (%d) to finish\n", mbox);
7210                return -ETIMEDOUT;
7211        }
7212
7213        I915_WRITE(GEN6_PCODE_DATA, 0);
7214
7215        return 0;
7216}
7217
7218static int vlv_gpu_freq_div(unsigned int czclk_freq)
7219{
7220        switch (czclk_freq) {
7221        case 200:
7222                return 10;
7223        case 267:
7224                return 12;
7225        case 320:
7226        case 333:
7227                return 16;
7228        case 400:
7229                return 20;
7230        default:
7231                return -1;
7232        }
7233}
7234
7235static int byt_gpu_freq(struct drm_i915_private *dev_priv, int val)
7236{
7237        int div, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->czclk_freq, 1000);
7238
7239        div = vlv_gpu_freq_div(czclk_freq);
7240        if (div < 0)
7241                return div;
7242
7243        return DIV_ROUND_CLOSEST(czclk_freq * (val + 6 - 0xbd), div);
7244}
7245
7246static int byt_freq_opcode(struct drm_i915_private *dev_priv, int val)
7247{
7248        int mul, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->czclk_freq, 1000);
7249
7250        mul = vlv_gpu_freq_div(czclk_freq);
7251        if (mul < 0)
7252                return mul;
7253
7254        return DIV_ROUND_CLOSEST(mul * val, czclk_freq) + 0xbd - 6;
7255}
7256
7257static int chv_gpu_freq(struct drm_i915_private *dev_priv, int val)
7258{
7259        int div, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->czclk_freq, 1000);
7260
7261        div = vlv_gpu_freq_div(czclk_freq) / 2;
7262        if (div < 0)
7263                return div;
7264
7265        return DIV_ROUND_CLOSEST(czclk_freq * val, 2 * div) / 2;
7266}
7267
7268static int chv_freq_opcode(struct drm_i915_private *dev_priv, int val)
7269{
7270        int mul, czclk_freq = DIV_ROUND_CLOSEST(dev_priv->czclk_freq, 1000);
7271
7272        mul = vlv_gpu_freq_div(czclk_freq) / 2;
7273        if (mul < 0)
7274                return mul;
7275
7276        /* CHV needs even values */
7277        return DIV_ROUND_CLOSEST(val * 2 * mul, czclk_freq) * 2;
7278}
7279
7280int intel_gpu_freq(struct drm_i915_private *dev_priv, int val)
7281{
7282        if (IS_GEN9(dev_priv->dev))
7283                return DIV_ROUND_CLOSEST(val * GT_FREQUENCY_MULTIPLIER,
7284                                         GEN9_FREQ_SCALER);
7285        else if (IS_CHERRYVIEW(dev_priv->dev))
7286                return chv_gpu_freq(dev_priv, val);
7287        else if (IS_VALLEYVIEW(dev_priv->dev))
7288                return byt_gpu_freq(dev_priv, val);
7289        else
7290                return val * GT_FREQUENCY_MULTIPLIER;
7291}
7292
7293int intel_freq_opcode(struct drm_i915_private *dev_priv, int val)
7294{
7295        if (IS_GEN9(dev_priv->dev))
7296                return DIV_ROUND_CLOSEST(val * GEN9_FREQ_SCALER,
7297                                         GT_FREQUENCY_MULTIPLIER);
7298        else if (IS_CHERRYVIEW(dev_priv->dev))
7299                return chv_freq_opcode(dev_priv, val);
7300        else if (IS_VALLEYVIEW(dev_priv->dev))
7301                return byt_freq_opcode(dev_priv, val);
7302        else
7303                return DIV_ROUND_CLOSEST(val, GT_FREQUENCY_MULTIPLIER);
7304}
7305
7306struct request_boost {
7307        struct work_struct work;
7308        struct drm_i915_gem_request *req;
7309};
7310
7311static void __intel_rps_boost_work(struct work_struct *work)
7312{
7313        struct request_boost *boost = container_of(work, struct request_boost, work);
7314        struct drm_i915_gem_request *req = boost->req;
7315
7316        if (!i915_gem_request_completed(req, true))
7317                gen6_rps_boost(to_i915(req->ring->dev), NULL,
7318                               req->emitted_jiffies);
7319
7320        i915_gem_request_unreference__unlocked(req);
7321        kfree(boost);
7322}
7323
7324void intel_queue_rps_boost_for_request(struct drm_device *dev,
7325                                       struct drm_i915_gem_request *req)
7326{
7327        struct request_boost *boost;
7328
7329        if (req == NULL || INTEL_INFO(dev)->gen < 6)
7330                return;
7331
7332        if (i915_gem_request_completed(req, true))
7333                return;
7334
7335        boost = kmalloc(sizeof(*boost), GFP_ATOMIC);
7336        if (boost == NULL)
7337                return;
7338
7339        i915_gem_request_reference(req);
7340        boost->req = req;
7341
7342        INIT_WORK(&boost->work, __intel_rps_boost_work);
7343        queue_work(to_i915(dev)->wq, &boost->work);
7344}
7345
7346void intel_pm_setup(struct drm_device *dev)
7347{
7348        struct drm_i915_private *dev_priv = dev->dev_private;
7349
7350        mutex_init(&dev_priv->rps.hw_lock);
7351        spin_lock_init(&dev_priv->rps.client_lock);
7352
7353        INIT_DELAYED_WORK(&dev_priv->rps.delayed_resume_work,
7354                          intel_gen6_powersave_work);
7355        INIT_LIST_HEAD(&dev_priv->rps.clients);
7356        INIT_LIST_HEAD(&dev_priv->rps.semaphores.link);
7357        INIT_LIST_HEAD(&dev_priv->rps.mmioflips.link);
7358
7359        dev_priv->pm.suspended = false;
7360}
Note: See TracBrowser for help on using the repository browser.