]> Git Repo - linux.git/blob - drivers/gpu/drm/i915/intel_pm.c
drm/i915/guc: Properly capture & release GuC interrupts on Gen11+
[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 <[email protected]>
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->uapi.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->uapi.plane);
790
791         /* FIXME check the 'enable' instead */
792         if (!crtc_state->hw.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->hw.fb != NULL;
805         else
806                 return plane_state->uapi.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->hw.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->uapi.plane);
1079         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1080         const struct drm_display_mode *adjusted_mode =
1081                 &crtc_state->hw.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->hw.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->uapi.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->uapi.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->uapi.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->uapi.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->uapi.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->uapi.crtc);
1295         struct intel_atomic_state *state =
1296                 to_intel_atomic_state(crtc_state->uapi.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->hw.crtc != &crtc->base &&
1312                     old_plane_state->hw.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->uapi.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->uapi.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->hw.active || drm_atomic_crtc_needs_modeset(&new_crtc_state->uapi)) {
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->uapi.crtc->dev);
1526         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.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->uapi.crtc->dev);
1538         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.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->uapi.plane);
1585         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
1586         const struct drm_display_mode *adjusted_mode =
1587                 &crtc_state->hw.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->hw.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->uapi.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->uapi.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->uapi.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->uapi.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->uapi.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->uapi);
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->hw.crtc != &crtc->base &&
1833                     old_plane_state->hw.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->uapi.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->uapi.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->uapi.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->hw.active || drm_atomic_crtc_needs_modeset(&new_crtc_state->uapi)) {
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->uapi.crtc->dev);
2145         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.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->uapi.crtc->dev);
2157         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.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->hw.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->hw.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->hw.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->hw.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->hw.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->hw.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->hw.adjusted_mode.crtc_htotal,
2487                                  drm_rect_width(&plane_state->uapi.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->hw.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->hw.adjusted_mode.crtc_htotal,
2515                                  drm_rect_width(&plane_state->uapi.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->hw.fb->format->cpp[0];
2537
2538         return ilk_wm_method2(crtc_state->pixel_rate,
2539                               crtc_state->hw.adjusted_mode.crtc_htotal,
2540                               drm_rect_width(&plane_state->uapi.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->hw.fb->format->cpp[0];
2555
2556         return ilk_wm_fbc(pri_val, drm_rect_width(&plane_state->uapi.dst),
2557                           cpp);
2558 }
2559
2560 static unsigned int
2561 ilk_display_fifo_size(const struct drm_i915_private *dev_priv)
2562 {
2563         if (INTEL_GEN(dev_priv) >= 8)
2564                 return 3072;
2565         else if (INTEL_GEN(dev_priv) >= 7)
2566                 return 768;
2567         else
2568                 return 512;
2569 }
2570
2571 static unsigned int
2572 ilk_plane_wm_reg_max(const struct drm_i915_private *dev_priv,
2573                      int level, bool is_sprite)
2574 {
2575         if (INTEL_GEN(dev_priv) >= 8)
2576                 /* BDW primary/sprite plane watermarks */
2577                 return level == 0 ? 255 : 2047;
2578         else if (INTEL_GEN(dev_priv) >= 7)
2579                 /* IVB/HSW primary/sprite plane watermarks */
2580                 return level == 0 ? 127 : 1023;
2581         else if (!is_sprite)
2582                 /* ILK/SNB primary plane watermarks */
2583                 return level == 0 ? 127 : 511;
2584         else
2585                 /* ILK/SNB sprite plane watermarks */
2586                 return level == 0 ? 63 : 255;
2587 }
2588
2589 static unsigned int
2590 ilk_cursor_wm_reg_max(const struct drm_i915_private *dev_priv, int level)
2591 {
2592         if (INTEL_GEN(dev_priv) >= 7)
2593                 return level == 0 ? 63 : 255;
2594         else
2595                 return level == 0 ? 31 : 63;
2596 }
2597
2598 static unsigned int ilk_fbc_wm_reg_max(const struct drm_i915_private *dev_priv)
2599 {
2600         if (INTEL_GEN(dev_priv) >= 8)
2601                 return 31;
2602         else
2603                 return 15;
2604 }
2605
2606 /* Calculate the maximum primary/sprite plane watermark */
2607 static unsigned int ilk_plane_wm_max(const struct drm_i915_private *dev_priv,
2608                                      int level,
2609                                      const struct intel_wm_config *config,
2610                                      enum intel_ddb_partitioning ddb_partitioning,
2611                                      bool is_sprite)
2612 {
2613         unsigned int fifo_size = ilk_display_fifo_size(dev_priv);
2614
2615         /* if sprites aren't enabled, sprites get nothing */
2616         if (is_sprite && !config->sprites_enabled)
2617                 return 0;
2618
2619         /* HSW allows LP1+ watermarks even with multiple pipes */
2620         if (level == 0 || config->num_pipes_active > 1) {
2621                 fifo_size /= INTEL_NUM_PIPES(dev_priv);
2622
2623                 /*
2624                  * For some reason the non self refresh
2625                  * FIFO size is only half of the self
2626                  * refresh FIFO size on ILK/SNB.
2627                  */
2628                 if (INTEL_GEN(dev_priv) <= 6)
2629                         fifo_size /= 2;
2630         }
2631
2632         if (config->sprites_enabled) {
2633                 /* level 0 is always calculated with 1:1 split */
2634                 if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
2635                         if (is_sprite)
2636                                 fifo_size *= 5;
2637                         fifo_size /= 6;
2638                 } else {
2639                         fifo_size /= 2;
2640                 }
2641         }
2642
2643         /* clamp to max that the registers can hold */
2644         return min(fifo_size, ilk_plane_wm_reg_max(dev_priv, level, is_sprite));
2645 }
2646
2647 /* Calculate the maximum cursor plane watermark */
2648 static unsigned int ilk_cursor_wm_max(const struct drm_i915_private *dev_priv,
2649                                       int level,
2650                                       const struct intel_wm_config *config)
2651 {
2652         /* HSW LP1+ watermarks w/ multiple pipes */
2653         if (level > 0 && config->num_pipes_active > 1)
2654                 return 64;
2655
2656         /* otherwise just report max that registers can hold */
2657         return ilk_cursor_wm_reg_max(dev_priv, level);
2658 }
2659
2660 static void ilk_compute_wm_maximums(const struct drm_i915_private *dev_priv,
2661                                     int level,
2662                                     const struct intel_wm_config *config,
2663                                     enum intel_ddb_partitioning ddb_partitioning,
2664                                     struct ilk_wm_maximums *max)
2665 {
2666         max->pri = ilk_plane_wm_max(dev_priv, level, config, ddb_partitioning, false);
2667         max->spr = ilk_plane_wm_max(dev_priv, level, config, ddb_partitioning, true);
2668         max->cur = ilk_cursor_wm_max(dev_priv, level, config);
2669         max->fbc = ilk_fbc_wm_reg_max(dev_priv);
2670 }
2671
2672 static void ilk_compute_wm_reg_maximums(const struct drm_i915_private *dev_priv,
2673                                         int level,
2674                                         struct ilk_wm_maximums *max)
2675 {
2676         max->pri = ilk_plane_wm_reg_max(dev_priv, level, false);
2677         max->spr = ilk_plane_wm_reg_max(dev_priv, level, true);
2678         max->cur = ilk_cursor_wm_reg_max(dev_priv, level);
2679         max->fbc = ilk_fbc_wm_reg_max(dev_priv);
2680 }
2681
2682 static bool ilk_validate_wm_level(int level,
2683                                   const struct ilk_wm_maximums *max,
2684                                   struct intel_wm_level *result)
2685 {
2686         bool ret;
2687
2688         /* already determined to be invalid? */
2689         if (!result->enable)
2690                 return false;
2691
2692         result->enable = result->pri_val <= max->pri &&
2693                          result->spr_val <= max->spr &&
2694                          result->cur_val <= max->cur;
2695
2696         ret = result->enable;
2697
2698         /*
2699          * HACK until we can pre-compute everything,
2700          * and thus fail gracefully if LP0 watermarks
2701          * are exceeded...
2702          */
2703         if (level == 0 && !result->enable) {
2704                 if (result->pri_val > max->pri)
2705                         DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
2706                                       level, result->pri_val, max->pri);
2707                 if (result->spr_val > max->spr)
2708                         DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
2709                                       level, result->spr_val, max->spr);
2710                 if (result->cur_val > max->cur)
2711                         DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
2712                                       level, result->cur_val, max->cur);
2713
2714                 result->pri_val = min_t(u32, result->pri_val, max->pri);
2715                 result->spr_val = min_t(u32, result->spr_val, max->spr);
2716                 result->cur_val = min_t(u32, result->cur_val, max->cur);
2717                 result->enable = true;
2718         }
2719
2720         return ret;
2721 }
2722
2723 static void ilk_compute_wm_level(const struct drm_i915_private *dev_priv,
2724                                  const struct intel_crtc *intel_crtc,
2725                                  int level,
2726                                  struct intel_crtc_state *crtc_state,
2727                                  const struct intel_plane_state *pristate,
2728                                  const struct intel_plane_state *sprstate,
2729                                  const struct intel_plane_state *curstate,
2730                                  struct intel_wm_level *result)
2731 {
2732         u16 pri_latency = dev_priv->wm.pri_latency[level];
2733         u16 spr_latency = dev_priv->wm.spr_latency[level];
2734         u16 cur_latency = dev_priv->wm.cur_latency[level];
2735
2736         /* WM1+ latency values stored in 0.5us units */
2737         if (level > 0) {
2738                 pri_latency *= 5;
2739                 spr_latency *= 5;
2740                 cur_latency *= 5;
2741         }
2742
2743         if (pristate) {
2744                 result->pri_val = ilk_compute_pri_wm(crtc_state, pristate,
2745                                                      pri_latency, level);
2746                 result->fbc_val = ilk_compute_fbc_wm(crtc_state, pristate, result->pri_val);
2747         }
2748
2749         if (sprstate)
2750                 result->spr_val = ilk_compute_spr_wm(crtc_state, sprstate, spr_latency);
2751
2752         if (curstate)
2753                 result->cur_val = ilk_compute_cur_wm(crtc_state, curstate, cur_latency);
2754
2755         result->enable = true;
2756 }
2757
2758 static u32
2759 hsw_compute_linetime_wm(const struct intel_crtc_state *crtc_state)
2760 {
2761         const struct intel_atomic_state *intel_state =
2762                 to_intel_atomic_state(crtc_state->uapi.state);
2763         const struct drm_display_mode *adjusted_mode =
2764                 &crtc_state->hw.adjusted_mode;
2765         u32 linetime, ips_linetime;
2766
2767         if (!crtc_state->hw.active)
2768                 return 0;
2769         if (WARN_ON(adjusted_mode->crtc_clock == 0))
2770                 return 0;
2771         if (WARN_ON(intel_state->cdclk.logical.cdclk == 0))
2772                 return 0;
2773
2774         /* The WM are computed with base on how long it takes to fill a single
2775          * row at the given clock rate, multiplied by 8.
2776          * */
2777         linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2778                                      adjusted_mode->crtc_clock);
2779         ips_linetime = DIV_ROUND_CLOSEST(adjusted_mode->crtc_htotal * 1000 * 8,
2780                                          intel_state->cdclk.logical.cdclk);
2781
2782         return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
2783                PIPE_WM_LINETIME_TIME(linetime);
2784 }
2785
2786 static void intel_read_wm_latency(struct drm_i915_private *dev_priv,
2787                                   u16 wm[8])
2788 {
2789         struct intel_uncore *uncore = &dev_priv->uncore;
2790
2791         if (INTEL_GEN(dev_priv) >= 9) {
2792                 u32 val;
2793                 int ret, i;
2794                 int level, max_level = ilk_wm_max_level(dev_priv);
2795
2796                 /* read the first set of memory latencies[0:3] */
2797                 val = 0; /* data0 to be programmed to 0 for first set */
2798                 ret = sandybridge_pcode_read(dev_priv,
2799                                              GEN9_PCODE_READ_MEM_LATENCY,
2800                                              &val, NULL);
2801
2802                 if (ret) {
2803                         DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2804                         return;
2805                 }
2806
2807                 wm[0] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2808                 wm[1] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2809                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2810                 wm[2] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2811                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2812                 wm[3] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2813                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2814
2815                 /* read the second set of memory latencies[4:7] */
2816                 val = 1; /* data0 to be programmed to 1 for second set */
2817                 ret = sandybridge_pcode_read(dev_priv,
2818                                              GEN9_PCODE_READ_MEM_LATENCY,
2819                                              &val, NULL);
2820                 if (ret) {
2821                         DRM_ERROR("SKL Mailbox read error = %d\n", ret);
2822                         return;
2823                 }
2824
2825                 wm[4] = val & GEN9_MEM_LATENCY_LEVEL_MASK;
2826                 wm[5] = (val >> GEN9_MEM_LATENCY_LEVEL_1_5_SHIFT) &
2827                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2828                 wm[6] = (val >> GEN9_MEM_LATENCY_LEVEL_2_6_SHIFT) &
2829                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2830                 wm[7] = (val >> GEN9_MEM_LATENCY_LEVEL_3_7_SHIFT) &
2831                                 GEN9_MEM_LATENCY_LEVEL_MASK;
2832
2833                 /*
2834                  * If a level n (n > 1) has a 0us latency, all levels m (m >= n)
2835                  * need to be disabled. We make sure to sanitize the values out
2836                  * of the punit to satisfy this requirement.
2837                  */
2838                 for (level = 1; level <= max_level; level++) {
2839                         if (wm[level] == 0) {
2840                                 for (i = level + 1; i <= max_level; i++)
2841                                         wm[i] = 0;
2842                                 break;
2843                         }
2844                 }
2845
2846                 /*
2847                  * WaWmMemoryReadLatency:skl+,glk
2848                  *
2849                  * punit doesn't take into account the read latency so we need
2850                  * to add 2us to the various latency levels we retrieve from the
2851                  * punit when level 0 response data us 0us.
2852                  */
2853                 if (wm[0] == 0) {
2854                         wm[0] += 2;
2855                         for (level = 1; level <= max_level; level++) {
2856                                 if (wm[level] == 0)
2857                                         break;
2858                                 wm[level] += 2;
2859                         }
2860                 }
2861
2862                 /*
2863                  * WA Level-0 adjustment for 16GB DIMMs: SKL+
2864                  * If we could not get dimm info enable this WA to prevent from
2865                  * any underrun. If not able to get Dimm info assume 16GB dimm
2866                  * to avoid any underrun.
2867                  */
2868                 if (dev_priv->dram_info.is_16gb_dimm)
2869                         wm[0] += 1;
2870
2871         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2872                 u64 sskpd = intel_uncore_read64(uncore, MCH_SSKPD);
2873
2874                 wm[0] = (sskpd >> 56) & 0xFF;
2875                 if (wm[0] == 0)
2876                         wm[0] = sskpd & 0xF;
2877                 wm[1] = (sskpd >> 4) & 0xFF;
2878                 wm[2] = (sskpd >> 12) & 0xFF;
2879                 wm[3] = (sskpd >> 20) & 0x1FF;
2880                 wm[4] = (sskpd >> 32) & 0x1FF;
2881         } else if (INTEL_GEN(dev_priv) >= 6) {
2882                 u32 sskpd = intel_uncore_read(uncore, MCH_SSKPD);
2883
2884                 wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
2885                 wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
2886                 wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
2887                 wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
2888         } else if (INTEL_GEN(dev_priv) >= 5) {
2889                 u32 mltr = intel_uncore_read(uncore, MLTR_ILK);
2890
2891                 /* ILK primary LP0 latency is 700 ns */
2892                 wm[0] = 7;
2893                 wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
2894                 wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
2895         } else {
2896                 MISSING_CASE(INTEL_DEVID(dev_priv));
2897         }
2898 }
2899
2900 static void intel_fixup_spr_wm_latency(struct drm_i915_private *dev_priv,
2901                                        u16 wm[5])
2902 {
2903         /* ILK sprite LP0 latency is 1300 ns */
2904         if (IS_GEN(dev_priv, 5))
2905                 wm[0] = 13;
2906 }
2907
2908 static void intel_fixup_cur_wm_latency(struct drm_i915_private *dev_priv,
2909                                        u16 wm[5])
2910 {
2911         /* ILK cursor LP0 latency is 1300 ns */
2912         if (IS_GEN(dev_priv, 5))
2913                 wm[0] = 13;
2914 }
2915
2916 int ilk_wm_max_level(const struct drm_i915_private *dev_priv)
2917 {
2918         /* how many WM levels are we expecting */
2919         if (INTEL_GEN(dev_priv) >= 9)
2920                 return 7;
2921         else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2922                 return 4;
2923         else if (INTEL_GEN(dev_priv) >= 6)
2924                 return 3;
2925         else
2926                 return 2;
2927 }
2928
2929 static void intel_print_wm_latency(struct drm_i915_private *dev_priv,
2930                                    const char *name,
2931                                    const u16 wm[8])
2932 {
2933         int level, max_level = ilk_wm_max_level(dev_priv);
2934
2935         for (level = 0; level <= max_level; level++) {
2936                 unsigned int latency = wm[level];
2937
2938                 if (latency == 0) {
2939                         DRM_DEBUG_KMS("%s WM%d latency not provided\n",
2940                                       name, level);
2941                         continue;
2942                 }
2943
2944                 /*
2945                  * - latencies are in us on gen9.
2946                  * - before then, WM1+ latency values are in 0.5us units
2947                  */
2948                 if (INTEL_GEN(dev_priv) >= 9)
2949                         latency *= 10;
2950                 else if (level > 0)
2951                         latency *= 5;
2952
2953                 DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
2954                               name, level, wm[level],
2955                               latency / 10, latency % 10);
2956         }
2957 }
2958
2959 static bool ilk_increase_wm_latency(struct drm_i915_private *dev_priv,
2960                                     u16 wm[5], u16 min)
2961 {
2962         int level, max_level = ilk_wm_max_level(dev_priv);
2963
2964         if (wm[0] >= min)
2965                 return false;
2966
2967         wm[0] = max(wm[0], min);
2968         for (level = 1; level <= max_level; level++)
2969                 wm[level] = max_t(u16, wm[level], DIV_ROUND_UP(min, 5));
2970
2971         return true;
2972 }
2973
2974 static void snb_wm_latency_quirk(struct drm_i915_private *dev_priv)
2975 {
2976         bool changed;
2977
2978         /*
2979          * The BIOS provided WM memory latency values are often
2980          * inadequate for high resolution displays. Adjust them.
2981          */
2982         changed = ilk_increase_wm_latency(dev_priv, dev_priv->wm.pri_latency, 12) |
2983                 ilk_increase_wm_latency(dev_priv, dev_priv->wm.spr_latency, 12) |
2984                 ilk_increase_wm_latency(dev_priv, dev_priv->wm.cur_latency, 12);
2985
2986         if (!changed)
2987                 return;
2988
2989         DRM_DEBUG_KMS("WM latency values increased to avoid potential underruns\n");
2990         intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
2991         intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
2992         intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
2993 }
2994
2995 static void snb_wm_lp3_irq_quirk(struct drm_i915_private *dev_priv)
2996 {
2997         /*
2998          * On some SNB machines (Thinkpad X220 Tablet at least)
2999          * LP3 usage can cause vblank interrupts to be lost.
3000          * The DEIIR bit will go high but it looks like the CPU
3001          * never gets interrupted.
3002          *
3003          * It's not clear whether other interrupt source could
3004          * be affected or if this is somehow limited to vblank
3005          * interrupts only. To play it safe we disable LP3
3006          * watermarks entirely.
3007          */
3008         if (dev_priv->wm.pri_latency[3] == 0 &&
3009             dev_priv->wm.spr_latency[3] == 0 &&
3010             dev_priv->wm.cur_latency[3] == 0)
3011                 return;
3012
3013         dev_priv->wm.pri_latency[3] = 0;
3014         dev_priv->wm.spr_latency[3] = 0;
3015         dev_priv->wm.cur_latency[3] = 0;
3016
3017         DRM_DEBUG_KMS("LP3 watermarks disabled due to potential for lost interrupts\n");
3018         intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
3019         intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
3020         intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
3021 }
3022
3023 static void ilk_setup_wm_latency(struct drm_i915_private *dev_priv)
3024 {
3025         intel_read_wm_latency(dev_priv, dev_priv->wm.pri_latency);
3026
3027         memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
3028                sizeof(dev_priv->wm.pri_latency));
3029         memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
3030                sizeof(dev_priv->wm.pri_latency));
3031
3032         intel_fixup_spr_wm_latency(dev_priv, dev_priv->wm.spr_latency);
3033         intel_fixup_cur_wm_latency(dev_priv, dev_priv->wm.cur_latency);
3034
3035         intel_print_wm_latency(dev_priv, "Primary", dev_priv->wm.pri_latency);
3036         intel_print_wm_latency(dev_priv, "Sprite", dev_priv->wm.spr_latency);
3037         intel_print_wm_latency(dev_priv, "Cursor", dev_priv->wm.cur_latency);
3038
3039         if (IS_GEN(dev_priv, 6)) {
3040                 snb_wm_latency_quirk(dev_priv);
3041                 snb_wm_lp3_irq_quirk(dev_priv);
3042         }
3043 }
3044
3045 static void skl_setup_wm_latency(struct drm_i915_private *dev_priv)
3046 {
3047         intel_read_wm_latency(dev_priv, dev_priv->wm.skl_latency);
3048         intel_print_wm_latency(dev_priv, "Gen9 Plane", dev_priv->wm.skl_latency);
3049 }
3050
3051 static bool ilk_validate_pipe_wm(const struct drm_i915_private *dev_priv,
3052                                  struct intel_pipe_wm *pipe_wm)
3053 {
3054         /* LP0 watermark maximums depend on this pipe alone */
3055         const struct intel_wm_config config = {
3056                 .num_pipes_active = 1,
3057                 .sprites_enabled = pipe_wm->sprites_enabled,
3058                 .sprites_scaled = pipe_wm->sprites_scaled,
3059         };
3060         struct ilk_wm_maximums max;
3061
3062         /* LP0 watermarks always use 1/2 DDB partitioning */
3063         ilk_compute_wm_maximums(dev_priv, 0, &config, INTEL_DDB_PART_1_2, &max);
3064
3065         /* At least LP0 must be valid */
3066         if (!ilk_validate_wm_level(0, &max, &pipe_wm->wm[0])) {
3067                 DRM_DEBUG_KMS("LP0 watermark invalid\n");
3068                 return false;
3069         }
3070
3071         return true;
3072 }
3073
3074 /* Compute new watermarks for the pipe */
3075 static int ilk_compute_pipe_wm(struct intel_crtc_state *crtc_state)
3076 {
3077         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
3078         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->uapi.crtc);
3079         struct intel_pipe_wm *pipe_wm;
3080         struct intel_plane *plane;
3081         const struct intel_plane_state *plane_state;
3082         const struct intel_plane_state *pristate = NULL;
3083         const struct intel_plane_state *sprstate = NULL;
3084         const struct intel_plane_state *curstate = NULL;
3085         int level, max_level = ilk_wm_max_level(dev_priv), usable_level;
3086         struct ilk_wm_maximums max;
3087
3088         pipe_wm = &crtc_state->wm.ilk.optimal;
3089
3090         intel_atomic_crtc_state_for_each_plane_state(plane, plane_state, crtc_state) {
3091                 if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
3092                         pristate = plane_state;
3093                 else if (plane->base.type == DRM_PLANE_TYPE_OVERLAY)
3094                         sprstate = plane_state;
3095                 else if (plane->base.type == DRM_PLANE_TYPE_CURSOR)
3096                         curstate = plane_state;
3097         }
3098
3099         pipe_wm->pipe_enabled = crtc_state->hw.active;
3100         if (sprstate) {
3101                 pipe_wm->sprites_enabled = sprstate->uapi.visible;
3102                 pipe_wm->sprites_scaled = sprstate->uapi.visible &&
3103                         (drm_rect_width(&sprstate->uapi.dst) != drm_rect_width(&sprstate->uapi.src) >> 16 ||
3104                          drm_rect_height(&sprstate->uapi.dst) != drm_rect_height(&sprstate->uapi.src) >> 16);
3105         }
3106
3107         usable_level = max_level;
3108
3109         /* ILK/SNB: LP2+ watermarks only w/o sprites */
3110         if (INTEL_GEN(dev_priv) <= 6 && pipe_wm->sprites_enabled)
3111                 usable_level = 1;
3112
3113         /* ILK/SNB/IVB: LP1+ watermarks only w/o scaling */
3114         if (pipe_wm->sprites_scaled)
3115                 usable_level = 0;
3116
3117         memset(&pipe_wm->wm, 0, sizeof(pipe_wm->wm));
3118         ilk_compute_wm_level(dev_priv, intel_crtc, 0, crtc_state,
3119                              pristate, sprstate, curstate, &pipe_wm->wm[0]);
3120
3121         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3122                 pipe_wm->linetime = hsw_compute_linetime_wm(crtc_state);
3123
3124         if (!ilk_validate_pipe_wm(dev_priv, pipe_wm))
3125                 return -EINVAL;
3126
3127         ilk_compute_wm_reg_maximums(dev_priv, 1, &max);
3128
3129         for (level = 1; level <= usable_level; level++) {
3130                 struct intel_wm_level *wm = &pipe_wm->wm[level];
3131
3132                 ilk_compute_wm_level(dev_priv, intel_crtc, level, crtc_state,
3133                                      pristate, sprstate, curstate, wm);
3134
3135                 /*
3136                  * Disable any watermark level that exceeds the
3137                  * register maximums since such watermarks are
3138                  * always invalid.
3139                  */
3140                 if (!ilk_validate_wm_level(level, &max, wm)) {
3141                         memset(wm, 0, sizeof(*wm));
3142                         break;
3143                 }
3144         }
3145
3146         return 0;
3147 }
3148
3149 /*
3150  * Build a set of 'intermediate' watermark values that satisfy both the old
3151  * state and the new state.  These can be programmed to the hardware
3152  * immediately.
3153  */
3154 static int ilk_compute_intermediate_wm(struct intel_crtc_state *newstate)
3155 {
3156         struct intel_crtc *intel_crtc = to_intel_crtc(newstate->uapi.crtc);
3157         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3158         struct intel_pipe_wm *a = &newstate->wm.ilk.intermediate;
3159         struct intel_atomic_state *intel_state =
3160                 to_intel_atomic_state(newstate->uapi.state);
3161         const struct intel_crtc_state *oldstate =
3162                 intel_atomic_get_old_crtc_state(intel_state, intel_crtc);
3163         const struct intel_pipe_wm *b = &oldstate->wm.ilk.optimal;
3164         int level, max_level = ilk_wm_max_level(dev_priv);
3165
3166         /*
3167          * Start with the final, target watermarks, then combine with the
3168          * currently active watermarks to get values that are safe both before
3169          * and after the vblank.
3170          */
3171         *a = newstate->wm.ilk.optimal;
3172         if (!newstate->hw.active || drm_atomic_crtc_needs_modeset(&newstate->uapi) ||
3173             intel_state->skip_intermediate_wm)
3174                 return 0;
3175
3176         a->pipe_enabled |= b->pipe_enabled;
3177         a->sprites_enabled |= b->sprites_enabled;
3178         a->sprites_scaled |= b->sprites_scaled;
3179
3180         for (level = 0; level <= max_level; level++) {
3181                 struct intel_wm_level *a_wm = &a->wm[level];
3182                 const struct intel_wm_level *b_wm = &b->wm[level];
3183
3184                 a_wm->enable &= b_wm->enable;
3185                 a_wm->pri_val = max(a_wm->pri_val, b_wm->pri_val);
3186                 a_wm->spr_val = max(a_wm->spr_val, b_wm->spr_val);
3187                 a_wm->cur_val = max(a_wm->cur_val, b_wm->cur_val);
3188                 a_wm->fbc_val = max(a_wm->fbc_val, b_wm->fbc_val);
3189         }
3190
3191         /*
3192          * We need to make sure that these merged watermark values are
3193          * actually a valid configuration themselves.  If they're not,
3194          * there's no safe way to transition from the old state to
3195          * the new state, so we need to fail the atomic transaction.
3196          */
3197         if (!ilk_validate_pipe_wm(dev_priv, a))
3198                 return -EINVAL;
3199
3200         /*
3201          * If our intermediate WM are identical to the final WM, then we can
3202          * omit the post-vblank programming; only update if it's different.
3203          */
3204         if (memcmp(a, &newstate->wm.ilk.optimal, sizeof(*a)) != 0)
3205                 newstate->wm.need_postvbl_update = true;
3206
3207         return 0;
3208 }
3209
3210 /*
3211  * Merge the watermarks from all active pipes for a specific level.
3212  */
3213 static void ilk_merge_wm_level(struct drm_i915_private *dev_priv,
3214                                int level,
3215                                struct intel_wm_level *ret_wm)
3216 {
3217         const struct intel_crtc *intel_crtc;
3218
3219         ret_wm->enable = true;
3220
3221         for_each_intel_crtc(&dev_priv->drm, intel_crtc) {
3222                 const struct intel_pipe_wm *active = &intel_crtc->wm.active.ilk;
3223                 const struct intel_wm_level *wm = &active->wm[level];
3224
3225                 if (!active->pipe_enabled)
3226                         continue;
3227
3228                 /*
3229                  * The watermark values may have been used in the past,
3230                  * so we must maintain them in the registers for some
3231                  * time even if the level is now disabled.
3232                  */
3233                 if (!wm->enable)
3234                         ret_wm->enable = false;
3235
3236                 ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
3237                 ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
3238                 ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
3239                 ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
3240         }
3241 }
3242
3243 /*
3244  * Merge all low power watermarks for all active pipes.
3245  */
3246 static void ilk_wm_merge(struct drm_i915_private *dev_priv,
3247                          const struct intel_wm_config *config,
3248                          const struct ilk_wm_maximums *max,
3249                          struct intel_pipe_wm *merged)
3250 {
3251         int level, max_level = ilk_wm_max_level(dev_priv);
3252         int last_enabled_level = max_level;
3253
3254         /* ILK/SNB/IVB: LP1+ watermarks only w/ single pipe */
3255         if ((INTEL_GEN(dev_priv) <= 6 || IS_IVYBRIDGE(dev_priv)) &&
3256             config->num_pipes_active > 1)
3257                 last_enabled_level = 0;
3258
3259         /* ILK: FBC WM must be disabled always */
3260         merged->fbc_wm_enabled = INTEL_GEN(dev_priv) >= 6;
3261
3262         /* merge each WM1+ level */
3263         for (level = 1; level <= max_level; level++) {
3264                 struct intel_wm_level *wm = &merged->wm[level];
3265
3266                 ilk_merge_wm_level(dev_priv, level, wm);
3267
3268                 if (level > last_enabled_level)
3269                         wm->enable = false;
3270                 else if (!ilk_validate_wm_level(level, max, wm))
3271                         /* make sure all following levels get disabled */
3272                         last_enabled_level = level - 1;
3273
3274                 /*
3275                  * The spec says it is preferred to disable
3276                  * FBC WMs instead of disabling a WM level.
3277                  */
3278                 if (wm->fbc_val > max->fbc) {
3279                         if (wm->enable)
3280                                 merged->fbc_wm_enabled = false;
3281                         wm->fbc_val = 0;
3282                 }
3283         }
3284
3285         /* ILK: LP2+ must be disabled when FBC WM is disabled but FBC enabled */
3286         /*
3287          * FIXME this is racy. FBC might get enabled later.
3288          * What we should check here is whether FBC can be
3289          * enabled sometime later.
3290          */
3291         if (IS_GEN(dev_priv, 5) && !merged->fbc_wm_enabled &&
3292             intel_fbc_is_active(dev_priv)) {
3293                 for (level = 2; level <= max_level; level++) {
3294                         struct intel_wm_level *wm = &merged->wm[level];
3295
3296                         wm->enable = false;
3297                 }
3298         }
3299 }
3300
3301 static int ilk_wm_lp_to_level(int wm_lp, const struct intel_pipe_wm *pipe_wm)
3302 {
3303         /* LP1,LP2,LP3 levels are either 1,2,3 or 1,3,4 */
3304         return wm_lp + (wm_lp >= 2 && pipe_wm->wm[4].enable);
3305 }
3306
3307 /* The value we need to program into the WM_LPx latency field */
3308 static unsigned int ilk_wm_lp_latency(struct drm_i915_private *dev_priv,
3309                                       int level)
3310 {
3311         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3312                 return 2 * level;
3313         else
3314                 return dev_priv->wm.pri_latency[level];
3315 }
3316
3317 static void ilk_compute_wm_results(struct drm_i915_private *dev_priv,
3318                                    const struct intel_pipe_wm *merged,
3319                                    enum intel_ddb_partitioning partitioning,
3320                                    struct ilk_wm_values *results)
3321 {
3322         struct intel_crtc *intel_crtc;
3323         int level, wm_lp;
3324
3325         results->enable_fbc_wm = merged->fbc_wm_enabled;
3326         results->partitioning = partitioning;
3327
3328         /* LP1+ register values */
3329         for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
3330                 const struct intel_wm_level *r;
3331
3332                 level = ilk_wm_lp_to_level(wm_lp, merged);
3333
3334                 r = &merged->wm[level];
3335
3336                 /*
3337                  * Maintain the watermark values even if the level is
3338                  * disabled. Doing otherwise could cause underruns.
3339                  */
3340                 results->wm_lp[wm_lp - 1] =
3341                         (ilk_wm_lp_latency(dev_priv, level) << WM1_LP_LATENCY_SHIFT) |
3342                         (r->pri_val << WM1_LP_SR_SHIFT) |
3343                         r->cur_val;
3344
3345                 if (r->enable)
3346                         results->wm_lp[wm_lp - 1] |= WM1_LP_SR_EN;
3347
3348                 if (INTEL_GEN(dev_priv) >= 8)
3349                         results->wm_lp[wm_lp - 1] |=
3350                                 r->fbc_val << WM1_LP_FBC_SHIFT_BDW;
3351                 else
3352                         results->wm_lp[wm_lp - 1] |=
3353                                 r->fbc_val << WM1_LP_FBC_SHIFT;
3354
3355                 /*
3356                  * Always set WM1S_LP_EN when spr_val != 0, even if the
3357                  * level is disabled. Doing otherwise could cause underruns.
3358                  */
3359                 if (INTEL_GEN(dev_priv) <= 6 && r->spr_val) {
3360                         WARN_ON(wm_lp != 1);
3361                         results->wm_lp_spr[wm_lp - 1] = WM1S_LP_EN | r->spr_val;
3362                 } else
3363                         results->wm_lp_spr[wm_lp - 1] = r->spr_val;
3364         }
3365
3366         /* LP0 register values */
3367         for_each_intel_crtc(&dev_priv->drm, intel_crtc) {
3368                 enum pipe pipe = intel_crtc->pipe;
3369                 const struct intel_wm_level *r =
3370                         &intel_crtc->wm.active.ilk.wm[0];
3371
3372                 if (WARN_ON(!r->enable))
3373                         continue;
3374
3375                 results->wm_linetime[pipe] = intel_crtc->wm.active.ilk.linetime;
3376
3377                 results->wm_pipe[pipe] =
3378                         (r->pri_val << WM0_PIPE_PLANE_SHIFT) |
3379                         (r->spr_val << WM0_PIPE_SPRITE_SHIFT) |
3380                         r->cur_val;
3381         }
3382 }
3383
3384 /* Find the result with the highest level enabled. Check for enable_fbc_wm in
3385  * case both are at the same level. Prefer r1 in case they're the same. */
3386 static struct intel_pipe_wm *
3387 ilk_find_best_result(struct drm_i915_private *dev_priv,
3388                      struct intel_pipe_wm *r1,
3389                      struct intel_pipe_wm *r2)
3390 {
3391         int level, max_level = ilk_wm_max_level(dev_priv);
3392         int level1 = 0, level2 = 0;
3393
3394         for (level = 1; level <= max_level; level++) {
3395                 if (r1->wm[level].enable)
3396                         level1 = level;
3397                 if (r2->wm[level].enable)
3398                         level2 = level;
3399         }
3400
3401         if (level1 == level2) {
3402                 if (r2->fbc_wm_enabled && !r1->fbc_wm_enabled)
3403                         return r2;
3404                 else
3405                         return r1;
3406         } else if (level1 > level2) {
3407                 return r1;
3408         } else {
3409                 return r2;
3410         }
3411 }
3412
3413 /* dirty bits used to track which watermarks need changes */
3414 #define WM_DIRTY_PIPE(pipe) (1 << (pipe))
3415 #define WM_DIRTY_LINETIME(pipe) (1 << (8 + (pipe)))
3416 #define WM_DIRTY_LP(wm_lp) (1 << (15 + (wm_lp)))
3417 #define WM_DIRTY_LP_ALL (WM_DIRTY_LP(1) | WM_DIRTY_LP(2) | WM_DIRTY_LP(3))
3418 #define WM_DIRTY_FBC (1 << 24)
3419 #define WM_DIRTY_DDB (1 << 25)
3420
3421 static unsigned int ilk_compute_wm_dirty(struct drm_i915_private *dev_priv,
3422                                          const struct ilk_wm_values *old,
3423                                          const struct ilk_wm_values *new)
3424 {
3425         unsigned int dirty = 0;
3426         enum pipe pipe;
3427         int wm_lp;
3428
3429         for_each_pipe(dev_priv, pipe) {
3430                 if (old->wm_linetime[pipe] != new->wm_linetime[pipe]) {
3431                         dirty |= WM_DIRTY_LINETIME(pipe);
3432                         /* Must disable LP1+ watermarks too */
3433                         dirty |= WM_DIRTY_LP_ALL;
3434                 }
3435
3436                 if (old->wm_pipe[pipe] != new->wm_pipe[pipe]) {
3437                         dirty |= WM_DIRTY_PIPE(pipe);
3438                         /* Must disable LP1+ watermarks too */
3439                         dirty |= WM_DIRTY_LP_ALL;
3440                 }
3441         }
3442
3443         if (old->enable_fbc_wm != new->enable_fbc_wm) {
3444                 dirty |= WM_DIRTY_FBC;
3445                 /* Must disable LP1+ watermarks too */
3446                 dirty |= WM_DIRTY_LP_ALL;
3447         }
3448
3449         if (old->partitioning != new->partitioning) {
3450                 dirty |= WM_DIRTY_DDB;
3451                 /* Must disable LP1+ watermarks too */
3452                 dirty |= WM_DIRTY_LP_ALL;
3453         }
3454
3455         /* LP1+ watermarks already deemed dirty, no need to continue */
3456         if (dirty & WM_DIRTY_LP_ALL)
3457                 return dirty;
3458
3459         /* Find the lowest numbered LP1+ watermark in need of an update... */
3460         for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
3461                 if (old->wm_lp[wm_lp - 1] != new->wm_lp[wm_lp - 1] ||
3462                     old->wm_lp_spr[wm_lp - 1] != new->wm_lp_spr[wm_lp - 1])
3463                         break;
3464         }
3465
3466         /* ...and mark it and all higher numbered LP1+ watermarks as dirty */
3467         for (; wm_lp <= 3; wm_lp++)
3468                 dirty |= WM_DIRTY_LP(wm_lp);
3469
3470         return dirty;
3471 }
3472
3473 static bool _ilk_disable_lp_wm(struct drm_i915_private *dev_priv,
3474                                unsigned int dirty)
3475 {
3476         struct ilk_wm_values *previous = &dev_priv->wm.hw;
3477         bool changed = false;
3478
3479         if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] & WM1_LP_SR_EN) {
3480                 previous->wm_lp[2] &= ~WM1_LP_SR_EN;
3481                 I915_WRITE(WM3_LP_ILK, previous->wm_lp[2]);
3482                 changed = true;
3483         }
3484         if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] & WM1_LP_SR_EN) {
3485                 previous->wm_lp[1] &= ~WM1_LP_SR_EN;
3486                 I915_WRITE(WM2_LP_ILK, previous->wm_lp[1]);
3487                 changed = true;
3488         }
3489         if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] & WM1_LP_SR_EN) {
3490                 previous->wm_lp[0] &= ~WM1_LP_SR_EN;
3491                 I915_WRITE(WM1_LP_ILK, previous->wm_lp[0]);
3492                 changed = true;
3493         }
3494
3495         /*
3496          * Don't touch WM1S_LP_EN here.
3497          * Doing so could cause underruns.
3498          */
3499
3500         return changed;
3501 }
3502
3503 /*
3504  * The spec says we shouldn't write when we don't need, because every write
3505  * causes WMs to be re-evaluated, expending some power.
3506  */
3507 static void ilk_write_wm_values(struct drm_i915_private *dev_priv,
3508                                 struct ilk_wm_values *results)
3509 {
3510         struct ilk_wm_values *previous = &dev_priv->wm.hw;
3511         unsigned int dirty;
3512         u32 val;
3513
3514         dirty = ilk_compute_wm_dirty(dev_priv, previous, results);
3515         if (!dirty)
3516                 return;
3517
3518         _ilk_disable_lp_wm(dev_priv, dirty);
3519
3520         if (dirty & WM_DIRTY_PIPE(PIPE_A))
3521                 I915_WRITE(WM0_PIPEA_ILK, results->wm_pipe[0]);
3522         if (dirty & WM_DIRTY_PIPE(PIPE_B))
3523                 I915_WRITE(WM0_PIPEB_ILK, results->wm_pipe[1]);
3524         if (dirty & WM_DIRTY_PIPE(PIPE_C))
3525                 I915_WRITE(WM0_PIPEC_IVB, results->wm_pipe[2]);
3526
3527         if (dirty & WM_DIRTY_LINETIME(PIPE_A))
3528                 I915_WRITE(PIPE_WM_LINETIME(PIPE_A), results->wm_linetime[0]);
3529         if (dirty & WM_DIRTY_LINETIME(PIPE_B))
3530                 I915_WRITE(PIPE_WM_LINETIME(PIPE_B), results->wm_linetime[1]);
3531         if (dirty & WM_DIRTY_LINETIME(PIPE_C))
3532                 I915_WRITE(PIPE_WM_LINETIME(PIPE_C), results->wm_linetime[2]);
3533
3534         if (dirty & WM_DIRTY_DDB) {
3535                 if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3536                         val = I915_READ(WM_MISC);
3537                         if (results->partitioning == INTEL_DDB_PART_1_2)
3538                                 val &= ~WM_MISC_DATA_PARTITION_5_6;
3539                         else
3540                                 val |= WM_MISC_DATA_PARTITION_5_6;
3541                         I915_WRITE(WM_MISC, val);
3542                 } else {
3543                         val = I915_READ(DISP_ARB_CTL2);
3544                         if (results->partitioning == INTEL_DDB_PART_1_2)
3545                                 val &= ~DISP_DATA_PARTITION_5_6;
3546                         else
3547                                 val |= DISP_DATA_PARTITION_5_6;
3548                         I915_WRITE(DISP_ARB_CTL2, val);
3549                 }
3550         }
3551
3552         if (dirty & WM_DIRTY_FBC) {
3553                 val = I915_READ(DISP_ARB_CTL);
3554                 if (results->enable_fbc_wm)
3555                         val &= ~DISP_FBC_WM_DIS;
3556                 else
3557                         val |= DISP_FBC_WM_DIS;
3558                 I915_WRITE(DISP_ARB_CTL, val);
3559         }
3560
3561         if (dirty & WM_DIRTY_LP(1) &&
3562             previous->wm_lp_spr[0] != results->wm_lp_spr[0])
3563                 I915_WRITE(WM1S_LP_ILK, results->wm_lp_spr[0]);
3564
3565         if (INTEL_GEN(dev_priv) >= 7) {
3566                 if (dirty & WM_DIRTY_LP(2) && previous->wm_lp_spr[1] != results->wm_lp_spr[1])
3567                         I915_WRITE(WM2S_LP_IVB, results->wm_lp_spr[1]);
3568                 if (dirty & WM_DIRTY_LP(3) && previous->wm_lp_spr[2] != results->wm_lp_spr[2])
3569                         I915_WRITE(WM3S_LP_IVB, results->wm_lp_spr[2]);
3570         }
3571
3572         if (dirty & WM_DIRTY_LP(1) && previous->wm_lp[0] != results->wm_lp[0])
3573                 I915_WRITE(WM1_LP_ILK, results->wm_lp[0]);
3574         if (dirty & WM_DIRTY_LP(2) && previous->wm_lp[1] != results->wm_lp[1])
3575                 I915_WRITE(WM2_LP_ILK, results->wm_lp[1]);
3576         if (dirty & WM_DIRTY_LP(3) && previous->wm_lp[2] != results->wm_lp[2])
3577                 I915_WRITE(WM3_LP_ILK, results->wm_lp[2]);
3578
3579         dev_priv->wm.hw = *results;
3580 }
3581
3582 bool ilk_disable_lp_wm(struct drm_device *dev)
3583 {
3584         struct drm_i915_private *dev_priv = to_i915(dev);
3585
3586         return _ilk_disable_lp_wm(dev_priv, WM_DIRTY_LP_ALL);
3587 }
3588
3589 static u8 intel_enabled_dbuf_slices_num(struct drm_i915_private *dev_priv)
3590 {
3591         u8 enabled_slices;
3592
3593         /* Slice 1 will always be enabled */
3594         enabled_slices = 1;
3595
3596         /* Gen prior to GEN11 have only one DBuf slice */
3597         if (INTEL_GEN(dev_priv) < 11)
3598                 return enabled_slices;
3599
3600         /*
3601          * FIXME: for now we'll only ever use 1 slice; pretend that we have
3602          * only that 1 slice enabled until we have a proper way for on-demand
3603          * toggling of the second slice.
3604          */
3605         if (0 && I915_READ(DBUF_CTL_S2) & DBUF_POWER_STATE)
3606                 enabled_slices++;
3607
3608         return enabled_slices;
3609 }
3610
3611 /*
3612  * FIXME: We still don't have the proper code detect if we need to apply the WA,
3613  * so assume we'll always need it in order to avoid underruns.
3614  */
3615 static bool skl_needs_memory_bw_wa(struct drm_i915_private *dev_priv)
3616 {
3617         return IS_GEN9_BC(dev_priv) || IS_BROXTON(dev_priv);
3618 }
3619
3620 static bool
3621 intel_has_sagv(struct drm_i915_private *dev_priv)
3622 {
3623         /* HACK! */
3624         if (IS_GEN(dev_priv, 12))
3625                 return false;
3626
3627         return (IS_GEN9_BC(dev_priv) || INTEL_GEN(dev_priv) >= 10) &&
3628                 dev_priv->sagv_status != I915_SAGV_NOT_CONTROLLED;
3629 }
3630
3631 static void
3632 skl_setup_sagv_block_time(struct drm_i915_private *dev_priv)
3633 {
3634         if (INTEL_GEN(dev_priv) >= 12) {
3635                 u32 val = 0;
3636                 int ret;
3637
3638                 ret = sandybridge_pcode_read(dev_priv,
3639                                              GEN12_PCODE_READ_SAGV_BLOCK_TIME_US,
3640                                              &val, NULL);
3641                 if (!ret) {
3642                         dev_priv->sagv_block_time_us = val;
3643                         return;
3644                 }
3645
3646                 DRM_DEBUG_DRIVER("Couldn't read SAGV block time!\n");
3647         } else if (IS_GEN(dev_priv, 11)) {
3648                 dev_priv->sagv_block_time_us = 10;
3649                 return;
3650         } else if (IS_GEN(dev_priv, 10)) {
3651                 dev_priv->sagv_block_time_us = 20;
3652                 return;
3653         } else if (IS_GEN(dev_priv, 9)) {
3654                 dev_priv->sagv_block_time_us = 30;
3655                 return;
3656         } else {
3657                 MISSING_CASE(INTEL_GEN(dev_priv));
3658         }
3659
3660         /* Default to an unusable block time */
3661         dev_priv->sagv_block_time_us = -1;
3662 }
3663
3664 /*
3665  * SAGV dynamically adjusts the system agent voltage and clock frequencies
3666  * depending on power and performance requirements. The display engine access
3667  * to system memory is blocked during the adjustment time. Because of the
3668  * blocking time, having this enabled can cause full system hangs and/or pipe
3669  * underruns if we don't meet all of the following requirements:
3670  *
3671  *  - <= 1 pipe enabled
3672  *  - All planes can enable watermarks for latencies >= SAGV engine block time
3673  *  - We're not using an interlaced display configuration
3674  */
3675 int
3676 intel_enable_sagv(struct drm_i915_private *dev_priv)
3677 {
3678         int ret;
3679
3680         if (!intel_has_sagv(dev_priv))
3681                 return 0;
3682
3683         if (dev_priv->sagv_status == I915_SAGV_ENABLED)
3684                 return 0;
3685
3686         DRM_DEBUG_KMS("Enabling SAGV\n");
3687         ret = sandybridge_pcode_write(dev_priv, GEN9_PCODE_SAGV_CONTROL,
3688                                       GEN9_SAGV_ENABLE);
3689
3690         /* We don't need to wait for SAGV when enabling */
3691
3692         /*
3693          * Some skl systems, pre-release machines in particular,
3694          * don't actually have SAGV.
3695          */
3696         if (IS_SKYLAKE(dev_priv) && ret == -ENXIO) {
3697                 DRM_DEBUG_DRIVER("No SAGV found on system, ignoring\n");
3698                 dev_priv->sagv_status = I915_SAGV_NOT_CONTROLLED;
3699                 return 0;
3700         } else if (ret < 0) {
3701                 DRM_ERROR("Failed to enable SAGV\n");
3702                 return ret;
3703         }
3704
3705         dev_priv->sagv_status = I915_SAGV_ENABLED;
3706         return 0;
3707 }
3708
3709 int
3710 intel_disable_sagv(struct drm_i915_private *dev_priv)
3711 {
3712         int ret;
3713
3714         if (!intel_has_sagv(dev_priv))
3715                 return 0;
3716
3717         if (dev_priv->sagv_status == I915_SAGV_DISABLED)
3718                 return 0;
3719
3720         DRM_DEBUG_KMS("Disabling SAGV\n");
3721         /* bspec says to keep retrying for at least 1 ms */
3722         ret = skl_pcode_request(dev_priv, GEN9_PCODE_SAGV_CONTROL,
3723                                 GEN9_SAGV_DISABLE,
3724                                 GEN9_SAGV_IS_DISABLED, GEN9_SAGV_IS_DISABLED,
3725                                 1);
3726         /*
3727          * Some skl systems, pre-release machines in particular,
3728          * don't actually have SAGV.
3729          */
3730         if (IS_SKYLAKE(dev_priv) && ret == -ENXIO) {
3731                 DRM_DEBUG_DRIVER("No SAGV found on system, ignoring\n");
3732                 dev_priv->sagv_status = I915_SAGV_NOT_CONTROLLED;
3733                 return 0;
3734         } else if (ret < 0) {
3735                 DRM_ERROR("Failed to disable SAGV (%d)\n", ret);
3736                 return ret;
3737         }
3738
3739         dev_priv->sagv_status = I915_SAGV_DISABLED;
3740         return 0;
3741 }
3742
3743 bool intel_can_enable_sagv(struct intel_atomic_state *state)
3744 {
3745         struct drm_device *dev = state->base.dev;
3746         struct drm_i915_private *dev_priv = to_i915(dev);
3747         struct intel_crtc *crtc;
3748         struct intel_plane *plane;
3749         struct intel_crtc_state *crtc_state;
3750         enum pipe pipe;
3751         int level, latency;
3752
3753         if (!intel_has_sagv(dev_priv))
3754                 return false;
3755
3756         /*
3757          * If there are no active CRTCs, no additional checks need be performed
3758          */
3759         if (hweight8(state->active_pipes) == 0)
3760                 return true;
3761
3762         /*
3763          * SKL+ workaround: bspec recommends we disable SAGV when we have
3764          * more then one pipe enabled
3765          */
3766         if (hweight8(state->active_pipes) > 1)
3767                 return false;
3768
3769         /* Since we're now guaranteed to only have one active CRTC... */
3770         pipe = ffs(state->active_pipes) - 1;
3771         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
3772         crtc_state = to_intel_crtc_state(crtc->base.state);
3773
3774         if (crtc_state->hw.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
3775                 return false;
3776
3777         for_each_intel_plane_on_crtc(dev, crtc, plane) {
3778                 struct skl_plane_wm *wm =
3779                         &crtc_state->wm.skl.optimal.planes[plane->id];
3780
3781                 /* Skip this plane if it's not enabled */
3782                 if (!wm->wm[0].plane_en)
3783                         continue;
3784
3785                 /* Find the highest enabled wm level for this plane */
3786                 for (level = ilk_wm_max_level(dev_priv);
3787                      !wm->wm[level].plane_en; --level)
3788                      { }
3789
3790                 latency = dev_priv->wm.skl_latency[level];
3791
3792                 if (skl_needs_memory_bw_wa(dev_priv) &&
3793                     plane->base.state->fb->modifier ==
3794                     I915_FORMAT_MOD_X_TILED)
3795                         latency += 15;
3796
3797                 /*
3798                  * If any of the planes on this pipe don't enable wm levels that
3799                  * incur memory latencies higher than sagv_block_time_us we
3800                  * can't enable SAGV.
3801                  */
3802                 if (latency < dev_priv->sagv_block_time_us)
3803                         return false;
3804         }
3805
3806         return true;
3807 }
3808
3809 static u16 intel_get_ddb_size(struct drm_i915_private *dev_priv,
3810                               const struct intel_crtc_state *crtc_state,
3811                               const u64 total_data_rate,
3812                               const int num_active,
3813                               struct skl_ddb_allocation *ddb)
3814 {
3815         const struct drm_display_mode *adjusted_mode;
3816         u64 total_data_bw;
3817         u16 ddb_size = INTEL_INFO(dev_priv)->ddb_size;
3818
3819         WARN_ON(ddb_size == 0);
3820
3821         if (INTEL_GEN(dev_priv) < 11)
3822                 return ddb_size - 4; /* 4 blocks for bypass path allocation */
3823
3824         adjusted_mode = &crtc_state->hw.adjusted_mode;
3825         total_data_bw = total_data_rate * drm_mode_vrefresh(adjusted_mode);
3826
3827         /*
3828          * 12GB/s is maximum BW supported by single DBuf slice.
3829          *
3830          * FIXME dbuf slice code is broken:
3831          * - must wait for planes to stop using the slice before powering it off
3832          * - plane straddling both slices is illegal in multi-pipe scenarios
3833          * - should validate we stay within the hw bandwidth limits
3834          */
3835         if (0 && (num_active > 1 || total_data_bw >= GBps(12))) {
3836                 ddb->enabled_slices = 2;
3837         } else {
3838                 ddb->enabled_slices = 1;
3839                 ddb_size /= 2;
3840         }
3841
3842         return ddb_size;
3843 }
3844
3845 static void
3846 skl_ddb_get_pipe_allocation_limits(struct drm_i915_private *dev_priv,
3847                                    const struct intel_crtc_state *crtc_state,
3848                                    const u64 total_data_rate,
3849                                    struct skl_ddb_allocation *ddb,
3850                                    struct skl_ddb_entry *alloc, /* out */
3851                                    int *num_active /* out */)
3852 {
3853         struct drm_atomic_state *state = crtc_state->uapi.state;
3854         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
3855         struct drm_crtc *for_crtc = crtc_state->uapi.crtc;
3856         const struct intel_crtc *crtc;
3857         u32 pipe_width = 0, total_width = 0, width_before_pipe = 0;
3858         enum pipe for_pipe = to_intel_crtc(for_crtc)->pipe;
3859         u16 ddb_size;
3860         u32 i;
3861
3862         if (WARN_ON(!state) || !crtc_state->hw.active) {
3863                 alloc->start = 0;
3864                 alloc->end = 0;
3865                 *num_active = hweight8(dev_priv->active_pipes);
3866                 return;
3867         }
3868
3869         if (intel_state->active_pipe_changes)
3870                 *num_active = hweight8(intel_state->active_pipes);
3871         else
3872                 *num_active = hweight8(dev_priv->active_pipes);
3873
3874         ddb_size = intel_get_ddb_size(dev_priv, crtc_state, total_data_rate,
3875                                       *num_active, ddb);
3876
3877         /*
3878          * If the state doesn't change the active CRTC's or there is no
3879          * modeset request, then there's no need to recalculate;
3880          * the existing pipe allocation limits should remain unchanged.
3881          * Note that we're safe from racing commits since any racing commit
3882          * that changes the active CRTC list or do modeset would need to
3883          * grab _all_ crtc locks, including the one we currently hold.
3884          */
3885         if (!intel_state->active_pipe_changes && !intel_state->modeset) {
3886                 /*
3887                  * alloc may be cleared by clear_intel_crtc_state,
3888                  * copy from old state to be sure
3889                  */
3890                 *alloc = to_intel_crtc_state(for_crtc->state)->wm.skl.ddb;
3891                 return;
3892         }
3893
3894         /*
3895          * Watermark/ddb requirement highly depends upon width of the
3896          * framebuffer, So instead of allocating DDB equally among pipes
3897          * distribute DDB based on resolution/width of the display.
3898          */
3899         for_each_new_intel_crtc_in_state(intel_state, crtc, crtc_state, i) {
3900                 const struct drm_display_mode *adjusted_mode =
3901                         &crtc_state->hw.adjusted_mode;
3902                 enum pipe pipe = crtc->pipe;
3903                 int hdisplay, vdisplay;
3904
3905                 if (!crtc_state->hw.enable)
3906                         continue;
3907
3908                 drm_mode_get_hv_timing(adjusted_mode, &hdisplay, &vdisplay);
3909                 total_width += hdisplay;
3910
3911                 if (pipe < for_pipe)
3912                         width_before_pipe += hdisplay;
3913                 else if (pipe == for_pipe)
3914                         pipe_width = hdisplay;
3915         }
3916
3917         alloc->start = ddb_size * width_before_pipe / total_width;
3918         alloc->end = ddb_size * (width_before_pipe + pipe_width) / total_width;
3919 }
3920
3921 static int skl_compute_wm_params(const struct intel_crtc_state *crtc_state,
3922                                  int width, const struct drm_format_info *format,
3923                                  u64 modifier, unsigned int rotation,
3924                                  u32 plane_pixel_rate, struct skl_wm_params *wp,
3925                                  int color_plane);
3926 static void skl_compute_plane_wm(const struct intel_crtc_state *crtc_state,
3927                                  int level,
3928                                  const struct skl_wm_params *wp,
3929                                  const struct skl_wm_level *result_prev,
3930                                  struct skl_wm_level *result /* out */);
3931
3932 static unsigned int
3933 skl_cursor_allocation(const struct intel_crtc_state *crtc_state,
3934                       int num_active)
3935 {
3936         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
3937         int level, max_level = ilk_wm_max_level(dev_priv);
3938         struct skl_wm_level wm = {};
3939         int ret, min_ddb_alloc = 0;
3940         struct skl_wm_params wp;
3941
3942         ret = skl_compute_wm_params(crtc_state, 256,
3943                                     drm_format_info(DRM_FORMAT_ARGB8888),
3944                                     DRM_FORMAT_MOD_LINEAR,
3945                                     DRM_MODE_ROTATE_0,
3946                                     crtc_state->pixel_rate, &wp, 0);
3947         WARN_ON(ret);
3948
3949         for (level = 0; level <= max_level; level++) {
3950                 skl_compute_plane_wm(crtc_state, level, &wp, &wm, &wm);
3951                 if (wm.min_ddb_alloc == U16_MAX)
3952                         break;
3953
3954                 min_ddb_alloc = wm.min_ddb_alloc;
3955         }
3956
3957         return max(num_active == 1 ? 32 : 8, min_ddb_alloc);
3958 }
3959
3960 static void skl_ddb_entry_init_from_hw(struct drm_i915_private *dev_priv,
3961                                        struct skl_ddb_entry *entry, u32 reg)
3962 {
3963
3964         entry->start = reg & DDB_ENTRY_MASK;
3965         entry->end = (reg >> DDB_ENTRY_END_SHIFT) & DDB_ENTRY_MASK;
3966
3967         if (entry->end)
3968                 entry->end += 1;
3969 }
3970
3971 static void
3972 skl_ddb_get_hw_plane_state(struct drm_i915_private *dev_priv,
3973                            const enum pipe pipe,
3974                            const enum plane_id plane_id,
3975                            struct skl_ddb_entry *ddb_y,
3976                            struct skl_ddb_entry *ddb_uv)
3977 {
3978         u32 val, val2;
3979         u32 fourcc = 0;
3980
3981         /* Cursor doesn't support NV12/planar, so no extra calculation needed */
3982         if (plane_id == PLANE_CURSOR) {
3983                 val = I915_READ(CUR_BUF_CFG(pipe));
3984                 skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
3985                 return;
3986         }
3987
3988         val = I915_READ(PLANE_CTL(pipe, plane_id));
3989
3990         /* No DDB allocated for disabled planes */
3991         if (val & PLANE_CTL_ENABLE)
3992                 fourcc = skl_format_to_fourcc(val & PLANE_CTL_FORMAT_MASK,
3993                                               val & PLANE_CTL_ORDER_RGBX,
3994                                               val & PLANE_CTL_ALPHA_MASK);
3995
3996         if (INTEL_GEN(dev_priv) >= 11) {
3997                 val = I915_READ(PLANE_BUF_CFG(pipe, plane_id));
3998                 skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
3999         } else {
4000                 val = I915_READ(PLANE_BUF_CFG(pipe, plane_id));
4001                 val2 = I915_READ(PLANE_NV12_BUF_CFG(pipe, plane_id));
4002
4003                 if (fourcc &&
4004                     drm_format_info_is_yuv_semiplanar(drm_format_info(fourcc)))
4005                         swap(val, val2);
4006
4007                 skl_ddb_entry_init_from_hw(dev_priv, ddb_y, val);
4008                 skl_ddb_entry_init_from_hw(dev_priv, ddb_uv, val2);
4009         }
4010 }
4011
4012 void skl_pipe_ddb_get_hw_state(struct intel_crtc *crtc,
4013                                struct skl_ddb_entry *ddb_y,
4014                                struct skl_ddb_entry *ddb_uv)
4015 {
4016         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4017         enum intel_display_power_domain power_domain;
4018         enum pipe pipe = crtc->pipe;
4019         intel_wakeref_t wakeref;
4020         enum plane_id plane_id;
4021
4022         power_domain = POWER_DOMAIN_PIPE(pipe);
4023         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
4024         if (!wakeref)
4025                 return;
4026
4027         for_each_plane_id_on_crtc(crtc, plane_id)
4028                 skl_ddb_get_hw_plane_state(dev_priv, pipe,
4029                                            plane_id,
4030                                            &ddb_y[plane_id],
4031                                            &ddb_uv[plane_id]);
4032
4033         intel_display_power_put(dev_priv, power_domain, wakeref);
4034 }
4035
4036 void skl_ddb_get_hw_state(struct drm_i915_private *dev_priv,
4037                           struct skl_ddb_allocation *ddb /* out */)
4038 {
4039         ddb->enabled_slices = intel_enabled_dbuf_slices_num(dev_priv);
4040 }
4041
4042 /*
4043  * Determines the downscale amount of a plane for the purposes of watermark calculations.
4044  * The bspec defines downscale amount as:
4045  *
4046  * """
4047  * Horizontal down scale amount = maximum[1, Horizontal source size /
4048  *                                           Horizontal destination size]
4049  * Vertical down scale amount = maximum[1, Vertical source size /
4050  *                                         Vertical destination size]
4051  * Total down scale amount = Horizontal down scale amount *
4052  *                           Vertical down scale amount
4053  * """
4054  *
4055  * Return value is provided in 16.16 fixed point form to retain fractional part.
4056  * Caller should take care of dividing & rounding off the value.
4057  */
4058 static uint_fixed_16_16_t
4059 skl_plane_downscale_amount(const struct intel_crtc_state *crtc_state,
4060                            const struct intel_plane_state *plane_state)
4061 {
4062         u32 src_w, src_h, dst_w, dst_h;
4063         uint_fixed_16_16_t fp_w_ratio, fp_h_ratio;
4064         uint_fixed_16_16_t downscale_h, downscale_w;
4065
4066         if (WARN_ON(!intel_wm_plane_visible(crtc_state, plane_state)))
4067                 return u32_to_fixed16(0);
4068
4069         /*
4070          * Src coordinates are already rotated by 270 degrees for
4071          * the 90/270 degree plane rotation cases (to match the
4072          * GTT mapping), hence no need to account for rotation here.
4073          *
4074          * n.b., src is 16.16 fixed point, dst is whole integer.
4075          */
4076         src_w = drm_rect_width(&plane_state->uapi.src) >> 16;
4077         src_h = drm_rect_height(&plane_state->uapi.src) >> 16;
4078         dst_w = drm_rect_width(&plane_state->uapi.dst);
4079         dst_h = drm_rect_height(&plane_state->uapi.dst);
4080
4081         fp_w_ratio = div_fixed16(src_w, dst_w);
4082         fp_h_ratio = div_fixed16(src_h, dst_h);
4083         downscale_w = max_fixed16(fp_w_ratio, u32_to_fixed16(1));
4084         downscale_h = max_fixed16(fp_h_ratio, u32_to_fixed16(1));
4085
4086         return mul_fixed16(downscale_w, downscale_h);
4087 }
4088
4089 static u64
4090 skl_plane_relative_data_rate(const struct intel_crtc_state *crtc_state,
4091                              const struct intel_plane_state *plane_state,
4092                              int color_plane)
4093 {
4094         struct intel_plane *plane = to_intel_plane(plane_state->uapi.plane);
4095         const struct drm_framebuffer *fb = plane_state->hw.fb;
4096         u32 data_rate;
4097         u32 width = 0, height = 0;
4098         uint_fixed_16_16_t down_scale_amount;
4099         u64 rate;
4100
4101         if (!plane_state->uapi.visible)
4102                 return 0;
4103
4104         if (plane->id == PLANE_CURSOR)
4105                 return 0;
4106
4107         if (color_plane == 1 &&
4108             !drm_format_info_is_yuv_semiplanar(fb->format))
4109                 return 0;
4110
4111         /*
4112          * Src coordinates are already rotated by 270 degrees for
4113          * the 90/270 degree plane rotation cases (to match the
4114          * GTT mapping), hence no need to account for rotation here.
4115          */
4116         width = drm_rect_width(&plane_state->uapi.src) >> 16;
4117         height = drm_rect_height(&plane_state->uapi.src) >> 16;
4118
4119         /* UV plane does 1/2 pixel sub-sampling */
4120         if (color_plane == 1) {
4121                 width /= 2;
4122                 height /= 2;
4123         }
4124
4125         data_rate = width * height;
4126
4127         down_scale_amount = skl_plane_downscale_amount(crtc_state, plane_state);
4128
4129         rate = mul_round_up_u32_fixed16(data_rate, down_scale_amount);
4130
4131         rate *= fb->format->cpp[color_plane];
4132         return rate;
4133 }
4134
4135 static u64
4136 skl_get_total_relative_data_rate(struct intel_crtc_state *crtc_state,
4137                                  u64 *plane_data_rate,
4138                                  u64 *uv_plane_data_rate)
4139 {
4140         struct drm_atomic_state *state = crtc_state->uapi.state;
4141         struct intel_plane *plane;
4142         const struct intel_plane_state *plane_state;
4143         u64 total_data_rate = 0;
4144
4145         if (WARN_ON(!state))
4146                 return 0;
4147
4148         /* Calculate and cache data rate for each plane */
4149         intel_atomic_crtc_state_for_each_plane_state(plane, plane_state, crtc_state) {
4150                 enum plane_id plane_id = plane->id;
4151                 u64 rate;
4152
4153                 /* packed/y */
4154                 rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4155                 plane_data_rate[plane_id] = rate;
4156                 total_data_rate += rate;
4157
4158                 /* uv-plane */
4159                 rate = skl_plane_relative_data_rate(crtc_state, plane_state, 1);
4160                 uv_plane_data_rate[plane_id] = rate;
4161                 total_data_rate += rate;
4162         }
4163
4164         return total_data_rate;
4165 }
4166
4167 static u64
4168 icl_get_total_relative_data_rate(struct intel_crtc_state *crtc_state,
4169                                  u64 *plane_data_rate)
4170 {
4171         struct intel_plane *plane;
4172         const struct intel_plane_state *plane_state;
4173         u64 total_data_rate = 0;
4174
4175         if (WARN_ON(!crtc_state->uapi.state))
4176                 return 0;
4177
4178         /* Calculate and cache data rate for each plane */
4179         intel_atomic_crtc_state_for_each_plane_state(plane, plane_state, crtc_state) {
4180                 enum plane_id plane_id = plane->id;
4181                 u64 rate;
4182
4183                 if (!plane_state->planar_linked_plane) {
4184                         rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4185                         plane_data_rate[plane_id] = rate;
4186                         total_data_rate += rate;
4187                 } else {
4188                         enum plane_id y_plane_id;
4189
4190                         /*
4191                          * The slave plane might not iterate in
4192                          * intel_atomic_crtc_state_for_each_plane_state(),
4193                          * and needs the master plane state which may be
4194                          * NULL if we try get_new_plane_state(), so we
4195                          * always calculate from the master.
4196                          */
4197                         if (plane_state->planar_slave)
4198                                 continue;
4199
4200                         /* Y plane rate is calculated on the slave */
4201                         rate = skl_plane_relative_data_rate(crtc_state, plane_state, 0);
4202                         y_plane_id = plane_state->planar_linked_plane->id;
4203                         plane_data_rate[y_plane_id] = rate;
4204                         total_data_rate += rate;
4205
4206                         rate = skl_plane_relative_data_rate(crtc_state, plane_state, 1);
4207                         plane_data_rate[plane_id] = rate;
4208                         total_data_rate += rate;
4209                 }
4210         }
4211
4212         return total_data_rate;
4213 }
4214
4215 static int
4216 skl_allocate_pipe_ddb(struct intel_crtc_state *crtc_state,
4217                       struct skl_ddb_allocation *ddb /* out */)
4218 {
4219         struct drm_atomic_state *state = crtc_state->uapi.state;
4220         struct drm_crtc *crtc = crtc_state->uapi.crtc;
4221         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4222         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4223         struct skl_ddb_entry *alloc = &crtc_state->wm.skl.ddb;
4224         u16 alloc_size, start = 0;
4225         u16 total[I915_MAX_PLANES] = {};
4226         u16 uv_total[I915_MAX_PLANES] = {};
4227         u64 total_data_rate;
4228         enum plane_id plane_id;
4229         int num_active;
4230         u64 plane_data_rate[I915_MAX_PLANES] = {};
4231         u64 uv_plane_data_rate[I915_MAX_PLANES] = {};
4232         u32 blocks;
4233         int level;
4234
4235         /* Clear the partitioning for disabled planes. */
4236         memset(crtc_state->wm.skl.plane_ddb_y, 0, sizeof(crtc_state->wm.skl.plane_ddb_y));
4237         memset(crtc_state->wm.skl.plane_ddb_uv, 0, sizeof(crtc_state->wm.skl.plane_ddb_uv));
4238
4239         if (WARN_ON(!state))
4240                 return 0;
4241
4242         if (!crtc_state->hw.active) {
4243                 alloc->start = alloc->end = 0;
4244                 return 0;
4245         }
4246
4247         if (INTEL_GEN(dev_priv) >= 11)
4248                 total_data_rate =
4249                         icl_get_total_relative_data_rate(crtc_state,
4250                                                          plane_data_rate);
4251         else
4252                 total_data_rate =
4253                         skl_get_total_relative_data_rate(crtc_state,
4254                                                          plane_data_rate,
4255                                                          uv_plane_data_rate);
4256
4257
4258         skl_ddb_get_pipe_allocation_limits(dev_priv, crtc_state, total_data_rate,
4259                                            ddb, alloc, &num_active);
4260         alloc_size = skl_ddb_entry_size(alloc);
4261         if (alloc_size == 0)
4262                 return 0;
4263
4264         /* Allocate fixed number of blocks for cursor. */
4265         total[PLANE_CURSOR] = skl_cursor_allocation(crtc_state, num_active);
4266         alloc_size -= total[PLANE_CURSOR];
4267         crtc_state->wm.skl.plane_ddb_y[PLANE_CURSOR].start =
4268                 alloc->end - total[PLANE_CURSOR];
4269         crtc_state->wm.skl.plane_ddb_y[PLANE_CURSOR].end = alloc->end;
4270
4271         if (total_data_rate == 0)
4272                 return 0;
4273
4274         /*
4275          * Find the highest watermark level for which we can satisfy the block
4276          * requirement of active planes.
4277          */
4278         for (level = ilk_wm_max_level(dev_priv); level >= 0; level--) {
4279                 blocks = 0;
4280                 for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4281                         const struct skl_plane_wm *wm =
4282                                 &crtc_state->wm.skl.optimal.planes[plane_id];
4283
4284                         if (plane_id == PLANE_CURSOR) {
4285                                 if (WARN_ON(wm->wm[level].min_ddb_alloc >
4286                                             total[PLANE_CURSOR])) {
4287                                         blocks = U32_MAX;
4288                                         break;
4289                                 }
4290                                 continue;
4291                         }
4292
4293                         blocks += wm->wm[level].min_ddb_alloc;
4294                         blocks += wm->uv_wm[level].min_ddb_alloc;
4295                 }
4296
4297                 if (blocks <= alloc_size) {
4298                         alloc_size -= blocks;
4299                         break;
4300                 }
4301         }
4302
4303         if (level < 0) {
4304                 DRM_DEBUG_KMS("Requested display configuration exceeds system DDB limitations");
4305                 DRM_DEBUG_KMS("minimum required %d/%d\n", blocks,
4306                               alloc_size);
4307                 return -EINVAL;
4308         }
4309
4310         /*
4311          * Grant each plane the blocks it requires at the highest achievable
4312          * watermark level, plus an extra share of the leftover blocks
4313          * proportional to its relative data rate.
4314          */
4315         for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4316                 const struct skl_plane_wm *wm =
4317                         &crtc_state->wm.skl.optimal.planes[plane_id];
4318                 u64 rate;
4319                 u16 extra;
4320
4321                 if (plane_id == PLANE_CURSOR)
4322                         continue;
4323
4324                 /*
4325                  * We've accounted for all active planes; remaining planes are
4326                  * all disabled.
4327                  */
4328                 if (total_data_rate == 0)
4329                         break;
4330
4331                 rate = plane_data_rate[plane_id];
4332                 extra = min_t(u16, alloc_size,
4333                               DIV64_U64_ROUND_UP(alloc_size * rate,
4334                                                  total_data_rate));
4335                 total[plane_id] = wm->wm[level].min_ddb_alloc + extra;
4336                 alloc_size -= extra;
4337                 total_data_rate -= rate;
4338
4339                 if (total_data_rate == 0)
4340                         break;
4341
4342                 rate = uv_plane_data_rate[plane_id];
4343                 extra = min_t(u16, alloc_size,
4344                               DIV64_U64_ROUND_UP(alloc_size * rate,
4345                                                  total_data_rate));
4346                 uv_total[plane_id] = wm->uv_wm[level].min_ddb_alloc + extra;
4347                 alloc_size -= extra;
4348                 total_data_rate -= rate;
4349         }
4350         WARN_ON(alloc_size != 0 || total_data_rate != 0);
4351
4352         /* Set the actual DDB start/end points for each plane */
4353         start = alloc->start;
4354         for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4355                 struct skl_ddb_entry *plane_alloc =
4356                         &crtc_state->wm.skl.plane_ddb_y[plane_id];
4357                 struct skl_ddb_entry *uv_plane_alloc =
4358                         &crtc_state->wm.skl.plane_ddb_uv[plane_id];
4359
4360                 if (plane_id == PLANE_CURSOR)
4361                         continue;
4362
4363                 /* Gen11+ uses a separate plane for UV watermarks */
4364                 WARN_ON(INTEL_GEN(dev_priv) >= 11 && uv_total[plane_id]);
4365
4366                 /* Leave disabled planes at (0,0) */
4367                 if (total[plane_id]) {
4368                         plane_alloc->start = start;
4369                         start += total[plane_id];
4370                         plane_alloc->end = start;
4371                 }
4372
4373                 if (uv_total[plane_id]) {
4374                         uv_plane_alloc->start = start;
4375                         start += uv_total[plane_id];
4376                         uv_plane_alloc->end = start;
4377                 }
4378         }
4379
4380         /*
4381          * When we calculated watermark values we didn't know how high
4382          * of a level we'd actually be able to hit, so we just marked
4383          * all levels as "enabled."  Go back now and disable the ones
4384          * that aren't actually possible.
4385          */
4386         for (level++; level <= ilk_wm_max_level(dev_priv); level++) {
4387                 for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4388                         struct skl_plane_wm *wm =
4389                                 &crtc_state->wm.skl.optimal.planes[plane_id];
4390
4391                         /*
4392                          * We only disable the watermarks for each plane if
4393                          * they exceed the ddb allocation of said plane. This
4394                          * is done so that we don't end up touching cursor
4395                          * watermarks needlessly when some other plane reduces
4396                          * our max possible watermark level.
4397                          *
4398                          * Bspec has this to say about the PLANE_WM enable bit:
4399                          * "All the watermarks at this level for all enabled
4400                          *  planes must be enabled before the level will be used."
4401                          * So this is actually safe to do.
4402                          */
4403                         if (wm->wm[level].min_ddb_alloc > total[plane_id] ||
4404                             wm->uv_wm[level].min_ddb_alloc > uv_total[plane_id])
4405                                 memset(&wm->wm[level], 0, sizeof(wm->wm[level]));
4406
4407                         /*
4408                          * Wa_1408961008:icl, ehl
4409                          * Underruns with WM1+ disabled
4410                          */
4411                         if (IS_GEN(dev_priv, 11) &&
4412                             level == 1 && wm->wm[0].plane_en) {
4413                                 wm->wm[level].plane_res_b = wm->wm[0].plane_res_b;
4414                                 wm->wm[level].plane_res_l = wm->wm[0].plane_res_l;
4415                                 wm->wm[level].ignore_lines = wm->wm[0].ignore_lines;
4416                         }
4417                 }
4418         }
4419
4420         /*
4421          * Go back and disable the transition watermark if it turns out we
4422          * don't have enough DDB blocks for it.
4423          */
4424         for_each_plane_id_on_crtc(intel_crtc, plane_id) {
4425                 struct skl_plane_wm *wm =
4426                         &crtc_state->wm.skl.optimal.planes[plane_id];
4427
4428                 if (wm->trans_wm.plane_res_b >= total[plane_id])
4429                         memset(&wm->trans_wm, 0, sizeof(wm->trans_wm));
4430         }
4431
4432         return 0;
4433 }
4434
4435 /*
4436  * The max latency should be 257 (max the punit can code is 255 and we add 2us
4437  * for the read latency) and cpp should always be <= 8, so that
4438  * should allow pixel_rate up to ~2 GHz which seems sufficient since max
4439  * 2xcdclk is 1350 MHz and the pixel rate should never exceed that.
4440 */
4441 static uint_fixed_16_16_t
4442 skl_wm_method1(const struct drm_i915_private *dev_priv, u32 pixel_rate,
4443                u8 cpp, u32 latency, u32 dbuf_block_size)
4444 {
4445         u32 wm_intermediate_val;
4446         uint_fixed_16_16_t ret;
4447
4448         if (latency == 0)
4449                 return FP_16_16_MAX;
4450
4451         wm_intermediate_val = latency * pixel_rate * cpp;
4452         ret = div_fixed16(wm_intermediate_val, 1000 * dbuf_block_size);
4453
4454         if (INTEL_GEN(dev_priv) >= 10)
4455                 ret = add_fixed16_u32(ret, 1);
4456
4457         return ret;
4458 }
4459
4460 static uint_fixed_16_16_t
4461 skl_wm_method2(u32 pixel_rate, u32 pipe_htotal, u32 latency,
4462                uint_fixed_16_16_t plane_blocks_per_line)
4463 {
4464         u32 wm_intermediate_val;
4465         uint_fixed_16_16_t ret;
4466
4467         if (latency == 0)
4468                 return FP_16_16_MAX;
4469
4470         wm_intermediate_val = latency * pixel_rate;
4471         wm_intermediate_val = DIV_ROUND_UP(wm_intermediate_val,
4472                                            pipe_htotal * 1000);
4473         ret = mul_u32_fixed16(wm_intermediate_val, plane_blocks_per_line);
4474         return ret;
4475 }
4476
4477 static uint_fixed_16_16_t
4478 intel_get_linetime_us(const struct intel_crtc_state *crtc_state)
4479 {
4480         u32 pixel_rate;
4481         u32 crtc_htotal;
4482         uint_fixed_16_16_t linetime_us;
4483
4484         if (!crtc_state->hw.active)
4485                 return u32_to_fixed16(0);
4486
4487         pixel_rate = crtc_state->pixel_rate;
4488
4489         if (WARN_ON(pixel_rate == 0))
4490                 return u32_to_fixed16(0);
4491
4492         crtc_htotal = crtc_state->hw.adjusted_mode.crtc_htotal;
4493         linetime_us = div_fixed16(crtc_htotal * 1000, pixel_rate);
4494
4495         return linetime_us;
4496 }
4497
4498 static u32
4499 skl_adjusted_plane_pixel_rate(const struct intel_crtc_state *crtc_state,
4500                               const struct intel_plane_state *plane_state)
4501 {
4502         u64 adjusted_pixel_rate;
4503         uint_fixed_16_16_t downscale_amount;
4504
4505         /* Shouldn't reach here on disabled planes... */
4506         if (WARN_ON(!intel_wm_plane_visible(crtc_state, plane_state)))
4507                 return 0;
4508
4509         /*
4510          * Adjusted plane pixel rate is just the pipe's adjusted pixel rate
4511          * with additional adjustments for plane-specific scaling.
4512          */
4513         adjusted_pixel_rate = crtc_state->pixel_rate;
4514         downscale_amount = skl_plane_downscale_amount(crtc_state, plane_state);
4515
4516         return mul_round_up_u32_fixed16(adjusted_pixel_rate,
4517                                             downscale_amount);
4518 }
4519
4520 static int
4521 skl_compute_wm_params(const struct intel_crtc_state *crtc_state,
4522                       int width, const struct drm_format_info *format,
4523                       u64 modifier, unsigned int rotation,
4524                       u32 plane_pixel_rate, struct skl_wm_params *wp,
4525                       int color_plane)
4526 {
4527         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
4528         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4529         u32 interm_pbpl;
4530
4531         /* only planar format has two planes */
4532         if (color_plane == 1 && !drm_format_info_is_yuv_semiplanar(format)) {
4533                 DRM_DEBUG_KMS("Non planar format have single plane\n");
4534                 return -EINVAL;
4535         }
4536
4537         wp->y_tiled = modifier == I915_FORMAT_MOD_Y_TILED ||
4538                       modifier == I915_FORMAT_MOD_Yf_TILED ||
4539                       modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
4540                       modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
4541         wp->x_tiled = modifier == I915_FORMAT_MOD_X_TILED;
4542         wp->rc_surface = modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
4543                          modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
4544         wp->is_planar = drm_format_info_is_yuv_semiplanar(format);
4545
4546         wp->width = width;
4547         if (color_plane == 1 && wp->is_planar)
4548                 wp->width /= 2;
4549
4550         wp->cpp = format->cpp[color_plane];
4551         wp->plane_pixel_rate = plane_pixel_rate;
4552
4553         if (INTEL_GEN(dev_priv) >= 11 &&
4554             modifier == I915_FORMAT_MOD_Yf_TILED  && wp->cpp == 1)
4555                 wp->dbuf_block_size = 256;
4556         else
4557                 wp->dbuf_block_size = 512;
4558
4559         if (drm_rotation_90_or_270(rotation)) {
4560                 switch (wp->cpp) {
4561                 case 1:
4562                         wp->y_min_scanlines = 16;
4563                         break;
4564                 case 2:
4565                         wp->y_min_scanlines = 8;
4566                         break;
4567                 case 4:
4568                         wp->y_min_scanlines = 4;
4569                         break;
4570                 default:
4571                         MISSING_CASE(wp->cpp);
4572                         return -EINVAL;
4573                 }
4574         } else {
4575                 wp->y_min_scanlines = 4;
4576         }
4577
4578         if (skl_needs_memory_bw_wa(dev_priv))
4579                 wp->y_min_scanlines *= 2;
4580
4581         wp->plane_bytes_per_line = wp->width * wp->cpp;
4582         if (wp->y_tiled) {
4583                 interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line *
4584                                            wp->y_min_scanlines,
4585                                            wp->dbuf_block_size);
4586
4587                 if (INTEL_GEN(dev_priv) >= 10)
4588                         interm_pbpl++;
4589
4590                 wp->plane_blocks_per_line = div_fixed16(interm_pbpl,
4591                                                         wp->y_min_scanlines);
4592         } else if (wp->x_tiled && IS_GEN(dev_priv, 9)) {
4593                 interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line,
4594                                            wp->dbuf_block_size);
4595                 wp->plane_blocks_per_line = u32_to_fixed16(interm_pbpl);
4596         } else {
4597                 interm_pbpl = DIV_ROUND_UP(wp->plane_bytes_per_line,
4598                                            wp->dbuf_block_size) + 1;
4599                 wp->plane_blocks_per_line = u32_to_fixed16(interm_pbpl);
4600         }
4601
4602         wp->y_tile_minimum = mul_u32_fixed16(wp->y_min_scanlines,
4603                                              wp->plane_blocks_per_line);
4604
4605         wp->linetime_us = fixed16_to_u32_round_up(
4606                                         intel_get_linetime_us(crtc_state));
4607
4608         return 0;
4609 }
4610
4611 static int
4612 skl_compute_plane_wm_params(const struct intel_crtc_state *crtc_state,
4613                             const struct intel_plane_state *plane_state,
4614                             struct skl_wm_params *wp, int color_plane)
4615 {
4616         const struct drm_framebuffer *fb = plane_state->hw.fb;
4617         int width;
4618
4619         /*
4620          * Src coordinates are already rotated by 270 degrees for
4621          * the 90/270 degree plane rotation cases (to match the
4622          * GTT mapping), hence no need to account for rotation here.
4623          */
4624         width = drm_rect_width(&plane_state->uapi.src) >> 16;
4625
4626         return skl_compute_wm_params(crtc_state, width,
4627                                      fb->format, fb->modifier,
4628                                      plane_state->hw.rotation,
4629                                      skl_adjusted_plane_pixel_rate(crtc_state, plane_state),
4630                                      wp, color_plane);
4631 }
4632
4633 static bool skl_wm_has_lines(struct drm_i915_private *dev_priv, int level)
4634 {
4635         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4636                 return true;
4637
4638         /* The number of lines are ignored for the level 0 watermark. */
4639         return level > 0;
4640 }
4641
4642 static void skl_compute_plane_wm(const struct intel_crtc_state *crtc_state,
4643                                  int level,
4644                                  const struct skl_wm_params *wp,
4645                                  const struct skl_wm_level *result_prev,
4646                                  struct skl_wm_level *result /* out */)
4647 {
4648         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
4649         u32 latency = dev_priv->wm.skl_latency[level];
4650         uint_fixed_16_16_t method1, method2;
4651         uint_fixed_16_16_t selected_result;
4652         u32 res_blocks, res_lines, min_ddb_alloc = 0;
4653
4654         if (latency == 0) {
4655                 /* reject it */
4656                 result->min_ddb_alloc = U16_MAX;
4657                 return;
4658         }
4659
4660         /*
4661          * WaIncreaseLatencyIPCEnabled: kbl,cfl
4662          * Display WA #1141: kbl,cfl
4663          */
4664         if ((IS_KABYLAKE(dev_priv) || IS_COFFEELAKE(dev_priv)) ||
4665             dev_priv->ipc_enabled)
4666                 latency += 4;
4667
4668         if (skl_needs_memory_bw_wa(dev_priv) && wp->x_tiled)
4669                 latency += 15;
4670
4671         method1 = skl_wm_method1(dev_priv, wp->plane_pixel_rate,
4672                                  wp->cpp, latency, wp->dbuf_block_size);
4673         method2 = skl_wm_method2(wp->plane_pixel_rate,
4674                                  crtc_state->hw.adjusted_mode.crtc_htotal,
4675                                  latency,
4676                                  wp->plane_blocks_per_line);
4677
4678         if (wp->y_tiled) {
4679                 selected_result = max_fixed16(method2, wp->y_tile_minimum);
4680         } else {
4681                 if ((wp->cpp * crtc_state->hw.adjusted_mode.crtc_htotal /
4682                      wp->dbuf_block_size < 1) &&
4683                      (wp->plane_bytes_per_line / wp->dbuf_block_size < 1)) {
4684                         selected_result = method2;
4685                 } else if (latency >= wp->linetime_us) {
4686                         if (IS_GEN(dev_priv, 9) &&
4687                             !IS_GEMINILAKE(dev_priv))
4688                                 selected_result = min_fixed16(method1, method2);
4689                         else
4690                                 selected_result = method2;
4691                 } else {
4692                         selected_result = method1;
4693                 }
4694         }
4695
4696         res_blocks = fixed16_to_u32_round_up(selected_result) + 1;
4697         res_lines = div_round_up_fixed16(selected_result,
4698                                          wp->plane_blocks_per_line);
4699
4700         if (IS_GEN9_BC(dev_priv) || IS_BROXTON(dev_priv)) {
4701                 /* Display WA #1125: skl,bxt,kbl */
4702                 if (level == 0 && wp->rc_surface)
4703                         res_blocks +=
4704                                 fixed16_to_u32_round_up(wp->y_tile_minimum);
4705
4706                 /* Display WA #1126: skl,bxt,kbl */
4707                 if (level >= 1 && level <= 7) {
4708                         if (wp->y_tiled) {
4709                                 res_blocks +=
4710                                     fixed16_to_u32_round_up(wp->y_tile_minimum);
4711                                 res_lines += wp->y_min_scanlines;
4712                         } else {
4713                                 res_blocks++;
4714                         }
4715
4716                         /*
4717                          * Make sure result blocks for higher latency levels are
4718                          * atleast as high as level below the current level.
4719                          * Assumption in DDB algorithm optimization for special
4720                          * cases. Also covers Display WA #1125 for RC.
4721                          */
4722                         if (result_prev->plane_res_b > res_blocks)
4723                                 res_blocks = result_prev->plane_res_b;
4724                 }
4725         }
4726
4727         if (INTEL_GEN(dev_priv) >= 11) {
4728                 if (wp->y_tiled) {
4729                         int extra_lines;
4730
4731                         if (res_lines % wp->y_min_scanlines == 0)
4732                                 extra_lines = wp->y_min_scanlines;
4733                         else
4734                                 extra_lines = wp->y_min_scanlines * 2 -
4735                                         res_lines % wp->y_min_scanlines;
4736
4737                         min_ddb_alloc = mul_round_up_u32_fixed16(res_lines + extra_lines,
4738                                                                  wp->plane_blocks_per_line);
4739                 } else {
4740                         min_ddb_alloc = res_blocks +
4741                                 DIV_ROUND_UP(res_blocks, 10);
4742                 }
4743         }
4744
4745         if (!skl_wm_has_lines(dev_priv, level))
4746                 res_lines = 0;
4747
4748         if (res_lines > 31) {
4749                 /* reject it */
4750                 result->min_ddb_alloc = U16_MAX;
4751                 return;
4752         }
4753
4754         /*
4755          * If res_lines is valid, assume we can use this watermark level
4756          * for now.  We'll come back and disable it after we calculate the
4757          * DDB allocation if it turns out we don't actually have enough
4758          * blocks to satisfy it.
4759          */
4760         result->plane_res_b = res_blocks;
4761         result->plane_res_l = res_lines;
4762         /* Bspec says: value >= plane ddb allocation -> invalid, hence the +1 here */
4763         result->min_ddb_alloc = max(min_ddb_alloc, res_blocks) + 1;
4764         result->plane_en = true;
4765 }
4766
4767 static void
4768 skl_compute_wm_levels(const struct intel_crtc_state *crtc_state,
4769                       const struct skl_wm_params *wm_params,
4770                       struct skl_wm_level *levels)
4771 {
4772         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
4773         int level, max_level = ilk_wm_max_level(dev_priv);
4774         struct skl_wm_level *result_prev = &levels[0];
4775
4776         for (level = 0; level <= max_level; level++) {
4777                 struct skl_wm_level *result = &levels[level];
4778
4779                 skl_compute_plane_wm(crtc_state, level, wm_params,
4780                                      result_prev, result);
4781
4782                 result_prev = result;
4783         }
4784 }
4785
4786 static u32
4787 skl_compute_linetime_wm(const struct intel_crtc_state *crtc_state)
4788 {
4789         struct drm_atomic_state *state = crtc_state->uapi.state;
4790         struct drm_i915_private *dev_priv = to_i915(state->dev);
4791         uint_fixed_16_16_t linetime_us;
4792         u32 linetime_wm;
4793
4794         linetime_us = intel_get_linetime_us(crtc_state);
4795         linetime_wm = fixed16_to_u32_round_up(mul_u32_fixed16(8, linetime_us));
4796
4797         /* Display WA #1135: BXT:ALL GLK:ALL */
4798         if (IS_GEN9_LP(dev_priv) && dev_priv->ipc_enabled)
4799                 linetime_wm /= 2;
4800
4801         return linetime_wm;
4802 }
4803
4804 static void skl_compute_transition_wm(const struct intel_crtc_state *crtc_state,
4805                                       const struct skl_wm_params *wp,
4806                                       struct skl_plane_wm *wm)
4807 {
4808         struct drm_device *dev = crtc_state->uapi.crtc->dev;
4809         const struct drm_i915_private *dev_priv = to_i915(dev);
4810         u16 trans_min, trans_y_tile_min;
4811         const u16 trans_amount = 10; /* This is configurable amount */
4812         u16 wm0_sel_res_b, trans_offset_b, res_blocks;
4813
4814         /* Transition WM are not recommended by HW team for GEN9 */
4815         if (INTEL_GEN(dev_priv) <= 9)
4816                 return;
4817
4818         /* Transition WM don't make any sense if ipc is disabled */
4819         if (!dev_priv->ipc_enabled)
4820                 return;
4821
4822         trans_min = 14;
4823         if (INTEL_GEN(dev_priv) >= 11)
4824                 trans_min = 4;
4825
4826         trans_offset_b = trans_min + trans_amount;
4827
4828         /*
4829          * The spec asks for Selected Result Blocks for wm0 (the real value),
4830          * not Result Blocks (the integer value). Pay attention to the capital
4831          * letters. The value wm_l0->plane_res_b is actually Result Blocks, but
4832          * since Result Blocks is the ceiling of Selected Result Blocks plus 1,
4833          * and since we later will have to get the ceiling of the sum in the
4834          * transition watermarks calculation, we can just pretend Selected
4835          * Result Blocks is Result Blocks minus 1 and it should work for the
4836          * current platforms.
4837          */
4838         wm0_sel_res_b = wm->wm[0].plane_res_b - 1;
4839
4840         if (wp->y_tiled) {
4841                 trans_y_tile_min =
4842                         (u16)mul_round_up_u32_fixed16(2, wp->y_tile_minimum);
4843                 res_blocks = max(wm0_sel_res_b, trans_y_tile_min) +
4844                                 trans_offset_b;
4845         } else {
4846                 res_blocks = wm0_sel_res_b + trans_offset_b;
4847
4848                 /* WA BUG:1938466 add one block for non y-tile planes */
4849                 if (IS_CNL_REVID(dev_priv, CNL_REVID_A0, CNL_REVID_A0))
4850                         res_blocks += 1;
4851
4852         }
4853
4854         /*
4855          * Just assume we can enable the transition watermark.  After
4856          * computing the DDB we'll come back and disable it if that
4857          * assumption turns out to be false.
4858          */
4859         wm->trans_wm.plane_res_b = res_blocks + 1;
4860         wm->trans_wm.plane_en = true;
4861 }
4862
4863 static int skl_build_plane_wm_single(struct intel_crtc_state *crtc_state,
4864                                      const struct intel_plane_state *plane_state,
4865                                      enum plane_id plane_id, int color_plane)
4866 {
4867         struct skl_plane_wm *wm = &crtc_state->wm.skl.optimal.planes[plane_id];
4868         struct skl_wm_params wm_params;
4869         int ret;
4870
4871         ret = skl_compute_plane_wm_params(crtc_state, plane_state,
4872                                           &wm_params, color_plane);
4873         if (ret)
4874                 return ret;
4875
4876         skl_compute_wm_levels(crtc_state, &wm_params, wm->wm);
4877         skl_compute_transition_wm(crtc_state, &wm_params, wm);
4878
4879         return 0;
4880 }
4881
4882 static int skl_build_plane_wm_uv(struct intel_crtc_state *crtc_state,
4883                                  const struct intel_plane_state *plane_state,
4884                                  enum plane_id plane_id)
4885 {
4886         struct skl_plane_wm *wm = &crtc_state->wm.skl.optimal.planes[plane_id];
4887         struct skl_wm_params wm_params;
4888         int ret;
4889
4890         wm->is_planar = true;
4891
4892         /* uv plane watermarks must also be validated for NV12/Planar */
4893         ret = skl_compute_plane_wm_params(crtc_state, plane_state,
4894                                           &wm_params, 1);
4895         if (ret)
4896                 return ret;
4897
4898         skl_compute_wm_levels(crtc_state, &wm_params, wm->uv_wm);
4899
4900         return 0;
4901 }
4902
4903 static int skl_build_plane_wm(struct intel_crtc_state *crtc_state,
4904                               const struct intel_plane_state *plane_state)
4905 {
4906         struct intel_plane *plane = to_intel_plane(plane_state->uapi.plane);
4907         const struct drm_framebuffer *fb = plane_state->hw.fb;
4908         enum plane_id plane_id = plane->id;
4909         int ret;
4910
4911         if (!intel_wm_plane_visible(crtc_state, plane_state))
4912                 return 0;
4913
4914         ret = skl_build_plane_wm_single(crtc_state, plane_state,
4915                                         plane_id, 0);
4916         if (ret)
4917                 return ret;
4918
4919         if (fb->format->is_yuv && fb->format->num_planes > 1) {
4920                 ret = skl_build_plane_wm_uv(crtc_state, plane_state,
4921                                             plane_id);
4922                 if (ret)
4923                         return ret;
4924         }
4925
4926         return 0;
4927 }
4928
4929 static int icl_build_plane_wm(struct intel_crtc_state *crtc_state,
4930                               const struct intel_plane_state *plane_state)
4931 {
4932         enum plane_id plane_id = to_intel_plane(plane_state->uapi.plane)->id;
4933         int ret;
4934
4935         /* Watermarks calculated in master */
4936         if (plane_state->planar_slave)
4937                 return 0;
4938
4939         if (plane_state->planar_linked_plane) {
4940                 const struct drm_framebuffer *fb = plane_state->hw.fb;
4941                 enum plane_id y_plane_id = plane_state->planar_linked_plane->id;
4942
4943                 WARN_ON(!intel_wm_plane_visible(crtc_state, plane_state));
4944                 WARN_ON(!fb->format->is_yuv ||
4945                         fb->format->num_planes == 1);
4946
4947                 ret = skl_build_plane_wm_single(crtc_state, plane_state,
4948                                                 y_plane_id, 0);
4949                 if (ret)
4950                         return ret;
4951
4952                 ret = skl_build_plane_wm_single(crtc_state, plane_state,
4953                                                 plane_id, 1);
4954                 if (ret)
4955                         return ret;
4956         } else if (intel_wm_plane_visible(crtc_state, plane_state)) {
4957                 ret = skl_build_plane_wm_single(crtc_state, plane_state,
4958                                                 plane_id, 0);
4959                 if (ret)
4960                         return ret;
4961         }
4962
4963         return 0;
4964 }
4965
4966 static int skl_build_pipe_wm(struct intel_crtc_state *crtc_state)
4967 {
4968         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
4969         struct skl_pipe_wm *pipe_wm = &crtc_state->wm.skl.optimal;
4970         struct intel_plane *plane;
4971         const struct intel_plane_state *plane_state;
4972         int ret;
4973
4974         /*
4975          * We'll only calculate watermarks for planes that are actually
4976          * enabled, so make sure all other planes are set as disabled.
4977          */
4978         memset(pipe_wm->planes, 0, sizeof(pipe_wm->planes));
4979
4980         intel_atomic_crtc_state_for_each_plane_state(plane, plane_state,
4981                                                      crtc_state) {
4982
4983                 if (INTEL_GEN(dev_priv) >= 11)
4984                         ret = icl_build_plane_wm(crtc_state, plane_state);
4985                 else
4986                         ret = skl_build_plane_wm(crtc_state, plane_state);
4987                 if (ret)
4988                         return ret;
4989         }
4990
4991         pipe_wm->linetime = skl_compute_linetime_wm(crtc_state);
4992
4993         return 0;
4994 }
4995
4996 static void skl_ddb_entry_write(struct drm_i915_private *dev_priv,
4997                                 i915_reg_t reg,
4998                                 const struct skl_ddb_entry *entry)
4999 {
5000         if (entry->end)
5001                 I915_WRITE_FW(reg, (entry->end - 1) << 16 | entry->start);
5002         else
5003                 I915_WRITE_FW(reg, 0);
5004 }
5005
5006 static void skl_write_wm_level(struct drm_i915_private *dev_priv,
5007                                i915_reg_t reg,
5008                                const struct skl_wm_level *level)
5009 {
5010         u32 val = 0;
5011
5012         if (level->plane_en)
5013                 val |= PLANE_WM_EN;
5014         if (level->ignore_lines)
5015                 val |= PLANE_WM_IGNORE_LINES;
5016         val |= level->plane_res_b;
5017         val |= level->plane_res_l << PLANE_WM_LINES_SHIFT;
5018
5019         I915_WRITE_FW(reg, val);
5020 }
5021
5022 void skl_write_plane_wm(struct intel_plane *plane,
5023                         const struct intel_crtc_state *crtc_state)
5024 {
5025         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
5026         int level, max_level = ilk_wm_max_level(dev_priv);
5027         enum plane_id plane_id = plane->id;
5028         enum pipe pipe = plane->pipe;
5029         const struct skl_plane_wm *wm =
5030                 &crtc_state->wm.skl.optimal.planes[plane_id];
5031         const struct skl_ddb_entry *ddb_y =
5032                 &crtc_state->wm.skl.plane_ddb_y[plane_id];
5033         const struct skl_ddb_entry *ddb_uv =
5034                 &crtc_state->wm.skl.plane_ddb_uv[plane_id];
5035
5036         for (level = 0; level <= max_level; level++) {
5037                 skl_write_wm_level(dev_priv, PLANE_WM(pipe, plane_id, level),
5038                                    &wm->wm[level]);
5039         }
5040         skl_write_wm_level(dev_priv, PLANE_WM_TRANS(pipe, plane_id),
5041                            &wm->trans_wm);
5042
5043         if (INTEL_GEN(dev_priv) >= 11) {
5044                 skl_ddb_entry_write(dev_priv,
5045                                     PLANE_BUF_CFG(pipe, plane_id), ddb_y);
5046                 return;
5047         }
5048
5049         if (wm->is_planar)
5050                 swap(ddb_y, ddb_uv);
5051
5052         skl_ddb_entry_write(dev_priv,
5053                             PLANE_BUF_CFG(pipe, plane_id), ddb_y);
5054         skl_ddb_entry_write(dev_priv,
5055                             PLANE_NV12_BUF_CFG(pipe, plane_id), ddb_uv);
5056 }
5057
5058 void skl_write_cursor_wm(struct intel_plane *plane,
5059                          const struct intel_crtc_state *crtc_state)
5060 {
5061         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
5062         int level, max_level = ilk_wm_max_level(dev_priv);
5063         enum plane_id plane_id = plane->id;
5064         enum pipe pipe = plane->pipe;
5065         const struct skl_plane_wm *wm =
5066                 &crtc_state->wm.skl.optimal.planes[plane_id];
5067         const struct skl_ddb_entry *ddb =
5068                 &crtc_state->wm.skl.plane_ddb_y[plane_id];
5069
5070         for (level = 0; level <= max_level; level++) {
5071                 skl_write_wm_level(dev_priv, CUR_WM(pipe, level),
5072                                    &wm->wm[level]);
5073         }
5074         skl_write_wm_level(dev_priv, CUR_WM_TRANS(pipe), &wm->trans_wm);
5075
5076         skl_ddb_entry_write(dev_priv, CUR_BUF_CFG(pipe), ddb);
5077 }
5078
5079 bool skl_wm_level_equals(const struct skl_wm_level *l1,
5080                          const struct skl_wm_level *l2)
5081 {
5082         return l1->plane_en == l2->plane_en &&
5083                 l1->ignore_lines == l2->ignore_lines &&
5084                 l1->plane_res_l == l2->plane_res_l &&
5085                 l1->plane_res_b == l2->plane_res_b;
5086 }
5087
5088 static bool skl_plane_wm_equals(struct drm_i915_private *dev_priv,
5089                                 const struct skl_plane_wm *wm1,
5090                                 const struct skl_plane_wm *wm2)
5091 {
5092         int level, max_level = ilk_wm_max_level(dev_priv);
5093
5094         for (level = 0; level <= max_level; level++) {
5095                 if (!skl_wm_level_equals(&wm1->wm[level], &wm2->wm[level]) ||
5096                     !skl_wm_level_equals(&wm1->uv_wm[level], &wm2->uv_wm[level]))
5097                         return false;
5098         }
5099
5100         return skl_wm_level_equals(&wm1->trans_wm, &wm2->trans_wm);
5101 }
5102
5103 static bool skl_pipe_wm_equals(struct intel_crtc *crtc,
5104                                const struct skl_pipe_wm *wm1,
5105                                const struct skl_pipe_wm *wm2)
5106 {
5107         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5108         enum plane_id plane_id;
5109
5110         for_each_plane_id_on_crtc(crtc, plane_id) {
5111                 if (!skl_plane_wm_equals(dev_priv,
5112                                          &wm1->planes[plane_id],
5113                                          &wm2->planes[plane_id]))
5114                         return false;
5115         }
5116
5117         return wm1->linetime == wm2->linetime;
5118 }
5119
5120 static inline bool skl_ddb_entries_overlap(const struct skl_ddb_entry *a,
5121                                            const struct skl_ddb_entry *b)
5122 {
5123         return a->start < b->end && b->start < a->end;
5124 }
5125
5126 bool skl_ddb_allocation_overlaps(const struct skl_ddb_entry *ddb,
5127                                  const struct skl_ddb_entry *entries,
5128                                  int num_entries, int ignore_idx)
5129 {
5130         int i;
5131
5132         for (i = 0; i < num_entries; i++) {
5133                 if (i != ignore_idx &&
5134                     skl_ddb_entries_overlap(ddb, &entries[i]))
5135                         return true;
5136         }
5137
5138         return false;
5139 }
5140
5141 static int
5142 skl_ddb_add_affected_planes(const struct intel_crtc_state *old_crtc_state,
5143                             struct intel_crtc_state *new_crtc_state)
5144 {
5145         struct intel_atomic_state *state = to_intel_atomic_state(new_crtc_state->uapi.state);
5146         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->uapi.crtc);
5147         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5148         struct intel_plane *plane;
5149
5150         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
5151                 struct intel_plane_state *plane_state;
5152                 enum plane_id plane_id = plane->id;
5153
5154                 if (skl_ddb_entry_equal(&old_crtc_state->wm.skl.plane_ddb_y[plane_id],
5155                                         &new_crtc_state->wm.skl.plane_ddb_y[plane_id]) &&
5156                     skl_ddb_entry_equal(&old_crtc_state->wm.skl.plane_ddb_uv[plane_id],
5157                                         &new_crtc_state->wm.skl.plane_ddb_uv[plane_id]))
5158                         continue;
5159
5160                 plane_state = intel_atomic_get_plane_state(state, plane);
5161                 if (IS_ERR(plane_state))
5162                         return PTR_ERR(plane_state);
5163
5164                 new_crtc_state->update_planes |= BIT(plane_id);
5165         }
5166
5167         return 0;
5168 }
5169
5170 static int
5171 skl_compute_ddb(struct intel_atomic_state *state)
5172 {
5173         const struct drm_i915_private *dev_priv = to_i915(state->base.dev);
5174         struct skl_ddb_allocation *ddb = &state->wm_results.ddb;
5175         struct intel_crtc_state *old_crtc_state;
5176         struct intel_crtc_state *new_crtc_state;
5177         struct intel_crtc *crtc;
5178         int ret, i;
5179
5180         memcpy(ddb, &dev_priv->wm.skl_hw.ddb, sizeof(*ddb));
5181
5182         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
5183                                             new_crtc_state, i) {
5184                 ret = skl_allocate_pipe_ddb(new_crtc_state, ddb);
5185                 if (ret)
5186                         return ret;
5187
5188                 ret = skl_ddb_add_affected_planes(old_crtc_state,
5189                                                   new_crtc_state);
5190                 if (ret)
5191                         return ret;
5192         }
5193
5194         return 0;
5195 }
5196
5197 static char enast(bool enable)
5198 {
5199         return enable ? '*' : ' ';
5200 }
5201
5202 static void
5203 skl_print_wm_changes(struct intel_atomic_state *state)
5204 {
5205         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
5206         const struct intel_crtc_state *old_crtc_state;
5207         const struct intel_crtc_state *new_crtc_state;
5208         struct intel_plane *plane;
5209         struct intel_crtc *crtc;
5210         int i;
5211
5212         if ((drm_debug & DRM_UT_KMS) == 0)
5213                 return;
5214
5215         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
5216                                             new_crtc_state, i) {
5217                 const struct skl_pipe_wm *old_pipe_wm, *new_pipe_wm;
5218
5219                 old_pipe_wm = &old_crtc_state->wm.skl.optimal;
5220                 new_pipe_wm = &new_crtc_state->wm.skl.optimal;
5221
5222                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
5223                         enum plane_id plane_id = plane->id;
5224                         const struct skl_ddb_entry *old, *new;
5225
5226                         old = &old_crtc_state->wm.skl.plane_ddb_y[plane_id];
5227                         new = &new_crtc_state->wm.skl.plane_ddb_y[plane_id];
5228
5229                         if (skl_ddb_entry_equal(old, new))
5230                                 continue;
5231
5232                         DRM_DEBUG_KMS("[PLANE:%d:%s] ddb (%4d - %4d) -> (%4d - %4d), size %4d -> %4d\n",
5233                                       plane->base.base.id, plane->base.name,
5234                                       old->start, old->end, new->start, new->end,
5235                                       skl_ddb_entry_size(old), skl_ddb_entry_size(new));
5236                 }
5237
5238                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
5239                         enum plane_id plane_id = plane->id;
5240                         const struct skl_plane_wm *old_wm, *new_wm;
5241
5242                         old_wm = &old_pipe_wm->planes[plane_id];
5243                         new_wm = &new_pipe_wm->planes[plane_id];
5244
5245                         if (skl_plane_wm_equals(dev_priv, old_wm, new_wm))
5246                                 continue;
5247
5248                         DRM_DEBUG_KMS("[PLANE:%d:%s]   level %cwm0,%cwm1,%cwm2,%cwm3,%cwm4,%cwm5,%cwm6,%cwm7,%ctwm"
5249                                       " -> %cwm0,%cwm1,%cwm2,%cwm3,%cwm4,%cwm5,%cwm6,%cwm7,%ctwm\n",
5250                                       plane->base.base.id, plane->base.name,
5251                                       enast(old_wm->wm[0].plane_en), enast(old_wm->wm[1].plane_en),
5252                                       enast(old_wm->wm[2].plane_en), enast(old_wm->wm[3].plane_en),
5253                                       enast(old_wm->wm[4].plane_en), enast(old_wm->wm[5].plane_en),
5254                                       enast(old_wm->wm[6].plane_en), enast(old_wm->wm[7].plane_en),
5255                                       enast(old_wm->trans_wm.plane_en),
5256                                       enast(new_wm->wm[0].plane_en), enast(new_wm->wm[1].plane_en),
5257                                       enast(new_wm->wm[2].plane_en), enast(new_wm->wm[3].plane_en),
5258                                       enast(new_wm->wm[4].plane_en), enast(new_wm->wm[5].plane_en),
5259                                       enast(new_wm->wm[6].plane_en), enast(new_wm->wm[7].plane_en),
5260                                       enast(new_wm->trans_wm.plane_en));
5261
5262                         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"
5263                                       " -> %c%3d,%c%3d,%c%3d,%c%3d,%c%3d,%c%3d,%c%3d,%c%3d,%c%3d\n",
5264                                       plane->base.base.id, plane->base.name,
5265                                       enast(old_wm->wm[0].ignore_lines), old_wm->wm[0].plane_res_l,
5266                                       enast(old_wm->wm[1].ignore_lines), old_wm->wm[1].plane_res_l,
5267                                       enast(old_wm->wm[2].ignore_lines), old_wm->wm[2].plane_res_l,
5268                                       enast(old_wm->wm[3].ignore_lines), old_wm->wm[3].plane_res_l,
5269                                       enast(old_wm->wm[4].ignore_lines), old_wm->wm[4].plane_res_l,
5270                                       enast(old_wm->wm[5].ignore_lines), old_wm->wm[5].plane_res_l,
5271                                       enast(old_wm->wm[6].ignore_lines), old_wm->wm[6].plane_res_l,
5272                                       enast(old_wm->wm[7].ignore_lines), old_wm->wm[7].plane_res_l,
5273                                       enast(old_wm->trans_wm.ignore_lines), old_wm->trans_wm.plane_res_l,
5274
5275                                       enast(new_wm->wm[0].ignore_lines), new_wm->wm[0].plane_res_l,
5276                                       enast(new_wm->wm[1].ignore_lines), new_wm->wm[1].plane_res_l,
5277                                       enast(new_wm->wm[2].ignore_lines), new_wm->wm[2].plane_res_l,
5278                                       enast(new_wm->wm[3].ignore_lines), new_wm->wm[3].plane_res_l,
5279                                       enast(new_wm->wm[4].ignore_lines), new_wm->wm[4].plane_res_l,
5280                                       enast(new_wm->wm[5].ignore_lines), new_wm->wm[5].plane_res_l,
5281                                       enast(new_wm->wm[6].ignore_lines), new_wm->wm[6].plane_res_l,
5282                                       enast(new_wm->wm[7].ignore_lines), new_wm->wm[7].plane_res_l,
5283                                       enast(new_wm->trans_wm.ignore_lines), new_wm->trans_wm.plane_res_l);
5284
5285                         DRM_DEBUG_KMS("[PLANE:%d:%s]  blocks %4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d"
5286                                       " -> %4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d\n",
5287                                       plane->base.base.id, plane->base.name,
5288                                       old_wm->wm[0].plane_res_b, old_wm->wm[1].plane_res_b,
5289                                       old_wm->wm[2].plane_res_b, old_wm->wm[3].plane_res_b,
5290                                       old_wm->wm[4].plane_res_b, old_wm->wm[5].plane_res_b,
5291                                       old_wm->wm[6].plane_res_b, old_wm->wm[7].plane_res_b,
5292                                       old_wm->trans_wm.plane_res_b,
5293                                       new_wm->wm[0].plane_res_b, new_wm->wm[1].plane_res_b,
5294                                       new_wm->wm[2].plane_res_b, new_wm->wm[3].plane_res_b,
5295                                       new_wm->wm[4].plane_res_b, new_wm->wm[5].plane_res_b,
5296                                       new_wm->wm[6].plane_res_b, new_wm->wm[7].plane_res_b,
5297                                       new_wm->trans_wm.plane_res_b);
5298
5299                         DRM_DEBUG_KMS("[PLANE:%d:%s] min_ddb %4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d"
5300                                       " -> %4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d,%4d\n",
5301                                       plane->base.base.id, plane->base.name,
5302                                       old_wm->wm[0].min_ddb_alloc, old_wm->wm[1].min_ddb_alloc,
5303                                       old_wm->wm[2].min_ddb_alloc, old_wm->wm[3].min_ddb_alloc,
5304                                       old_wm->wm[4].min_ddb_alloc, old_wm->wm[5].min_ddb_alloc,
5305                                       old_wm->wm[6].min_ddb_alloc, old_wm->wm[7].min_ddb_alloc,
5306                                       old_wm->trans_wm.min_ddb_alloc,
5307                                       new_wm->wm[0].min_ddb_alloc, new_wm->wm[1].min_ddb_alloc,
5308                                       new_wm->wm[2].min_ddb_alloc, new_wm->wm[3].min_ddb_alloc,
5309                                       new_wm->wm[4].min_ddb_alloc, new_wm->wm[5].min_ddb_alloc,
5310                                       new_wm->wm[6].min_ddb_alloc, new_wm->wm[7].min_ddb_alloc,
5311                                       new_wm->trans_wm.min_ddb_alloc);
5312                 }
5313         }
5314 }
5315
5316 static int intel_add_all_pipes(struct intel_atomic_state *state)
5317 {
5318         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
5319         struct intel_crtc *crtc;
5320
5321         for_each_intel_crtc(&dev_priv->drm, crtc) {
5322                 struct intel_crtc_state *crtc_state;
5323
5324                 crtc_state = intel_atomic_get_crtc_state(&state->base, crtc);
5325                 if (IS_ERR(crtc_state))
5326                         return PTR_ERR(crtc_state);
5327         }
5328
5329         return 0;
5330 }
5331
5332 static int
5333 skl_ddb_add_affected_pipes(struct intel_atomic_state *state)
5334 {
5335         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
5336         int ret;
5337
5338         /*
5339          * If this is our first atomic update following hardware readout,
5340          * we can't trust the DDB that the BIOS programmed for us.  Let's
5341          * pretend that all pipes switched active status so that we'll
5342          * ensure a full DDB recompute.
5343          */
5344         if (dev_priv->wm.distrust_bios_wm) {
5345                 ret = drm_modeset_lock(&dev_priv->drm.mode_config.connection_mutex,
5346                                        state->base.acquire_ctx);
5347                 if (ret)
5348                         return ret;
5349
5350                 state->active_pipe_changes = ~0;
5351
5352                 /*
5353                  * We usually only initialize state->active_pipes if we
5354                  * we're doing a modeset; make sure this field is always
5355                  * initialized during the sanitization process that happens
5356                  * on the first commit too.
5357                  */
5358                 if (!state->modeset)
5359                         state->active_pipes = dev_priv->active_pipes;
5360         }
5361
5362         /*
5363          * If the modeset changes which CRTC's are active, we need to
5364          * recompute the DDB allocation for *all* active pipes, even
5365          * those that weren't otherwise being modified in any way by this
5366          * atomic commit.  Due to the shrinking of the per-pipe allocations
5367          * when new active CRTC's are added, it's possible for a pipe that
5368          * we were already using and aren't changing at all here to suddenly
5369          * become invalid if its DDB needs exceeds its new allocation.
5370          *
5371          * Note that if we wind up doing a full DDB recompute, we can't let
5372          * any other display updates race with this transaction, so we need
5373          * to grab the lock on *all* CRTC's.
5374          */
5375         if (state->active_pipe_changes || state->modeset) {
5376                 state->wm_results.dirty_pipes = ~0;
5377
5378                 ret = intel_add_all_pipes(state);
5379                 if (ret)
5380                         return ret;
5381         }
5382
5383         return 0;
5384 }
5385
5386 /*
5387  * To make sure the cursor watermark registers are always consistent
5388  * with our computed state the following scenario needs special
5389  * treatment:
5390  *
5391  * 1. enable cursor
5392  * 2. move cursor entirely offscreen
5393  * 3. disable cursor
5394  *
5395  * Step 2. does call .disable_plane() but does not zero the watermarks
5396  * (since we consider an offscreen cursor still active for the purposes
5397  * of watermarks). Step 3. would not normally call .disable_plane()
5398  * because the actual plane visibility isn't changing, and we don't
5399  * deallocate the cursor ddb until the pipe gets disabled. So we must
5400  * force step 3. to call .disable_plane() to update the watermark
5401  * registers properly.
5402  *
5403  * Other planes do not suffer from this issues as their watermarks are
5404  * calculated based on the actual plane visibility. The only time this
5405  * can trigger for the other planes is during the initial readout as the
5406  * default value of the watermarks registers is not zero.
5407  */
5408 static int skl_wm_add_affected_planes(struct intel_atomic_state *state,
5409                                       struct intel_crtc *crtc)
5410 {
5411         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5412         const struct intel_crtc_state *old_crtc_state =
5413                 intel_atomic_get_old_crtc_state(state, crtc);
5414         struct intel_crtc_state *new_crtc_state =
5415                 intel_atomic_get_new_crtc_state(state, crtc);
5416         struct intel_plane *plane;
5417
5418         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
5419                 struct intel_plane_state *plane_state;
5420                 enum plane_id plane_id = plane->id;
5421
5422                 /*
5423                  * Force a full wm update for every plane on modeset.
5424                  * Required because the reset value of the wm registers
5425                  * is non-zero, whereas we want all disabled planes to
5426                  * have zero watermarks. So if we turn off the relevant
5427                  * power well the hardware state will go out of sync
5428                  * with the software state.
5429                  */
5430                 if (!drm_atomic_crtc_needs_modeset(&new_crtc_state->uapi) &&
5431                     skl_plane_wm_equals(dev_priv,
5432                                         &old_crtc_state->wm.skl.optimal.planes[plane_id],
5433                                         &new_crtc_state->wm.skl.optimal.planes[plane_id]))
5434                         continue;
5435
5436                 plane_state = intel_atomic_get_plane_state(state, plane);
5437                 if (IS_ERR(plane_state))
5438                         return PTR_ERR(plane_state);
5439
5440                 new_crtc_state->update_planes |= BIT(plane_id);
5441         }
5442
5443         return 0;
5444 }
5445
5446 static int
5447 skl_compute_wm(struct intel_atomic_state *state)
5448 {
5449         struct intel_crtc *crtc;
5450         struct intel_crtc_state *new_crtc_state;
5451         struct intel_crtc_state *old_crtc_state;
5452         struct skl_ddb_values *results = &state->wm_results;
5453         int ret, i;
5454
5455         /* Clear all dirty flags */
5456         results->dirty_pipes = 0;
5457
5458         ret = skl_ddb_add_affected_pipes(state);
5459         if (ret)
5460                 return ret;
5461
5462         /*
5463          * Calculate WM's for all pipes that are part of this transaction.
5464          * Note that skl_ddb_add_affected_pipes may have added more CRTC's that
5465          * weren't otherwise being modified (and set bits in dirty_pipes) if
5466          * pipe allocations had to change.
5467          */
5468         for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state,
5469                                             new_crtc_state, i) {
5470                 ret = skl_build_pipe_wm(new_crtc_state);
5471                 if (ret)
5472                         return ret;
5473
5474                 ret = skl_wm_add_affected_planes(state, crtc);
5475                 if (ret)
5476                         return ret;
5477
5478                 if (!skl_pipe_wm_equals(crtc,
5479                                         &old_crtc_state->wm.skl.optimal,
5480                                         &new_crtc_state->wm.skl.optimal))
5481                         results->dirty_pipes |= BIT(crtc->pipe);
5482         }
5483
5484         ret = skl_compute_ddb(state);
5485         if (ret)
5486                 return ret;
5487
5488         skl_print_wm_changes(state);
5489
5490         return 0;
5491 }
5492
5493 static void skl_atomic_update_crtc_wm(struct intel_atomic_state *state,
5494                                       struct intel_crtc_state *crtc_state)
5495 {
5496         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
5497         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
5498         struct skl_pipe_wm *pipe_wm = &crtc_state->wm.skl.optimal;
5499         enum pipe pipe = crtc->pipe;
5500
5501         if ((state->wm_results.dirty_pipes & BIT(crtc->pipe)) == 0)
5502                 return;
5503
5504         I915_WRITE(PIPE_WM_LINETIME(pipe), pipe_wm->linetime);
5505 }
5506
5507 static void skl_initial_wm(struct intel_atomic_state *state,
5508                            struct intel_crtc_state *crtc_state)
5509 {
5510         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
5511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5512         struct skl_ddb_values *results = &state->wm_results;
5513
5514         if ((results->dirty_pipes & BIT(crtc->pipe)) == 0)
5515                 return;
5516
5517         mutex_lock(&dev_priv->wm.wm_mutex);
5518
5519         if (crtc_state->uapi.active_changed)
5520                 skl_atomic_update_crtc_wm(state, crtc_state);
5521
5522         mutex_unlock(&dev_priv->wm.wm_mutex);
5523 }
5524
5525 static void ilk_compute_wm_config(struct drm_i915_private *dev_priv,
5526                                   struct intel_wm_config *config)
5527 {
5528         struct intel_crtc *crtc;
5529
5530         /* Compute the currently _active_ config */
5531         for_each_intel_crtc(&dev_priv->drm, crtc) {
5532                 const struct intel_pipe_wm *wm = &crtc->wm.active.ilk;
5533
5534                 if (!wm->pipe_enabled)
5535                         continue;
5536
5537                 config->sprites_enabled |= wm->sprites_enabled;
5538                 config->sprites_scaled |= wm->sprites_scaled;
5539                 config->num_pipes_active++;
5540         }
5541 }
5542
5543 static void ilk_program_watermarks(struct drm_i915_private *dev_priv)
5544 {
5545         struct intel_pipe_wm lp_wm_1_2 = {}, lp_wm_5_6 = {}, *best_lp_wm;
5546         struct ilk_wm_maximums max;
5547         struct intel_wm_config config = {};
5548         struct ilk_wm_values results = {};
5549         enum intel_ddb_partitioning partitioning;
5550
5551         ilk_compute_wm_config(dev_priv, &config);
5552
5553         ilk_compute_wm_maximums(dev_priv, 1, &config, INTEL_DDB_PART_1_2, &max);
5554         ilk_wm_merge(dev_priv, &config, &max, &lp_wm_1_2);
5555
5556         /* 5/6 split only in single pipe config on IVB+ */
5557         if (INTEL_GEN(dev_priv) >= 7 &&
5558             config.num_pipes_active == 1 && config.sprites_enabled) {
5559                 ilk_compute_wm_maximums(dev_priv, 1, &config, INTEL_DDB_PART_5_6, &max);
5560                 ilk_wm_merge(dev_priv, &config, &max, &lp_wm_5_6);
5561
5562                 best_lp_wm = ilk_find_best_result(dev_priv, &lp_wm_1_2, &lp_wm_5_6);
5563         } else {
5564                 best_lp_wm = &lp_wm_1_2;
5565         }
5566
5567         partitioning = (best_lp_wm == &lp_wm_1_2) ?
5568                        INTEL_DDB_PART_1_2 : INTEL_DDB_PART_5_6;
5569
5570         ilk_compute_wm_results(dev_priv, best_lp_wm, partitioning, &results);
5571
5572         ilk_write_wm_values(dev_priv, &results);
5573 }
5574
5575 static void ilk_initial_watermarks(struct intel_atomic_state *state,
5576                                    struct intel_crtc_state *crtc_state)
5577 {
5578         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
5579         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
5580
5581         mutex_lock(&dev_priv->wm.wm_mutex);
5582         crtc->wm.active.ilk = crtc_state->wm.ilk.intermediate;
5583         ilk_program_watermarks(dev_priv);
5584         mutex_unlock(&dev_priv->wm.wm_mutex);
5585 }
5586
5587 static void ilk_optimize_watermarks(struct intel_atomic_state *state,
5588                                     struct intel_crtc_state *crtc_state)
5589 {
5590         struct drm_i915_private *dev_priv = to_i915(crtc_state->uapi.crtc->dev);
5591         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
5592
5593         if (!crtc_state->wm.need_postvbl_update)
5594                 return;
5595
5596         mutex_lock(&dev_priv->wm.wm_mutex);
5597         crtc->wm.active.ilk = crtc_state->wm.ilk.optimal;
5598         ilk_program_watermarks(dev_priv);
5599         mutex_unlock(&dev_priv->wm.wm_mutex);
5600 }
5601
5602 static inline void skl_wm_level_from_reg_val(u32 val,
5603                                              struct skl_wm_level *level)
5604 {
5605         level->plane_en = val & PLANE_WM_EN;
5606         level->ignore_lines = val & PLANE_WM_IGNORE_LINES;
5607         level->plane_res_b = val & PLANE_WM_BLOCKS_MASK;
5608         level->plane_res_l = (val >> PLANE_WM_LINES_SHIFT) &
5609                 PLANE_WM_LINES_MASK;
5610 }
5611
5612 void skl_pipe_wm_get_hw_state(struct intel_crtc *crtc,
5613                               struct skl_pipe_wm *out)
5614 {
5615         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5616         enum pipe pipe = crtc->pipe;
5617         int level, max_level;
5618         enum plane_id plane_id;
5619         u32 val;
5620
5621         max_level = ilk_wm_max_level(dev_priv);
5622
5623         for_each_plane_id_on_crtc(crtc, plane_id) {
5624                 struct skl_plane_wm *wm = &out->planes[plane_id];
5625
5626                 for (level = 0; level <= max_level; level++) {
5627                         if (plane_id != PLANE_CURSOR)
5628                                 val = I915_READ(PLANE_WM(pipe, plane_id, level));
5629                         else
5630                                 val = I915_READ(CUR_WM(pipe, level));
5631
5632                         skl_wm_level_from_reg_val(val, &wm->wm[level]);
5633                 }
5634
5635                 if (plane_id != PLANE_CURSOR)
5636                         val = I915_READ(PLANE_WM_TRANS(pipe, plane_id));
5637                 else
5638                         val = I915_READ(CUR_WM_TRANS(pipe));
5639
5640                 skl_wm_level_from_reg_val(val, &wm->trans_wm);
5641         }
5642
5643         if (!crtc->active)
5644                 return;
5645
5646         out->linetime = I915_READ(PIPE_WM_LINETIME(pipe));
5647 }
5648
5649 void skl_wm_get_hw_state(struct drm_i915_private *dev_priv)
5650 {
5651         struct skl_ddb_values *hw = &dev_priv->wm.skl_hw;
5652         struct skl_ddb_allocation *ddb = &dev_priv->wm.skl_hw.ddb;
5653         struct intel_crtc *crtc;
5654         struct intel_crtc_state *crtc_state;
5655
5656         skl_ddb_get_hw_state(dev_priv, ddb);
5657         for_each_intel_crtc(&dev_priv->drm, crtc) {
5658                 crtc_state = to_intel_crtc_state(crtc->base.state);
5659
5660                 skl_pipe_wm_get_hw_state(crtc, &crtc_state->wm.skl.optimal);
5661
5662                 if (crtc->active)
5663                         hw->dirty_pipes |= BIT(crtc->pipe);
5664         }
5665
5666         if (dev_priv->active_pipes) {
5667                 /* Fully recompute DDB on first atomic commit */
5668                 dev_priv->wm.distrust_bios_wm = true;
5669         }
5670 }
5671
5672 static void ilk_pipe_wm_get_hw_state(struct intel_crtc *crtc)
5673 {
5674         struct drm_device *dev = crtc->base.dev;
5675         struct drm_i915_private *dev_priv = to_i915(dev);
5676         struct ilk_wm_values *hw = &dev_priv->wm.hw;
5677         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
5678         struct intel_pipe_wm *active = &crtc_state->wm.ilk.optimal;
5679         enum pipe pipe = crtc->pipe;
5680         static const i915_reg_t wm0_pipe_reg[] = {
5681                 [PIPE_A] = WM0_PIPEA_ILK,
5682                 [PIPE_B] = WM0_PIPEB_ILK,
5683                 [PIPE_C] = WM0_PIPEC_IVB,
5684         };
5685
5686         hw->wm_pipe[pipe] = I915_READ(wm0_pipe_reg[pipe]);
5687         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5688                 hw->wm_linetime[pipe] = I915_READ(PIPE_WM_LINETIME(pipe));
5689
5690         memset(active, 0, sizeof(*active));
5691
5692         active->pipe_enabled = crtc->active;
5693
5694         if (active->pipe_enabled) {
5695                 u32 tmp = hw->wm_pipe[pipe];
5696
5697                 /*
5698                  * For active pipes LP0 watermark is marked as
5699                  * enabled, and LP1+ watermaks as disabled since
5700                  * we can't really reverse compute them in case
5701                  * multiple pipes are active.
5702                  */
5703                 active->wm[0].enable = true;
5704                 active->wm[0].pri_val = (tmp & WM0_PIPE_PLANE_MASK) >> WM0_PIPE_PLANE_SHIFT;
5705                 active->wm[0].spr_val = (tmp & WM0_PIPE_SPRITE_MASK) >> WM0_PIPE_SPRITE_SHIFT;
5706                 active->wm[0].cur_val = tmp & WM0_PIPE_CURSOR_MASK;
5707                 active->linetime = hw->wm_linetime[pipe];
5708         } else {
5709                 int level, max_level = ilk_wm_max_level(dev_priv);
5710
5711                 /*
5712                  * For inactive pipes, all watermark levels
5713                  * should be marked as enabled but zeroed,
5714                  * which is what we'd compute them to.
5715                  */
5716                 for (level = 0; level <= max_level; level++)
5717                         active->wm[level].enable = true;
5718         }
5719
5720         crtc->wm.active.ilk = *active;
5721 }
5722
5723 #define _FW_WM(value, plane) \
5724         (((value) & DSPFW_ ## plane ## _MASK) >> DSPFW_ ## plane ## _SHIFT)
5725 #define _FW_WM_VLV(value, plane) \
5726         (((value) & DSPFW_ ## plane ## _MASK_VLV) >> DSPFW_ ## plane ## _SHIFT)
5727
5728 static void g4x_read_wm_values(struct drm_i915_private *dev_priv,
5729                                struct g4x_wm_values *wm)
5730 {
5731         u32 tmp;
5732
5733         tmp = I915_READ(DSPFW1);
5734         wm->sr.plane = _FW_WM(tmp, SR);
5735         wm->pipe[PIPE_B].plane[PLANE_CURSOR] = _FW_WM(tmp, CURSORB);
5736         wm->pipe[PIPE_B].plane[PLANE_PRIMARY] = _FW_WM(tmp, PLANEB);
5737         wm->pipe[PIPE_A].plane[PLANE_PRIMARY] = _FW_WM(tmp, PLANEA);
5738
5739         tmp = I915_READ(DSPFW2);
5740         wm->fbc_en = tmp & DSPFW_FBC_SR_EN;
5741         wm->sr.fbc = _FW_WM(tmp, FBC_SR);
5742         wm->hpll.fbc = _FW_WM(tmp, FBC_HPLL_SR);
5743         wm->pipe[PIPE_B].plane[PLANE_SPRITE0] = _FW_WM(tmp, SPRITEB);
5744         wm->pipe[PIPE_A].plane[PLANE_CURSOR] = _FW_WM(tmp, CURSORA);
5745         wm->pipe[PIPE_A].plane[PLANE_SPRITE0] = _FW_WM(tmp, SPRITEA);
5746
5747         tmp = I915_READ(DSPFW3);
5748         wm->hpll_en = tmp & DSPFW_HPLL_SR_EN;
5749         wm->sr.cursor = _FW_WM(tmp, CURSOR_SR);
5750         wm->hpll.cursor = _FW_WM(tmp, HPLL_CURSOR);
5751         wm->hpll.plane = _FW_WM(tmp, HPLL_SR);
5752 }
5753
5754 static void vlv_read_wm_values(struct drm_i915_private *dev_priv,
5755                                struct vlv_wm_values *wm)
5756 {
5757         enum pipe pipe;
5758         u32 tmp;
5759
5760         for_each_pipe(dev_priv, pipe) {
5761                 tmp = I915_READ(VLV_DDL(pipe));
5762
5763                 wm->ddl[pipe].plane[PLANE_PRIMARY] =
5764                         (tmp >> DDL_PLANE_SHIFT) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
5765                 wm->ddl[pipe].plane[PLANE_CURSOR] =
5766                         (tmp >> DDL_CURSOR_SHIFT) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
5767                 wm->ddl[pipe].plane[PLANE_SPRITE0] =
5768                         (tmp >> DDL_SPRITE_SHIFT(0)) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
5769                 wm->ddl[pipe].plane[PLANE_SPRITE1] =
5770                         (tmp >> DDL_SPRITE_SHIFT(1)) & (DDL_PRECISION_HIGH | DRAIN_LATENCY_MASK);
5771         }
5772
5773         tmp = I915_READ(DSPFW1);
5774         wm->sr.plane = _FW_WM(tmp, SR);
5775         wm->pipe[PIPE_B].plane[PLANE_CURSOR] = _FW_WM(tmp, CURSORB);
5776         wm->pipe[PIPE_B].plane[PLANE_PRIMARY] = _FW_WM_VLV(tmp, PLANEB);
5777         wm->pipe[PIPE_A].plane[PLANE_PRIMARY] = _FW_WM_VLV(tmp, PLANEA);
5778
5779         tmp = I915_READ(DSPFW2);
5780         wm->pipe[PIPE_A].plane[PLANE_SPRITE1] = _FW_WM_VLV(tmp, SPRITEB);
5781         wm->pipe[PIPE_A].plane[PLANE_CURSOR] = _FW_WM(tmp, CURSORA);
5782         wm->pipe[PIPE_A].plane[PLANE_SPRITE0] = _FW_WM_VLV(tmp, SPRITEA);
5783
5784         tmp = I915_READ(DSPFW3);
5785         wm->sr.cursor = _FW_WM(tmp, CURSOR_SR);
5786
5787         if (IS_CHERRYVIEW(dev_priv)) {
5788                 tmp = I915_READ(DSPFW7_CHV);
5789                 wm->pipe[PIPE_B].plane[PLANE_SPRITE1] = _FW_WM_VLV(tmp, SPRITED);
5790                 wm->pipe[PIPE_B].plane[PLANE_SPRITE0] = _FW_WM_VLV(tmp, SPRITEC);
5791
5792                 tmp = I915_READ(DSPFW8_CHV);
5793                 wm->pipe[PIPE_C].plane[PLANE_SPRITE1] = _FW_WM_VLV(tmp, SPRITEF);
5794                 wm->pipe[PIPE_C].plane[PLANE_SPRITE0] = _FW_WM_VLV(tmp, SPRITEE);
5795
5796                 tmp = I915_READ(DSPFW9_CHV);
5797                 wm->pipe[PIPE_C].plane[PLANE_PRIMARY] = _FW_WM_VLV(tmp, PLANEC);
5798                 wm->pipe[PIPE_C].plane[PLANE_CURSOR] = _FW_WM(tmp, CURSORC);
5799
5800                 tmp = I915_READ(DSPHOWM);
5801                 wm->sr.plane |= _FW_WM(tmp, SR_HI) << 9;
5802                 wm->pipe[PIPE_C].plane[PLANE_SPRITE1] |= _FW_WM(tmp, SPRITEF_HI) << 8;
5803                 wm->pipe[PIPE_C].plane[PLANE_SPRITE0] |= _FW_WM(tmp, SPRITEE_HI) << 8;
5804                 wm->pipe[PIPE_C].plane[PLANE_PRIMARY] |= _FW_WM(tmp, PLANEC_HI) << 8;
5805                 wm->pipe[PIPE_B].plane[PLANE_SPRITE1] |= _FW_WM(tmp, SPRITED_HI) << 8;
5806                 wm->pipe[PIPE_B].plane[PLANE_SPRITE0] |= _FW_WM(tmp, SPRITEC_HI) << 8;
5807                 wm->pipe[PIPE_B].plane[PLANE_PRIMARY] |= _FW_WM(tmp, PLANEB_HI) << 8;
5808                 wm->pipe[PIPE_A].plane[PLANE_SPRITE1] |= _FW_WM(tmp, SPRITEB_HI) << 8;
5809                 wm->pipe[PIPE_A].plane[PLANE_SPRITE0] |= _FW_WM(tmp, SPRITEA_HI) << 8;
5810                 wm->pipe[PIPE_A].plane[PLANE_PRIMARY] |= _FW_WM(tmp, PLANEA_HI) << 8;
5811         } else {
5812                 tmp = I915_READ(DSPFW7);
5813                 wm->pipe[PIPE_B].plane[PLANE_SPRITE1] = _FW_WM_VLV(tmp, SPRITED);
5814                 wm->pipe[PIPE_B].plane[PLANE_SPRITE0] = _FW_WM_VLV(tmp, SPRITEC);
5815
5816                 tmp = I915_READ(DSPHOWM);
5817                 wm->sr.plane |= _FW_WM(tmp, SR_HI) << 9;
5818                 wm->pipe[PIPE_B].plane[PLANE_SPRITE1] |= _FW_WM(tmp, SPRITED_HI) << 8;
5819                 wm->pipe[PIPE_B].plane[PLANE_SPRITE0] |= _FW_WM(tmp, SPRITEC_HI) << 8;
5820                 wm->pipe[PIPE_B].plane[PLANE_PRIMARY] |= _FW_WM(tmp, PLANEB_HI) << 8;
5821                 wm->pipe[PIPE_A].plane[PLANE_SPRITE1] |= _FW_WM(tmp, SPRITEB_HI) << 8;
5822                 wm->pipe[PIPE_A].plane[PLANE_SPRITE0] |= _FW_WM(tmp, SPRITEA_HI) << 8;
5823                 wm->pipe[PIPE_A].plane[PLANE_PRIMARY] |= _FW_WM(tmp, PLANEA_HI) << 8;
5824         }
5825 }
5826
5827 #undef _FW_WM
5828 #undef _FW_WM_VLV
5829
5830 void g4x_wm_get_hw_state(struct drm_i915_private *dev_priv)
5831 {
5832         struct g4x_wm_values *wm = &dev_priv->wm.g4x;
5833         struct intel_crtc *crtc;
5834
5835         g4x_read_wm_values(dev_priv, wm);
5836
5837         wm->cxsr = I915_READ(FW_BLC_SELF) & FW_BLC_SELF_EN;
5838
5839         for_each_intel_crtc(&dev_priv->drm, crtc) {
5840                 struct intel_crtc_state *crtc_state =
5841                         to_intel_crtc_state(crtc->base.state);
5842                 struct g4x_wm_state *active = &crtc->wm.active.g4x;
5843                 struct g4x_pipe_wm *raw;
5844                 enum pipe pipe = crtc->pipe;
5845                 enum plane_id plane_id;
5846                 int level, max_level;
5847
5848                 active->cxsr = wm->cxsr;
5849                 active->hpll_en = wm->hpll_en;
5850                 active->fbc_en = wm->fbc_en;
5851
5852                 active->sr = wm->sr;
5853                 active->hpll = wm->hpll;
5854
5855                 for_each_plane_id_on_crtc(crtc, plane_id) {
5856                         active->wm.plane[plane_id] =
5857                                 wm->pipe[pipe].plane[plane_id];
5858                 }
5859
5860                 if (wm->cxsr && wm->hpll_en)
5861                         max_level = G4X_WM_LEVEL_HPLL;
5862                 else if (wm->cxsr)
5863                         max_level = G4X_WM_LEVEL_SR;
5864                 else
5865                         max_level = G4X_WM_LEVEL_NORMAL;
5866
5867                 level = G4X_WM_LEVEL_NORMAL;
5868                 raw = &crtc_state->wm.g4x.raw[level];
5869                 for_each_plane_id_on_crtc(crtc, plane_id)
5870                         raw->plane[plane_id] = active->wm.plane[plane_id];
5871
5872                 if (++level > max_level)
5873                         goto out;
5874
5875                 raw = &crtc_state->wm.g4x.raw[level];
5876                 raw->plane[PLANE_PRIMARY] = active->sr.plane;
5877                 raw->plane[PLANE_CURSOR] = active->sr.cursor;
5878                 raw->plane[PLANE_SPRITE0] = 0;
5879                 raw->fbc = active->sr.fbc;
5880
5881                 if (++level > max_level)
5882                         goto out;
5883
5884                 raw = &crtc_state->wm.g4x.raw[level];
5885                 raw->plane[PLANE_PRIMARY] = active->hpll.plane;
5886                 raw->plane[PLANE_CURSOR] = active->hpll.cursor;
5887                 raw->plane[PLANE_SPRITE0] = 0;
5888                 raw->fbc = active->hpll.fbc;
5889
5890         out:
5891                 for_each_plane_id_on_crtc(crtc, plane_id)
5892                         g4x_raw_plane_wm_set(crtc_state, level,
5893                                              plane_id, USHRT_MAX);
5894                 g4x_raw_fbc_wm_set(crtc_state, level, USHRT_MAX);
5895
5896                 crtc_state->wm.g4x.optimal = *active;
5897                 crtc_state->wm.g4x.intermediate = *active;
5898
5899                 DRM_DEBUG_KMS("Initial watermarks: pipe %c, plane=%d, cursor=%d, sprite=%d\n",
5900                               pipe_name(pipe),
5901                               wm->pipe[pipe].plane[PLANE_PRIMARY],
5902                               wm->pipe[pipe].plane[PLANE_CURSOR],
5903                               wm->pipe[pipe].plane[PLANE_SPRITE0]);
5904         }
5905
5906         DRM_DEBUG_KMS("Initial SR watermarks: plane=%d, cursor=%d fbc=%d\n",
5907                       wm->sr.plane, wm->sr.cursor, wm->sr.fbc);
5908         DRM_DEBUG_KMS("Initial HPLL watermarks: plane=%d, SR cursor=%d fbc=%d\n",
5909                       wm->hpll.plane, wm->hpll.cursor, wm->hpll.fbc);
5910         DRM_DEBUG_KMS("Initial SR=%s HPLL=%s FBC=%s\n",
5911                       yesno(wm->cxsr), yesno(wm->hpll_en), yesno(wm->fbc_en));
5912 }
5913
5914 void g4x_wm_sanitize(struct drm_i915_private *dev_priv)
5915 {
5916         struct intel_plane *plane;
5917         struct intel_crtc *crtc;
5918
5919         mutex_lock(&dev_priv->wm.wm_mutex);
5920
5921         for_each_intel_plane(&dev_priv->drm, plane) {
5922                 struct intel_crtc *crtc =
5923                         intel_get_crtc_for_pipe(dev_priv, plane->pipe);
5924                 struct intel_crtc_state *crtc_state =
5925                         to_intel_crtc_state(crtc->base.state);
5926                 struct intel_plane_state *plane_state =
5927                         to_intel_plane_state(plane->base.state);
5928                 struct g4x_wm_state *wm_state = &crtc_state->wm.g4x.optimal;
5929                 enum plane_id plane_id = plane->id;
5930                 int level;
5931
5932                 if (plane_state->uapi.visible)
5933                         continue;
5934
5935                 for (level = 0; level < 3; level++) {
5936                         struct g4x_pipe_wm *raw =
5937                                 &crtc_state->wm.g4x.raw[level];
5938
5939                         raw->plane[plane_id] = 0;
5940                         wm_state->wm.plane[plane_id] = 0;
5941                 }
5942
5943                 if (plane_id == PLANE_PRIMARY) {
5944                         for (level = 0; level < 3; level++) {
5945                                 struct g4x_pipe_wm *raw =
5946                                         &crtc_state->wm.g4x.raw[level];
5947                                 raw->fbc = 0;
5948                         }
5949
5950                         wm_state->sr.fbc = 0;
5951                         wm_state->hpll.fbc = 0;
5952                         wm_state->fbc_en = false;
5953                 }
5954         }
5955
5956         for_each_intel_crtc(&dev_priv->drm, crtc) {
5957                 struct intel_crtc_state *crtc_state =
5958                         to_intel_crtc_state(crtc->base.state);
5959
5960                 crtc_state->wm.g4x.intermediate =
5961                         crtc_state->wm.g4x.optimal;
5962                 crtc->wm.active.g4x = crtc_state->wm.g4x.optimal;
5963         }
5964
5965         g4x_program_watermarks(dev_priv);
5966
5967         mutex_unlock(&dev_priv->wm.wm_mutex);
5968 }
5969
5970 void vlv_wm_get_hw_state(struct drm_i915_private *dev_priv)
5971 {
5972         struct vlv_wm_values *wm = &dev_priv->wm.vlv;
5973         struct intel_crtc *crtc;
5974         u32 val;
5975
5976         vlv_read_wm_values(dev_priv, wm);
5977
5978         wm->cxsr = I915_READ(FW_BLC_SELF_VLV) & FW_CSPWRDWNEN;
5979         wm->level = VLV_WM_LEVEL_PM2;
5980
5981         if (IS_CHERRYVIEW(dev_priv)) {
5982                 vlv_punit_get(dev_priv);
5983
5984                 val = vlv_punit_read(dev_priv, PUNIT_REG_DSPSSPM);
5985                 if (val & DSP_MAXFIFO_PM5_ENABLE)
5986                         wm->level = VLV_WM_LEVEL_PM5;
5987
5988                 /*
5989                  * If DDR DVFS is disabled in the BIOS, Punit
5990                  * will never ack the request. So if that happens
5991                  * assume we don't have to enable/disable DDR DVFS
5992                  * dynamically. To test that just set the REQ_ACK
5993                  * bit to poke the Punit, but don't change the
5994                  * HIGH/LOW bits so that we don't actually change
5995                  * the current state.
5996                  */
5997                 val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
5998                 val |= FORCE_DDR_FREQ_REQ_ACK;
5999                 vlv_punit_write(dev_priv, PUNIT_REG_DDR_SETUP2, val);
6000
6001                 if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2) &
6002                               FORCE_DDR_FREQ_REQ_ACK) == 0, 3)) {
6003                         DRM_DEBUG_KMS("Punit not acking DDR DVFS request, "
6004                                       "assuming DDR DVFS is disabled\n");
6005                         dev_priv->wm.max_level = VLV_WM_LEVEL_PM5;
6006                 } else {
6007                         val = vlv_punit_read(dev_priv, PUNIT_REG_DDR_SETUP2);
6008                         if ((val & FORCE_DDR_HIGH_FREQ) == 0)
6009                                 wm->level = VLV_WM_LEVEL_DDR_DVFS;
6010                 }
6011
6012                 vlv_punit_put(dev_priv);
6013         }
6014
6015         for_each_intel_crtc(&dev_priv->drm, crtc) {
6016                 struct intel_crtc_state *crtc_state =
6017                         to_intel_crtc_state(crtc->base.state);
6018                 struct vlv_wm_state *active = &crtc->wm.active.vlv;
6019                 const struct vlv_fifo_state *fifo_state =
6020                         &crtc_state->wm.vlv.fifo_state;
6021                 enum pipe pipe = crtc->pipe;
6022                 enum plane_id plane_id;
6023                 int level;
6024
6025                 vlv_get_fifo_size(crtc_state);
6026
6027                 active->num_levels = wm->level + 1;
6028                 active->cxsr = wm->cxsr;
6029
6030                 for (level = 0; level < active->num_levels; level++) {
6031                         struct g4x_pipe_wm *raw =
6032                                 &crtc_state->wm.vlv.raw[level];
6033
6034                         active->sr[level].plane = wm->sr.plane;
6035                         active->sr[level].cursor = wm->sr.cursor;
6036
6037                         for_each_plane_id_on_crtc(crtc, plane_id) {
6038                                 active->wm[level].plane[plane_id] =
6039                                         wm->pipe[pipe].plane[plane_id];
6040
6041                                 raw->plane[plane_id] =
6042                                         vlv_invert_wm_value(active->wm[level].plane[plane_id],
6043                                                             fifo_state->plane[plane_id]);
6044                         }
6045                 }
6046
6047                 for_each_plane_id_on_crtc(crtc, plane_id)
6048                         vlv_raw_plane_wm_set(crtc_state, level,
6049                                              plane_id, USHRT_MAX);
6050                 vlv_invalidate_wms(crtc, active, level);
6051
6052                 crtc_state->wm.vlv.optimal = *active;
6053                 crtc_state->wm.vlv.intermediate = *active;
6054
6055                 DRM_DEBUG_KMS("Initial watermarks: pipe %c, plane=%d, cursor=%d, sprite0=%d, sprite1=%d\n",
6056                               pipe_name(pipe),
6057                               wm->pipe[pipe].plane[PLANE_PRIMARY],
6058                               wm->pipe[pipe].plane[PLANE_CURSOR],
6059                               wm->pipe[pipe].plane[PLANE_SPRITE0],
6060                               wm->pipe[pipe].plane[PLANE_SPRITE1]);
6061         }
6062
6063         DRM_DEBUG_KMS("Initial watermarks: SR plane=%d, SR cursor=%d level=%d cxsr=%d\n",
6064                       wm->sr.plane, wm->sr.cursor, wm->level, wm->cxsr);
6065 }
6066
6067 void vlv_wm_sanitize(struct drm_i915_private *dev_priv)
6068 {
6069         struct intel_plane *plane;
6070         struct intel_crtc *crtc;
6071
6072         mutex_lock(&dev_priv->wm.wm_mutex);
6073
6074         for_each_intel_plane(&dev_priv->drm, plane) {
6075                 struct intel_crtc *crtc =
6076                         intel_get_crtc_for_pipe(dev_priv, plane->pipe);
6077                 struct intel_crtc_state *crtc_state =
6078                         to_intel_crtc_state(crtc->base.state);
6079                 struct intel_plane_state *plane_state =
6080                         to_intel_plane_state(plane->base.state);
6081                 struct vlv_wm_state *wm_state = &crtc_state->wm.vlv.optimal;
6082                 const struct vlv_fifo_state *fifo_state =
6083                         &crtc_state->wm.vlv.fifo_state;
6084                 enum plane_id plane_id = plane->id;
6085                 int level;
6086
6087                 if (plane_state->uapi.visible)
6088                         continue;
6089
6090                 for (level = 0; level < wm_state->num_levels; level++) {
6091                         struct g4x_pipe_wm *raw =
6092                                 &crtc_state->wm.vlv.raw[level];
6093
6094                         raw->plane[plane_id] = 0;
6095
6096                         wm_state->wm[level].plane[plane_id] =
6097                                 vlv_invert_wm_value(raw->plane[plane_id],
6098                                                     fifo_state->plane[plane_id]);
6099                 }
6100         }
6101
6102         for_each_intel_crtc(&dev_priv->drm, crtc) {
6103                 struct intel_crtc_state *crtc_state =
6104                         to_intel_crtc_state(crtc->base.state);
6105
6106                 crtc_state->wm.vlv.intermediate =
6107                         crtc_state->wm.vlv.optimal;
6108                 crtc->wm.active.vlv = crtc_state->wm.vlv.optimal;
6109         }
6110
6111         vlv_program_watermarks(dev_priv);
6112
6113         mutex_unlock(&dev_priv->wm.wm_mutex);
6114 }
6115
6116 /*
6117  * FIXME should probably kill this and improve
6118  * the real watermark readout/sanitation instead
6119  */
6120 static void ilk_init_lp_watermarks(struct drm_i915_private *dev_priv)
6121 {
6122         I915_WRITE(WM3_LP_ILK, I915_READ(WM3_LP_ILK) & ~WM1_LP_SR_EN);
6123         I915_WRITE(WM2_LP_ILK, I915_READ(WM2_LP_ILK) & ~WM1_LP_SR_EN);
6124         I915_WRITE(WM1_LP_ILK, I915_READ(WM1_LP_ILK) & ~WM1_LP_SR_EN);
6125
6126         /*
6127          * Don't touch WM1S_LP_EN here.
6128          * Doing so could cause underruns.
6129          */
6130 }
6131
6132 void ilk_wm_get_hw_state(struct drm_i915_private *dev_priv)
6133 {
6134         struct ilk_wm_values *hw = &dev_priv->wm.hw;
6135         struct intel_crtc *crtc;
6136
6137         ilk_init_lp_watermarks(dev_priv);
6138
6139         for_each_intel_crtc(&dev_priv->drm, crtc)
6140                 ilk_pipe_wm_get_hw_state(crtc);
6141
6142         hw->wm_lp[0] = I915_READ(WM1_LP_ILK);
6143         hw->wm_lp[1] = I915_READ(WM2_LP_ILK);
6144         hw->wm_lp[2] = I915_READ(WM3_LP_ILK);
6145
6146         hw->wm_lp_spr[0] = I915_READ(WM1S_LP_ILK);
6147         if (INTEL_GEN(dev_priv) >= 7) {
6148                 hw->wm_lp_spr[1] = I915_READ(WM2S_LP_IVB);
6149                 hw->wm_lp_spr[2] = I915_READ(WM3S_LP_IVB);
6150         }
6151
6152         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
6153                 hw->partitioning = (I915_READ(WM_MISC) & WM_MISC_DATA_PARTITION_5_6) ?
6154                         INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
6155         else if (IS_IVYBRIDGE(dev_priv))
6156                 hw->partitioning = (I915_READ(DISP_ARB_CTL2) & DISP_DATA_PARTITION_5_6) ?
6157                         INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
6158
6159         hw->enable_fbc_wm =
6160                 !(I915_READ(DISP_ARB_CTL) & DISP_FBC_WM_DIS);
6161 }
6162
6163 /**
6164  * intel_update_watermarks - update FIFO watermark values based on current modes
6165  * @crtc: the #intel_crtc on which to compute the WM
6166  *
6167  * Calculate watermark values for the various WM regs based on current mode
6168  * and plane configuration.
6169  *
6170  * There are several cases to deal with here:
6171  *   - normal (i.e. non-self-refresh)
6172  *   - self-refresh (SR) mode
6173  *   - lines are large relative to FIFO size (buffer can hold up to 2)
6174  *   - lines are small relative to FIFO size (buffer can hold more than 2
6175  *     lines), so need to account for TLB latency
6176  *
6177  *   The normal calculation is:
6178  *     watermark = dotclock * bytes per pixel * latency
6179  *   where latency is platform & configuration dependent (we assume pessimal
6180  *   values here).
6181  *
6182  *   The SR calculation is:
6183  *     watermark = (trunc(latency/line time)+1) * surface width *
6184  *       bytes per pixel
6185  *   where
6186  *     line time = htotal / dotclock
6187  *     surface width = hdisplay for normal plane and 64 for cursor
6188  *   and latency is assumed to be high, as above.
6189  *
6190  * The final value programmed to the register should always be rounded up,
6191  * and include an extra 2 entries to account for clock crossings.
6192  *
6193  * We don't use the sprite, so we can ignore that.  And on Crestline we have
6194  * to set the non-SR watermarks to 8.
6195  */
6196 void intel_update_watermarks(struct intel_crtc *crtc)
6197 {
6198         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6199
6200         if (dev_priv->display.update_wm)
6201                 dev_priv->display.update_wm(crtc);
6202 }
6203
6204 void intel_enable_ipc(struct drm_i915_private *dev_priv)
6205 {
6206         u32 val;
6207
6208         if (!HAS_IPC(dev_priv))
6209                 return;
6210
6211         val = I915_READ(DISP_ARB_CTL2);
6212
6213         if (dev_priv->ipc_enabled)
6214                 val |= DISP_IPC_ENABLE;
6215         else
6216                 val &= ~DISP_IPC_ENABLE;
6217
6218         I915_WRITE(DISP_ARB_CTL2, val);
6219 }
6220
6221 static bool intel_can_enable_ipc(struct drm_i915_private *dev_priv)
6222 {
6223         /* Display WA #0477 WaDisableIPC: skl */
6224         if (IS_SKYLAKE(dev_priv))
6225                 return false;
6226
6227         /* Display WA #1141: SKL:all KBL:all CFL */
6228         if (IS_KABYLAKE(dev_priv) || IS_COFFEELAKE(dev_priv))
6229                 return dev_priv->dram_info.symmetric_memory;
6230
6231         return true;
6232 }
6233
6234 void intel_init_ipc(struct drm_i915_private *dev_priv)
6235 {
6236         if (!HAS_IPC(dev_priv))
6237                 return;
6238
6239         dev_priv->ipc_enabled = intel_can_enable_ipc(dev_priv);
6240
6241         intel_enable_ipc(dev_priv);
6242 }
6243
6244 static void ibx_init_clock_gating(struct drm_i915_private *dev_priv)
6245 {
6246         /*
6247          * On Ibex Peak and Cougar Point, we need to disable clock
6248          * gating for the panel power sequencer or it will fail to
6249          * start up when no ports are active.
6250          */
6251         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
6252 }
6253
6254 static void g4x_disable_trickle_feed(struct drm_i915_private *dev_priv)
6255 {
6256         enum pipe pipe;
6257
6258         for_each_pipe(dev_priv, pipe) {
6259                 I915_WRITE(DSPCNTR(pipe),
6260                            I915_READ(DSPCNTR(pipe)) |
6261                            DISPPLANE_TRICKLE_FEED_DISABLE);
6262
6263                 I915_WRITE(DSPSURF(pipe), I915_READ(DSPSURF(pipe)));
6264                 POSTING_READ(DSPSURF(pipe));
6265         }
6266 }
6267
6268 static void ilk_init_clock_gating(struct drm_i915_private *dev_priv)
6269 {
6270         u32 dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
6271
6272         /*
6273          * Required for FBC
6274          * WaFbcDisableDpfcClockGating:ilk
6275          */
6276         dspclk_gate |= ILK_DPFCRUNIT_CLOCK_GATE_DISABLE |
6277                    ILK_DPFCUNIT_CLOCK_GATE_DISABLE |
6278                    ILK_DPFDUNIT_CLOCK_GATE_ENABLE;
6279
6280         I915_WRITE(PCH_3DCGDIS0,
6281                    MARIUNIT_CLOCK_GATE_DISABLE |
6282                    SVSMUNIT_CLOCK_GATE_DISABLE);
6283         I915_WRITE(PCH_3DCGDIS1,
6284                    VFMUNIT_CLOCK_GATE_DISABLE);
6285
6286         /*
6287          * According to the spec the following bits should be set in
6288          * order to enable memory self-refresh
6289          * The bit 22/21 of 0x42004
6290          * The bit 5 of 0x42020
6291          * The bit 15 of 0x45000
6292          */
6293         I915_WRITE(ILK_DISPLAY_CHICKEN2,
6294                    (I915_READ(ILK_DISPLAY_CHICKEN2) |
6295                     ILK_DPARB_GATE | ILK_VSDPFD_FULL));
6296         dspclk_gate |= ILK_DPARBUNIT_CLOCK_GATE_ENABLE;
6297         I915_WRITE(DISP_ARB_CTL,
6298                    (I915_READ(DISP_ARB_CTL) |
6299                     DISP_FBC_WM_DIS));
6300
6301         /*
6302          * Based on the document from hardware guys the following bits
6303          * should be set unconditionally in order to enable FBC.
6304          * The bit 22 of 0x42000
6305          * The bit 22 of 0x42004
6306          * The bit 7,8,9 of 0x42020.
6307          */
6308         if (IS_IRONLAKE_M(dev_priv)) {
6309                 /* WaFbcAsynchFlipDisableFbcQueue:ilk */
6310                 I915_WRITE(ILK_DISPLAY_CHICKEN1,
6311                            I915_READ(ILK_DISPLAY_CHICKEN1) |
6312                            ILK_FBCQ_DIS);
6313                 I915_WRITE(ILK_DISPLAY_CHICKEN2,
6314                            I915_READ(ILK_DISPLAY_CHICKEN2) |
6315                            ILK_DPARB_GATE);
6316         }
6317
6318         I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
6319
6320         I915_WRITE(ILK_DISPLAY_CHICKEN2,
6321                    I915_READ(ILK_DISPLAY_CHICKEN2) |
6322                    ILK_ELPIN_409_SELECT);
6323         I915_WRITE(_3D_CHICKEN2,
6324                    _3D_CHICKEN2_WM_READ_PIPELINED << 16 |
6325                    _3D_CHICKEN2_WM_READ_PIPELINED);
6326
6327         /* WaDisableRenderCachePipelinedFlush:ilk */
6328         I915_WRITE(CACHE_MODE_0,
6329                    _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
6330
6331         /* WaDisable_RenderCache_OperationalFlush:ilk */
6332         I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6333
6334         g4x_disable_trickle_feed(dev_priv);
6335
6336         ibx_init_clock_gating(dev_priv);
6337 }
6338
6339 static void cpt_init_clock_gating(struct drm_i915_private *dev_priv)
6340 {
6341         enum pipe pipe;
6342         u32 val;
6343
6344         /*
6345          * On Ibex Peak and Cougar Point, we need to disable clock
6346          * gating for the panel power sequencer or it will fail to
6347          * start up when no ports are active.
6348          */
6349         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE |
6350                    PCH_DPLUNIT_CLOCK_GATE_DISABLE |
6351                    PCH_CPUNIT_CLOCK_GATE_DISABLE);
6352         I915_WRITE(SOUTH_CHICKEN2, I915_READ(SOUTH_CHICKEN2) |
6353                    DPLS_EDP_PPS_FIX_DIS);
6354         /* The below fixes the weird display corruption, a few pixels shifted
6355          * downward, on (only) LVDS of some HP laptops with IVY.
6356          */
6357         for_each_pipe(dev_priv, pipe) {
6358                 val = I915_READ(TRANS_CHICKEN2(pipe));
6359                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
6360                 val &= ~TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
6361                 if (dev_priv->vbt.fdi_rx_polarity_inverted)
6362                         val |= TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
6363                 val &= ~TRANS_CHICKEN2_FRAME_START_DELAY_MASK;
6364                 val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_COUNTER;
6365                 val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_MODESWITCH;
6366                 I915_WRITE(TRANS_CHICKEN2(pipe), val);
6367         }
6368         /* WADP0ClockGatingDisable */
6369         for_each_pipe(dev_priv, pipe) {
6370                 I915_WRITE(TRANS_CHICKEN1(pipe),
6371                            TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
6372         }
6373 }
6374
6375 static void gen6_check_mch_setup(struct drm_i915_private *dev_priv)
6376 {
6377         u32 tmp;
6378
6379         tmp = I915_READ(MCH_SSKPD);
6380         if ((tmp & MCH_SSKPD_WM0_MASK) != MCH_SSKPD_WM0_VAL)
6381                 DRM_DEBUG_KMS("Wrong MCH_SSKPD value: 0x%08x This can cause underruns.\n",
6382                               tmp);
6383 }
6384
6385 static void gen6_init_clock_gating(struct drm_i915_private *dev_priv)
6386 {
6387         u32 dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
6388
6389         I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
6390
6391         I915_WRITE(ILK_DISPLAY_CHICKEN2,
6392                    I915_READ(ILK_DISPLAY_CHICKEN2) |
6393                    ILK_ELPIN_409_SELECT);
6394
6395         /* WaDisableHiZPlanesWhenMSAAEnabled:snb */
6396         I915_WRITE(_3D_CHICKEN,
6397                    _MASKED_BIT_ENABLE(_3D_CHICKEN_HIZ_PLANE_DISABLE_MSAA_4X_SNB));
6398
6399         /* WaDisable_RenderCache_OperationalFlush:snb */
6400         I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6401
6402         /*
6403          * BSpec recoomends 8x4 when MSAA is used,
6404          * however in practice 16x4 seems fastest.
6405          *
6406          * Note that PS/WM thread counts depend on the WIZ hashing
6407          * disable bit, which we don't touch here, but it's good
6408          * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6409          */
6410         I915_WRITE(GEN6_GT_MODE,
6411                    _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6412
6413         I915_WRITE(CACHE_MODE_0,
6414                    _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
6415
6416         I915_WRITE(GEN6_UCGCTL1,
6417                    I915_READ(GEN6_UCGCTL1) |
6418                    GEN6_BLBUNIT_CLOCK_GATE_DISABLE |
6419                    GEN6_CSUNIT_CLOCK_GATE_DISABLE);
6420
6421         /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
6422          * gating disable must be set.  Failure to set it results in
6423          * flickering pixels due to Z write ordering failures after
6424          * some amount of runtime in the Mesa "fire" demo, and Unigine
6425          * Sanctuary and Tropics, and apparently anything else with
6426          * alpha test or pixel discard.
6427          *
6428          * According to the spec, bit 11 (RCCUNIT) must also be set,
6429          * but we didn't debug actual testcases to find it out.
6430          *
6431          * WaDisableRCCUnitClockGating:snb
6432          * WaDisableRCPBUnitClockGating:snb
6433          */
6434         I915_WRITE(GEN6_UCGCTL2,
6435                    GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
6436                    GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
6437
6438         /* WaStripsFansDisableFastClipPerformanceFix:snb */
6439         I915_WRITE(_3D_CHICKEN3,
6440                    _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_FASTCLIP_CULL));
6441
6442         /*
6443          * Bspec says:
6444          * "This bit must be set if 3DSTATE_CLIP clip mode is set to normal and
6445          * 3DSTATE_SF number of SF output attributes is more than 16."
6446          */
6447         I915_WRITE(_3D_CHICKEN3,
6448                    _MASKED_BIT_ENABLE(_3D_CHICKEN3_SF_DISABLE_PIPELINED_ATTR_FETCH));
6449
6450         /*
6451          * According to the spec the following bits should be
6452          * set in order to enable memory self-refresh and fbc:
6453          * The bit21 and bit22 of 0x42000
6454          * The bit21 and bit22 of 0x42004
6455          * The bit5 and bit7 of 0x42020
6456          * The bit14 of 0x70180
6457          * The bit14 of 0x71180
6458          *
6459          * WaFbcAsynchFlipDisableFbcQueue:snb
6460          */
6461         I915_WRITE(ILK_DISPLAY_CHICKEN1,
6462                    I915_READ(ILK_DISPLAY_CHICKEN1) |
6463                    ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
6464         I915_WRITE(ILK_DISPLAY_CHICKEN2,
6465                    I915_READ(ILK_DISPLAY_CHICKEN2) |
6466                    ILK_DPARB_GATE | ILK_VSDPFD_FULL);
6467         I915_WRITE(ILK_DSPCLK_GATE_D,
6468                    I915_READ(ILK_DSPCLK_GATE_D) |
6469                    ILK_DPARBUNIT_CLOCK_GATE_ENABLE  |
6470                    ILK_DPFDUNIT_CLOCK_GATE_ENABLE);
6471
6472         g4x_disable_trickle_feed(dev_priv);
6473
6474         cpt_init_clock_gating(dev_priv);
6475
6476         gen6_check_mch_setup(dev_priv);
6477 }
6478
6479 static void gen7_setup_fixed_func_scheduler(struct drm_i915_private *dev_priv)
6480 {
6481         u32 reg = I915_READ(GEN7_FF_THREAD_MODE);
6482
6483         /*
6484          * WaVSThreadDispatchOverride:ivb,vlv
6485          *
6486          * This actually overrides the dispatch
6487          * mode for all thread types.
6488          */
6489         reg &= ~GEN7_FF_SCHED_MASK;
6490         reg |= GEN7_FF_TS_SCHED_HW;
6491         reg |= GEN7_FF_VS_SCHED_HW;
6492         reg |= GEN7_FF_DS_SCHED_HW;
6493
6494         I915_WRITE(GEN7_FF_THREAD_MODE, reg);
6495 }
6496
6497 static void lpt_init_clock_gating(struct drm_i915_private *dev_priv)
6498 {
6499         /*
6500          * TODO: this bit should only be enabled when really needed, then
6501          * disabled when not needed anymore in order to save power.
6502          */
6503         if (HAS_PCH_LPT_LP(dev_priv))
6504                 I915_WRITE(SOUTH_DSPCLK_GATE_D,
6505                            I915_READ(SOUTH_DSPCLK_GATE_D) |
6506                            PCH_LP_PARTITION_LEVEL_DISABLE);
6507
6508         /* WADPOClockGatingDisable:hsw */
6509         I915_WRITE(TRANS_CHICKEN1(PIPE_A),
6510                    I915_READ(TRANS_CHICKEN1(PIPE_A)) |
6511                    TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
6512 }
6513
6514 static void lpt_suspend_hw(struct drm_i915_private *dev_priv)
6515 {
6516         if (HAS_PCH_LPT_LP(dev_priv)) {
6517                 u32 val = I915_READ(SOUTH_DSPCLK_GATE_D);
6518
6519                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
6520                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
6521         }
6522 }
6523
6524 static void gen8_set_l3sqc_credits(struct drm_i915_private *dev_priv,
6525                                    int general_prio_credits,
6526                                    int high_prio_credits)
6527 {
6528         u32 misccpctl;
6529         u32 val;
6530
6531         /* WaTempDisableDOPClkGating:bdw */
6532         misccpctl = I915_READ(GEN7_MISCCPCTL);
6533         I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
6534
6535         val = I915_READ(GEN8_L3SQCREG1);
6536         val &= ~L3_PRIO_CREDITS_MASK;
6537         val |= L3_GENERAL_PRIO_CREDITS(general_prio_credits);
6538         val |= L3_HIGH_PRIO_CREDITS(high_prio_credits);
6539         I915_WRITE(GEN8_L3SQCREG1, val);
6540
6541         /*
6542          * Wait at least 100 clocks before re-enabling clock gating.
6543          * See the definition of L3SQCREG1 in BSpec.
6544          */
6545         POSTING_READ(GEN8_L3SQCREG1);
6546         udelay(1);
6547         I915_WRITE(GEN7_MISCCPCTL, misccpctl);
6548 }
6549
6550 static void icl_init_clock_gating(struct drm_i915_private *dev_priv)
6551 {
6552         /* This is not an Wa. Enable to reduce Sampler power */
6553         I915_WRITE(GEN10_DFR_RATIO_EN_AND_CHICKEN,
6554                    I915_READ(GEN10_DFR_RATIO_EN_AND_CHICKEN) & ~DFR_DISABLE);
6555
6556         /* WaEnable32PlaneMode:icl */
6557         I915_WRITE(GEN9_CSFE_CHICKEN1_RCS,
6558                    _MASKED_BIT_ENABLE(GEN11_ENABLE_32_PLANE_MODE));
6559 }
6560
6561 static void tgl_init_clock_gating(struct drm_i915_private *dev_priv)
6562 {
6563         u32 vd_pg_enable = 0;
6564         unsigned int i;
6565
6566         /* This is not a WA. Enable VD HCP & MFX_ENC powergate */
6567         for (i = 0; i < I915_MAX_VCS; i++) {
6568                 if (HAS_ENGINE(dev_priv, _VCS(i)))
6569                         vd_pg_enable |= VDN_HCP_POWERGATE_ENABLE(i) |
6570                                         VDN_MFX_POWERGATE_ENABLE(i);
6571         }
6572
6573         I915_WRITE(POWERGATE_ENABLE,
6574                    I915_READ(POWERGATE_ENABLE) | vd_pg_enable);
6575 }
6576
6577 static void cnp_init_clock_gating(struct drm_i915_private *dev_priv)
6578 {
6579         if (!HAS_PCH_CNP(dev_priv))
6580                 return;
6581
6582         /* Display WA #1181 WaSouthDisplayDisablePWMCGEGating: cnp */
6583         I915_WRITE(SOUTH_DSPCLK_GATE_D, I915_READ(SOUTH_DSPCLK_GATE_D) |
6584                    CNP_PWM_CGE_GATING_DISABLE);
6585 }
6586
6587 static void cnl_init_clock_gating(struct drm_i915_private *dev_priv)
6588 {
6589         u32 val;
6590         cnp_init_clock_gating(dev_priv);
6591
6592         /* This is not an Wa. Enable for better image quality */
6593         I915_WRITE(_3D_CHICKEN3,
6594                    _MASKED_BIT_ENABLE(_3D_CHICKEN3_AA_LINE_QUALITY_FIX_ENABLE));
6595
6596         /* WaEnableChickenDCPR:cnl */
6597         I915_WRITE(GEN8_CHICKEN_DCPR_1,
6598                    I915_READ(GEN8_CHICKEN_DCPR_1) | MASK_WAKEMEM);
6599
6600         /* WaFbcWakeMemOn:cnl */
6601         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
6602                    DISP_FBC_MEMORY_WAKE);
6603
6604         val = I915_READ(SLICE_UNIT_LEVEL_CLKGATE);
6605         /* ReadHitWriteOnlyDisable:cnl */
6606         val |= RCCUNIT_CLKGATE_DIS;
6607         /* WaSarbUnitClockGatingDisable:cnl (pre-prod) */
6608         if (IS_CNL_REVID(dev_priv, CNL_REVID_A0, CNL_REVID_B0))
6609                 val |= SARBUNIT_CLKGATE_DIS;
6610         I915_WRITE(SLICE_UNIT_LEVEL_CLKGATE, val);
6611
6612         /* Wa_2201832410:cnl */
6613         val = I915_READ(SUBSLICE_UNIT_LEVEL_CLKGATE);
6614         val |= GWUNIT_CLKGATE_DIS;
6615         I915_WRITE(SUBSLICE_UNIT_LEVEL_CLKGATE, val);
6616
6617         /* WaDisableVFclkgate:cnl */
6618         /* WaVFUnitClockGatingDisable:cnl */
6619         val = I915_READ(UNSLICE_UNIT_LEVEL_CLKGATE);
6620         val |= VFUNIT_CLKGATE_DIS;
6621         I915_WRITE(UNSLICE_UNIT_LEVEL_CLKGATE, val);
6622 }
6623
6624 static void cfl_init_clock_gating(struct drm_i915_private *dev_priv)
6625 {
6626         cnp_init_clock_gating(dev_priv);
6627         gen9_init_clock_gating(dev_priv);
6628
6629         /* WaFbcNukeOnHostModify:cfl */
6630         I915_WRITE(ILK_DPFC_CHICKEN, I915_READ(ILK_DPFC_CHICKEN) |
6631                    ILK_DPFC_NUKE_ON_ANY_MODIFICATION);
6632 }
6633
6634 static void kbl_init_clock_gating(struct drm_i915_private *dev_priv)
6635 {
6636         gen9_init_clock_gating(dev_priv);
6637
6638         /* WaDisableSDEUnitClockGating:kbl */
6639         if (IS_KBL_REVID(dev_priv, 0, KBL_REVID_B0))
6640                 I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6641                            GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6642
6643         /* WaDisableGamClockGating:kbl */
6644         if (IS_KBL_REVID(dev_priv, 0, KBL_REVID_B0))
6645                 I915_WRITE(GEN6_UCGCTL1, I915_READ(GEN6_UCGCTL1) |
6646                            GEN6_GAMUNIT_CLOCK_GATE_DISABLE);
6647
6648         /* WaFbcNukeOnHostModify:kbl */
6649         I915_WRITE(ILK_DPFC_CHICKEN, I915_READ(ILK_DPFC_CHICKEN) |
6650                    ILK_DPFC_NUKE_ON_ANY_MODIFICATION);
6651 }
6652
6653 static void skl_init_clock_gating(struct drm_i915_private *dev_priv)
6654 {
6655         gen9_init_clock_gating(dev_priv);
6656
6657         /* WAC6entrylatency:skl */
6658         I915_WRITE(FBC_LLC_READ_CTRL, I915_READ(FBC_LLC_READ_CTRL) |
6659                    FBC_LLC_FULLY_OPEN);
6660
6661         /* WaFbcNukeOnHostModify:skl */
6662         I915_WRITE(ILK_DPFC_CHICKEN, I915_READ(ILK_DPFC_CHICKEN) |
6663                    ILK_DPFC_NUKE_ON_ANY_MODIFICATION);
6664 }
6665
6666 static void bdw_init_clock_gating(struct drm_i915_private *dev_priv)
6667 {
6668         enum pipe pipe;
6669
6670         /* WaSwitchSolVfFArbitrationPriority:bdw */
6671         I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6672
6673         /* WaPsrDPAMaskVBlankInSRD:bdw */
6674         I915_WRITE(CHICKEN_PAR1_1,
6675                    I915_READ(CHICKEN_PAR1_1) | DPA_MASK_VBLANK_SRD);
6676
6677         /* WaPsrDPRSUnmaskVBlankInSRD:bdw */
6678         for_each_pipe(dev_priv, pipe) {
6679                 I915_WRITE(CHICKEN_PIPESL_1(pipe),
6680                            I915_READ(CHICKEN_PIPESL_1(pipe)) |
6681                            BDW_DPRS_MASK_VBLANK_SRD);
6682         }
6683
6684         /* WaVSRefCountFullforceMissDisable:bdw */
6685         /* WaDSRefCountFullforceMissDisable:bdw */
6686         I915_WRITE(GEN7_FF_THREAD_MODE,
6687                    I915_READ(GEN7_FF_THREAD_MODE) &
6688                    ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6689
6690         I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6691                    _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6692
6693         /* WaDisableSDEUnitClockGating:bdw */
6694         I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6695                    GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6696
6697         /* WaProgramL3SqcReg1Default:bdw */
6698         gen8_set_l3sqc_credits(dev_priv, 30, 2);
6699
6700         /* WaKVMNotificationOnConfigChange:bdw */
6701         I915_WRITE(CHICKEN_PAR2_1, I915_READ(CHICKEN_PAR2_1)
6702                    | KVM_CONFIG_CHANGE_NOTIFICATION_SELECT);
6703
6704         lpt_init_clock_gating(dev_priv);
6705
6706         /* WaDisableDopClockGating:bdw
6707          *
6708          * Also see the CHICKEN2 write in bdw_init_workarounds() to disable DOP
6709          * clock gating.
6710          */
6711         I915_WRITE(GEN6_UCGCTL1,
6712                    I915_READ(GEN6_UCGCTL1) | GEN6_EU_TCUNIT_CLOCK_GATE_DISABLE);
6713 }
6714
6715 static void hsw_init_clock_gating(struct drm_i915_private *dev_priv)
6716 {
6717         /* L3 caching of data atomics doesn't work -- disable it. */
6718         I915_WRITE(HSW_SCRATCH1, HSW_SCRATCH1_L3_DATA_ATOMICS_DISABLE);
6719         I915_WRITE(HSW_ROW_CHICKEN3,
6720                    _MASKED_BIT_ENABLE(HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE));
6721
6722         /* This is required by WaCatErrorRejectionIssue:hsw */
6723         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6724                         I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6725                         GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6726
6727         /* WaVSRefCountFullforceMissDisable:hsw */
6728         I915_WRITE(GEN7_FF_THREAD_MODE,
6729                    I915_READ(GEN7_FF_THREAD_MODE) & ~GEN7_FF_VS_REF_CNT_FFME);
6730
6731         /* WaDisable_RenderCache_OperationalFlush:hsw */
6732         I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6733
6734         /* enable HiZ Raw Stall Optimization */
6735         I915_WRITE(CACHE_MODE_0_GEN7,
6736                    _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6737
6738         /* WaDisable4x2SubspanOptimization:hsw */
6739         I915_WRITE(CACHE_MODE_1,
6740                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6741
6742         /*
6743          * BSpec recommends 8x4 when MSAA is used,
6744          * however in practice 16x4 seems fastest.
6745          *
6746          * Note that PS/WM thread counts depend on the WIZ hashing
6747          * disable bit, which we don't touch here, but it's good
6748          * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6749          */
6750         I915_WRITE(GEN7_GT_MODE,
6751                    _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6752
6753         /* WaSampleCChickenBitEnable:hsw */
6754         I915_WRITE(HALF_SLICE_CHICKEN3,
6755                    _MASKED_BIT_ENABLE(HSW_SAMPLE_C_PERFORMANCE));
6756
6757         /* WaSwitchSolVfFArbitrationPriority:hsw */
6758         I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
6759
6760         lpt_init_clock_gating(dev_priv);
6761 }
6762
6763 static void ivb_init_clock_gating(struct drm_i915_private *dev_priv)
6764 {
6765         u32 snpcr;
6766
6767         I915_WRITE(ILK_DSPCLK_GATE_D, ILK_VRHUNIT_CLOCK_GATE_DISABLE);
6768
6769         /* WaDisableEarlyCull:ivb */
6770         I915_WRITE(_3D_CHICKEN3,
6771                    _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6772
6773         /* WaDisableBackToBackFlipFix:ivb */
6774         I915_WRITE(IVB_CHICKEN3,
6775                    CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6776                    CHICKEN3_DGMG_DONE_FIX_DISABLE);
6777
6778         /* WaDisablePSDDualDispatchEnable:ivb */
6779         if (IS_IVB_GT1(dev_priv))
6780                 I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6781                            _MASKED_BIT_ENABLE(GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6782
6783         /* WaDisable_RenderCache_OperationalFlush:ivb */
6784         I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6785
6786         /* Apply the WaDisableRHWOOptimizationForRenderHang:ivb workaround. */
6787         I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
6788                    GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
6789
6790         /* WaApplyL3ControlAndL3ChickenMode:ivb */
6791         I915_WRITE(GEN7_L3CNTLREG1,
6792                         GEN7_WA_FOR_GEN7_L3_CONTROL);
6793         I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
6794                    GEN7_WA_L3_CHICKEN_MODE);
6795         if (IS_IVB_GT1(dev_priv))
6796                 I915_WRITE(GEN7_ROW_CHICKEN2,
6797                            _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6798         else {
6799                 /* must write both registers */
6800                 I915_WRITE(GEN7_ROW_CHICKEN2,
6801                            _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6802                 I915_WRITE(GEN7_ROW_CHICKEN2_GT2,
6803                            _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6804         }
6805
6806         /* WaForceL3Serialization:ivb */
6807         I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6808                    ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6809
6810         /*
6811          * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6812          * This implements the WaDisableRCZUnitClockGating:ivb workaround.
6813          */
6814         I915_WRITE(GEN6_UCGCTL2,
6815                    GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6816
6817         /* This is required by WaCatErrorRejectionIssue:ivb */
6818         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6819                         I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6820                         GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6821
6822         g4x_disable_trickle_feed(dev_priv);
6823
6824         gen7_setup_fixed_func_scheduler(dev_priv);
6825
6826         if (0) { /* causes HiZ corruption on ivb:gt1 */
6827                 /* enable HiZ Raw Stall Optimization */
6828                 I915_WRITE(CACHE_MODE_0_GEN7,
6829                            _MASKED_BIT_DISABLE(HIZ_RAW_STALL_OPT_DISABLE));
6830         }
6831
6832         /* WaDisable4x2SubspanOptimization:ivb */
6833         I915_WRITE(CACHE_MODE_1,
6834                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6835
6836         /*
6837          * BSpec recommends 8x4 when MSAA is used,
6838          * however in practice 16x4 seems fastest.
6839          *
6840          * Note that PS/WM thread counts depend on the WIZ hashing
6841          * disable bit, which we don't touch here, but it's good
6842          * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6843          */
6844         I915_WRITE(GEN7_GT_MODE,
6845                    _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6846
6847         snpcr = I915_READ(GEN6_MBCUNIT_SNPCR);
6848         snpcr &= ~GEN6_MBC_SNPCR_MASK;
6849         snpcr |= GEN6_MBC_SNPCR_MED;
6850         I915_WRITE(GEN6_MBCUNIT_SNPCR, snpcr);
6851
6852         if (!HAS_PCH_NOP(dev_priv))
6853                 cpt_init_clock_gating(dev_priv);
6854
6855         gen6_check_mch_setup(dev_priv);
6856 }
6857
6858 static void vlv_init_clock_gating(struct drm_i915_private *dev_priv)
6859 {
6860         /* WaDisableEarlyCull:vlv */
6861         I915_WRITE(_3D_CHICKEN3,
6862                    _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
6863
6864         /* WaDisableBackToBackFlipFix:vlv */
6865         I915_WRITE(IVB_CHICKEN3,
6866                    CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
6867                    CHICKEN3_DGMG_DONE_FIX_DISABLE);
6868
6869         /* WaPsdDispatchEnable:vlv */
6870         /* WaDisablePSDDualDispatchEnable:vlv */
6871         I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
6872                    _MASKED_BIT_ENABLE(GEN7_MAX_PS_THREAD_DEP |
6873                                       GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
6874
6875         /* WaDisable_RenderCache_OperationalFlush:vlv */
6876         I915_WRITE(CACHE_MODE_0_GEN7, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6877
6878         /* WaForceL3Serialization:vlv */
6879         I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
6880                    ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
6881
6882         /* WaDisableDopClockGating:vlv */
6883         I915_WRITE(GEN7_ROW_CHICKEN2,
6884                    _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
6885
6886         /* This is required by WaCatErrorRejectionIssue:vlv */
6887         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
6888                    I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
6889                    GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
6890
6891         gen7_setup_fixed_func_scheduler(dev_priv);
6892
6893         /*
6894          * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
6895          * This implements the WaDisableRCZUnitClockGating:vlv workaround.
6896          */
6897         I915_WRITE(GEN6_UCGCTL2,
6898                    GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
6899
6900         /* WaDisableL3Bank2xClockGate:vlv
6901          * Disabling L3 clock gating- MMIO 940c[25] = 1
6902          * Set bit 25, to disable L3_BANK_2x_CLK_GATING */
6903         I915_WRITE(GEN7_UCGCTL4,
6904                    I915_READ(GEN7_UCGCTL4) | GEN7_L3BANK2X_CLOCK_GATE_DISABLE);
6905
6906         /*
6907          * BSpec says this must be set, even though
6908          * WaDisable4x2SubspanOptimization isn't listed for VLV.
6909          */
6910         I915_WRITE(CACHE_MODE_1,
6911                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
6912
6913         /*
6914          * BSpec recommends 8x4 when MSAA is used,
6915          * however in practice 16x4 seems fastest.
6916          *
6917          * Note that PS/WM thread counts depend on the WIZ hashing
6918          * disable bit, which we don't touch here, but it's good
6919          * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
6920          */
6921         I915_WRITE(GEN7_GT_MODE,
6922                    _MASKED_FIELD(GEN6_WIZ_HASHING_MASK, GEN6_WIZ_HASHING_16x4));
6923
6924         /*
6925          * WaIncreaseL3CreditsForVLVB0:vlv
6926          * This is the hardware default actually.
6927          */
6928         I915_WRITE(GEN7_L3SQCREG1, VLV_B0_WA_L3SQCREG1_VALUE);
6929
6930         /*
6931          * WaDisableVLVClockGating_VBIIssue:vlv
6932          * Disable clock gating on th GCFG unit to prevent a delay
6933          * in the reporting of vblank events.
6934          */
6935         I915_WRITE(VLV_GUNIT_CLOCK_GATE, GCFG_DIS);
6936 }
6937
6938 static void chv_init_clock_gating(struct drm_i915_private *dev_priv)
6939 {
6940         /* WaVSRefCountFullforceMissDisable:chv */
6941         /* WaDSRefCountFullforceMissDisable:chv */
6942         I915_WRITE(GEN7_FF_THREAD_MODE,
6943                    I915_READ(GEN7_FF_THREAD_MODE) &
6944                    ~(GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME));
6945
6946         /* WaDisableSemaphoreAndSyncFlipWait:chv */
6947         I915_WRITE(GEN6_RC_SLEEP_PSMI_CONTROL,
6948                    _MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
6949
6950         /* WaDisableCSUnitClockGating:chv */
6951         I915_WRITE(GEN6_UCGCTL1, I915_READ(GEN6_UCGCTL1) |
6952                    GEN6_CSUNIT_CLOCK_GATE_DISABLE);
6953
6954         /* WaDisableSDEUnitClockGating:chv */
6955         I915_WRITE(GEN8_UCGCTL6, I915_READ(GEN8_UCGCTL6) |
6956                    GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
6957
6958         /*
6959          * WaProgramL3SqcReg1Default:chv
6960          * See gfxspecs/Related Documents/Performance Guide/
6961          * LSQC Setting Recommendations.
6962          */
6963         gen8_set_l3sqc_credits(dev_priv, 38, 2);
6964 }
6965
6966 static void g4x_init_clock_gating(struct drm_i915_private *dev_priv)
6967 {
6968         u32 dspclk_gate;
6969
6970         I915_WRITE(RENCLK_GATE_D1, 0);
6971         I915_WRITE(RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
6972                    GS_UNIT_CLOCK_GATE_DISABLE |
6973                    CL_UNIT_CLOCK_GATE_DISABLE);
6974         I915_WRITE(RAMCLK_GATE_D, 0);
6975         dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
6976                 OVRUNIT_CLOCK_GATE_DISABLE |
6977                 OVCUNIT_CLOCK_GATE_DISABLE;
6978         if (IS_GM45(dev_priv))
6979                 dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
6980         I915_WRITE(DSPCLK_GATE_D, dspclk_gate);
6981
6982         /* WaDisableRenderCachePipelinedFlush */
6983         I915_WRITE(CACHE_MODE_0,
6984                    _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
6985
6986         /* WaDisable_RenderCache_OperationalFlush:g4x */
6987         I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
6988
6989         g4x_disable_trickle_feed(dev_priv);
6990 }
6991
6992 static void i965gm_init_clock_gating(struct drm_i915_private *dev_priv)
6993 {
6994         struct intel_uncore *uncore = &dev_priv->uncore;
6995
6996         intel_uncore_write(uncore, RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
6997         intel_uncore_write(uncore, RENCLK_GATE_D2, 0);
6998         intel_uncore_write(uncore, DSPCLK_GATE_D, 0);
6999         intel_uncore_write(uncore, RAMCLK_GATE_D, 0);
7000         intel_uncore_write16(uncore, DEUC, 0);
7001         intel_uncore_write(uncore,
7002                            MI_ARB_STATE,
7003                            _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
7004
7005         /* WaDisable_RenderCache_OperationalFlush:gen4 */
7006         intel_uncore_write(uncore,
7007                            CACHE_MODE_0,
7008                            _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
7009 }
7010
7011 static void i965g_init_clock_gating(struct drm_i915_private *dev_priv)
7012 {
7013         I915_WRITE(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
7014                    I965_RCC_CLOCK_GATE_DISABLE |
7015                    I965_RCPB_CLOCK_GATE_DISABLE |
7016                    I965_ISC_CLOCK_GATE_DISABLE |
7017                    I965_FBC_CLOCK_GATE_DISABLE);
7018         I915_WRITE(RENCLK_GATE_D2, 0);
7019         I915_WRITE(MI_ARB_STATE,
7020                    _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
7021
7022         /* WaDisable_RenderCache_OperationalFlush:gen4 */
7023         I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(RC_OP_FLUSH_ENABLE));
7024 }
7025
7026 static void gen3_init_clock_gating(struct drm_i915_private *dev_priv)
7027 {
7028         u32 dstate = I915_READ(D_STATE);
7029
7030         dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
7031                 DSTATE_DOT_CLOCK_GATING;
7032         I915_WRITE(D_STATE, dstate);
7033
7034         if (IS_PINEVIEW(dev_priv))
7035                 I915_WRITE(ECOSKPD, _MASKED_BIT_ENABLE(ECO_GATING_CX_ONLY));
7036
7037         /* IIR "flip pending" means done if this bit is set */
7038         I915_WRITE(ECOSKPD, _MASKED_BIT_DISABLE(ECO_FLIP_DONE));
7039
7040         /* interrupts should cause a wake up from C3 */
7041         I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_AGPBUSY_INT_EN));
7042
7043         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
7044         I915_WRITE(MI_ARB_STATE, _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
7045
7046         I915_WRITE(MI_ARB_STATE,
7047                    _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
7048 }
7049
7050 static void i85x_init_clock_gating(struct drm_i915_private *dev_priv)
7051 {
7052         I915_WRITE(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
7053
7054         /* interrupts should cause a wake up from C3 */
7055         I915_WRITE(MI_STATE, _MASKED_BIT_ENABLE(MI_AGPBUSY_INT_EN) |
7056                    _MASKED_BIT_DISABLE(MI_AGPBUSY_830_MODE));
7057
7058         I915_WRITE(MEM_MODE,
7059                    _MASKED_BIT_ENABLE(MEM_DISPLAY_TRICKLE_FEED_DISABLE));
7060 }
7061
7062 static void i830_init_clock_gating(struct drm_i915_private *dev_priv)
7063 {
7064         I915_WRITE(MEM_MODE,
7065                    _MASKED_BIT_ENABLE(MEM_DISPLAY_A_TRICKLE_FEED_DISABLE) |
7066                    _MASKED_BIT_ENABLE(MEM_DISPLAY_B_TRICKLE_FEED_DISABLE));
7067 }
7068
7069 void intel_init_clock_gating(struct drm_i915_private *dev_priv)
7070 {
7071         dev_priv->display.init_clock_gating(dev_priv);
7072 }
7073
7074 void intel_suspend_hw(struct drm_i915_private *dev_priv)
7075 {
7076         if (HAS_PCH_LPT(dev_priv))
7077                 lpt_suspend_hw(dev_priv);
7078 }
7079
7080 static void nop_init_clock_gating(struct drm_i915_private *dev_priv)
7081 {
7082         DRM_DEBUG_KMS("No clock gating settings or workarounds applied.\n");
7083 }
7084
7085 /**
7086  * intel_init_clock_gating_hooks - setup the clock gating hooks
7087  * @dev_priv: device private
7088  *
7089  * Setup the hooks that configure which clocks of a given platform can be
7090  * gated and also apply various GT and display specific workarounds for these
7091  * platforms. Note that some GT specific workarounds are applied separately
7092  * when GPU contexts or batchbuffers start their execution.
7093  */
7094 void intel_init_clock_gating_hooks(struct drm_i915_private *dev_priv)
7095 {
7096         if (IS_GEN(dev_priv, 12))
7097                 dev_priv->display.init_clock_gating = tgl_init_clock_gating;
7098         else if (IS_GEN(dev_priv, 11))
7099                 dev_priv->display.init_clock_gating = icl_init_clock_gating;
7100         else if (IS_CANNONLAKE(dev_priv))
7101                 dev_priv->display.init_clock_gating = cnl_init_clock_gating;
7102         else if (IS_COFFEELAKE(dev_priv))
7103                 dev_priv->display.init_clock_gating = cfl_init_clock_gating;
7104         else if (IS_SKYLAKE(dev_priv))
7105                 dev_priv->display.init_clock_gating = skl_init_clock_gating;
7106         else if (IS_KABYLAKE(dev_priv))
7107                 dev_priv->display.init_clock_gating = kbl_init_clock_gating;
7108         else if (IS_BROXTON(dev_priv))
7109                 dev_priv->display.init_clock_gating = bxt_init_clock_gating;
7110         else if (IS_GEMINILAKE(dev_priv))
7111                 dev_priv->display.init_clock_gating = glk_init_clock_gating;
7112         else if (IS_BROADWELL(dev_priv))
7113                 dev_priv->display.init_clock_gating = bdw_init_clock_gating;
7114         else if (IS_CHERRYVIEW(dev_priv))
7115                 dev_priv->display.init_clock_gating = chv_init_clock_gating;
7116         else if (IS_HASWELL(dev_priv))
7117                 dev_priv->display.init_clock_gating = hsw_init_clock_gating;
7118         else if (IS_IVYBRIDGE(dev_priv))
7119                 dev_priv->display.init_clock_gating = ivb_init_clock_gating;
7120         else if (IS_VALLEYVIEW(dev_priv))
7121                 dev_priv->display.init_clock_gating = vlv_init_clock_gating;
7122         else if (IS_GEN(dev_priv, 6))
7123                 dev_priv->display.init_clock_gating = gen6_init_clock_gating;
7124         else if (IS_GEN(dev_priv, 5))
7125                 dev_priv->display.init_clock_gating = ilk_init_clock_gating;
7126         else if (IS_G4X(dev_priv))
7127                 dev_priv->display.init_clock_gating = g4x_init_clock_gating;
7128         else if (IS_I965GM(dev_priv))
7129                 dev_priv->display.init_clock_gating = i965gm_init_clock_gating;
7130         else if (IS_I965G(dev_priv))
7131                 dev_priv->display.init_clock_gating = i965g_init_clock_gating;
7132         else if (IS_GEN(dev_priv, 3))
7133                 dev_priv->display.init_clock_gating = gen3_init_clock_gating;
7134         else if (IS_I85X(dev_priv) || IS_I865G(dev_priv))
7135                 dev_priv->display.init_clock_gating = i85x_init_clock_gating;
7136         else if (IS_GEN(dev_priv, 2))
7137                 dev_priv->display.init_clock_gating = i830_init_clock_gating;
7138         else {
7139                 MISSING_CASE(INTEL_DEVID(dev_priv));
7140                 dev_priv->display.init_clock_gating = nop_init_clock_gating;
7141         }
7142 }
7143
7144 /* Set up chip specific power management-related functions */
7145 void intel_init_pm(struct drm_i915_private *dev_priv)
7146 {
7147         /* For cxsr */
7148         if (IS_PINEVIEW(dev_priv))
7149                 i915_pineview_get_mem_freq(dev_priv);
7150         else if (IS_GEN(dev_priv, 5))
7151                 i915_ironlake_get_mem_freq(dev_priv);
7152
7153         if (intel_has_sagv(dev_priv))
7154                 skl_setup_sagv_block_time(dev_priv);
7155
7156         /* For FIFO watermark updates */
7157         if (INTEL_GEN(dev_priv) >= 9) {
7158                 skl_setup_wm_latency(dev_priv);
7159                 dev_priv->display.initial_watermarks = skl_initial_wm;
7160                 dev_priv->display.atomic_update_watermarks = skl_atomic_update_crtc_wm;
7161                 dev_priv->display.compute_global_watermarks = skl_compute_wm;
7162         } else if (HAS_PCH_SPLIT(dev_priv)) {
7163                 ilk_setup_wm_latency(dev_priv);
7164
7165                 if ((IS_GEN(dev_priv, 5) && dev_priv->wm.pri_latency[1] &&
7166                      dev_priv->wm.spr_latency[1] && dev_priv->wm.cur_latency[1]) ||
7167                     (!IS_GEN(dev_priv, 5) && dev_priv->wm.pri_latency[0] &&
7168                      dev_priv->wm.spr_latency[0] && dev_priv->wm.cur_latency[0])) {
7169                         dev_priv->display.compute_pipe_wm = ilk_compute_pipe_wm;
7170                         dev_priv->display.compute_intermediate_wm =
7171                                 ilk_compute_intermediate_wm;
7172                         dev_priv->display.initial_watermarks =
7173                                 ilk_initial_watermarks;
7174                         dev_priv->display.optimize_watermarks =
7175                                 ilk_optimize_watermarks;
7176                 } else {
7177                         DRM_DEBUG_KMS("Failed to read display plane latency. "
7178                                       "Disable CxSR\n");
7179                 }
7180         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
7181                 vlv_setup_wm_latency(dev_priv);
7182                 dev_priv->display.compute_pipe_wm = vlv_compute_pipe_wm;
7183                 dev_priv->display.compute_intermediate_wm = vlv_compute_intermediate_wm;
7184                 dev_priv->display.initial_watermarks = vlv_initial_watermarks;
7185                 dev_priv->display.optimize_watermarks = vlv_optimize_watermarks;
7186                 dev_priv->display.atomic_update_watermarks = vlv_atomic_update_fifo;
7187         } else if (IS_G4X(dev_priv)) {
7188                 g4x_setup_wm_latency(dev_priv);
7189                 dev_priv->display.compute_pipe_wm = g4x_compute_pipe_wm;
7190                 dev_priv->display.compute_intermediate_wm = g4x_compute_intermediate_wm;
7191                 dev_priv->display.initial_watermarks = g4x_initial_watermarks;
7192                 dev_priv->display.optimize_watermarks = g4x_optimize_watermarks;
7193         } else if (IS_PINEVIEW(dev_priv)) {
7194                 if (!intel_get_cxsr_latency(!IS_MOBILE(dev_priv),
7195                                             dev_priv->is_ddr3,
7196                                             dev_priv->fsb_freq,
7197                                             dev_priv->mem_freq)) {
7198                         DRM_INFO("failed to find known CxSR latency "
7199                                  "(found ddr%s fsb freq %d, mem freq %d), "
7200                                  "disabling CxSR\n",
7201                                  (dev_priv->is_ddr3 == 1) ? "3" : "2",
7202                                  dev_priv->fsb_freq, dev_priv->mem_freq);
7203                         /* Disable CxSR and never update its watermark again */
7204                         intel_set_memory_cxsr(dev_priv, false);
7205                         dev_priv->display.update_wm = NULL;
7206                 } else
7207                         dev_priv->display.update_wm = pineview_update_wm;
7208         } else if (IS_GEN(dev_priv, 4)) {
7209                 dev_priv->display.update_wm = i965_update_wm;
7210         } else if (IS_GEN(dev_priv, 3)) {
7211                 dev_priv->display.update_wm = i9xx_update_wm;
7212                 dev_priv->display.get_fifo_size = i9xx_get_fifo_size;
7213         } else if (IS_GEN(dev_priv, 2)) {
7214                 if (INTEL_NUM_PIPES(dev_priv) == 1) {
7215                         dev_priv->display.update_wm = i845_update_wm;
7216                         dev_priv->display.get_fifo_size = i845_get_fifo_size;
7217                 } else {
7218                         dev_priv->display.update_wm = i9xx_update_wm;
7219                         dev_priv->display.get_fifo_size = i830_get_fifo_size;
7220                 }
7221         } else {
7222                 DRM_ERROR("unexpected fall-through in intel_init_pm\n");
7223         }
7224 }
7225
7226 void intel_pm_setup(struct drm_i915_private *dev_priv)
7227 {
7228         dev_priv->runtime_pm.suspended = false;
7229         atomic_set(&dev_priv->runtime_pm.wakeref_count, 0);
7230 }
This page took 0.466282 seconds and 4 git commands to generate.