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