Revert "drm/i915/skl: New ddb allocation algorithm"
[muen/linux.git] / drivers / gpu / drm / i915 / intel_pm.c
1 /*
2  * Copyright © 2012 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eugeni Dodonov <eugeni.dodonov@intel.com>
25  *
26  */
27
28 #include <linux/cpufreq.h>
29 #include <drm/drm_plane_helper.h>
30 #include "i915_drv.h"
31 #include "intel_drv.h"
32 #include "../../../platform/x86/intel_ips.h"
33 #include <linux/module.h>
34 #include <drm/drm_atomic_helper.h>
35
36 /**
37  * DOC: RC6
38  *
39  * RC6 is a special power stage which allows the GPU to enter an very
40  * low-voltage mode when idle, using down to 0V while at this stage.  This
41  * stage is entered automatically when the GPU is idle when RC6 support is
42  * enabled, and as soon as new workload arises GPU wakes up automatically as well.
43  *
44  * There are different RC6 modes available in Intel GPU, which differentiate
45  * among each other with the latency required to enter and leave RC6 and
46  * voltage consumed by the GPU in different states.
47  *
48  * The combination of the following flags define which states GPU is allowed
49  * to enter, while RC6 is the normal RC6 state, RC6p is the deep RC6, and
50  * RC6pp is deepest RC6. Their support by hardware varies according to the
51  * GPU, BIOS, chipset and platform. RC6 is usually the safest one and the one
52  * which brings the most power savings; deeper states save more power, but
53  * require higher latency to switch to and wake up.
54  */
55 #define INTEL_RC6_ENABLE                        (1<<0)
56 #define INTEL_RC6p_ENABLE                       (1<<1)
57 #define INTEL_RC6pp_ENABLE                      (1<<2)
58
59 static void gen9_init_clock_gating(struct drm_i915_private *dev_priv)
60 {
61         /* See Bspec note for PSR2_CTL bit 31, Wa#828:skl,bxt,kbl,cfl */
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,cfl */
69         I915_WRITE(GEN8_CHICKEN_DCPR_1,
70                    I915_READ(GEN8_CHICKEN_DCPR_1) | MASK_WAKEMEM);
71
72         /* WaFbcTurnOffFbcWatermark:skl,bxt,kbl,cfl */
73         /* WaFbcWakeMemOn:skl,bxt,kbl,glk,cfl */
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,cfl */
79         I915_WRITE(ILK_DPFC_CHICKEN, I915_READ(ILK_DPFC_CHICKEN) |
80                    ILK_DPFC_DISABLE_DUMMY0);
81 }
82
83 static void bxt_init_clock_gating(struct drm_i915_private *dev_priv)
84 {
85         gen9_init_clock_gating(dev_priv);
86
87         /* WaDisableSDEUnitClockGating:bxt */
88         I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
89                    GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
90
91         /*
92          * FIXME:
93          * GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ applies on 3x6 GT SKUs only.
94          */
95         I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
96                    GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ);
97
98         /*
99          * Wa: Backlight PWM may stop in the asserted state, causing backlight
100          * to stay fully on.
101          */
102         I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
103                    PWM1_GATING_DIS | PWM2_GATING_DIS);
104 }
105
106 static void glk_init_clock_gating(struct drm_i915_private *dev_priv)
107 {
108         gen9_init_clock_gating(dev_priv);
109
110         /*
111          * WaDisablePWMClockGating:glk
112          * Backlight PWM may stop in the asserted state, causing backlight
113          * to stay fully on.
114          */
115         I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
116                    PWM1_GATING_DIS | PWM2_GATING_DIS);
117
118         /* WaDDIIOTimeout:glk */
119         if (IS_GLK_REVID(dev_priv, 0, GLK_REVID_A1)) {
120                 u32 val = I915_READ(CHICKEN_MISC_2);
121                 val &= ~(GLK_CL0_PWR_DOWN |
122                          GLK_CL1_PWR_DOWN |
123                          GLK_CL2_PWR_DOWN);
124                 I915_WRITE(CHICKEN_MISC_2, val);
125         }
126
127 }
128
129 static void i915_pineview_get_mem_freq(struct drm_i915_private *dev_priv)
130 {
131         u32 tmp;
132
133         tmp = I915_READ(CLKCFG);
134
135         switch (tmp & CLKCFG_FSB_MASK) {
136         case CLKCFG_FSB_533:
137                 dev_priv->fsb_freq = 533; /* 133*4 */
138                 break;
139         case CLKCFG_FSB_800:
140                 dev_priv->fsb_freq = 800; /* 200*4 */
141                 break;
142         case CLKCFG_FSB_667:
143                 dev_priv->fsb_freq =  667; /* 167*4 */
144                 break;
145         case CLKCFG_FSB_400:
146                 dev_priv->fsb_freq = 400; /* 100*4 */
147                 break;
148         }
149
150         switch (tmp & CLKCFG_MEM_MASK) {
151         case CLKCFG_MEM_533:
152                 dev_priv->mem_freq = 533;
153                 break;
154         case CLKCFG_MEM_667:
155                 dev_priv->mem_freq = 667;
156                 break;
157         case CLKCFG_MEM_800:
158                 dev_priv->mem_freq = 800;
159                 break;
160         }
161
162         /* detect pineview DDR3 setting */
163         tmp = I915_READ(CSHRDDR3CTL);
164         dev_priv->is_ddr3 = (tmp & CSHRDDR3CTL_DDR3) ? 1 : 0;
165 }
166
167 static void i915_ironlake_get_mem_freq(struct drm_i915_private *dev_priv)
168 {
169         u16 ddrpll, csipll;
170
171         ddrpll = I915_READ16(DDRMPLL1);
172         csipll = I915_READ16(CSIPLL0);
173
174         switch (ddrpll & 0xff) {
175         case 0xc:
176                 dev_priv->mem_freq = 800;
177                 break;
178         case 0x10:
179                 dev_priv->mem_freq = 1066;
180                 break;
181         case 0x14:
182                 dev_priv->mem_freq = 1333;
183                 break;
184         case 0x18:
185                 dev_priv->mem_freq = 1600;
186                 break;
187         default:
188                 DRM_DEBUG_DRIVER("unknown memory frequency 0x%02x\n",
189                                  ddrpll & 0xff);
190                 dev_priv->mem_freq = 0;
191                 break;
192         }
193
194         dev_priv->ips.r_t = dev_priv->mem_freq;
195
196         switch (csipll & 0x3ff) {
197         case 0x00c:
198                 dev_priv->fsb_freq = 3200;
199                 break;
200         case 0x00e:
201                 dev_priv->fsb_freq = 3733;
202                 break;
203         case 0x010:
204                 dev_priv->fsb_freq = 4266;
205                 break;
206         case 0x012:
207                 dev_priv->fsb_freq = 4800;
208                 break;
209         case 0x014:
210                 dev_priv->fsb_freq = 5333;
211                 break;
212         case 0x016:
213                 dev_priv->fsb_freq = 5866;
214                 break;
215         case 0x018:
216                 dev_priv->fsb_freq = 6400;
217                 break;
218         default:
219                 DRM_DEBUG_DRIVER("unknown fsb frequency 0x%04x\n",
220                                  csipll & 0x3ff);
221                 dev_priv->fsb_freq = 0;
222                 break;
223         }
224
225         if (dev_priv->fsb_freq == 3200) {
226                 dev_priv->ips.c_m = 0;
227         } else if (dev_priv->fsb_freq > 3200 && dev_priv->fsb_freq <= 4800) {
228                 dev_priv->ips.c_m = 1;
229         } else {
230                 dev_priv->ips.c_m = 2;
231         }
232 }
233
234 static const struct cxsr_latency cxsr_latency_table[] = {
235         {1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
236         {1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
237         {1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
238         {1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
239         {1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
240
241         {1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
242         {1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
243         {1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
244         {1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
245         {1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
246
247         {1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
248         {1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
249         {1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
250         {1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
251         {1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
252
253         {0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
254         {0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
255         {0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
256         {0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
257         {0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
258
259         {0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
260         {0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
261         {0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
262         {0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
263         {0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
264
265         {0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
266         {0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
267         {0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
268         {0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
269         {0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
270 };
271
272 static const struct cxsr_latency *intel_get_cxsr_latency(bool is_desktop,
273                                                          bool is_ddr3,
274                                                          int fsb,
275                                                          int mem)
276 {
277         const struct cxsr_latency *latency;
278         int i;
279
280         if (fsb == 0 || mem == 0)
281                 return NULL;
282
283         for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
284                 latency = &cxsr_latency_table[i];
285                 if (is_desktop == latency->is_desktop &&
286                     is_ddr3 == latency->is_ddr3 &&
287                     fsb == latency->fsb_freq && mem == latency->mem_freq)
288                         return latency;
289         }
290
291         DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
292
293         return NULL;
294 }
295
296 static void chv_set_memory_dvfs(struct drm_i915_private *dev_priv, bool enable)
297 {
298         u32 val;
299
300         mutex_lock(&dev_priv->rps.hw_lock);
301
302         val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
303         if (enable)
304                 val &= ~FORCE_DDR_HIGH_FREQ;
305         else
306                 val |= FORCE_DDR_HIGH_FREQ;
307         val &= ~FORCE_DDR_LOW_FREQ;
308         val |= FORCE_DDR_FREQ_REQ_ACK;
309         vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
310
311         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
312                       FORCE_DDR_FREQ_REQ_ACK) == 0, 3))
313                 DRM_ERROR("timed out waiting for Punit DDR DVFS request\n");
314
315         mutex_unlock(&dev_priv->rps.hw_lock);
316 }
317
318 static void chv_set_memory_pm5(struct drm_i915_private *dev_priv, bool enable)
319 {
320         u32 val;
321
322         mutex_lock(&dev_priv->rps.hw_lock);
323
324         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
325         if (enable)
326                 val |= DSP_MAXFIFO_PM5_ENABLE;
327         else
328                 val &= ~DSP_MAXFIFO_PM5_ENABLE;
329         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
330
331         mutex_unlock(&dev_priv->rps.hw_lock);
332 }
333
334 #define FW_WM(value, plane) \
335         (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK)
336
337 static bool _intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
338 {
339         bool was_enabled;
340         u32 val;
341
342         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
343                 was_enabled = I915_READ(FW_BLC_SELF_VLV) & FW_CSPWRDWNEN;
344                 I915_WRITE(FW_BLC_SELF_VLV, enable ? FW_CSPWRDWNEN : 0);
345                 POSTING_READ(FW_BLC_SELF_VLV);
346         } else if (IS_G4X(dev_priv) || IS_I965GM(dev_priv)) {
347                 was_enabled = I915_READ(FW_BLC_SELF) & FW_BLC_SELF_EN;
348                 I915_WRITE(FW_BLC_SELF, enable ? FW_BLC_SELF_EN : 0);
349                 POSTING_READ(FW_BLC_SELF);
350         } else if (IS_PINEVIEW(dev_priv)) {
351                 val = I915_READ(DSPFW3);
352                 was_enabled = val & PINEVIEW_SELF_REFRESH_EN;
353                 if (enable)
354                         val |= PINEVIEW_SELF_REFRESH_EN;
355                 else
356                         val &= ~PINEVIEW_SELF_REFRESH_EN;
357                 I915_WRITE(DSPFW3, val);
358                 POSTING_READ(DSPFW3);
359         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv)) {
360                 was_enabled = I915_READ(FW_BLC_SELF) & FW_BLC_SELF_EN;
361                 val = enable ? _MASKED_BIT_ENABLE(FW_BLC_SELF_EN) :
362                                _MASKED_BIT_DISABLE(FW_BLC_SELF_EN);
363                 I915_WRITE(FW_BLC_SELF, val);
364                 POSTING_READ(FW_BLC_SELF);
365         } else if (IS_I915GM(dev_priv)) {
366                 /*
367                  * FIXME can't find a bit like this for 915G, and
368                  * and yet it does have the related watermark in
369                  * FW_BLC_SELF. What's going on?
370                  */
371                 was_enabled = I915_READ(INSTPM) & INSTPM_SELF_EN;
372                 val = enable ? _MASKED_BIT_ENABLE(INSTPM_SELF_EN) :
373                                _MASKED_BIT_DISABLE(INSTPM_SELF_EN);
374                 I915_WRITE(INSTPM, val);
375                 POSTING_READ(INSTPM);
376         } else {
377                 return false;
378         }
379
380         trace_intel_memory_cxsr(dev_priv, was_enabled, enable);
381
382         DRM_DEBUG_KMS("memory self-refresh is %s (was %s)\n",
383                       enableddisabled(enable),
384                       enableddisabled(was_enabled));
385
386         return was_enabled;
387 }
388
389 /**
390  * intel_set_memory_cxsr - Configure CxSR state
391  * @dev_priv: i915 device
392  * @enable: Allow vs. disallow CxSR
393  *
394  * Allow or disallow the system to enter a special CxSR
395  * (C-state self refresh) state. What typically happens in CxSR mode
396  * is that several display FIFOs may get combined into a single larger
397  * FIFO for a particular plane (so called max FIFO mode) to allow the
398  * system to defer memory fetches longer, and the memory will enter
399  * self refresh.
400  *
401  * Note that enabling CxSR does not guarantee that the system enter
402  * this special mode, nor does it guarantee that the system stays
403  * in that mode once entered. So this just allows/disallows the system
404  * to autonomously utilize the CxSR mode. Other factors such as core
405  * C-states will affect when/if the system actually enters/exits the
406  * CxSR mode.
407  *
408  * Note that on VLV/CHV this actually only controls the max FIFO mode,
409  * and the system is free to enter/exit memory self refresh at any time
410  * even when the use of CxSR has been disallowed.
411  *
412  * While the system is actually in the CxSR/max FIFO mode, some plane
413  * control registers will not get latched on vblank. Thus in order to
414  * guarantee the system will respond to changes in the plane registers
415  * we must always disallow CxSR prior to making changes to those registers.
416  * Unfortunately the system will re-evaluate the CxSR conditions at
417  * frame start which happens after vblank start (which is when the plane
418  * registers would get latched), so we can't proceed with the plane update
419  * during the same frame where we disallowed CxSR.
420  *
421  * Certain platforms also have a deeper HPLL SR mode. Fortunately the
422  * HPLL SR mode depends on CxSR itself, so we don't have to hand hold
423  * the hardware w.r.t. HPLL SR when writing to plane registers.
424  * Disallowing just CxSR is sufficient.
425  */
426 bool intel_set_memory_cxsr(struct drm_i915_private *dev_priv, bool enable)
427 {
428         bool ret;
429
430         mutex_lock(&dev_priv->wm.wm_mutex);
431         ret = _intel_set_memory_cxsr(dev_priv, enable);
432         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
433                 dev_priv->wm.vlv.cxsr = enable;
434         else if (IS_G4X(dev_priv))
435                 dev_priv->wm.g4x.cxsr = enable;
436         mutex_unlock(&dev_priv->wm.wm_mutex);
437
438         return ret;
439 }
440
441 /*
442  * Latency for FIFO fetches is dependent on several factors:
443  *   - memory configuration (speed, channels)
444  *   - chipset
445  *   - current MCH state
446  * It can be fairly high in some situations, so here we assume a fairly
447  * pessimal value.  It's a tradeoff between extra memory fetches (if we
448  * set this value too high, the FIFO will fetch frequently to stay full)
449  * and power consumption (set it too low to save power and we might see
450  * FIFO underruns and display "flicker").
451  *
452  * A value of 5us seems to be a good balance; safe for very low end
453  * platforms but not overly aggressive on lower latency configs.
454  */
455 static const int pessimal_latency_ns = 5000;
456
457 #define VLV_FIFO_START(dsparb, dsparb2, lo_shift, hi_shift) \
458         ((((dsparb) >> (lo_shift)) & 0xff) | ((((dsparb2) >> (hi_shift)) & 0x1) << 8))
459
460 static void vlv_get_fifo_size(struct intel_crtc_state *crtc_state)
461 {
462         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
463         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
464         struct vlv_fifo_state *fifo_state = &crtc_state->wm.vlv.fifo_state;
465         enum pipe pipe = crtc->pipe;
466         int sprite0_start, sprite1_start;
467
468         switch (pipe) {
469                 uint32_t dsparb, dsparb2, dsparb3;
470         case PIPE_A:
471                 dsparb = I915_READ(DSPARB);
472                 dsparb2 = I915_READ(DSPARB2);
473                 sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 0, 0);
474                 sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 8, 4);
475                 break;
476         case PIPE_B:
477                 dsparb = I915_READ(DSPARB);
478                 dsparb2 = I915_READ(DSPARB2);
479                 sprite0_start = VLV_FIFO_START(dsparb, dsparb2, 16, 8);
480                 sprite1_start = VLV_FIFO_START(dsparb, dsparb2, 24, 12);
481                 break;
482         case PIPE_C:
483                 dsparb2 = I915_READ(DSPARB2);
484                 dsparb3 = I915_READ(DSPARB3);
485                 sprite0_start = VLV_FIFO_START(dsparb3, dsparb2, 0, 16);
486                 sprite1_start = VLV_FIFO_START(dsparb3, dsparb2, 8, 20);
487                 break;
488         default:
489                 MISSING_CASE(pipe);
490                 return;
491         }
492
493         fifo_state->plane[PLANE_PRIMARY] = sprite0_start;
494         fifo_state->plane[PLANE_SPRITE0] = sprite1_start - sprite0_start;
495         fifo_state->plane[PLANE_SPRITE1] = 511 - sprite1_start;
496         fifo_state->plane[PLANE_CURSOR] = 63;
497 }
498
499 static int i9xx_get_fifo_size(struct drm_i915_private *dev_priv, int plane)
500 {
501         uint32_t dsparb = I915_READ(DSPARB);
502         int size;
503
504         size = dsparb & 0x7f;
505         if (plane)
506                 size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
507
508         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
509                       plane ? "B" : "A", size);
510
511         return size;
512 }
513
514 static int i830_get_fifo_size(struct drm_i915_private *dev_priv, int plane)
515 {
516         uint32_t dsparb = I915_READ(DSPARB);
517         int size;
518
519         size = dsparb & 0x1ff;
520         if (plane)
521                 size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
522         size >>= 1; /* Convert to cachelines */
523
524         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
525                       plane ? "B" : "A", size);
526
527         return size;
528 }
529
530 static int i845_get_fifo_size(struct drm_i915_private *dev_priv, int plane)
531 {
532         uint32_t dsparb = I915_READ(DSPARB);
533         int size;
534
535         size = dsparb & 0x7f;
536         size >>= 2; /* Convert to cachelines */
537
538         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
539                       plane ? "B" : "A",
540                       size);
541
542         return size;
543 }
544
545 /* Pineview has different values for various configs */
546 static const struct intel_watermark_params pineview_display_wm = {
547         .fifo_size = PINEVIEW_DISPLAY_FIFO,
548         .max_wm = PINEVIEW_MAX_WM,
549         .default_wm = PINEVIEW_DFT_WM,
550         .guard_size = PINEVIEW_GUARD_WM,
551         .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
552 };
553 static const struct intel_watermark_params pineview_display_hplloff_wm = {
554         .fifo_size = PINEVIEW_DISPLAY_FIFO,
555         .max_wm = PINEVIEW_MAX_WM,
556         .default_wm = PINEVIEW_DFT_HPLLOFF_WM,
557         .guard_size = PINEVIEW_GUARD_WM,
558         .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
559 };
560 static const struct intel_watermark_params pineview_cursor_wm = {
561         .fifo_size = PINEVIEW_CURSOR_FIFO,
562         .max_wm = PINEVIEW_CURSOR_MAX_WM,
563         .default_wm = PINEVIEW_CURSOR_DFT_WM,
564         .guard_size = PINEVIEW_CURSOR_GUARD_WM,
565         .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
566 };
567 static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
568         .fifo_size = PINEVIEW_CURSOR_FIFO,
569         .max_wm = PINEVIEW_CURSOR_MAX_WM,
570         .default_wm = PINEVIEW_CURSOR_DFT_WM,
571         .guard_size = PINEVIEW_CURSOR_GUARD_WM,
572         .cacheline_size = PINEVIEW_FIFO_LINE_SIZE,
573 };
574 static const struct intel_watermark_params i965_cursor_wm_info = {
575         .fifo_size = I965_CURSOR_FIFO,
576         .max_wm = I965_CURSOR_MAX_WM,
577         .default_wm = I965_CURSOR_DFT_WM,
578         .guard_size = 2,
579         .cacheline_size = I915_FIFO_LINE_SIZE,
580 };
581 static const struct intel_watermark_params i945_wm_info = {
582         .fifo_size = I945_FIFO_SIZE,
583         .max_wm = I915_MAX_WM,
584         .default_wm = 1,
585         .guard_size = 2,
586         .cacheline_size = I915_FIFO_LINE_SIZE,
587 };
588 static const struct intel_watermark_params i915_wm_info = {
589         .fifo_size = I915_FIFO_SIZE,
590         .max_wm = I915_MAX_WM,
591         .default_wm = 1,
592         .guard_size = 2,
593         .cacheline_size = I915_FIFO_LINE_SIZE,
594 };
595 static const struct intel_watermark_params i830_a_wm_info = {
596         .fifo_size = I855GM_FIFO_SIZE,
597         .max_wm = I915_MAX_WM,
598         .default_wm = 1,
599         .guard_size = 2,
600         .cacheline_size = I830_FIFO_LINE_SIZE,
601 };
602 static const struct intel_watermark_params i830_bc_wm_info = {
603         .fifo_size = I855GM_FIFO_SIZE,
604         .max_wm = I915_MAX_WM/2,
605         .default_wm = 1,
606         .guard_size = 2,
607         .cacheline_size = I830_FIFO_LINE_SIZE,
608 };
609 static const struct intel_watermark_params i845_wm_info = {
610         .fifo_size = I830_FIFO_SIZE,
611         .max_wm = I915_MAX_WM,
612         .default_wm = 1,
613         .guard_size = 2,
614         .cacheline_size = I830_FIFO_LINE_SIZE,
615 };
616
617 /**
618  * intel_wm_method1 - Method 1 / "small buffer" watermark formula
619  * @pixel_rate: Pipe pixel rate in kHz
620  * @cpp: Plane bytes per pixel
621  * @latency: Memory wakeup latency in 0.1us units
622  *
623  * Compute the watermark using the method 1 or "small buffer"
624  * formula. The caller may additonally add extra cachelines
625  * to account for TLB misses and clock crossings.
626  *
627  * This method is concerned with the short term drain rate
628  * of the FIFO, ie. it does not account for blanking periods
629  * which would effectively reduce the average drain rate across
630  * a longer period. The name "small" refers to the fact the
631  * FIFO is relatively small compared to the amount of data
632  * fetched.
633  *
634  * The FIFO level vs. time graph might look something like:
635  *
636  *   |\   |\
637  *   | \  | \
638  * __---__---__ (- plane active, _ blanking)
639  * -> time
640  *
641  * or perhaps like this:
642  *
643  *   |\|\  |\|\
644  * __----__----__ (- plane active, _ blanking)
645  * -> time
646  *
647  * Returns:
648  * The watermark in bytes
649  */
650 static unsigned int intel_wm_method1(unsigned int pixel_rate,
651                                      unsigned int cpp,
652                                      unsigned int latency)
653 {
654         uint64_t ret;
655
656         ret = (uint64_t) pixel_rate * cpp * latency;
657         ret = DIV_ROUND_UP_ULL(ret, 10000);
658
659         return ret;
660 }
661
662 /**
663  * intel_wm_method2 - Method 2 / "large buffer" watermark formula
664  * @pixel_rate: Pipe pixel rate in kHz
665  * @htotal: Pipe horizontal total
666  * @width: Plane width in pixels
667  * @cpp: Plane bytes per pixel
668  * @latency: Memory wakeup latency in 0.1us units
669  *
670  * Compute the watermark using the method 2 or "large buffer"
671  * formula. The caller may additonally add extra cachelines
672  * to account for TLB misses and clock crossings.
673  *
674  * This method is concerned with the long term drain rate
675  * of the FIFO, ie. it does account for blanking periods
676  * which effectively reduce the average drain rate across
677  * a longer period. The name "large" refers to the fact the
678  * FIFO is relatively large compared to the amount of data
679  * fetched.
680  *
681  * The FIFO level vs. time graph might look something like:
682  *
683  *    |\___       |\___
684  *    |    \___   |    \___
685  *    |        \  |        \
686  * __ --__--__--__--__--__--__ (- plane active, _ blanking)
687  * -> time
688  *
689  * Returns:
690  * The watermark in bytes
691  */
692 static unsigned int intel_wm_method2(unsigned int pixel_rate,
693                                      unsigned int htotal,
694                                      unsigned int width,
695                                      unsigned int cpp,
696                                      unsigned int latency)
697 {
698         unsigned int ret;
699
700         /*
701          * FIXME remove once all users are computing
702          * watermarks in the correct place.
703          */
704         if (WARN_ON_ONCE(htotal == 0))
705                 htotal = 1;
706
707         ret = (latency * pixel_rate) / (htotal * 10000);
708         ret = (ret + 1) * width * cpp;
709
710         return ret;
711 }
712
713 /**
714  * intel_calculate_wm - calculate watermark level
715  * @pixel_rate: pixel clock
716  * @wm: chip FIFO params
717  * @cpp: bytes per pixel
718  * @latency_ns: memory latency for the platform
719  *
720  * Calculate the watermark level (the level at which the display plane will
721  * start fetching from memory again).  Each chip has a different display
722  * FIFO size and allocation, so the caller needs to figure that out and pass
723  * in the correct intel_watermark_params structure.
724  *
725  * As the pixel clock runs, the FIFO will be drained at a rate that depends
726  * on the pixel size.  When it reaches the watermark level, it'll start
727  * fetching FIFO line sized based chunks from memory until the FIFO fills
728  * past the watermark point.  If the FIFO drains completely, a FIFO underrun
729  * will occur, and a display engine hang could result.
730  */
731 static unsigned int intel_calculate_wm(int pixel_rate,
732                                        const struct intel_watermark_params *wm,
733                                        int fifo_size, int cpp,
734                                        unsigned int latency_ns)
735 {
736         int entries, wm_size;
737
738         /*
739          * Note: we need to make sure we don't overflow for various clock &
740          * latency values.
741          * clocks go from a few thousand to several hundred thousand.
742          * latency is usually a few thousand
743          */
744         entries = intel_wm_method1(pixel_rate, cpp,
745                                    latency_ns / 100);
746         entries = DIV_ROUND_UP(entries, wm->cacheline_size) +
747                 wm->guard_size;
748         DRM_DEBUG_KMS("FIFO entries required for mode: %d\n", entries);
749
750         wm_size = fifo_size - entries;
751         DRM_DEBUG_KMS("FIFO watermark level: %d\n", wm_size);
752
753         /* Don't promote wm_size to unsigned... */
754         if (wm_size > wm->max_wm)
755                 wm_size = wm->max_wm;
756         if (wm_size <= 0)
757                 wm_size = wm->default_wm;
758
759         /*
760          * Bspec seems to indicate that the value shouldn't be lower than
761          * 'burst size + 1'. Certainly 830 is quite unhappy with low values.
762          * Lets go for 8 which is the burst size since certain platforms
763          * already use a hardcoded 8 (which is what the spec says should be
764          * done).
765          */
766         if (wm_size <= 8)
767                 wm_size = 8;
768
769         return wm_size;
770 }
771
772 static bool is_disabling(int old, int new, int threshold)
773 {
774         return old >= threshold && new < threshold;
775 }
776
777 static bool is_enabling(int old, int new, int threshold)
778 {
779         return old < threshold && new >= threshold;
780 }
781
782 static int intel_wm_num_levels(struct drm_i915_private *dev_priv)
783 {
784         return dev_priv->wm.max_level + 1;
785 }
786
787 static bool intel_wm_plane_visible(const struct intel_crtc_state *crtc_state,
788                                    const struct intel_plane_state *plane_state)
789 {
790         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
791
792         /* FIXME check the 'enable' instead */
793         if (!crtc_state->base.active)
794                 return false;
795
796         /*
797          * Treat cursor with fb as always visible since cursor updates
798          * can happen faster than the vrefresh rate, and the current
799          * watermark code doesn't handle that correctly. Cursor updates
800          * which set/clear the fb or change the cursor size are going
801          * to get throttled by intel_legacy_cursor_update() to work
802          * around this problem with the watermark code.
803          */
804         if (plane->id == PLANE_CURSOR)
805                 return plane_state->base.fb != NULL;
806         else
807                 return plane_state->base.visible;
808 }
809
810 static struct intel_crtc *single_enabled_crtc(struct drm_i915_private *dev_priv)
811 {
812         struct intel_crtc *crtc, *enabled = NULL;
813
814         for_each_intel_crtc(&dev_priv->drm, crtc) {
815                 if (intel_crtc_active(crtc)) {
816                         if (enabled)
817                                 return NULL;
818                         enabled = crtc;
819                 }
820         }
821
822         return enabled;
823 }
824
825 static void pineview_update_wm(struct intel_crtc *unused_crtc)
826 {
827         struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
828         struct intel_crtc *crtc;
829         const struct cxsr_latency *latency;
830         u32 reg;
831         unsigned int wm;
832
833         latency = intel_get_cxsr_latency(IS_PINEVIEW_G(dev_priv),
834                                          dev_priv->is_ddr3,
835                                          dev_priv->fsb_freq,
836                                          dev_priv->mem_freq);
837         if (!latency) {
838                 DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
839                 intel_set_memory_cxsr(dev_priv, false);
840                 return;
841         }
842
843         crtc = single_enabled_crtc(dev_priv);
844         if (crtc) {
845                 const struct drm_display_mode *adjusted_mode =
846                         &crtc->config->base.adjusted_mode;
847                 const struct drm_framebuffer *fb =
848                         crtc->base.primary->state->fb;
849                 int cpp = fb->format->cpp[0];
850                 int clock = adjusted_mode->crtc_clock;
851
852                 /* Display SR */
853                 wm = intel_calculate_wm(clock, &pineview_display_wm,
854                                         pineview_display_wm.fifo_size,
855                                         cpp, latency->display_sr);
856                 reg = I915_READ(DSPFW1);
857                 reg &= ~DSPFW_SR_MASK;
858                 reg |= FW_WM(wm, SR);
859                 I915_WRITE(DSPFW1, reg);
860                 DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
861
862                 /* cursor SR */
863                 wm = intel_calculate_wm(clock, &pineview_cursor_wm,
864                                         pineview_display_wm.fifo_size,
865                                         4, latency->cursor_sr);
866                 reg = I915_READ(DSPFW3);
867                 reg &= ~DSPFW_CURSOR_SR_MASK;
868                 reg |= FW_WM(wm, CURSOR_SR);
869                 I915_WRITE(DSPFW3, reg);
870
871                 /* Display HPLL off SR */
872                 wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
873                                         pineview_display_hplloff_wm.fifo_size,
874                                         cpp, latency->display_hpll_disable);
875                 reg = I915_READ(DSPFW3);
876                 reg &= ~DSPFW_HPLL_SR_MASK;
877                 reg |= FW_WM(wm, HPLL_SR);
878                 I915_WRITE(DSPFW3, reg);
879
880                 /* cursor HPLL off SR */
881                 wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
882                                         pineview_display_hplloff_wm.fifo_size,
883                                         4, latency->cursor_hpll_disable);
884                 reg = I915_READ(DSPFW3);
885                 reg &= ~DSPFW_HPLL_CURSOR_MASK;
886                 reg |= FW_WM(wm, HPLL_CURSOR);
887                 I915_WRITE(DSPFW3, reg);
888                 DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
889
890                 intel_set_memory_cxsr(dev_priv, true);
891         } else {
892                 intel_set_memory_cxsr(dev_priv, false);
893         }
894 }
895
896 /*
897  * Documentation says:
898  * "If the line size is small, the TLB fetches can get in the way of the
899  *  data fetches, causing some lag in the pixel data return which is not
900  *  accounted for in the above formulas. The following adjustment only
901  *  needs to be applied if eight whole lines fit in the buffer at once.
902  *  The WM is adjusted upwards by the difference between the FIFO size
903  *  and the size of 8 whole lines. This adjustment is always performed
904  *  in the actual pixel depth regardless of whether FBC is enabled or not."
905  */
906 static int g4x_tlb_miss_wa(int fifo_size, int width, int cpp)
907 {
908         int tlb_miss = fifo_size * 64 - width * cpp * 8;
909
910         return max(0, tlb_miss);
911 }
912
913 static void g4x_write_wm_values(struct drm_i915_private *dev_priv,
914                                 const struct g4x_wm_values *wm)
915 {
916         enum pipe pipe;
917
918         for_each_pipe(dev_priv, pipe)
919                 trace_g4x_wm(intel_get_crtc_for_pipe(dev_priv, pipe), wm);
920
921         I915_WRITE(DSPFW1,
922                    FW_WM(wm->sr.plane, SR) |
923                    FW_WM(wm->pipe[PIPE_B].plane[PLANE_CURSOR], CURSORB) |
924                    FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY], PLANEB) |
925                    FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY], PLANEA));
926         I915_WRITE(DSPFW2,
927                    (wm->fbc_en ? DSPFW_FBC_SR_EN : 0) |
928                    FW_WM(wm->sr.fbc, FBC_SR) |
929                    FW_WM(wm->hpll.fbc, FBC_HPLL_SR) |
930                    FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEB) |
931                    FW_WM(wm->pipe[PIPE_A].plane[PLANE_CURSOR], CURSORA) |
932                    FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0], SPRITEA));
933         I915_WRITE(DSPFW3,
934                    (wm->hpll_en ? DSPFW_HPLL_SR_EN : 0) |
935                    FW_WM(wm->sr.cursor, CURSOR_SR) |
936                    FW_WM(wm->hpll.cursor, HPLL_CURSOR) |
937                    FW_WM(wm->hpll.plane, HPLL_SR));
938
939         POSTING_READ(DSPFW1);
940 }
941
942 #define FW_WM_VLV(value, plane) \
943         (((value) << DSPFW_ ## plane ## _SHIFT) & DSPFW_ ## plane ## _MASK_VLV)
944
945 static void vlv_write_wm_values(struct drm_i915_private *dev_priv,
946                                 const struct vlv_wm_values *wm)
947 {
948         enum pipe pipe;
949
950         for_each_pipe(dev_priv, pipe) {
951                 trace_vlv_wm(intel_get_crtc_for_pipe(dev_priv, pipe), wm);
952
953                 I915_WRITE(VLV_DDL(pipe),
954                            (wm->ddl[pipe].plane[PLANE_CURSOR] << DDL_CURSOR_SHIFT) |
955                            (wm->ddl[pipe].plane[PLANE_SPRITE1] << DDL_SPRITE_SHIFT(1)) |
956                            (wm->ddl[pipe].plane[PLANE_SPRITE0] << DDL_SPRITE_SHIFT(0)) |
957                            (wm->ddl[pipe].plane[PLANE_PRIMARY] << DDL_PLANE_SHIFT));
958         }
959
960         /*
961          * Zero the (unused) WM1 watermarks, and also clear all the
962          * high order bits so that there are no out of bounds values
963          * present in the registers during the reprogramming.
964          */
965         I915_WRITE(DSPHOWM, 0);
966         I915_WRITE(DSPHOWM1, 0);
967         I915_WRITE(DSPFW4, 0);
968         I915_WRITE(DSPFW5, 0);
969         I915_WRITE(DSPFW6, 0);
970
971         I915_WRITE(DSPFW1,
972                    FW_WM(wm->sr.plane, SR) |
973                    FW_WM(wm->pipe[PIPE_B].plane[PLANE_CURSOR], CURSORB) |
974                    FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_PRIMARY], PLANEB) |
975                    FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_PRIMARY], PLANEA));
976         I915_WRITE(DSPFW2,
977                    FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_SPRITE1], SPRITEB) |
978                    FW_WM(wm->pipe[PIPE_A].plane[PLANE_CURSOR], CURSORA) |
979                    FW_WM_VLV(wm->pipe[PIPE_A].plane[PLANE_SPRITE0], SPRITEA));
980         I915_WRITE(DSPFW3,
981                    FW_WM(wm->sr.cursor, CURSOR_SR));
982
983         if (IS_CHERRYVIEW(dev_priv)) {
984                 I915_WRITE(DSPFW7_CHV,
985                            FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE1], SPRITED) |
986                            FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEC));
987                 I915_WRITE(DSPFW8_CHV,
988                            FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_SPRITE1], SPRITEF) |
989                            FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_SPRITE0], SPRITEE));
990                 I915_WRITE(DSPFW9_CHV,
991                            FW_WM_VLV(wm->pipe[PIPE_C].plane[PLANE_PRIMARY], PLANEC) |
992                            FW_WM(wm->pipe[PIPE_C].plane[PLANE_CURSOR], CURSORC));
993                 I915_WRITE(DSPHOWM,
994                            FW_WM(wm->sr.plane >> 9, SR_HI) |
995                            FW_WM(wm->pipe[PIPE_C].plane[PLANE_SPRITE1] >> 8, SPRITEF_HI) |
996                            FW_WM(wm->pipe[PIPE_C].plane[PLANE_SPRITE0] >> 8, SPRITEE_HI) |
997                            FW_WM(wm->pipe[PIPE_C].plane[PLANE_PRIMARY] >> 8, PLANEC_HI) |
998                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE1] >> 8, SPRITED_HI) |
999                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0] >> 8, SPRITEC_HI) |
1000                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY] >> 8, PLANEB_HI) |
1001                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE1] >> 8, SPRITEB_HI) |
1002                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0] >> 8, SPRITEA_HI) |
1003                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY] >> 8, PLANEA_HI));
1004         } else {
1005                 I915_WRITE(DSPFW7,
1006                            FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE1], SPRITED) |
1007                            FW_WM_VLV(wm->pipe[PIPE_B].plane[PLANE_SPRITE0], SPRITEC));
1008                 I915_WRITE(DSPHOWM,
1009                            FW_WM(wm->sr.plane >> 9, SR_HI) |
1010                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE1] >> 8, SPRITED_HI) |
1011                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_SPRITE0] >> 8, SPRITEC_HI) |
1012                            FW_WM(wm->pipe[PIPE_B].plane[PLANE_PRIMARY] >> 8, PLANEB_HI) |
1013                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE1] >> 8, SPRITEB_HI) |
1014                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_SPRITE0] >> 8, SPRITEA_HI) |
1015                            FW_WM(wm->pipe[PIPE_A].plane[PLANE_PRIMARY] >> 8, PLANEA_HI));
1016         }
1017
1018         POSTING_READ(DSPFW1);
1019 }
1020
1021 #undef FW_WM_VLV
1022
1023 static void g4x_setup_wm_latency(struct drm_i915_private *dev_priv)
1024 {
1025         /* all latencies in usec */
1026         dev_priv->wm.pri_latency[G4X_WM_LEVEL_NORMAL] = 5;
1027         dev_priv->wm.pri_latency[G4X_WM_LEVEL_SR] = 12;
1028         dev_priv->wm.pri_latency[G4X_WM_LEVEL_HPLL] = 35;
1029
1030         dev_priv->wm.max_level = G4X_WM_LEVEL_HPLL;
1031 }
1032
1033 static int g4x_plane_fifo_size(enum plane_id plane_id, int level)
1034 {
1035         /*
1036          * DSPCNTR[13] supposedly controls whether the
1037          * primary plane can use the FIFO space otherwise
1038          * reserved for the sprite plane. It's not 100% clear
1039          * what the actual FIFO size is, but it looks like we
1040          * can happily set both primary and sprite watermarks
1041          * up to 127 cachelines. So that would seem to mean
1042          * that either DSPCNTR[13] doesn't do anything, or that
1043          * the total FIFO is >= 256 cachelines in size. Either
1044          * way, we don't seem to have to worry about this
1045          * repartitioning as the maximum watermark value the
1046          * register can hold for each plane is lower than the
1047          * minimum FIFO size.
1048          */
1049         switch (plane_id) {
1050         case PLANE_CURSOR:
1051                 return 63;
1052         case PLANE_PRIMARY:
1053                 return level == G4X_WM_LEVEL_NORMAL ? 127 : 511;
1054         case PLANE_SPRITE0:
1055                 return level == G4X_WM_LEVEL_NORMAL ? 127 : 0;
1056         default:
1057                 MISSING_CASE(plane_id);
1058                 return 0;
1059         }
1060 }
1061
1062 static int g4x_fbc_fifo_size(int level)
1063 {
1064         switch (level) {
1065         case G4X_WM_LEVEL_SR:
1066                 return 7;
1067         case G4X_WM_LEVEL_HPLL:
1068                 return 15;
1069         default:
1070                 MISSING_CASE(level);
1071                 return 0;
1072         }
1073 }
1074
1075 static uint16_t g4x_compute_wm(const struct intel_crtc_state *crtc_state,
1076                                const struct intel_plane_state *plane_state,
1077                                int level)
1078 {
1079         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1080         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1081         const struct drm_display_mode *adjusted_mode =
1082                 &crtc_state->base.adjusted_mode;
1083         int clock, htotal, cpp, width, wm;
1084         int latency = dev_priv->wm.pri_latency[level] * 10;
1085
1086         if (latency == 0)
1087                 return USHRT_MAX;
1088
1089         if (!intel_wm_plane_visible(crtc_state, plane_state))
1090                 return 0;
1091
1092         /*
1093          * Not 100% sure which way ELK should go here as the
1094          * spec only says CL/CTG should assume 32bpp and BW
1095          * doesn't need to. But as these things followed the
1096          * mobile vs. desktop lines on gen3 as well, let's
1097          * assume ELK doesn't need this.
1098          *
1099          * The spec also fails to list such a restriction for
1100          * the HPLL watermark, which seems a little strange.
1101          * Let's use 32bpp for the HPLL watermark as well.
1102          */
1103         if (IS_GM45(dev_priv) && plane->id == PLANE_PRIMARY &&
1104             level != G4X_WM_LEVEL_NORMAL)
1105                 cpp = 4;
1106         else
1107                 cpp = plane_state->base.fb->format->cpp[0];
1108
1109         clock = adjusted_mode->crtc_clock;
1110         htotal = adjusted_mode->crtc_htotal;
1111
1112         if (plane->id == PLANE_CURSOR)
1113                 width = plane_state->base.crtc_w;
1114         else
1115                 width = drm_rect_width(&plane_state->base.dst);
1116
1117         if (plane->id == PLANE_CURSOR) {
1118                 wm = intel_wm_method2(clock, htotal, width, cpp, latency);
1119         } else if (plane->id == PLANE_PRIMARY &&
1120                    level == G4X_WM_LEVEL_NORMAL) {
1121                 wm = intel_wm_method1(clock, cpp, latency);
1122         } else {
1123                 int small, large;
1124
1125                 small = intel_wm_method1(clock, cpp, latency);
1126                 large = intel_wm_method2(clock, htotal, width, cpp, latency);
1127
1128                 wm = min(small, large);
1129         }
1130
1131         wm += g4x_tlb_miss_wa(g4x_plane_fifo_size(plane->id, level),
1132                               width, cpp);
1133
1134         wm = DIV_ROUND_UP(wm, 64) + 2;
1135
1136         return min_t(int, wm, USHRT_MAX);
1137 }
1138
1139 static bool g4x_raw_plane_wm_set(struct intel_crtc_state *crtc_state,
1140                                  int level, enum plane_id plane_id, u16 value)
1141 {
1142         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1143         bool dirty = false;
1144
1145         for (; level < intel_wm_num_levels(dev_priv); level++) {
1146                 struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1147
1148                 dirty |= raw->plane[plane_id] != value;
1149                 raw->plane[plane_id] = value;
1150         }
1151
1152         return dirty;
1153 }
1154
1155 static bool g4x_raw_fbc_wm_set(struct intel_crtc_state *crtc_state,
1156                                int level, u16 value)
1157 {
1158         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1159         bool dirty = false;
1160
1161         /* NORMAL level doesn't have an FBC watermark */
1162         level = max(level, G4X_WM_LEVEL_SR);
1163
1164         for (; level < intel_wm_num_levels(dev_priv); level++) {
1165                 struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1166
1167                 dirty |= raw->fbc != value;
1168                 raw->fbc = value;
1169         }
1170
1171         return dirty;
1172 }
1173
1174 static uint32_t ilk_compute_fbc_wm(const struct intel_crtc_state *cstate,
1175                                    const struct intel_plane_state *pstate,
1176                                    uint32_t pri_val);
1177
1178 static bool g4x_raw_plane_wm_compute(struct intel_crtc_state *crtc_state,
1179                                      const struct intel_plane_state *plane_state)
1180 {
1181         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1182         int num_levels = intel_wm_num_levels(to_i915(plane->base.dev));
1183         enum plane_id plane_id = plane->id;
1184         bool dirty = false;
1185         int level;
1186
1187         if (!intel_wm_plane_visible(crtc_state, plane_state)) {
1188                 dirty |= g4x_raw_plane_wm_set(crtc_state, 0, plane_id, 0);
1189                 if (plane_id == PLANE_PRIMARY)
1190                         dirty |= g4x_raw_fbc_wm_set(crtc_state, 0, 0);
1191                 goto out;
1192         }
1193
1194         for (level = 0; level < num_levels; level++) {
1195                 struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1196                 int wm, max_wm;
1197
1198                 wm = g4x_compute_wm(crtc_state, plane_state, level);
1199                 max_wm = g4x_plane_fifo_size(plane_id, level);
1200
1201                 if (wm > max_wm)
1202                         break;
1203
1204                 dirty |= raw->plane[plane_id] != wm;
1205                 raw->plane[plane_id] = wm;
1206
1207                 if (plane_id != PLANE_PRIMARY ||
1208                     level == G4X_WM_LEVEL_NORMAL)
1209                         continue;
1210
1211                 wm = ilk_compute_fbc_wm(crtc_state, plane_state,
1212                                         raw->plane[plane_id]);
1213                 max_wm = g4x_fbc_fifo_size(level);
1214
1215                 /*
1216                  * FBC wm is not mandatory as we
1217                  * can always just disable its use.
1218                  */
1219                 if (wm > max_wm)
1220                         wm = USHRT_MAX;
1221
1222                 dirty |= raw->fbc != wm;
1223                 raw->fbc = wm;
1224         }
1225
1226         /* mark watermarks as invalid */
1227         dirty |= g4x_raw_plane_wm_set(crtc_state, level, plane_id, USHRT_MAX);
1228
1229         if (plane_id == PLANE_PRIMARY)
1230                 dirty |= g4x_raw_fbc_wm_set(crtc_state, level, USHRT_MAX);
1231
1232  out:
1233         if (dirty) {
1234                 DRM_DEBUG_KMS("%s watermarks: normal=%d, SR=%d, HPLL=%d\n",
1235                               plane->base.name,
1236                               crtc_state->wm.g4x.raw[G4X_WM_LEVEL_NORMAL].plane[plane_id],
1237                               crtc_state->wm.g4x.raw[G4X_WM_LEVEL_SR].plane[plane_id],
1238                               crtc_state->wm.g4x.raw[G4X_WM_LEVEL_HPLL].plane[plane_id]);
1239
1240                 if (plane_id == PLANE_PRIMARY)
1241                         DRM_DEBUG_KMS("FBC watermarks: SR=%d, HPLL=%d\n",
1242                                       crtc_state->wm.g4x.raw[G4X_WM_LEVEL_SR].fbc,
1243                                       crtc_state->wm.g4x.raw[G4X_WM_LEVEL_HPLL].fbc);
1244         }
1245
1246         return dirty;
1247 }
1248
1249 static bool g4x_raw_plane_wm_is_valid(const struct intel_crtc_state *crtc_state,
1250                                       enum plane_id plane_id, int level)
1251 {
1252         const struct g4x_pipe_wm *raw = &crtc_state->wm.g4x.raw[level];
1253
1254         return raw->plane[plane_id] <= g4x_plane_fifo_size(plane_id, level);
1255 }
1256
1257 static bool g4x_raw_crtc_wm_is_valid(const struct intel_crtc_state *crtc_state,
1258                                      int level)
1259 {
1260         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1261
1262         if (level > dev_priv->wm.max_level)
1263                 return false;
1264
1265         return g4x_raw_plane_wm_is_valid(crtc_state, PLANE_PRIMARY, level) &&
1266                 g4x_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE0, level) &&
1267                 g4x_raw_plane_wm_is_valid(crtc_state, PLANE_CURSOR, level);
1268 }
1269
1270 /* mark all levels starting from 'level' as invalid */
1271 static void g4x_invalidate_wms(struct intel_crtc *crtc,
1272                                struct g4x_wm_state *wm_state, int level)
1273 {
1274         if (level <= G4X_WM_LEVEL_NORMAL) {
1275                 enum plane_id plane_id;
1276
1277                 for_each_plane_id_on_crtc(crtc, plane_id)
1278                         wm_state->wm.plane[plane_id] = USHRT_MAX;
1279         }
1280
1281         if (level <= G4X_WM_LEVEL_SR) {
1282                 wm_state->cxsr = false;
1283                 wm_state->sr.cursor = USHRT_MAX;
1284                 wm_state->sr.plane = USHRT_MAX;
1285                 wm_state->sr.fbc = USHRT_MAX;
1286         }
1287
1288         if (level <= G4X_WM_LEVEL_HPLL) {
1289                 wm_state->hpll_en = false;
1290                 wm_state->hpll.cursor = USHRT_MAX;
1291                 wm_state->hpll.plane = USHRT_MAX;
1292                 wm_state->hpll.fbc = USHRT_MAX;
1293         }
1294 }
1295
1296 static int g4x_compute_pipe_wm(struct intel_crtc_state *crtc_state)
1297 {
1298         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1299         struct intel_atomic_state *state =
1300                 to_intel_atomic_state(crtc_state->base.state);
1301         struct g4x_wm_state *wm_state = &crtc_state->wm.g4x.optimal;
1302         int num_active_planes = hweight32(crtc_state->active_planes &
1303                                           ~BIT(PLANE_CURSOR));
1304         const struct g4x_pipe_wm *raw;
1305         struct intel_plane_state *plane_state;
1306         struct intel_plane *plane;
1307         enum plane_id plane_id;
1308         int i, level;
1309         unsigned int dirty = 0;
1310
1311         for_each_intel_plane_in_state(state, plane, plane_state, i) {
1312                 const struct intel_plane_state *old_plane_state =
1313                         to_intel_plane_state(plane->base.state);
1314
1315                 if (plane_state->base.crtc != &crtc->base &&
1316                     old_plane_state->base.crtc != &crtc->base)
1317                         continue;
1318
1319                 if (g4x_raw_plane_wm_compute(crtc_state, plane_state))
1320                         dirty |= BIT(plane->id);
1321         }
1322
1323         if (!dirty)
1324                 return 0;
1325
1326         level = G4X_WM_LEVEL_NORMAL;
1327         if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1328                 goto out;
1329
1330         raw = &crtc_state->wm.g4x.raw[level];
1331         for_each_plane_id_on_crtc(crtc, plane_id)
1332                 wm_state->wm.plane[plane_id] = raw->plane[plane_id];
1333
1334         level = G4X_WM_LEVEL_SR;
1335
1336         if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1337                 goto out;
1338
1339         raw = &crtc_state->wm.g4x.raw[level];
1340         wm_state->sr.plane = raw->plane[PLANE_PRIMARY];
1341         wm_state->sr.cursor = raw->plane[PLANE_CURSOR];
1342         wm_state->sr.fbc = raw->fbc;
1343
1344         wm_state->cxsr = num_active_planes == BIT(PLANE_PRIMARY);
1345
1346         level = G4X_WM_LEVEL_HPLL;
1347
1348         if (!g4x_raw_crtc_wm_is_valid(crtc_state, level))
1349                 goto out;
1350
1351         raw = &crtc_state->wm.g4x.raw[level];
1352         wm_state->hpll.plane = raw->plane[PLANE_PRIMARY];
1353         wm_state->hpll.cursor = raw->plane[PLANE_CURSOR];
1354         wm_state->hpll.fbc = raw->fbc;
1355
1356         wm_state->hpll_en = wm_state->cxsr;
1357
1358         level++;
1359
1360  out:
1361         if (level == G4X_WM_LEVEL_NORMAL)
1362                 return -EINVAL;
1363
1364         /* invalidate the higher levels */
1365         g4x_invalidate_wms(crtc, wm_state, level);
1366
1367         /*
1368          * Determine if the FBC watermark(s) can be used. IF
1369          * this isn't the case we prefer to disable the FBC
1370          ( watermark(s) rather than disable the SR/HPLL
1371          * level(s) entirely.
1372          */
1373         wm_state->fbc_en = level > G4X_WM_LEVEL_NORMAL;
1374
1375         if (level >= G4X_WM_LEVEL_SR &&
1376             wm_state->sr.fbc > g4x_fbc_fifo_size(G4X_WM_LEVEL_SR))
1377                 wm_state->fbc_en = false;
1378         else if (level >= G4X_WM_LEVEL_HPLL &&
1379                  wm_state->hpll.fbc > g4x_fbc_fifo_size(G4X_WM_LEVEL_HPLL))
1380                 wm_state->fbc_en = false;
1381
1382         return 0;
1383 }
1384
1385 static int g4x_compute_intermediate_wm(struct drm_device *dev,
1386                                        struct intel_crtc *crtc,
1387                                        struct intel_crtc_state *crtc_state)
1388 {
1389         struct g4x_wm_state *intermediate = &crtc_state->wm.g4x.intermediate;
1390         const struct g4x_wm_state *optimal = &crtc_state->wm.g4x.optimal;
1391         const struct g4x_wm_state *active = &crtc->wm.active.g4x;
1392         enum plane_id plane_id;
1393
1394         intermediate->cxsr = optimal->cxsr && active->cxsr &&
1395                 !crtc_state->disable_cxsr;
1396         intermediate->hpll_en = optimal->hpll_en && active->hpll_en &&
1397                 !crtc_state->disable_cxsr;
1398         intermediate->fbc_en = optimal->fbc_en && active->fbc_en;
1399
1400         for_each_plane_id_on_crtc(crtc, plane_id) {
1401                 intermediate->wm.plane[plane_id] =
1402                         max(optimal->wm.plane[plane_id],
1403                             active->wm.plane[plane_id]);
1404
1405                 WARN_ON(intermediate->wm.plane[plane_id] >
1406                         g4x_plane_fifo_size(plane_id, G4X_WM_LEVEL_NORMAL));
1407         }
1408
1409         intermediate->sr.plane = max(optimal->sr.plane,
1410                                      active->sr.plane);
1411         intermediate->sr.cursor = max(optimal->sr.cursor,
1412                                       active->sr.cursor);
1413         intermediate->sr.fbc = max(optimal->sr.fbc,
1414                                    active->sr.fbc);
1415
1416         intermediate->hpll.plane = max(optimal->hpll.plane,
1417                                        active->hpll.plane);
1418         intermediate->hpll.cursor = max(optimal->hpll.cursor,
1419                                         active->hpll.cursor);
1420         intermediate->hpll.fbc = max(optimal->hpll.fbc,
1421                                      active->hpll.fbc);
1422
1423         WARN_ON((intermediate->sr.plane >
1424                  g4x_plane_fifo_size(PLANE_PRIMARY, G4X_WM_LEVEL_SR) ||
1425                  intermediate->sr.cursor >
1426                  g4x_plane_fifo_size(PLANE_CURSOR, G4X_WM_LEVEL_SR)) &&
1427                 intermediate->cxsr);
1428         WARN_ON((intermediate->sr.plane >
1429                  g4x_plane_fifo_size(PLANE_PRIMARY, G4X_WM_LEVEL_HPLL) ||
1430                  intermediate->sr.cursor >
1431                  g4x_plane_fifo_size(PLANE_CURSOR, G4X_WM_LEVEL_HPLL)) &&
1432                 intermediate->hpll_en);
1433
1434         WARN_ON(intermediate->sr.fbc > g4x_fbc_fifo_size(1) &&
1435                 intermediate->fbc_en && intermediate->cxsr);
1436         WARN_ON(intermediate->hpll.fbc > g4x_fbc_fifo_size(2) &&
1437                 intermediate->fbc_en && intermediate->hpll_en);
1438
1439         /*
1440          * If our intermediate WM are identical to the final WM, then we can
1441          * omit the post-vblank programming; only update if it's different.
1442          */
1443         if (memcmp(intermediate, optimal, sizeof(*intermediate)) != 0)
1444                 crtc_state->wm.need_postvbl_update = true;
1445
1446         return 0;
1447 }
1448
1449 static void g4x_merge_wm(struct drm_i915_private *dev_priv,
1450                          struct g4x_wm_values *wm)
1451 {
1452         struct intel_crtc *crtc;
1453         int num_active_crtcs = 0;
1454
1455         wm->cxsr = true;
1456         wm->hpll_en = true;
1457         wm->fbc_en = true;
1458
1459         for_each_intel_crtc(&dev_priv->drm, crtc) {
1460                 const struct g4x_wm_state *wm_state = &crtc->wm.active.g4x;
1461
1462                 if (!crtc->active)
1463                         continue;
1464
1465                 if (!wm_state->cxsr)
1466                         wm->cxsr = false;
1467                 if (!wm_state->hpll_en)
1468                         wm->hpll_en = false;
1469                 if (!wm_state->fbc_en)
1470                         wm->fbc_en = false;
1471
1472                 num_active_crtcs++;
1473         }
1474
1475         if (num_active_crtcs != 1) {
1476                 wm->cxsr = false;
1477                 wm->hpll_en = false;
1478                 wm->fbc_en = false;
1479         }
1480
1481         for_each_intel_crtc(&dev_priv->drm, crtc) {
1482                 const struct g4x_wm_state *wm_state = &crtc->wm.active.g4x;
1483                 enum pipe pipe = crtc->pipe;
1484
1485                 wm->pipe[pipe] = wm_state->wm;
1486                 if (crtc->active && wm->cxsr)
1487                         wm->sr = wm_state->sr;
1488                 if (crtc->active && wm->hpll_en)
1489                         wm->hpll = wm_state->hpll;
1490         }
1491 }
1492
1493 static void g4x_program_watermarks(struct drm_i915_private *dev_priv)
1494 {
1495         struct g4x_wm_values *old_wm = &dev_priv->wm.g4x;
1496         struct g4x_wm_values new_wm = {};
1497
1498         g4x_merge_wm(dev_priv, &new_wm);
1499
1500         if (memcmp(old_wm, &new_wm, sizeof(new_wm)) == 0)
1501                 return;
1502
1503         if (is_disabling(old_wm->cxsr, new_wm.cxsr, true))
1504                 _intel_set_memory_cxsr(dev_priv, false);
1505
1506         g4x_write_wm_values(dev_priv, &new_wm);
1507
1508         if (is_enabling(old_wm->cxsr, new_wm.cxsr, true))
1509                 _intel_set_memory_cxsr(dev_priv, true);
1510
1511         *old_wm = new_wm;
1512 }
1513
1514 static void g4x_initial_watermarks(struct intel_atomic_state *state,
1515                                    struct intel_crtc_state *crtc_state)
1516 {
1517         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1518         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1519
1520         mutex_lock(&dev_priv->wm.wm_mutex);
1521         crtc->wm.active.g4x = crtc_state->wm.g4x.intermediate;
1522         g4x_program_watermarks(dev_priv);
1523         mutex_unlock(&dev_priv->wm.wm_mutex);
1524 }
1525
1526 static void g4x_optimize_watermarks(struct intel_atomic_state *state,
1527                                     struct intel_crtc_state *crtc_state)
1528 {
1529         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
1531
1532         if (!crtc_state->wm.need_postvbl_update)
1533                 return;
1534
1535         mutex_lock(&dev_priv->wm.wm_mutex);
1536         intel_crtc->wm.active.g4x = crtc_state->wm.g4x.optimal;
1537         g4x_program_watermarks(dev_priv);
1538         mutex_unlock(&dev_priv->wm.wm_mutex);
1539 }
1540
1541 /* latency must be in 0.1us units. */
1542 static unsigned int vlv_wm_method2(unsigned int pixel_rate,
1543                                    unsigned int htotal,
1544                                    unsigned int width,
1545                                    unsigned int cpp,
1546                                    unsigned int latency)
1547 {
1548         unsigned int ret;
1549
1550         ret = intel_wm_method2(pixel_rate, htotal,
1551                                width, cpp, latency);
1552         ret = DIV_ROUND_UP(ret, 64);
1553
1554         return ret;
1555 }
1556
1557 static void vlv_setup_wm_latency(struct drm_i915_private *dev_priv)
1558 {
1559         /* all latencies in usec */
1560         dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM2] = 3;
1561
1562         dev_priv->wm.max_level = VLV_WM_LEVEL_PM2;
1563
1564         if (IS_CHERRYVIEW(dev_priv)) {
1565                 dev_priv->wm.pri_latency[VLV_WM_LEVEL_PM5] = 12;
1566                 dev_priv->wm.pri_latency[VLV_WM_LEVEL_DDR_DVFS] = 33;
1567
1568                 dev_priv->wm.max_level = VLV_WM_LEVEL_DDR_DVFS;
1569         }
1570 }
1571
1572 static uint16_t vlv_compute_wm_level(const struct intel_crtc_state *crtc_state,
1573                                      const struct intel_plane_state *plane_state,
1574                                      int level)
1575 {
1576         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1577         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1578         const struct drm_display_mode *adjusted_mode =
1579                 &crtc_state->base.adjusted_mode;
1580         int clock, htotal, cpp, width, wm;
1581
1582         if (dev_priv->wm.pri_latency[level] == 0)
1583                 return USHRT_MAX;
1584
1585         if (!intel_wm_plane_visible(crtc_state, plane_state))
1586                 return 0;
1587
1588         cpp = plane_state->base.fb->format->cpp[0];
1589         clock = adjusted_mode->crtc_clock;
1590         htotal = adjusted_mode->crtc_htotal;
1591         width = crtc_state->pipe_src_w;
1592
1593         if (plane->id == PLANE_CURSOR) {
1594                 /*
1595                  * FIXME the formula gives values that are
1596                  * too big for the cursor FIFO, and hence we
1597                  * would never be able to use cursors. For
1598                  * now just hardcode the watermark.
1599                  */
1600                 wm = 63;
1601         } else {
1602                 wm = vlv_wm_method2(clock, htotal, width, cpp,
1603                                     dev_priv->wm.pri_latency[level] * 10);
1604         }
1605
1606         return min_t(int, wm, USHRT_MAX);
1607 }
1608
1609 static bool vlv_need_sprite0_fifo_workaround(unsigned int active_planes)
1610 {
1611         return (active_planes & (BIT(PLANE_SPRITE0) |
1612                                  BIT(PLANE_SPRITE1))) == BIT(PLANE_SPRITE1);
1613 }
1614
1615 static int vlv_compute_fifo(struct intel_crtc_state *crtc_state)
1616 {
1617         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1618         const struct g4x_pipe_wm *raw =
1619                 &crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM2];
1620         struct vlv_fifo_state *fifo_state = &crtc_state->wm.vlv.fifo_state;
1621         unsigned int active_planes = crtc_state->active_planes & ~BIT(PLANE_CURSOR);
1622         int num_active_planes = hweight32(active_planes);
1623         const int fifo_size = 511;
1624         int fifo_extra, fifo_left = fifo_size;
1625         int sprite0_fifo_extra = 0;
1626         unsigned int total_rate;
1627         enum plane_id plane_id;
1628
1629         /*
1630          * When enabling sprite0 after sprite1 has already been enabled
1631          * we tend to get an underrun unless sprite0 already has some
1632          * FIFO space allcoated. Hence we always allocate at least one
1633          * cacheline for sprite0 whenever sprite1 is enabled.
1634          *
1635          * All other plane enable sequences appear immune to this problem.
1636          */
1637         if (vlv_need_sprite0_fifo_workaround(active_planes))
1638                 sprite0_fifo_extra = 1;
1639
1640         total_rate = raw->plane[PLANE_PRIMARY] +
1641                 raw->plane[PLANE_SPRITE0] +
1642                 raw->plane[PLANE_SPRITE1] +
1643                 sprite0_fifo_extra;
1644
1645         if (total_rate > fifo_size)
1646                 return -EINVAL;
1647
1648         if (total_rate == 0)
1649                 total_rate = 1;
1650
1651         for_each_plane_id_on_crtc(crtc, plane_id) {
1652                 unsigned int rate;
1653
1654                 if ((active_planes & BIT(plane_id)) == 0) {
1655                         fifo_state->plane[plane_id] = 0;
1656                         continue;
1657                 }
1658
1659                 rate = raw->plane[plane_id];
1660                 fifo_state->plane[plane_id] = fifo_size * rate / total_rate;
1661                 fifo_left -= fifo_state->plane[plane_id];
1662         }
1663
1664         fifo_state->plane[PLANE_SPRITE0] += sprite0_fifo_extra;
1665         fifo_left -= sprite0_fifo_extra;
1666
1667         fifo_state->plane[PLANE_CURSOR] = 63;
1668
1669         fifo_extra = DIV_ROUND_UP(fifo_left, num_active_planes ?: 1);
1670
1671         /* spread the remainder evenly */
1672         for_each_plane_id_on_crtc(crtc, plane_id) {
1673                 int plane_extra;
1674
1675                 if (fifo_left == 0)
1676                         break;
1677
1678                 if ((active_planes & BIT(plane_id)) == 0)
1679                         continue;
1680
1681                 plane_extra = min(fifo_extra, fifo_left);
1682                 fifo_state->plane[plane_id] += plane_extra;
1683                 fifo_left -= plane_extra;
1684         }
1685
1686         WARN_ON(active_planes != 0 && fifo_left != 0);
1687
1688         /* give it all to the first plane if none are active */
1689         if (active_planes == 0) {
1690                 WARN_ON(fifo_left != fifo_size);
1691                 fifo_state->plane[PLANE_PRIMARY] = fifo_left;
1692         }
1693
1694         return 0;
1695 }
1696
1697 /* mark all levels starting from 'level' as invalid */
1698 static void vlv_invalidate_wms(struct intel_crtc *crtc,
1699                                struct vlv_wm_state *wm_state, int level)
1700 {
1701         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1702
1703         for (; level < intel_wm_num_levels(dev_priv); level++) {
1704                 enum plane_id plane_id;
1705
1706                 for_each_plane_id_on_crtc(crtc, plane_id)
1707                         wm_state->wm[level].plane[plane_id] = USHRT_MAX;
1708
1709                 wm_state->sr[level].cursor = USHRT_MAX;
1710                 wm_state->sr[level].plane = USHRT_MAX;
1711         }
1712 }
1713
1714 static u16 vlv_invert_wm_value(u16 wm, u16 fifo_size)
1715 {
1716         if (wm > fifo_size)
1717                 return USHRT_MAX;
1718         else
1719                 return fifo_size - wm;
1720 }
1721
1722 /*
1723  * Starting from 'level' set all higher
1724  * levels to 'value' in the "raw" watermarks.
1725  */
1726 static bool vlv_raw_plane_wm_set(struct intel_crtc_state *crtc_state,
1727                                  int level, enum plane_id plane_id, u16 value)
1728 {
1729         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1730         int num_levels = intel_wm_num_levels(dev_priv);
1731         bool dirty = false;
1732
1733         for (; level < num_levels; level++) {
1734                 struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1735
1736                 dirty |= raw->plane[plane_id] != value;
1737                 raw->plane[plane_id] = value;
1738         }
1739
1740         return dirty;
1741 }
1742
1743 static bool vlv_raw_plane_wm_compute(struct intel_crtc_state *crtc_state,
1744                                      const struct intel_plane_state *plane_state)
1745 {
1746         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
1747         enum plane_id plane_id = plane->id;
1748         int num_levels = intel_wm_num_levels(to_i915(plane->base.dev));
1749         int level;
1750         bool dirty = false;
1751
1752         if (!intel_wm_plane_visible(crtc_state, plane_state)) {
1753                 dirty |= vlv_raw_plane_wm_set(crtc_state, 0, plane_id, 0);
1754                 goto out;
1755         }
1756
1757         for (level = 0; level < num_levels; level++) {
1758                 struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1759                 int wm = vlv_compute_wm_level(crtc_state, plane_state, level);
1760                 int max_wm = plane_id == PLANE_CURSOR ? 63 : 511;
1761
1762                 if (wm > max_wm)
1763                         break;
1764
1765                 dirty |= raw->plane[plane_id] != wm;
1766                 raw->plane[plane_id] = wm;
1767         }
1768
1769         /* mark all higher levels as invalid */
1770         dirty |= vlv_raw_plane_wm_set(crtc_state, level, plane_id, USHRT_MAX);
1771
1772 out:
1773         if (dirty)
1774                 DRM_DEBUG_KMS("%s watermarks: PM2=%d, PM5=%d, DDR DVFS=%d\n",
1775                               plane->base.name,
1776                               crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM2].plane[plane_id],
1777                               crtc_state->wm.vlv.raw[VLV_WM_LEVEL_PM5].plane[plane_id],
1778                               crtc_state->wm.vlv.raw[VLV_WM_LEVEL_DDR_DVFS].plane[plane_id]);
1779
1780         return dirty;
1781 }
1782
1783 static bool vlv_raw_plane_wm_is_valid(const struct intel_crtc_state *crtc_state,
1784                                       enum plane_id plane_id, int level)
1785 {
1786         const struct g4x_pipe_wm *raw =
1787                 &crtc_state->wm.vlv.raw[level];
1788         const struct vlv_fifo_state *fifo_state =
1789                 &crtc_state->wm.vlv.fifo_state;
1790
1791         return raw->plane[plane_id] <= fifo_state->plane[plane_id];
1792 }
1793
1794 static bool vlv_raw_crtc_wm_is_valid(const struct intel_crtc_state *crtc_state, int level)
1795 {
1796         return vlv_raw_plane_wm_is_valid(crtc_state, PLANE_PRIMARY, level) &&
1797                 vlv_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE0, level) &&
1798                 vlv_raw_plane_wm_is_valid(crtc_state, PLANE_SPRITE1, level) &&
1799                 vlv_raw_plane_wm_is_valid(crtc_state, PLANE_CURSOR, level);
1800 }
1801
1802 static int vlv_compute_pipe_wm(struct intel_crtc_state *crtc_state)
1803 {
1804         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1805         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1806         struct intel_atomic_state *state =
1807                 to_intel_atomic_state(crtc_state->base.state);
1808         struct vlv_wm_state *wm_state = &crtc_state->wm.vlv.optimal;
1809         const struct vlv_fifo_state *fifo_state =
1810                 &crtc_state->wm.vlv.fifo_state;
1811         int num_active_planes = hweight32(crtc_state->active_planes &
1812                                           ~BIT(PLANE_CURSOR));
1813         bool needs_modeset = drm_atomic_crtc_needs_modeset(&crtc_state->base);
1814         struct intel_plane_state *plane_state;
1815         struct intel_plane *plane;
1816         enum plane_id plane_id;
1817         int level, ret, i;
1818         unsigned int dirty = 0;
1819
1820         for_each_intel_plane_in_state(state, plane, plane_state, i) {
1821                 const struct intel_plane_state *old_plane_state =
1822                         to_intel_plane_state(plane->base.state);
1823
1824                 if (plane_state->base.crtc != &crtc->base &&
1825                     old_plane_state->base.crtc != &crtc->base)
1826                         continue;
1827
1828                 if (vlv_raw_plane_wm_compute(crtc_state, plane_state))
1829                         dirty |= BIT(plane->id);
1830         }
1831
1832         /*
1833          * DSPARB registers may have been reset due to the
1834          * power well being turned off. Make sure we restore
1835          * them to a consistent state even if no primary/sprite
1836          * planes are initially active.
1837          */
1838         if (needs_modeset)
1839                 crtc_state->fifo_changed = true;
1840
1841         if (!dirty)
1842                 return 0;
1843
1844         /* cursor changes don't warrant a FIFO recompute */
1845         if (dirty & ~BIT(PLANE_CURSOR)) {
1846                 const struct intel_crtc_state *old_crtc_state =
1847                         to_intel_crtc_state(crtc->base.state);
1848                 const struct vlv_fifo_state *old_fifo_state =
1849                         &old_crtc_state->wm.vlv.fifo_state;
1850
1851                 ret = vlv_compute_fifo(crtc_state);
1852                 if (ret)
1853                         return ret;
1854
1855                 if (needs_modeset ||
1856                     memcmp(old_fifo_state, fifo_state,
1857                            sizeof(*fifo_state)) != 0)
1858                         crtc_state->fifo_changed = true;
1859         }
1860
1861         /* initially allow all levels */
1862         wm_state->num_levels = intel_wm_num_levels(dev_priv);
1863         /*
1864          * Note that enabling cxsr with no primary/sprite planes
1865          * enabled can wedge the pipe. Hence we only allow cxsr
1866          * with exactly one enabled primary/sprite plane.
1867          */
1868         wm_state->cxsr = crtc->pipe != PIPE_C && num_active_planes == 1;
1869
1870         for (level = 0; level < wm_state->num_levels; level++) {
1871                 const struct g4x_pipe_wm *raw = &crtc_state->wm.vlv.raw[level];
1872                 const int sr_fifo_size = INTEL_INFO(dev_priv)->num_pipes * 512 - 1;
1873
1874                 if (!vlv_raw_crtc_wm_is_valid(crtc_state, level))
1875                         break;
1876
1877                 for_each_plane_id_on_crtc(crtc, plane_id) {
1878                         wm_state->wm[level].plane[plane_id] =
1879                                 vlv_invert_wm_value(raw->plane[plane_id],
1880                                                     fifo_state->plane[plane_id]);
1881                 }
1882
1883                 wm_state->sr[level].plane =
1884                         vlv_invert_wm_value(max3(raw->plane[PLANE_PRIMARY],
1885                                                  raw->plane[PLANE_SPRITE0],
1886                                                  raw->plane[PLANE_SPRITE1]),
1887                                             sr_fifo_size);
1888
1889                 wm_state->sr[level].cursor =
1890                         vlv_invert_wm_value(raw->plane[PLANE_CURSOR],
1891                                             63);
1892         }
1893
1894         if (level == 0)
1895                 return -EINVAL;
1896
1897         /* limit to only levels we can actually handle */
1898         wm_state->num_levels = level;
1899
1900         /* invalidate the higher levels */
1901         vlv_invalidate_wms(crtc, wm_state, level);
1902
1903         return 0;
1904 }
1905
1906 #define VLV_FIFO(plane, value) \
1907         (((value) << DSPARB_ ## plane ## _SHIFT_VLV) & DSPARB_ ## plane ## _MASK_VLV)
1908
1909 static void vlv_atomic_update_fifo(struct intel_atomic_state *state,
1910                                    struct intel_crtc_state *crtc_state)
1911 {
1912         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1913         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1914         const struct vlv_fifo_state *fifo_state =
1915                 &crtc_state->wm.vlv.fifo_state;
1916         int sprite0_start, sprite1_start, fifo_size;
1917
1918         if (!crtc_state->fifo_changed)
1919                 return;
1920
1921         sprite0_start = fifo_state->plane[PLANE_PRIMARY];
1922         sprite1_start = fifo_state->plane[PLANE_SPRITE0] + sprite0_start;
1923         fifo_size = fifo_state->plane[PLANE_SPRITE1] + sprite1_start;
1924
1925         WARN_ON(fifo_state->plane[PLANE_CURSOR] != 63);
1926         WARN_ON(fifo_size != 511);
1927
1928         trace_vlv_fifo_size(crtc, sprite0_start, sprite1_start, fifo_size);
1929
1930         /*
1931          * uncore.lock serves a double purpose here. It allows us to
1932          * use the less expensive I915_{READ,WRITE}_FW() functions, and
1933          * it protects the DSPARB registers from getting clobbered by
1934          * parallel updates from multiple pipes.
1935          *
1936          * intel_pipe_update_start() has already disabled interrupts
1937          * for us, so a plain spin_lock() is sufficient here.
1938          */
1939         spin_lock(&dev_priv->uncore.lock);
1940
1941         switch (crtc->pipe) {
1942                 uint32_t dsparb, dsparb2, dsparb3;
1943         case PIPE_A:
1944                 dsparb = I915_READ_FW(DSPARB);
1945                 dsparb2 = I915_READ_FW(DSPARB2);
1946
1947                 dsparb &= ~(VLV_FIFO(SPRITEA, 0xff) |
1948                             VLV_FIFO(SPRITEB, 0xff));
1949                 dsparb |= (VLV_FIFO(SPRITEA, sprite0_start) |
1950                            VLV_FIFO(SPRITEB, sprite1_start));
1951
1952                 dsparb2 &= ~(VLV_FIFO(SPRITEA_HI, 0x1) |
1953                              VLV_FIFO(SPRITEB_HI, 0x1));
1954                 dsparb2 |= (VLV_FIFO(SPRITEA_HI, sprite0_start >> 8) |
1955                            VLV_FIFO(SPRITEB_HI, sprite1_start >> 8));
1956
1957                 I915_WRITE_FW(DSPARB, dsparb);
1958                 I915_WRITE_FW(DSPARB2, dsparb2);
1959                 break;
1960         case PIPE_B:
1961                 dsparb = I915_READ_FW(DSPARB);
1962                 dsparb2 = I915_READ_FW(DSPARB2);
1963
1964                 dsparb &= ~(VLV_FIFO(SPRITEC, 0xff) |
1965                             VLV_FIFO(SPRITED, 0xff));
1966                 dsparb |= (VLV_FIFO(SPRITEC, sprite0_start) |
1967                            VLV_FIFO(SPRITED, sprite1_start));
1968
1969                 dsparb2 &= ~(VLV_FIFO(SPRITEC_HI, 0xff) |
1970                              VLV_FIFO(SPRITED_HI, 0xff));
1971                 dsparb2 |= (VLV_FIFO(SPRITEC_HI, sprite0_start >> 8) |
1972                            VLV_FIFO(SPRITED_HI, sprite1_start >> 8));
1973
1974                 I915_WRITE_FW(DSPARB, dsparb);
1975                 I915_WRITE_FW(DSPARB2, dsparb2);
1976                 break;
1977         case PIPE_C:
1978                 dsparb3 = I915_READ_FW(DSPARB3);
1979                 dsparb2 = I915_READ_FW(DSPARB2);
1980
1981                 dsparb3 &= ~(VLV_FIFO(SPRITEE, 0xff) |
1982                              VLV_FIFO(SPRITEF, 0xff));
1983                 dsparb3 |= (VLV_FIFO(SPRITEE, sprite0_start) |
1984                             VLV_FIFO(SPRITEF, sprite1_start));
1985
1986                 dsparb2 &= ~(VLV_FIFO(SPRITEE_HI, 0xff) |
1987                              VLV_FIFO(SPRITEF_HI, 0xff));
1988                 dsparb2 |= (VLV_FIFO(SPRITEE_HI, sprite0_start >> 8) |
1989                            VLV_FIFO(SPRITEF_HI, sprite1_start >> 8));
1990
1991                 I915_WRITE_FW(DSPARB3, dsparb3);
1992                 I915_WRITE_FW(DSPARB2, dsparb2);
1993                 break;
1994         default:
1995                 break;
1996         }
1997
1998         POSTING_READ_FW(DSPARB);
1999
2000         spin_unlock(&dev_priv->uncore.lock);
2001 }
2002
2003 #undef VLV_FIFO
2004
2005 static int vlv_compute_intermediate_wm(struct drm_device *dev,
2006                                        struct intel_crtc *crtc,
2007                                        struct intel_crtc_state *crtc_state)
2008 {
2009         struct vlv_wm_state *intermediate = &crtc_state->wm.vlv.intermediate;
2010         const struct vlv_wm_state *optimal = &crtc_state->wm.vlv.optimal;
2011         const struct vlv_wm_state *active = &crtc->wm.active.vlv;
2012         int level;
2013
2014         intermediate->num_levels = min(optimal->num_levels, active->num_levels);
2015         intermediate->cxsr = optimal->cxsr && active->cxsr &&
2016                 !crtc_state->disable_cxsr;
2017
2018         for (level = 0; level < intermediate->num_levels; level++) {
2019                 enum plane_id plane_id;
2020
2021                 for_each_plane_id_on_crtc(crtc, plane_id) {
2022                         intermediate->wm[level].plane[plane_id] =
2023                                 min(optimal->wm[level].plane[plane_id],
2024                                     active->wm[level].plane[plane_id]);
2025                 }
2026
2027                 intermediate->sr[level].plane = min(optimal->sr[level].plane,
2028                                                     active->sr[level].plane);
2029                 intermediate->sr[level].cursor = min(optimal->sr[level].cursor,
2030                                                      active->sr[level].cursor);
2031         }
2032
2033         vlv_invalidate_wms(crtc, intermediate, level);
2034
2035         /*
2036          * If our intermediate WM are identical to the final WM, then we can
2037          * omit the post-vblank programming; only update if it's different.
2038          */
2039         if (memcmp(intermediate, optimal, sizeof(*intermediate)) != 0)
2040                 crtc_state->wm.need_postvbl_update = true;
2041
2042         return 0;
2043 }
2044
2045 static void vlv_merge_wm(struct drm_i915_private *dev_priv,
2046                          struct vlv_wm_values *wm)
2047 {
2048         struct intel_crtc *crtc;
2049         int num_active_crtcs = 0;
2050
2051         wm->level = dev_priv->wm.max_level;
2052         wm->cxsr = true;
2053
2054         for_each_intel_crtc(&dev_priv->drm, crtc) {
2055                 const struct vlv_wm_state *wm_state = &crtc->wm.active.vlv;
2056
2057                 if (!crtc->active)
2058                         continue;
2059
2060                 if (!wm_state->cxsr)
2061                         wm->cxsr = false;
2062
2063                 num_active_crtcs++;
2064                 wm->level = min_t(int, wm->level, wm_state->num_levels - 1);
2065         }
2066
2067         if (num_active_crtcs != 1)
2068                 wm->cxsr = false;
2069
2070         if (num_active_crtcs > 1)
2071                 wm->level = VLV_WM_LEVEL_PM2;
2072
2073         for_each_intel_crtc(&dev_priv->drm, crtc) {
2074                 const struct vlv_wm_state *wm_state = &crtc->wm.active.vlv;
2075                 enum pipe pipe = crtc->pipe;
2076
2077                 wm->pipe[pipe] = wm_state->wm[wm->level];
2078                 if (crtc->active && wm->cxsr)
2079                         wm->sr = wm_state->sr[wm->level];
2080
2081                 wm->ddl[pipe].plane[PLANE_PRIMARY] = DDL_PRECISION_HIGH | 2;
2082                 wm->ddl[pipe].plane[PLANE_SPRITE0] = DDL_PRECISION_HIGH | 2;
2083                 wm->ddl[pipe].plane[PLANE_SPRITE1] = DDL_PRECISION_HIGH | 2;
2084                 wm->ddl[pipe].plane[PLANE_CURSOR] = DDL_PRECISION_HIGH | 2;
2085         }
2086 }
2087
2088 static void vlv_program_watermarks(struct drm_i915_private *dev_priv)
2089 {
2090         struct vlv_wm_values *old_wm = &dev_priv->wm.vlv;
2091         struct vlv_wm_values new_wm = {};
2092
2093         vlv_merge_wm(dev_priv, &new_wm);
2094
2095         if (memcmp(old_wm, &new_wm, sizeof(new_wm)) == 0)
2096                 return;
2097
2098         if (is_disabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_DDR_DVFS))
2099                 chv_set_memory_dvfs(dev_priv, false);
2100
2101         if (is_disabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_PM5))
2102                 chv_set_memory_pm5(dev_priv, false);
2103
2104         if (is_disabling(old_wm->cxsr, new_wm.cxsr, true))
2105                 _intel_set_memory_cxsr(dev_priv, false);
2106
2107         vlv_write_wm_values(dev_priv, &new_wm);
2108
2109         if (is_enabling(old_wm->cxsr, new_wm.cxsr, true))
2110                 _intel_set_memory_cxsr(dev_priv, true);
2111
2112         if (is_enabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_PM5))
2113                 chv_set_memory_pm5(dev_priv, true);
2114
2115         if (is_enabling(old_wm->level, new_wm.level, VLV_WM_LEVEL_DDR_DVFS))
2116                 chv_set_memory_dvfs(dev_priv, true);
2117
2118         *old_wm = new_wm;
2119 }
2120
2121 static void vlv_initial_watermarks(struct intel_atomic_state *state,
2122                                    struct intel_crtc_state *crtc_state)
2123 {
2124         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2125         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2126
2127         mutex_lock(&dev_priv->wm.wm_mutex);
2128         crtc->wm.active.vlv = crtc_state->wm.vlv.intermediate;
2129         vlv_program_watermarks(dev_priv);
2130         mutex_unlock(&dev_priv->wm.wm_mutex);
2131 }
2132
2133 static void vlv_optimize_watermarks(struct intel_atomic_state *state,
2134                                     struct intel_crtc_state *crtc_state)
2135 {
2136         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2137         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2138
2139         if (!crtc_state->wm.need_postvbl_update)
2140                 return;
2141
2142         mutex_lock(&dev_priv->wm.wm_mutex);
2143         intel_crtc->wm.active.vlv = crtc_state->wm.vlv.optimal;
2144         vlv_program_watermarks(dev_priv);
2145         mutex_unlock(&dev_priv->wm.wm_mutex);
2146 }
2147
2148 static void i965_update_wm(struct intel_crtc *unused_crtc)
2149 {
2150         struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2151         struct intel_crtc *crtc;
2152         int srwm = 1;
2153         int cursor_sr = 16;
2154         bool cxsr_enabled;
2155
2156         /* Calc sr entries for one plane configs */
2157         crtc = single_enabled_crtc(dev_priv);
2158         if (crtc) {
2159                 /* self-refresh has much higher latency */
2160                 static const int sr_latency_ns = 12000;
2161                 const struct drm_display_mode *adjusted_mode =
2162                         &crtc->config->base.adjusted_mode;
2163                 const struct drm_framebuffer *fb =
2164                         crtc->base.primary->state->fb;
2165                 int clock = adjusted_mode->crtc_clock;
2166                 int htotal = adjusted_mode->crtc_htotal;
2167                 int hdisplay = crtc->config->pipe_src_w;
2168                 int cpp = fb->format->cpp[0];
2169                 int entries;
2170
2171                 entries = intel_wm_method2(clock, htotal,
2172                                            hdisplay, cpp, sr_latency_ns / 100);
2173                 entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
2174                 srwm = I965_FIFO_SIZE - entries;
2175                 if (srwm < 0)
2176                         srwm = 1;
2177                 srwm &= 0x1ff;
2178                 DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
2179                               entries, srwm);
2180
2181                 entries = intel_wm_method2(clock, htotal,
2182                                            crtc->base.cursor->state->crtc_w, 4,
2183                                            sr_latency_ns / 100);
2184                 entries = DIV_ROUND_UP(entries,
2185                                        i965_cursor_wm_info.cacheline_size) +
2186                         i965_cursor_wm_info.guard_size;
2187
2188                 cursor_sr = i965_cursor_wm_info.fifo_size - entries;
2189                 if (cursor_sr > i965_cursor_wm_info.max_wm)
2190                         cursor_sr = i965_cursor_wm_info.max_wm;
2191
2192                 DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
2193                               "cursor %d\n", srwm, cursor_sr);
2194
2195                 cxsr_enabled = true;
2196         } else {
2197                 cxsr_enabled = false;
2198                 /* Turn off self refresh if both pipes are enabled */
2199                 intel_set_memory_cxsr(dev_priv, false);
2200         }
2201
2202         DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
2203                       srwm);
2204
2205         /* 965 has limitations... */
2206         I915_WRITE(DSPFW1, FW_WM(srwm, SR) |
2207                    FW_WM(8, CURSORB) |
2208                    FW_WM(8, PLANEB) |
2209                    FW_WM(8, PLANEA));
2210         I915_WRITE(DSPFW2, FW_WM(8, CURSORA) |
2211                    FW_WM(8, PLANEC_OLD));
2212         /* update cursor SR watermark */
2213         I915_WRITE(DSPFW3, FW_WM(cursor_sr, CURSOR_SR));
2214
2215         if (cxsr_enabled)
2216                 intel_set_memory_cxsr(dev_priv, true);
2217 }
2218
2219 #undef FW_WM
2220
2221 static void i9xx_update_wm(struct intel_crtc *unused_crtc)
2222 {
2223         struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2224         const struct intel_watermark_params *wm_info;
2225         uint32_t fwater_lo;
2226         uint32_t fwater_hi;
2227         int cwm, srwm = 1;
2228         int fifo_size;
2229         int planea_wm, planeb_wm;
2230         struct intel_crtc *crtc, *enabled = NULL;
2231
2232         if (IS_I945GM(dev_priv))
2233                 wm_info = &i945_wm_info;
2234         else if (!IS_GEN2(dev_priv))
2235                 wm_info = &i915_wm_info;
2236         else
2237                 wm_info = &i830_a_wm_info;
2238
2239         fifo_size = dev_priv->display.get_fifo_size(dev_priv, 0);
2240         crtc = intel_get_crtc_for_plane(dev_priv, 0);
2241         if (intel_crtc_active(crtc)) {
2242                 const struct drm_display_mode *adjusted_mode =
2243                         &crtc->config->base.adjusted_mode;
2244                 const struct drm_framebuffer *fb =
2245                         crtc->base.primary->state->fb;
2246                 int cpp;
2247
2248                 if (IS_GEN2(dev_priv))
2249                         cpp = 4;
2250                 else
2251                         cpp = fb->format->cpp[0];
2252
2253                 planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2254                                                wm_info, fifo_size, cpp,
2255                                                pessimal_latency_ns);
2256                 enabled = crtc;
2257         } else {
2258                 planea_wm = fifo_size - wm_info->guard_size;
2259                 if (planea_wm > (long)wm_info->max_wm)
2260                         planea_wm = wm_info->max_wm;
2261         }
2262
2263         if (IS_GEN2(dev_priv))
2264                 wm_info = &i830_bc_wm_info;
2265
2266         fifo_size = dev_priv->display.get_fifo_size(dev_priv, 1);
2267         crtc = intel_get_crtc_for_plane(dev_priv, 1);
2268         if (intel_crtc_active(crtc)) {
2269                 const struct drm_display_mode *adjusted_mode =
2270                         &crtc->config->base.adjusted_mode;
2271                 const struct drm_framebuffer *fb =
2272                         crtc->base.primary->state->fb;
2273                 int cpp;
2274
2275                 if (IS_GEN2(dev_priv))
2276                         cpp = 4;
2277                 else
2278                         cpp = fb->format->cpp[0];
2279
2280                 planeb_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2281                                                wm_info, fifo_size, cpp,
2282                                                pessimal_latency_ns);
2283                 if (enabled == NULL)
2284                         enabled = crtc;
2285                 else
2286                         enabled = NULL;
2287         } else {
2288                 planeb_wm = fifo_size - wm_info->guard_size;
2289                 if (planeb_wm > (long)wm_info->max_wm)
2290                         planeb_wm = wm_info->max_wm;
2291         }
2292
2293         DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
2294
2295         if (IS_I915GM(dev_priv) && enabled) {
2296                 struct drm_i915_gem_object *obj;
2297
2298                 obj = intel_fb_obj(enabled->base.primary->state->fb);
2299
2300                 /* self-refresh seems busted with untiled */
2301                 if (!i915_gem_object_is_tiled(obj))
2302                         enabled = NULL;
2303         }
2304
2305         /*
2306          * Overlay gets an aggressive default since video jitter is bad.
2307          */
2308         cwm = 2;
2309
2310         /* Play safe and disable self-refresh before adjusting watermarks. */
2311         intel_set_memory_cxsr(dev_priv, false);
2312
2313         /* Calc sr entries for one plane configs */
2314         if (HAS_FW_BLC(dev_priv) && enabled) {
2315                 /* self-refresh has much higher latency */
2316                 static const int sr_latency_ns = 6000;
2317                 const struct drm_display_mode *adjusted_mode =
2318                         &enabled->config->base.adjusted_mode;
2319                 const struct drm_framebuffer *fb =
2320                         enabled->base.primary->state->fb;
2321                 int clock = adjusted_mode->crtc_clock;
2322                 int htotal = adjusted_mode->crtc_htotal;
2323                 int hdisplay = enabled->config->pipe_src_w;
2324                 int cpp;
2325                 int entries;
2326
2327                 if (IS_I915GM(dev_priv) || IS_I945GM(dev_priv))
2328                         cpp = 4;
2329                 else
2330                         cpp = fb->format->cpp[0];
2331
2332                 entries = intel_wm_method2(clock, htotal, hdisplay, cpp,
2333                                            sr_latency_ns / 100);
2334                 entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
2335                 DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
2336                 srwm = wm_info->fifo_size - entries;
2337                 if (srwm < 0)
2338                         srwm = 1;
2339
2340                 if (IS_I945G(dev_priv) || IS_I945GM(dev_priv))
2341                         I915_WRITE(FW_BLC_SELF,
2342                                    FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
2343                 else
2344                         I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
2345         }
2346
2347         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
2348                       planea_wm, planeb_wm, cwm, srwm);
2349
2350         fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
2351         fwater_hi = (cwm & 0x1f);
2352
2353         /* Set request length to 8 cachelines per fetch */
2354         fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
2355         fwater_hi = fwater_hi | (1 << 8);
2356
2357         I915_WRITE(FW_BLC, fwater_lo);
2358         I915_WRITE(FW_BLC2, fwater_hi);
2359
2360         if (enabled)
2361                 intel_set_memory_cxsr(dev_priv, true);
2362 }
2363
2364 static void i845_update_wm(struct intel_crtc *unused_crtc)
2365 {
2366         struct drm_i915_private *dev_priv = to_i915(unused_crtc->base.dev);
2367         struct intel_crtc *crtc;
2368         const struct drm_display_mode *adjusted_mode;
2369         uint32_t fwater_lo;
2370         int planea_wm;
2371
2372         crtc = single_enabled_crtc(dev_priv);
2373         if (crtc == NULL)
2374                 return;
2375
2376         adjusted_mode = &crtc->config->base.adjusted_mode;
2377         planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
2378                                        &i845_wm_info,
2379                                        dev_priv->display.get_fifo_size(dev_priv, 0),
2380                                        4, pessimal_latency_ns);
2381         fwater_lo = I915_READ(FW_BLC) & ~0xfff;
2382         fwater_lo |= (3<<8) | planea_wm;
2383
2384         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
2385
2386         I915_WRITE(FW_BLC, fwater_lo);
2387 }
2388
2389 /* latency must be in 0.1us units. */
2390 static unsigned int ilk_wm_method1(unsigned int pixel_rate,
2391                                    unsigned int cpp,
2392                                    unsigned int latency)
2393 {
2394         unsigned int ret;
2395
2396         ret = intel_wm_method1(pixel_rate, cpp, latency);
2397         ret = DIV_ROUND_UP(ret, 64) + 2;
2398
2399         return ret;
2400 }
2401
2402 /* latency must be in 0.1us units. */
2403 static unsigned int ilk_wm_method2(unsigned int pixel_rate,
2404                                    unsigned int htotal,
2405                                    unsigned int width,
2406                                    unsigned int cpp,
2407                                    unsigned int latency)
2408 {
2409         unsigned int ret;
2410
2411         ret = intel_wm_method2(pixel_rate, htotal,
2412                                width, cpp, latency);
2413         ret = DIV_ROUND_UP(ret, 64) + 2;
2414
2415         return ret;
2416 }
2417
2418 static uint32_t ilk_wm_fbc(uint32_t pri_val, uint32_t horiz_pixels,
2419                            uint8_t cpp)
2420 {
2421         /*
2422          * Neither of these should be possible since this function shouldn't be
2423          * called if the CRTC is off or the plane is invisible.  But let's be
2424          * extra paranoid to avoid a potential divide-by-zero if we screw up
2425          * elsewhere in the driver.
2426          */
2427         if (WARN_ON(!cpp))
2428                 return 0;
2429         if (WARN_ON(!horiz_pixels))
2430                 return 0;
2431
2432         return DIV_ROUND_UP(pri_val * 64, horiz_pixels * cpp) + 2;
2433 }
2434
2435 struct ilk_wm_maximums {
2436         uint16_t pri;
2437         uint16_t spr;
2438         uint16_t cur;
2439         uint16_t fbc;
2440 };
2441
2442 /*
2443  * For both WM_PIPE and WM_LP.
2444  * mem_value must be in 0.1us units.
2445  */
2446 static uint32_t ilk_compute_pri_wm(const struct intel_crtc_state *cstate,
2447                                    const struct intel_plane_state *pstate,
2448                                    uint32_t mem_value,
2449                                    bool is_lp)
2450 {
2451         uint32_t method1, method2;
2452         int cpp;
2453
2454         if (!intel_wm_plane_visible(cstate, pstate))
2455                 return 0;
2456
2457         cpp = pstate->base.fb->format->cpp[0];
2458
2459         method1 = ilk_wm_method1(cstate->pixel_rate, cpp, mem_value);
2460
2461         if (!is_lp)
2462                 return method1;
2463
2464         method2 = ilk_wm_method2(cstate->pixel_rate,
2465                                  cstate->base.adjusted_mode.crtc_htotal,
2466                                  drm_rect_width(&pstate->base.dst),
2467                                  cpp, mem_value);
2468
2469         return min(method1, method2);
2470 }
2471
2472 /*
2473  * For both WM_PIPE and WM_LP.
2474  * mem_value must be in 0.1us units.
2475  */
2476 static uint32_t ilk_compute_spr_wm(const struct intel_crtc_state *cstate,
2477                                    const struct intel_plane_state *pstate,
2478                                    uint32_t mem_value)
2479 {
2480         uint32_t method1, method2;
2481         int cpp;
2482
2483         if (!intel_wm_plane_visible(cstate, pstate))
2484                 return 0;
2485
2486         cpp = pstate->base.fb->format->cpp[0];
2487
2488         method1 = ilk_wm_method1(cstate->pixel_rate, cpp, mem_value);
2489         method2 = ilk_wm_method2(cstate->pixel_rate,
2490                                  cstate->base.adjusted_mode.crtc_htotal,
2491                                  drm_rect_width(&pstate->base.dst),
2492                                  cpp, mem_value);
2493         return min(method1, method2);
2494 }
2495
2496 /*
2497  * For both WM_PIPE and WM_LP.
2498  * mem_value must be in 0.1us units.
2499  */
2500 static uint32_t ilk_compute_cur_wm(const struct intel_crtc_state *cstate,
2501                                    const struct intel_plane_state *pstate,
2502                                    uint32_t mem_value)
2503 {
2504         int cpp;
2505
2506         if (!intel_wm_plane_visible(cstate, pstate))
2507                 return 0;
2508
2509         cpp = pstate->base.fb->format->cpp[0];
2510
2511         return ilk_wm_method2(cstate->pixel_rate,
2512                               cstate->base.adjusted_mode.crtc_htotal,
2513                               pstate->base.crtc_w, cpp, mem_value);
2514 }
2515
2516 /* Only for WM_LP. */
2517 static uint32_t ilk_compute_fbc_wm(const struct intel_crtc_state *cstate,
2518                                    const struct intel_plane_state *pstate,
2519                                    uint32_t pri_val)
2520 {
2521         int cpp;
2522
2523         if (!intel_wm_plane_visible(cstate, pstate))
2524                 return 0;
2525
2526         cpp = pstate->base.fb->format->cpp[0];
2527
2528         return ilk_wm_fbc(pri_val, drm_rect_width(&pstate->base.dst), cpp);
2529 }
2530
2531 static unsigned int
2532 ilk_display_fifo_size(const struct drm_i915_private *dev_priv)
2533 {
2534         if (INTEL_GEN(dev_priv) >= 8)
2535                 return 3072;
2536         else if (INTEL_GEN(dev_priv) >= 7)
2537                 return 768;
2538         else
2539                 return 512;
2540 }
2541
2542 static unsigned int
2543 ilk_plane_wm_reg_max(const struct drm_i915_private *dev_priv,
2544                      int level, bool is_sprite)
2545 {
2546         if (INTEL_GEN(dev_priv) >= 8)
2547                 /* BDW primary/sprite plane watermarks */
2548                 return level == 0 ? 255 : 2047;
2549         else if (INTEL_GEN(dev_priv) >= 7)
2550                 /* IVB/HSW primary/sprite plane watermarks */
2551                 return level == 0 ? 127 : 1023;
2552         else if (!is_sprite)
2553                 /* ILK/SNB primary plane watermarks */
2554                 return level == 0 ? 127 : 511;
2555         else
2556                 /* ILK/SNB sprite plane watermarks */
2557                 return level == 0 ? 63 : 255;
2558 }
2559
2560 static unsigned int
2561 ilk_cursor_wm_reg_max(const struct drm_i915_private *dev_priv, int level)
2562 {
2563         if (INTEL_GEN(dev_priv) >= 7)
2564                 return level == 0 ? 63 : 255;
2565         else
2566                 return level == 0 ? 31 : 63;
2567 }
2568
2569 static unsigned int ilk_fbc_wm_reg_max(const struct drm_i915_private *dev_priv)
2570 {
2571         if (INTEL_GEN(dev_priv) >= 8)
2572                 return 31;
2573         else
2574                 return 15;
2575 }
2576
2577 /* Calculate the maximum primary/sprite plane watermark */
2578 static unsigned int ilk_plane_wm_max(const struct drm_device *dev,
2579                                      int level,
2580                                      const struct intel_wm_config *config,
2581                                      enum intel_ddb_partitioning ddb_partitioning,
2582                                      bool is_sprite)
2583 {
2584         struct drm_i915_private *dev_priv = to_i915(dev);
2585         unsigned int fifo_size = ilk_display_fifo_size(dev_priv);
2586
2587         /* if sprites aren't enabled, sprites get nothing */
2588         if (is_sprite && !config->sprites_enabled)
2589                 return 0;
2590
2591         /* HSW allows LP1+ watermarks even with multiple pipes */
2592         if (level == 0 || config->num_pipes_active > 1) {
2593                 fifo_size /= INTEL_INFO(dev_priv)->num_pipes;
2594
2595                 /*
2596                  * For some reason the non self refresh
2597                  * FIFO size is only half of the self
2598                  * refresh FIFO size on ILK/SNB.
2599                  */
2600                 if (INTEL_GEN(dev_priv) <= 6)
2601                         fifo_size /= 2;
2602         }
2603
2604         if (config->sprites_enabled) {
2605                 /* level 0 is always calculated with 1:1 split */
2606                 if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
2607                         if (is_sprite)
2608                                 fifo_size *= 5;
2609                         fifo_size /= 6;
2610                 } else {
2611                         fifo_size /= 2;
2612                 }
2613         }
2614
2615         /* clamp to max that the registers can hold */
2616         return min(fifo_size, ilk_plane_wm_reg_max(dev_priv, level, is_sprite));
2617 }
2618
2619 /* Calculate the maximum cursor plane watermark */
2620 static unsigned int ilk_cursor_wm_max(const struct drm_device *dev,
2621                                       int level,
2622                                       const struct intel_wm_config *config)
2623 {
2624         /* HSW LP1+ watermarks w/ multiple pipes */
2625         if (level > 0 && config->num_pipes_active > 1)
2626                 return 64;
2627
2628         /* otherwise just report max that registers can hold */
2629         return ilk_cursor_wm_reg_max(to_i915(dev), level);
2630 }
2631
2632 static void ilk_compute_wm_maximums(const struct drm_device *dev,
2633                                     int level,
2634                                     const struct intel_wm_config *config,
2635                                     enum intel_ddb_partitioning ddb_partitioning,
2636                                     struct ilk_wm_maximums *max)
2637 {
2638         max->pri = ilk_plane_wm_max(dev, level, config, ddb_partitioning, false);
2639         max->spr = ilk_plane_wm_max(dev, level, config, ddb_partitioning, true);
2640         max->cur = ilk_cursor_wm_max(dev, level, config);
2641         max->fbc = ilk_fbc_wm_reg_max(to_i915(dev));
2642 }
2643
2644 static void ilk_compute_wm_reg_maximums(const struct drm_i915_private *dev_priv,
2645                                         int level,
2646                                         struct ilk_wm_maximums *max)
2647 {
2648         max->pri = ilk_plane_wm_reg_max(dev_priv, level, false);
2649         max->spr = ilk_plane_wm_reg_max(dev_priv, level, true);
2650         max->cur = ilk_cursor_wm_reg_max(dev_priv, level);
2651         max->fbc = ilk_fbc_wm_reg_max(dev_priv);
2652 }
2653
2654 static bool ilk_validate_wm_level(int level,
2655                                   const struct ilk_wm_maximums *max,
2656                                   struct intel_wm_level *result)
2657 {
2658         bool ret;
2659
2660         /* already determined to be invalid? */
2661         if (!result->enable)
2662                 return false;
2663
2664         result->enable = result->pri_val <= max->pri &&
2665                          result->spr_val <= max->spr &&
2666                          result->cur_val <= max->cur;
2667
2668         ret = result->enable;
2669
2670         /*
2671          * HACK until we can pre-compute everything,
2672          * and thus fail gracefully if LP0 watermarks
2673          * are exceeded...
2674          */
2675         if (level == 0 && !result->enable) {
2676                 if (result->pri_val > max->pri)
2677                         DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
2678                                       level, result->pri_val, max->pri);
2679                 if (result->spr_val > max->spr)
2680                         DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
2681                                       level, result->spr_val, max->spr);
2682                 if (result->cur_val > max->cur)
2683                         DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
2684                                       level, result->cur_val, max->cur);
2685
2686                 result->pri_val = min_t(uint32_t, result->pri_val, max->pri);
2687                 result->spr_val = min_t(uint32_t, result->spr_val, max->spr);
2688                 result->cur_val = min_t(uint32_t, result->cur_val, max->cur);
2689                 result->enable = true;
2690         }
2691
2692         return ret;
2693 }
2694
2695 static void ilk_compute_wm_level(const struct drm_i915_private *dev_priv,
2696                                  const struct intel_crtc *intel_crtc,
2697                                  int level,
2698                                  struct intel_crtc_state *cstate,
2699                                  struct intel_plane_state *pristate,
2700                                  struct intel_plane_state *sprstate,
2701                                  struct intel_plane_state *curstate,
2702                                  struct intel_wm_level *result)
2703 {
2704         uint16_t pri_latency = dev_priv->wm.pri_latency[level];
2705         uint16_t spr_latency = dev_priv->wm.spr_latency[level];
2706         uint16_t cur_latency = dev_priv->wm.cur_latency[level];
2707
2708         /* WM1+ latency values stored in 0.5us units */
2709         if (level > 0) {
2710                 pri_latency *= 5;
2711                 spr_latency *= 5;
2712                 cur_latency *= 5;
2713         }
2714
2715         if (pristate) {
2716                 result->pri_val = ilk_compute_pri_wm(cstate, pristate,
2717                                                      pri_latency, level);
2718                 result->fbc_val = ilk_compute_fbc_wm(cstate, pristate, result->pri_val);
2719         }
2720
2721         if (sprstate)
2722                 result->spr_val = ilk_compute_spr_wm(cstate, sprstate, spr_latency);
2723
2724         if (curstate)
2725                 result->cur_val = ilk_compute_cur_wm(cstate, curstate, cur_latency);
2726
2727         result->enable = true;
2728 }
2729
2730 static uint32_t
2731 hsw_compute_linetime_wm(const struct intel_crtc_state *cstate)
2732 {
2733         const struct intel_atomic_state *intel_state =
2734                 to_intel_atomic_state(cstate->base.state);
2735         const struct drm_display_mode *adjusted_mode =
2736                 &cstate->base.adjusted_mode;
2737         u32 linetime, ips_linetime;
2738
2739         if (!cstate->base.active)
2740                 return 0;
2741         if (WARN_ON(adjusted_mode->crtc_clock == 0))
2742                 return 0;
2743         if (WARN_ON(intel_state->cdclk.logical.cdclk == 0))
2744                 return 0;
2745
2746         /* The WM are computed with base on how long it takes to fill a single
2747          * row at the given clock rate, multiplied by 8.
2748          * */
2749         linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2750                                      adjusted_mode->crtc_clock);
2751         ips_linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2752                                          intel_state->cdclk.logical.cdclk);
2753
2754         return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
2755                PIPE_WM_LINETIME_TIME(linetime);
2756 }
2757
2758 static void intel_read_wm_latency(struct drm_i915_private *dev_priv,
2759                                   uint16_t wm[8])
2760 {
2761         if (IS_GEN9(dev_priv)) {
2762                 uint32_t val;
2763                 int ret, i;
2764                 int level, max_level = ilk_wm_max_level(dev_priv);
2765
2766                 /* read the first set of memory latencies[0:3] */
2767                 val = 0; /* data0 to be programmed to 0 for first set */
2768                 mutex_lock(&dev_priv->rps.hw_lock);
2769                 ret = sandybridge_pcode_read(dev_priv,
2770                                              GEN9_PCODE_READ_MEM_LATENCY,
2771                                              &val);
2772                 mutex_unlock(&dev_priv->rps.hw_lock);
2773
2774                 if (ret) {
2775                         DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2776                         return;
2777                 }
2778
2779                 wm[0] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2780                 wm[1] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2781                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2782                 wm[2] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2783                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2784                 wm[3] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2785                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2786
2787                 /* read the second set of memory latencies[4:7] */
2788                 val = 1; /* data0 to be programmed to 1 for second set */
2789                 mutex_lock(&dev_priv->rps.hw_lock);
2790                 ret = sandybridge_pcode_read(dev_priv,
2791                                              GEN9_PCODE_READ_MEM_LATENCY,
2792                                              &val);
2793                 mutex_unlock(&dev_priv->rps.hw_lock);
2794                 if (ret) {
2795                         DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2796                         return;
2797                 }
2798
2799                 wm[4] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2800                 wm[5] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2801                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2802                 wm[6] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2803                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2804                 wm[7] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2805                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2806
2807                 /*
2808                  * If a level n (n > 1) has a 0us latency, all levels m (m >= n)
2809                  * need to be disabled. We make sure to sanitize the values out
2810                  * of the punit to satisfy this requirement.
2811                  */
2812                 for (level = 1; level <= max_level; level++) {
2813                         if (wm[level] == 0) {
2814                                 for (i = level + 1; i <= max_level; i++)
2815                                         wm[i] = 0;
2816                                 break;
2817                         }
2818                 }
2819
2820                 /*
2821                  * WaWmMemoryReadLatency:skl,glk
2822                  *
2823                  * punit doesn't take into account the read latency so we need
2824                  * to add 2us to the various latency levels we retrieve from the
2825                  * punit when level 0 response data us 0us.
2826                  */
2827                 if (wm[0] == 0) {
2828                         wm[0] += 2;
2829                         for (level = 1; level <= max_level; level++) {
2830                                 if (wm[level] == 0)
2831                                         break;
2832                                 wm[level] += 2;
2833                         }
2834                 }
2835
2836         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2837                 uint64_t sskpd = I915_READ64(MCH_SSKPD);
2838
2839                 wm[0] = (sskpd >> 56) & 0xFF;
2840                 if (wm[0] == 0)
2841                         wm[0] = sskpd & 0xF;
2842                 wm[1] = (sskpd >> 4) & 0xFF;
2843                 wm[2] = (sskpd >> 12) & 0xFF;
2844                 wm[3] = (sskpd >> 20) & 0x1FF;
2845                 wm[4] = (sskpd >> 32) & 0x1FF;
2846         } else if (INTEL_GEN(dev_priv) >= 6) {
2847                 uint32_t sskpd = I915_READ(MCH_SSKPD);
2848
2849                 wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
2850                 wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
2851                 wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
2852                 wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
2853         } else if (INTEL_GEN(dev_priv) >= 5) {
2854                 uint32_t mltr = I915_READ(MLTR_ILK);
2855
2856                 /* ILK primary LP0 latency is 700 ns */
2857                 wm[0] = 7;
2858                 wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
2859                 wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
2860         }
2861 }
2862
2863 static void intel_fixup_spr_wm_latency(struct drm_i915_private *dev_priv,
2864                                        uint16_t wm[5])
2865 {
2866         /* ILK sprite LP0 latency is 1300 ns */
2867         if (IS_GEN5(dev_priv))
2868                 wm[0] = 13;
2869 }
2870
2871 static void intel_fixup_cur_wm_latency(struct drm_i915_private *dev_priv,
2872                                        uint16_t wm[5])
2873 {
2874         /* ILK cursor LP0 latency is 1300 ns */
2875         if (IS_GEN5(dev_priv))
2876                 wm[0] = 13;
2877
2878         /* WaDoubleCursorLP3Latency:ivb */
2879         if (IS_IVYBRIDGE(dev_priv))
2880                 wm[3] *= 2;
2881 }
2882
2883 int ilk_wm_max_level(const struct drm_i915_private *dev_priv)
2884 {
2885         /* how many WM levels are we expecting */
2886         if (INTEL_GEN(dev_priv) >= 9)
2887                 return 7;
2888         else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2889                 return 4;
2890         else if (INTEL_GEN(dev_priv) >= 6)
2891                 return 3;
2892         else
2893                 return 2;
2894 }
2895
2896 static void intel_print_wm_latency(struct drm_i915_private *dev_priv,
2897                                    const char *name,
2898                                    const uint16_t wm[8])
2899 {
2900         int level, max_level = ilk_wm_max_level(dev_priv);
2901
2902         for (level = 0; level <= max_level; level++) {
2903                 unsigned int latency = wm[level];
2904
2905                 if (latency == 0) {
2906                         DRM_ERROR("%s WM%d latency not provided\n",
2907                                   name, level);
2908                         continue;
2909                 }
2910
2911                 /*
2912                  * - latencies are in us on gen9.
2913                  * - before then, WM1+ latency values are in 0.5us units
2914                  */
2915                 if (IS_GEN9(dev_priv))
2916                         latency *= 10;
2917                 else if (level > 0)
2918                         latency *= 5;
2919
2920                 DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
2921                               name, level, wm[level],
2922                               latency / 10, latency % 10);
2923         }
2924 }
2925
2926 static bool ilk_increase_wm_latency(struct drm_i915_private *dev_priv,
2927                                     uint16_t wm[5], uint16_t min)
2928 {
2929         int level, max_level = ilk_wm_max_level(dev_priv);
2930
2931         if (wm[0] >= min)
2932                 return false;
2933
2934         wm[0] = max(wm[0], min);
2935         for (level = 1; level <= max_level; level++)
2936                 wm[level] = max_t(uint16_t, wm[level], DIV_ROUND_UP(min, 5));
2937
2938         return true;
2939 }
2940
2941 static void snb_wm_latency_quirk(struct drm_i915_private *dev_priv)
2942 {
2943         bool changed;
2944
2945         /*
2946          * The BIOS provided WM memory latency values are often
2947          * inadequate for high resolution displays. Adjust them.
2948          */
2949         changed = ilk_increase_wm_latency(dev_priv, dev_priv->wm.pri_latency, 12) |
2950                 ilk_increase_wm_latency(dev_priv, dev_priv->wm.spr_latency, 12) |
2951                 ilk_increase_wm_latency(dev_priv, dev_priv->wm.cur_latency, 12);
2952
2953         if (!changed)
2954                 return;
2955
2956         DRM_DEBUG_KMS("WM latency values increased to avoid potential underruns\n");
2957         intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
2958         intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
2959         intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
2960 }
2961
2962 static void ilk_setup_wm_latency(struct drm_i915_private *dev_priv)
2963 {
2964         intel_read_wm_latency(dev_priv, dev_priv->wm.pri_latency);
2965
2966         memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
2967                sizeof(dev_priv->wm.pri_latency));
2968         memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
2969                sizeof(dev_priv->wm.pri_latency));
2970
2971         intel_fixup_spr_wm_latency(dev_priv, dev_priv->wm.spr_latency);
2972         intel_fixup_cur_wm_latency(dev_priv, dev_priv->wm.cur_latency);
2973
2974         intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
2975         intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
2976         intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
2977
2978         if (IS_GEN6(dev_priv))
2979                 snb_wm_latency_quirk(dev_priv);
2980 }
2981
2982 static void skl_setup_wm_latency(struct drm_i915_private *dev_priv)
2983 {
2984         intel_read_wm_latency(dev_priv, dev_priv->wm.skl_latency);
2985         intel_print_wm_latency(dev_priv, "Gen9 Plane", dev_priv->wm.skl_latency);
2986 }
2987
2988 static bool ilk_validate_pipe_wm(struct drm_device *dev,
2989                                  struct intel_pipe_wm *pipe_wm)
2990 {
2991         /* LP0 watermark maximums depend on this pipe alone */
2992         const struct intel_wm_config config = {
2993                 .num_pipes_active = 1,
2994                 .sprites_enabled = pipe_wm->sprites_enabled,
2995                 .sprites_scaled = pipe_wm->sprites_scaled,
2996         };
2997         struct ilk_wm_maximums max;
2998
2999         /* LP0 watermarks always use 1/2 DDB partitioning */
3000         ilk_compute_wm_maximums(dev, 0, &config, INTEL_DDB_PART_1_2, &max);
3001
3002         /* At least LP0 must be valid */
3003         if (!ilk_validate_wm_level(0, &max, &pipe_wm->wm[0])) {
3004                 DRM_DEBUG_KMS("LP0 watermark invalid\n");
3005                 return false;
3006         }
3007
3008         return true;
3009 }
3010
3011 /* Compute new watermarks for the pipe */
3012 static int ilk_compute_pipe_wm(struct intel_crtc_state *cstate)
3013 {
3014         struct drm_atomic_state *state = cstate->base.state;
3015         struct intel_crtc *intel_crtc = to_intel_crtc(cstate->base.crtc);
3016         struct intel_pipe_wm *pipe_wm;
3017         struct drm_device *dev = state->dev;
3018         const struct drm_i915_private *dev_priv = to_i915(dev);
3019         struct intel_plane *intel_plane;
3020         struct intel_plane_state *pristate = NULL;
3021         struct intel_plane_state *sprstate = NULL;
3022         struct intel_plane_state *curstate = NULL;
3023         int level, max_level = ilk_wm_max_level(dev_priv), usable_level;
3024         struct ilk_wm_maximums max;
3025
3026         pipe_wm = &cstate->wm.ilk.optimal;
3027
3028         for_each_intel_plane_on_crtc(dev, intel_crtc, intel_plane) {
3029                 struct intel_plane_state *ps;
3030
3031                 ps = intel_atomic_get_existing_plane_state(state,
3032                                                            intel_plane);
3033                 if (!ps)
3034                         continue;
3035
3036                 if (intel_plane->base.type == DRM_PLANE_TYPE_PRIMARY)
3037                         pristate = ps;
3038                 else if (intel_plane->base.type == DRM_PLANE_TYPE_OVERLAY)
3039                         sprstate = ps;
3040                 else if (intel_plane->base.type == DRM_PLANE_TYPE_CURSOR)
3041                         curstate = ps;
3042         }
3043
3044         pipe_wm->pipe_enabled = cstate->base.active;
3045         if (sprstate) {
3046                 pipe_wm->sprites_enabled = sprstate->base.visible;
3047                 pipe_wm->sprites_scaled = sprstate->base.visible &&
3048                         (drm_rect_width(&sprstate->base.dst) != drm_rect_width(&sprstate->base.src) >> 16 ||
3049                          drm_rect_height(&sprstate->base.dst) != drm_rect_height(&sprstate->base.src) >> 16);
3050         }
3051
3052         usable_level = max_level;
3053
3054         /* ILK/SNB: LP2+ watermarks only w/o sprites */
3055         if (INTEL_GEN(dev_priv) <= 6 && pipe_wm->sprites_enabled)
3056                 usable_level = 1;
3057
3058         /* ILK/SNB/IVB: LP1+ watermarks only w/o scaling */
3059         if (pipe_wm->sprites_scaled)
3060                 usable_level = 0;
3061
3062         ilk_compute_wm_level(dev_priv, intel_crtc, 0, cstate,
3063                              pristate, sprstate, curstate, &pipe_wm->raw_wm[0]);
3064
3065         memset(&pipe_wm->wm, 0, sizeof(pipe_wm->wm));
3066         pipe_wm->wm[0] = pipe_wm->raw_wm[0];
3067
3068         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3069                 pipe_wm->linetime = hsw_compute_linetime_wm(cstate);
3070
3071         if (!ilk_validate_pipe_wm(dev, pipe_wm))
3072                 return -EINVAL;
3073
3074         ilk_compute_wm_reg_maximums(dev_priv, 1, &max);
3075
3076         for (level = 1; level <= max_level; level++) {
3077                 struct intel_wm_level *wm = &pipe_wm->raw_wm[level];
3078
3079                 ilk_compute_wm_level(dev_priv, intel_crtc, level, cstate,
3080                                      pristate, sprstate, curstate, wm);
3081
3082                 /*
3083                  * Disable any watermark level that exceeds the
3084                  * register maximums since such watermarks are
3085                  * always invalid.
3086                  */
3087                 if (level > usable_level)
3088                         continue;
3089
3090                 if (ilk_validate_wm_level(level, &max, wm))
3091                         pipe_wm->wm[level] = *wm;
3092                 else
3093                         usable_level = level;
3094         }
3095
3096         return 0;
3097 }
3098
3099 /*
3100  * Build a set of 'intermediate' watermark values that satisfy both the old
3101  * state and the new state.  These can be programmed to the hardware
3102  * immediately.
3103  */
3104 static int ilk_compute_intermediate_wm(struct drm_device *dev,
3105                                        struct intel_crtc *intel_crtc,
3106                                        struct intel_crtc_state *newstate)
3107 {
3108         struct intel_pipe_wm *a = &newstate->wm.ilk.intermediate;
3109         struct intel_pipe_wm *b = &intel_crtc->wm.active.ilk;
3110         int level, max_level = ilk_wm_max_level(to_i915(dev));
3111
3112         /*
3113          * Start with the final, target watermarks, then combine with the
3114          * currently active watermarks to get values that are safe both before
3115          * and after the vblank.
3116          */
3117         *a = newstate->wm.ilk.optimal;
3118         a->pipe_enabled |= b->pipe_enabled;
3119         a->sprites_enabled |= b->sprites_enabled;
3120         a->sprites_scaled |= b->sprites_scaled;
3121
3122         for (level = 0; level <= max_level; level++) {
3123                 struct intel_wm_level *a_wm = &a->wm[level];
3124                 const struct intel_wm_level *b_wm = &b->wm[level];
3125
3126                 a_wm->enable &= b_wm->enable;
3127                 a_wm->pri_val = max(a_wm->pri_val, b_wm->pri_val);
3128                 a_wm->spr_val = max(a_wm->spr_val, b_wm->spr_val);
3129                 a_wm->cur_val = max(a_wm->cur_val, b_wm->cur_val);
3130                 a_wm->fbc_val = max(a_wm->fbc_val, b_wm->fbc_val);
3131         }
3132
3133         /*
3134          * We need to make sure that these merged watermark values are
3135          * actually a valid configuration themselves.  If they're not,
3136          * there's no safe way to transition from the old state to
3137          * the new state, so we need to fail the atomic transaction.
3138          */
3139         if (!ilk_validate_pipe_wm(dev, a))
3140                 return -EINVAL;
3141
3142         /*
3143          * If our intermediate WM are identical to the final WM, then we can
3144          * omit the post-vblank programming; only update if it's different.
3145          */
3146         if (memcmp(a, &newstate->wm.ilk.optimal, sizeof(*a)) != 0)
3147                 newstate->wm.need_postvbl_update = true;
3148
3149         return 0;
3150 }
3151
3152 /*
3153  * Merge the watermarks from all active pipes for a specific level.
3154  */
3155 static void ilk_merge_wm_level(struct drm_device *dev,
3156                                int level,
3157                                struct intel_wm_level *ret_wm)
3158 {
3159         const struct intel_crtc *intel_crtc;
3160
3161         ret_wm->enable = true;
3162
3163         for_each_intel_crtc(dev, intel_crtc) {
3164                 const struct intel_pipe_wm *active = &intel_crtc->wm.active.ilk;
3165                 const struct intel_wm_level *wm = &active->wm[level];
3166
3167                 if (!active->pipe_enabled)
3168                         continue;
3169
3170                 /*
3171                  * The watermark values may have been used in the past,
3172                  * so we must maintain them in the registers for some
3173                  * time even if the level is now disabled.
3174                  */
3175                 if (!wm->enable)
3176                         ret_wm->enable = false;
3177
3178                 ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
3179                 ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
3180                 ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
3181                 ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
3182         }
3183 }
3184
3185 /*
3186  * Merge all low power watermarks for all active pipes.
3187  */
3188 static void ilk_wm_merge(struct drm_device *dev,
3189                          const struct intel_wm_config *config,
3190                          const struct ilk_wm_maximums *max,
3191                          struct intel_pipe_wm *merged)
3192 {
3193         struct drm_i915_private *dev_priv = to_i915(dev);
3194         int level, max_level = ilk_wm_max_level(dev_priv);
3195         int last_enabled_level = max_level;
3196
3197         /* ILK/SNB/IVB: LP1+ watermarks only w/ single pipe */
3198         if ((INTEL_GEN(dev_priv) <= 6 || IS_IVYBRIDGE(dev_priv)) &&
3199             config->num_pipes_active > 1)
3200                 last_enabled_level = 0;
3201
3202         /* ILK: FBC WM must be disabled always */
3203         merged->fbc_wm_enabled = INTEL_GEN(dev_priv) >= 6;
3204
3205         /* merge each WM1+ level */
3206         for (level = 1; level <= max_level; level++) {
3207                 struct intel_wm_level *wm = &merged->wm[level];
3208
3209                 ilk_merge_wm_level(dev, level, wm);
3210
3211                 if (level > last_enabled_level)
3212                         wm->enable = false;
3213                 else if (!ilk_validate_wm_level(level, max, wm))
3214                         /* make sure all following levels get disabled */
3215                         last_enabled_level = level - 1;
3216
3217                 /*
3218                  * The spec says it is preferred to disable
3219                  * FBC WMs instead of disabling a WM level.
3220                  */
3221                 if (wm->fbc_val > max->fbc) {
3222                         if (wm->enable)
3223                                 merged->fbc_wm_enabled = false;
3224                         wm->fbc_val = 0;
3225                 }
3226         }
3227
3228         /* ILK: LP2+ must be disabled when FBC WM is disabled but FBC enabled */
3229         /*
3230          * FIXME this is racy. FBC might get enabled later.
3231          * What we should check here is whether FBC can be
3232          * enabled sometime later.
3233          */
3234         if (IS_GEN5(dev_priv) && !merged->fbc_wm_enabled &&
3235             intel_fbc_is_active(dev_priv)) {
3236                 for (level = 2; level <= max_level; level++) {
3237                         struct intel_wm_level *wm = &merged->wm[level];
3238
3239                         wm->enable = false;
3240                 }
3241         }
3242 }
3243