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