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