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