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