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