drm/i915: Refactor wm_lp to level calculation
[platform/adaptation/renesas_rcar/renesas_kernel.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 #include <drm/i915_powerwell.h>
34
35 /* FBC, or Frame Buffer Compression, is a technique employed to compress the
36  * framebuffer contents in-memory, aiming at reducing the required bandwidth
37  * during in-memory transfers and, therefore, reduce the power packet.
38  *
39  * The benefits of FBC are mostly visible with solid backgrounds and
40  * variation-less patterns.
41  *
42  * FBC-related functionality can be enabled by the means of the
43  * i915.i915_enable_fbc parameter
44  */
45
46 static void i8xx_disable_fbc(struct drm_device *dev)
47 {
48         struct drm_i915_private *dev_priv = dev->dev_private;
49         u32 fbc_ctl;
50
51         /* Disable compression */
52         fbc_ctl = I915_READ(FBC_CONTROL);
53         if ((fbc_ctl & FBC_CTL_EN) == 0)
54                 return;
55
56         fbc_ctl &= ~FBC_CTL_EN;
57         I915_WRITE(FBC_CONTROL, fbc_ctl);
58
59         /* Wait for compressing bit to clear */
60         if (wait_for((I915_READ(FBC_STATUS) & FBC_STAT_COMPRESSING) == 0, 10)) {
61                 DRM_DEBUG_KMS("FBC idle timed out\n");
62                 return;
63         }
64
65         DRM_DEBUG_KMS("disabled FBC\n");
66 }
67
68 static void i8xx_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
69 {
70         struct drm_device *dev = crtc->dev;
71         struct drm_i915_private *dev_priv = dev->dev_private;
72         struct drm_framebuffer *fb = crtc->fb;
73         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
74         struct drm_i915_gem_object *obj = intel_fb->obj;
75         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
76         int cfb_pitch;
77         int plane, i;
78         u32 fbc_ctl, fbc_ctl2;
79
80         cfb_pitch = dev_priv->fbc.size / FBC_LL_SIZE;
81         if (fb->pitches[0] < cfb_pitch)
82                 cfb_pitch = fb->pitches[0];
83
84         /* FBC_CTL wants 64B units */
85         cfb_pitch = (cfb_pitch / 64) - 1;
86         plane = intel_crtc->plane == 0 ? FBC_CTL_PLANEA : FBC_CTL_PLANEB;
87
88         /* Clear old tags */
89         for (i = 0; i < (FBC_LL_SIZE / 32) + 1; i++)
90                 I915_WRITE(FBC_TAG + (i * 4), 0);
91
92         /* Set it up... */
93         fbc_ctl2 = FBC_CTL_FENCE_DBL | FBC_CTL_IDLE_IMM | FBC_CTL_CPU_FENCE;
94         fbc_ctl2 |= plane;
95         I915_WRITE(FBC_CONTROL2, fbc_ctl2);
96         I915_WRITE(FBC_FENCE_OFF, crtc->y);
97
98         /* enable it... */
99         fbc_ctl = FBC_CTL_EN | FBC_CTL_PERIODIC;
100         if (IS_I945GM(dev))
101                 fbc_ctl |= FBC_CTL_C3_IDLE; /* 945 needs special SR handling */
102         fbc_ctl |= (cfb_pitch & 0xff) << FBC_CTL_STRIDE_SHIFT;
103         fbc_ctl |= (interval & 0x2fff) << FBC_CTL_INTERVAL_SHIFT;
104         fbc_ctl |= obj->fence_reg;
105         I915_WRITE(FBC_CONTROL, fbc_ctl);
106
107         DRM_DEBUG_KMS("enabled FBC, pitch %d, yoff %d, plane %c, ",
108                       cfb_pitch, crtc->y, plane_name(intel_crtc->plane));
109 }
110
111 static bool i8xx_fbc_enabled(struct drm_device *dev)
112 {
113         struct drm_i915_private *dev_priv = dev->dev_private;
114
115         return I915_READ(FBC_CONTROL) & FBC_CTL_EN;
116 }
117
118 static void g4x_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
119 {
120         struct drm_device *dev = crtc->dev;
121         struct drm_i915_private *dev_priv = dev->dev_private;
122         struct drm_framebuffer *fb = crtc->fb;
123         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
124         struct drm_i915_gem_object *obj = intel_fb->obj;
125         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
126         int plane = intel_crtc->plane == 0 ? DPFC_CTL_PLANEA : DPFC_CTL_PLANEB;
127         unsigned long stall_watermark = 200;
128         u32 dpfc_ctl;
129
130         dpfc_ctl = plane | DPFC_SR_EN | DPFC_CTL_LIMIT_1X;
131         dpfc_ctl |= DPFC_CTL_FENCE_EN | obj->fence_reg;
132         I915_WRITE(DPFC_CHICKEN, DPFC_HT_MODIFY);
133
134         I915_WRITE(DPFC_RECOMP_CTL, DPFC_RECOMP_STALL_EN |
135                    (stall_watermark << DPFC_RECOMP_STALL_WM_SHIFT) |
136                    (interval << DPFC_RECOMP_TIMER_COUNT_SHIFT));
137         I915_WRITE(DPFC_FENCE_YOFF, crtc->y);
138
139         /* enable it... */
140         I915_WRITE(DPFC_CONTROL, I915_READ(DPFC_CONTROL) | DPFC_CTL_EN);
141
142         DRM_DEBUG_KMS("enabled fbc on plane %c\n", plane_name(intel_crtc->plane));
143 }
144
145 static void g4x_disable_fbc(struct drm_device *dev)
146 {
147         struct drm_i915_private *dev_priv = dev->dev_private;
148         u32 dpfc_ctl;
149
150         /* Disable compression */
151         dpfc_ctl = I915_READ(DPFC_CONTROL);
152         if (dpfc_ctl & DPFC_CTL_EN) {
153                 dpfc_ctl &= ~DPFC_CTL_EN;
154                 I915_WRITE(DPFC_CONTROL, dpfc_ctl);
155
156                 DRM_DEBUG_KMS("disabled FBC\n");
157         }
158 }
159
160 static bool g4x_fbc_enabled(struct drm_device *dev)
161 {
162         struct drm_i915_private *dev_priv = dev->dev_private;
163
164         return I915_READ(DPFC_CONTROL) & DPFC_CTL_EN;
165 }
166
167 static void sandybridge_blit_fbc_update(struct drm_device *dev)
168 {
169         struct drm_i915_private *dev_priv = dev->dev_private;
170         u32 blt_ecoskpd;
171
172         /* Make sure blitter notifies FBC of writes */
173         gen6_gt_force_wake_get(dev_priv);
174         blt_ecoskpd = I915_READ(GEN6_BLITTER_ECOSKPD);
175         blt_ecoskpd |= GEN6_BLITTER_FBC_NOTIFY <<
176                 GEN6_BLITTER_LOCK_SHIFT;
177         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
178         blt_ecoskpd |= GEN6_BLITTER_FBC_NOTIFY;
179         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
180         blt_ecoskpd &= ~(GEN6_BLITTER_FBC_NOTIFY <<
181                          GEN6_BLITTER_LOCK_SHIFT);
182         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
183         POSTING_READ(GEN6_BLITTER_ECOSKPD);
184         gen6_gt_force_wake_put(dev_priv);
185 }
186
187 static void ironlake_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
188 {
189         struct drm_device *dev = crtc->dev;
190         struct drm_i915_private *dev_priv = dev->dev_private;
191         struct drm_framebuffer *fb = crtc->fb;
192         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
193         struct drm_i915_gem_object *obj = intel_fb->obj;
194         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
195         int plane = intel_crtc->plane == 0 ? DPFC_CTL_PLANEA : DPFC_CTL_PLANEB;
196         unsigned long stall_watermark = 200;
197         u32 dpfc_ctl;
198
199         dpfc_ctl = I915_READ(ILK_DPFC_CONTROL);
200         dpfc_ctl &= DPFC_RESERVED;
201         dpfc_ctl |= (plane | DPFC_CTL_LIMIT_1X);
202         /* Set persistent mode for front-buffer rendering, ala X. */
203         dpfc_ctl |= DPFC_CTL_PERSISTENT_MODE;
204         dpfc_ctl |= (DPFC_CTL_FENCE_EN | obj->fence_reg);
205         I915_WRITE(ILK_DPFC_CHICKEN, DPFC_HT_MODIFY);
206
207         I915_WRITE(ILK_DPFC_RECOMP_CTL, DPFC_RECOMP_STALL_EN |
208                    (stall_watermark << DPFC_RECOMP_STALL_WM_SHIFT) |
209                    (interval << DPFC_RECOMP_TIMER_COUNT_SHIFT));
210         I915_WRITE(ILK_DPFC_FENCE_YOFF, crtc->y);
211         I915_WRITE(ILK_FBC_RT_BASE, i915_gem_obj_ggtt_offset(obj) | ILK_FBC_RT_VALID);
212         /* enable it... */
213         I915_WRITE(ILK_DPFC_CONTROL, dpfc_ctl | DPFC_CTL_EN);
214
215         if (IS_GEN6(dev)) {
216                 I915_WRITE(SNB_DPFC_CTL_SA,
217                            SNB_CPU_FENCE_ENABLE | obj->fence_reg);
218                 I915_WRITE(DPFC_CPU_FENCE_OFFSET, crtc->y);
219                 sandybridge_blit_fbc_update(dev);
220         }
221
222         DRM_DEBUG_KMS("enabled fbc on plane %c\n", plane_name(intel_crtc->plane));
223 }
224
225 static void ironlake_disable_fbc(struct drm_device *dev)
226 {
227         struct drm_i915_private *dev_priv = dev->dev_private;
228         u32 dpfc_ctl;
229
230         /* Disable compression */
231         dpfc_ctl = I915_READ(ILK_DPFC_CONTROL);
232         if (dpfc_ctl & DPFC_CTL_EN) {
233                 dpfc_ctl &= ~DPFC_CTL_EN;
234                 I915_WRITE(ILK_DPFC_CONTROL, dpfc_ctl);
235
236                 if (IS_IVYBRIDGE(dev))
237                         /* WaFbcDisableDpfcClockGating:ivb */
238                         I915_WRITE(ILK_DSPCLK_GATE_D,
239                                    I915_READ(ILK_DSPCLK_GATE_D) &
240                                    ~ILK_DPFCUNIT_CLOCK_GATE_DISABLE);
241
242                 if (IS_HASWELL(dev))
243                         /* WaFbcDisableDpfcClockGating:hsw */
244                         I915_WRITE(HSW_CLKGATE_DISABLE_PART_1,
245                                    I915_READ(HSW_CLKGATE_DISABLE_PART_1) &
246                                    ~HSW_DPFC_GATING_DISABLE);
247
248                 DRM_DEBUG_KMS("disabled FBC\n");
249         }
250 }
251
252 static bool ironlake_fbc_enabled(struct drm_device *dev)
253 {
254         struct drm_i915_private *dev_priv = dev->dev_private;
255
256         return I915_READ(ILK_DPFC_CONTROL) & DPFC_CTL_EN;
257 }
258
259 static void gen7_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
260 {
261         struct drm_device *dev = crtc->dev;
262         struct drm_i915_private *dev_priv = dev->dev_private;
263         struct drm_framebuffer *fb = crtc->fb;
264         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
265         struct drm_i915_gem_object *obj = intel_fb->obj;
266         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
267
268         I915_WRITE(IVB_FBC_RT_BASE, i915_gem_obj_ggtt_offset(obj));
269
270         I915_WRITE(ILK_DPFC_CONTROL, DPFC_CTL_EN | DPFC_CTL_LIMIT_1X |
271                    IVB_DPFC_CTL_FENCE_EN |
272                    intel_crtc->plane << IVB_DPFC_CTL_PLANE_SHIFT);
273
274         if (IS_IVYBRIDGE(dev)) {
275                 /* WaFbcAsynchFlipDisableFbcQueue:ivb */
276                 I915_WRITE(ILK_DISPLAY_CHICKEN1, ILK_FBCQ_DIS);
277                 /* WaFbcDisableDpfcClockGating:ivb */
278                 I915_WRITE(ILK_DSPCLK_GATE_D,
279                            I915_READ(ILK_DSPCLK_GATE_D) |
280                            ILK_DPFCUNIT_CLOCK_GATE_DISABLE);
281         } else {
282                 /* WaFbcAsynchFlipDisableFbcQueue:hsw */
283                 I915_WRITE(HSW_PIPE_SLICE_CHICKEN_1(intel_crtc->pipe),
284                            HSW_BYPASS_FBC_QUEUE);
285                 /* WaFbcDisableDpfcClockGating:hsw */
286                 I915_WRITE(HSW_CLKGATE_DISABLE_PART_1,
287                            I915_READ(HSW_CLKGATE_DISABLE_PART_1) |
288                            HSW_DPFC_GATING_DISABLE);
289         }
290
291         I915_WRITE(SNB_DPFC_CTL_SA,
292                    SNB_CPU_FENCE_ENABLE | obj->fence_reg);
293         I915_WRITE(DPFC_CPU_FENCE_OFFSET, crtc->y);
294
295         sandybridge_blit_fbc_update(dev);
296
297         DRM_DEBUG_KMS("enabled fbc on plane %d\n", intel_crtc->plane);
298 }
299
300 bool intel_fbc_enabled(struct drm_device *dev)
301 {
302         struct drm_i915_private *dev_priv = dev->dev_private;
303
304         if (!dev_priv->display.fbc_enabled)
305                 return false;
306
307         return dev_priv->display.fbc_enabled(dev);
308 }
309
310 static void intel_fbc_work_fn(struct work_struct *__work)
311 {
312         struct intel_fbc_work *work =
313                 container_of(to_delayed_work(__work),
314                              struct intel_fbc_work, work);
315         struct drm_device *dev = work->crtc->dev;
316         struct drm_i915_private *dev_priv = dev->dev_private;
317
318         mutex_lock(&dev->struct_mutex);
319         if (work == dev_priv->fbc.fbc_work) {
320                 /* Double check that we haven't switched fb without cancelling
321                  * the prior work.
322                  */
323                 if (work->crtc->fb == work->fb) {
324                         dev_priv->display.enable_fbc(work->crtc,
325                                                      work->interval);
326
327                         dev_priv->fbc.plane = to_intel_crtc(work->crtc)->plane;
328                         dev_priv->fbc.fb_id = work->crtc->fb->base.id;
329                         dev_priv->fbc.y = work->crtc->y;
330                 }
331
332                 dev_priv->fbc.fbc_work = NULL;
333         }
334         mutex_unlock(&dev->struct_mutex);
335
336         kfree(work);
337 }
338
339 static void intel_cancel_fbc_work(struct drm_i915_private *dev_priv)
340 {
341         if (dev_priv->fbc.fbc_work == NULL)
342                 return;
343
344         DRM_DEBUG_KMS("cancelling pending FBC enable\n");
345
346         /* Synchronisation is provided by struct_mutex and checking of
347          * dev_priv->fbc.fbc_work, so we can perform the cancellation
348          * entirely asynchronously.
349          */
350         if (cancel_delayed_work(&dev_priv->fbc.fbc_work->work))
351                 /* tasklet was killed before being run, clean up */
352                 kfree(dev_priv->fbc.fbc_work);
353
354         /* Mark the work as no longer wanted so that if it does
355          * wake-up (because the work was already running and waiting
356          * for our mutex), it will discover that is no longer
357          * necessary to run.
358          */
359         dev_priv->fbc.fbc_work = NULL;
360 }
361
362 static void intel_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
363 {
364         struct intel_fbc_work *work;
365         struct drm_device *dev = crtc->dev;
366         struct drm_i915_private *dev_priv = dev->dev_private;
367
368         if (!dev_priv->display.enable_fbc)
369                 return;
370
371         intel_cancel_fbc_work(dev_priv);
372
373         work = kzalloc(sizeof(*work), GFP_KERNEL);
374         if (work == NULL) {
375                 DRM_ERROR("Failed to allocate FBC work structure\n");
376                 dev_priv->display.enable_fbc(crtc, interval);
377                 return;
378         }
379
380         work->crtc = crtc;
381         work->fb = crtc->fb;
382         work->interval = interval;
383         INIT_DELAYED_WORK(&work->work, intel_fbc_work_fn);
384
385         dev_priv->fbc.fbc_work = work;
386
387         /* Delay the actual enabling to let pageflipping cease and the
388          * display to settle before starting the compression. Note that
389          * this delay also serves a second purpose: it allows for a
390          * vblank to pass after disabling the FBC before we attempt
391          * to modify the control registers.
392          *
393          * A more complicated solution would involve tracking vblanks
394          * following the termination of the page-flipping sequence
395          * and indeed performing the enable as a co-routine and not
396          * waiting synchronously upon the vblank.
397          *
398          * WaFbcWaitForVBlankBeforeEnable:ilk,snb
399          */
400         schedule_delayed_work(&work->work, msecs_to_jiffies(50));
401 }
402
403 void intel_disable_fbc(struct drm_device *dev)
404 {
405         struct drm_i915_private *dev_priv = dev->dev_private;
406
407         intel_cancel_fbc_work(dev_priv);
408
409         if (!dev_priv->display.disable_fbc)
410                 return;
411
412         dev_priv->display.disable_fbc(dev);
413         dev_priv->fbc.plane = -1;
414 }
415
416 static bool set_no_fbc_reason(struct drm_i915_private *dev_priv,
417                               enum no_fbc_reason reason)
418 {
419         if (dev_priv->fbc.no_fbc_reason == reason)
420                 return false;
421
422         dev_priv->fbc.no_fbc_reason = reason;
423         return true;
424 }
425
426 /**
427  * intel_update_fbc - enable/disable FBC as needed
428  * @dev: the drm_device
429  *
430  * Set up the framebuffer compression hardware at mode set time.  We
431  * enable it if possible:
432  *   - plane A only (on pre-965)
433  *   - no pixel mulitply/line duplication
434  *   - no alpha buffer discard
435  *   - no dual wide
436  *   - framebuffer <= max_hdisplay in width, max_vdisplay in height
437  *
438  * We can't assume that any compression will take place (worst case),
439  * so the compressed buffer has to be the same size as the uncompressed
440  * one.  It also must reside (along with the line length buffer) in
441  * stolen memory.
442  *
443  * We need to enable/disable FBC on a global basis.
444  */
445 void intel_update_fbc(struct drm_device *dev)
446 {
447         struct drm_i915_private *dev_priv = dev->dev_private;
448         struct drm_crtc *crtc = NULL, *tmp_crtc;
449         struct intel_crtc *intel_crtc;
450         struct drm_framebuffer *fb;
451         struct intel_framebuffer *intel_fb;
452         struct drm_i915_gem_object *obj;
453         const struct drm_display_mode *adjusted_mode;
454         unsigned int max_width, max_height;
455
456         if (!I915_HAS_FBC(dev)) {
457                 set_no_fbc_reason(dev_priv, FBC_UNSUPPORTED);
458                 return;
459         }
460
461         if (!i915_powersave) {
462                 if (set_no_fbc_reason(dev_priv, FBC_MODULE_PARAM))
463                         DRM_DEBUG_KMS("fbc disabled per module param\n");
464                 return;
465         }
466
467         /*
468          * If FBC is already on, we just have to verify that we can
469          * keep it that way...
470          * Need to disable if:
471          *   - more than one pipe is active
472          *   - changing FBC params (stride, fence, mode)
473          *   - new fb is too large to fit in compressed buffer
474          *   - going to an unsupported config (interlace, pixel multiply, etc.)
475          */
476         list_for_each_entry(tmp_crtc, &dev->mode_config.crtc_list, head) {
477                 if (intel_crtc_active(tmp_crtc) &&
478                     to_intel_crtc(tmp_crtc)->primary_enabled) {
479                         if (crtc) {
480                                 if (set_no_fbc_reason(dev_priv, FBC_MULTIPLE_PIPES))
481                                         DRM_DEBUG_KMS("more than one pipe active, disabling compression\n");
482                                 goto out_disable;
483                         }
484                         crtc = tmp_crtc;
485                 }
486         }
487
488         if (!crtc || crtc->fb == NULL) {
489                 if (set_no_fbc_reason(dev_priv, FBC_NO_OUTPUT))
490                         DRM_DEBUG_KMS("no output, disabling\n");
491                 goto out_disable;
492         }
493
494         intel_crtc = to_intel_crtc(crtc);
495         fb = crtc->fb;
496         intel_fb = to_intel_framebuffer(fb);
497         obj = intel_fb->obj;
498         adjusted_mode = &intel_crtc->config.adjusted_mode;
499
500         if (i915_enable_fbc < 0 &&
501             INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev)) {
502                 if (set_no_fbc_reason(dev_priv, FBC_CHIP_DEFAULT))
503                         DRM_DEBUG_KMS("disabled per chip default\n");
504                 goto out_disable;
505         }
506         if (!i915_enable_fbc) {
507                 if (set_no_fbc_reason(dev_priv, FBC_MODULE_PARAM))
508                         DRM_DEBUG_KMS("fbc disabled per module param\n");
509                 goto out_disable;
510         }
511         if ((adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) ||
512             (adjusted_mode->flags & DRM_MODE_FLAG_DBLSCAN)) {
513                 if (set_no_fbc_reason(dev_priv, FBC_UNSUPPORTED_MODE))
514                         DRM_DEBUG_KMS("mode incompatible with compression, "
515                                       "disabling\n");
516                 goto out_disable;
517         }
518
519         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5) {
520                 max_width = 4096;
521                 max_height = 2048;
522         } else {
523                 max_width = 2048;
524                 max_height = 1536;
525         }
526         if (intel_crtc->config.pipe_src_w > max_width ||
527             intel_crtc->config.pipe_src_h > max_height) {
528                 if (set_no_fbc_reason(dev_priv, FBC_MODE_TOO_LARGE))
529                         DRM_DEBUG_KMS("mode too large for compression, disabling\n");
530                 goto out_disable;
531         }
532         if ((IS_I915GM(dev) || IS_I945GM(dev) || IS_HASWELL(dev)) &&
533             intel_crtc->plane != 0) {
534                 if (set_no_fbc_reason(dev_priv, FBC_BAD_PLANE))
535                         DRM_DEBUG_KMS("plane not 0, disabling compression\n");
536                 goto out_disable;
537         }
538
539         /* The use of a CPU fence is mandatory in order to detect writes
540          * by the CPU to the scanout and trigger updates to the FBC.
541          */
542         if (obj->tiling_mode != I915_TILING_X ||
543             obj->fence_reg == I915_FENCE_REG_NONE) {
544                 if (set_no_fbc_reason(dev_priv, FBC_NOT_TILED))
545                         DRM_DEBUG_KMS("framebuffer not tiled or fenced, disabling compression\n");
546                 goto out_disable;
547         }
548
549         /* If the kernel debugger is active, always disable compression */
550         if (in_dbg_master())
551                 goto out_disable;
552
553         if (i915_gem_stolen_setup_compression(dev, intel_fb->obj->base.size)) {
554                 if (set_no_fbc_reason(dev_priv, FBC_STOLEN_TOO_SMALL))
555                         DRM_DEBUG_KMS("framebuffer too large, disabling compression\n");
556                 goto out_disable;
557         }
558
559         /* If the scanout has not changed, don't modify the FBC settings.
560          * Note that we make the fundamental assumption that the fb->obj
561          * cannot be unpinned (and have its GTT offset and fence revoked)
562          * without first being decoupled from the scanout and FBC disabled.
563          */
564         if (dev_priv->fbc.plane == intel_crtc->plane &&
565             dev_priv->fbc.fb_id == fb->base.id &&
566             dev_priv->fbc.y == crtc->y)
567                 return;
568
569         if (intel_fbc_enabled(dev)) {
570                 /* We update FBC along two paths, after changing fb/crtc
571                  * configuration (modeswitching) and after page-flipping
572                  * finishes. For the latter, we know that not only did
573                  * we disable the FBC at the start of the page-flip
574                  * sequence, but also more than one vblank has passed.
575                  *
576                  * For the former case of modeswitching, it is possible
577                  * to switch between two FBC valid configurations
578                  * instantaneously so we do need to disable the FBC
579                  * before we can modify its control registers. We also
580                  * have to wait for the next vblank for that to take
581                  * effect. However, since we delay enabling FBC we can
582                  * assume that a vblank has passed since disabling and
583                  * that we can safely alter the registers in the deferred
584                  * callback.
585                  *
586                  * In the scenario that we go from a valid to invalid
587                  * and then back to valid FBC configuration we have
588                  * no strict enforcement that a vblank occurred since
589                  * disabling the FBC. However, along all current pipe
590                  * disabling paths we do need to wait for a vblank at
591                  * some point. And we wait before enabling FBC anyway.
592                  */
593                 DRM_DEBUG_KMS("disabling active FBC for update\n");
594                 intel_disable_fbc(dev);
595         }
596
597         intel_enable_fbc(crtc, 500);
598         dev_priv->fbc.no_fbc_reason = FBC_OK;
599         return;
600
601 out_disable:
602         /* Multiple disables should be harmless */
603         if (intel_fbc_enabled(dev)) {
604                 DRM_DEBUG_KMS("unsupported config, disabling FBC\n");
605                 intel_disable_fbc(dev);
606         }
607         i915_gem_stolen_cleanup_compression(dev);
608 }
609
610 static void i915_pineview_get_mem_freq(struct drm_device *dev)
611 {
612         drm_i915_private_t *dev_priv = dev->dev_private;
613         u32 tmp;
614
615         tmp = I915_READ(CLKCFG);
616
617         switch (tmp & CLKCFG_FSB_MASK) {
618         case CLKCFG_FSB_533:
619                 dev_priv->fsb_freq = 533; /* 133*4 */
620                 break;
621         case CLKCFG_FSB_800:
622                 dev_priv->fsb_freq = 800; /* 200*4 */
623                 break;
624         case CLKCFG_FSB_667:
625                 dev_priv->fsb_freq =  667; /* 167*4 */
626                 break;
627         case CLKCFG_FSB_400:
628                 dev_priv->fsb_freq = 400; /* 100*4 */
629                 break;
630         }
631
632         switch (tmp & CLKCFG_MEM_MASK) {
633         case CLKCFG_MEM_533:
634                 dev_priv->mem_freq = 533;
635                 break;
636         case CLKCFG_MEM_667:
637                 dev_priv->mem_freq = 667;
638                 break;
639         case CLKCFG_MEM_800:
640                 dev_priv->mem_freq = 800;
641                 break;
642         }
643
644         /* detect pineview DDR3 setting */
645         tmp = I915_READ(CSHRDDR3CTL);
646         dev_priv->is_ddr3 = (tmp & CSHRDDR3CTL_DDR3) ? 1 : 0;
647 }
648
649 static void i915_ironlake_get_mem_freq(struct drm_device *dev)
650 {
651         drm_i915_private_t *dev_priv = dev->dev_private;
652         u16 ddrpll, csipll;
653
654         ddrpll = I915_READ16(DDRMPLL1);
655         csipll = I915_READ16(CSIPLL0);
656
657         switch (ddrpll & 0xff) {
658         case 0xc:
659                 dev_priv->mem_freq = 800;
660                 break;
661         case 0x10:
662                 dev_priv->mem_freq = 1066;
663                 break;
664         case 0x14:
665                 dev_priv->mem_freq = 1333;
666                 break;
667         case 0x18:
668                 dev_priv->mem_freq = 1600;
669                 break;
670         default:
671                 DRM_DEBUG_DRIVER("unknown memory frequency 0x%02x\n",
672                                  ddrpll & 0xff);
673                 dev_priv->mem_freq = 0;
674                 break;
675         }
676
677         dev_priv->ips.r_t = dev_priv->mem_freq;
678
679         switch (csipll & 0x3ff) {
680         case 0x00c:
681                 dev_priv->fsb_freq = 3200;
682                 break;
683         case 0x00e:
684                 dev_priv->fsb_freq = 3733;
685                 break;
686         case 0x010:
687                 dev_priv->fsb_freq = 4266;
688                 break;
689         case 0x012:
690                 dev_priv->fsb_freq = 4800;
691                 break;
692         case 0x014:
693                 dev_priv->fsb_freq = 5333;
694                 break;
695         case 0x016:
696                 dev_priv->fsb_freq = 5866;
697                 break;
698         case 0x018:
699                 dev_priv->fsb_freq = 6400;
700                 break;
701         default:
702                 DRM_DEBUG_DRIVER("unknown fsb frequency 0x%04x\n",
703                                  csipll & 0x3ff);
704                 dev_priv->fsb_freq = 0;
705                 break;
706         }
707
708         if (dev_priv->fsb_freq == 3200) {
709                 dev_priv->ips.c_m = 0;
710         } else if (dev_priv->fsb_freq > 3200 && dev_priv->fsb_freq <= 4800) {
711                 dev_priv->ips.c_m = 1;
712         } else {
713                 dev_priv->ips.c_m = 2;
714         }
715 }
716
717 static const struct cxsr_latency cxsr_latency_table[] = {
718         {1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
719         {1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
720         {1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
721         {1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
722         {1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
723
724         {1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
725         {1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
726         {1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
727         {1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
728         {1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
729
730         {1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
731         {1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
732         {1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
733         {1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
734         {1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
735
736         {0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
737         {0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
738         {0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
739         {0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
740         {0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
741
742         {0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
743         {0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
744         {0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
745         {0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
746         {0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
747
748         {0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
749         {0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
750         {0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
751         {0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
752         {0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
753 };
754
755 static const struct cxsr_latency *intel_get_cxsr_latency(int is_desktop,
756                                                          int is_ddr3,
757                                                          int fsb,
758                                                          int mem)
759 {
760         const struct cxsr_latency *latency;
761         int i;
762
763         if (fsb == 0 || mem == 0)
764                 return NULL;
765
766         for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
767                 latency = &cxsr_latency_table[i];
768                 if (is_desktop == latency->is_desktop &&
769                     is_ddr3 == latency->is_ddr3 &&
770                     fsb == latency->fsb_freq && mem == latency->mem_freq)
771                         return latency;
772         }
773
774         DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
775
776         return NULL;
777 }
778
779 static void pineview_disable_cxsr(struct drm_device *dev)
780 {
781         struct drm_i915_private *dev_priv = dev->dev_private;
782
783         /* deactivate cxsr */
784         I915_WRITE(DSPFW3, I915_READ(DSPFW3) & ~PINEVIEW_SELF_REFRESH_EN);
785 }
786
787 /*
788  * Latency for FIFO fetches is dependent on several factors:
789  *   - memory configuration (speed, channels)
790  *   - chipset
791  *   - current MCH state
792  * It can be fairly high in some situations, so here we assume a fairly
793  * pessimal value.  It's a tradeoff between extra memory fetches (if we
794  * set this value too high, the FIFO will fetch frequently to stay full)
795  * and power consumption (set it too low to save power and we might see
796  * FIFO underruns and display "flicker").
797  *
798  * A value of 5us seems to be a good balance; safe for very low end
799  * platforms but not overly aggressive on lower latency configs.
800  */
801 static const int latency_ns = 5000;
802
803 static int i9xx_get_fifo_size(struct drm_device *dev, int plane)
804 {
805         struct drm_i915_private *dev_priv = dev->dev_private;
806         uint32_t dsparb = I915_READ(DSPARB);
807         int size;
808
809         size = dsparb & 0x7f;
810         if (plane)
811                 size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
812
813         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
814                       plane ? "B" : "A", size);
815
816         return size;
817 }
818
819 static int i85x_get_fifo_size(struct drm_device *dev, int plane)
820 {
821         struct drm_i915_private *dev_priv = dev->dev_private;
822         uint32_t dsparb = I915_READ(DSPARB);
823         int size;
824
825         size = dsparb & 0x1ff;
826         if (plane)
827                 size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
828         size >>= 1; /* Convert to cachelines */
829
830         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
831                       plane ? "B" : "A", size);
832
833         return size;
834 }
835
836 static int i845_get_fifo_size(struct drm_device *dev, int plane)
837 {
838         struct drm_i915_private *dev_priv = dev->dev_private;
839         uint32_t dsparb = I915_READ(DSPARB);
840         int size;
841
842         size = dsparb & 0x7f;
843         size >>= 2; /* Convert to cachelines */
844
845         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
846                       plane ? "B" : "A",
847                       size);
848
849         return size;
850 }
851
852 static int i830_get_fifo_size(struct drm_device *dev, int plane)
853 {
854         struct drm_i915_private *dev_priv = dev->dev_private;
855         uint32_t dsparb = I915_READ(DSPARB);
856         int size;
857
858         size = dsparb & 0x7f;
859         size >>= 1; /* Convert to cachelines */
860
861         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
862                       plane ? "B" : "A", size);
863
864         return size;
865 }
866
867 /* Pineview has different values for various configs */
868 static const struct intel_watermark_params pineview_display_wm = {
869         PINEVIEW_DISPLAY_FIFO,
870         PINEVIEW_MAX_WM,
871         PINEVIEW_DFT_WM,
872         PINEVIEW_GUARD_WM,
873         PINEVIEW_FIFO_LINE_SIZE
874 };
875 static const struct intel_watermark_params pineview_display_hplloff_wm = {
876         PINEVIEW_DISPLAY_FIFO,
877         PINEVIEW_MAX_WM,
878         PINEVIEW_DFT_HPLLOFF_WM,
879         PINEVIEW_GUARD_WM,
880         PINEVIEW_FIFO_LINE_SIZE
881 };
882 static const struct intel_watermark_params pineview_cursor_wm = {
883         PINEVIEW_CURSOR_FIFO,
884         PINEVIEW_CURSOR_MAX_WM,
885         PINEVIEW_CURSOR_DFT_WM,
886         PINEVIEW_CURSOR_GUARD_WM,
887         PINEVIEW_FIFO_LINE_SIZE,
888 };
889 static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
890         PINEVIEW_CURSOR_FIFO,
891         PINEVIEW_CURSOR_MAX_WM,
892         PINEVIEW_CURSOR_DFT_WM,
893         PINEVIEW_CURSOR_GUARD_WM,
894         PINEVIEW_FIFO_LINE_SIZE
895 };
896 static const struct intel_watermark_params g4x_wm_info = {
897         G4X_FIFO_SIZE,
898         G4X_MAX_WM,
899         G4X_MAX_WM,
900         2,
901         G4X_FIFO_LINE_SIZE,
902 };
903 static const struct intel_watermark_params g4x_cursor_wm_info = {
904         I965_CURSOR_FIFO,
905         I965_CURSOR_MAX_WM,
906         I965_CURSOR_DFT_WM,
907         2,
908         G4X_FIFO_LINE_SIZE,
909 };
910 static const struct intel_watermark_params valleyview_wm_info = {
911         VALLEYVIEW_FIFO_SIZE,
912         VALLEYVIEW_MAX_WM,
913         VALLEYVIEW_MAX_WM,
914         2,
915         G4X_FIFO_LINE_SIZE,
916 };
917 static const struct intel_watermark_params valleyview_cursor_wm_info = {
918         I965_CURSOR_FIFO,
919         VALLEYVIEW_CURSOR_MAX_WM,
920         I965_CURSOR_DFT_WM,
921         2,
922         G4X_FIFO_LINE_SIZE,
923 };
924 static const struct intel_watermark_params i965_cursor_wm_info = {
925         I965_CURSOR_FIFO,
926         I965_CURSOR_MAX_WM,
927         I965_CURSOR_DFT_WM,
928         2,
929         I915_FIFO_LINE_SIZE,
930 };
931 static const struct intel_watermark_params i945_wm_info = {
932         I945_FIFO_SIZE,
933         I915_MAX_WM,
934         1,
935         2,
936         I915_FIFO_LINE_SIZE
937 };
938 static const struct intel_watermark_params i915_wm_info = {
939         I915_FIFO_SIZE,
940         I915_MAX_WM,
941         1,
942         2,
943         I915_FIFO_LINE_SIZE
944 };
945 static const struct intel_watermark_params i855_wm_info = {
946         I855GM_FIFO_SIZE,
947         I915_MAX_WM,
948         1,
949         2,
950         I830_FIFO_LINE_SIZE
951 };
952 static const struct intel_watermark_params i830_wm_info = {
953         I830_FIFO_SIZE,
954         I915_MAX_WM,
955         1,
956         2,
957         I830_FIFO_LINE_SIZE
958 };
959
960 static const struct intel_watermark_params ironlake_display_wm_info = {
961         ILK_DISPLAY_FIFO,
962         ILK_DISPLAY_MAXWM,
963         ILK_DISPLAY_DFTWM,
964         2,
965         ILK_FIFO_LINE_SIZE
966 };
967 static const struct intel_watermark_params ironlake_cursor_wm_info = {
968         ILK_CURSOR_FIFO,
969         ILK_CURSOR_MAXWM,
970         ILK_CURSOR_DFTWM,
971         2,
972         ILK_FIFO_LINE_SIZE
973 };
974 static const struct intel_watermark_params ironlake_display_srwm_info = {
975         ILK_DISPLAY_SR_FIFO,
976         ILK_DISPLAY_MAX_SRWM,
977         ILK_DISPLAY_DFT_SRWM,
978         2,
979         ILK_FIFO_LINE_SIZE
980 };
981 static const struct intel_watermark_params ironlake_cursor_srwm_info = {
982         ILK_CURSOR_SR_FIFO,
983         ILK_CURSOR_MAX_SRWM,
984         ILK_CURSOR_DFT_SRWM,
985         2,
986         ILK_FIFO_LINE_SIZE
987 };
988
989 static const struct intel_watermark_params sandybridge_display_wm_info = {
990         SNB_DISPLAY_FIFO,
991         SNB_DISPLAY_MAXWM,
992         SNB_DISPLAY_DFTWM,
993         2,
994         SNB_FIFO_LINE_SIZE
995 };
996 static const struct intel_watermark_params sandybridge_cursor_wm_info = {
997         SNB_CURSOR_FIFO,
998         SNB_CURSOR_MAXWM,
999         SNB_CURSOR_DFTWM,
1000         2,
1001         SNB_FIFO_LINE_SIZE
1002 };
1003 static const struct intel_watermark_params sandybridge_display_srwm_info = {
1004         SNB_DISPLAY_SR_FIFO,
1005         SNB_DISPLAY_MAX_SRWM,
1006         SNB_DISPLAY_DFT_SRWM,
1007         2,
1008         SNB_FIFO_LINE_SIZE
1009 };
1010 static const struct intel_watermark_params sandybridge_cursor_srwm_info = {
1011         SNB_CURSOR_SR_FIFO,
1012         SNB_CURSOR_MAX_SRWM,
1013         SNB_CURSOR_DFT_SRWM,
1014         2,
1015         SNB_FIFO_LINE_SIZE
1016 };
1017
1018
1019 /**
1020  * intel_calculate_wm - calculate watermark level
1021  * @clock_in_khz: pixel clock
1022  * @wm: chip FIFO params
1023  * @pixel_size: display pixel size
1024  * @latency_ns: memory latency for the platform
1025  *
1026  * Calculate the watermark level (the level at which the display plane will
1027  * start fetching from memory again).  Each chip has a different display
1028  * FIFO size and allocation, so the caller needs to figure that out and pass
1029  * in the correct intel_watermark_params structure.
1030  *
1031  * As the pixel clock runs, the FIFO will be drained at a rate that depends
1032  * on the pixel size.  When it reaches the watermark level, it'll start
1033  * fetching FIFO line sized based chunks from memory until the FIFO fills
1034  * past the watermark point.  If the FIFO drains completely, a FIFO underrun
1035  * will occur, and a display engine hang could result.
1036  */
1037 static unsigned long intel_calculate_wm(unsigned long clock_in_khz,
1038                                         const struct intel_watermark_params *wm,
1039                                         int fifo_size,
1040                                         int pixel_size,
1041                                         unsigned long latency_ns)
1042 {
1043         long entries_required, wm_size;
1044
1045         /*
1046          * Note: we need to make sure we don't overflow for various clock &
1047          * latency values.
1048          * clocks go from a few thousand to several hundred thousand.
1049          * latency is usually a few thousand
1050          */
1051         entries_required = ((clock_in_khz / 1000) * pixel_size * latency_ns) /
1052                 1000;
1053         entries_required = DIV_ROUND_UP(entries_required, wm->cacheline_size);
1054
1055         DRM_DEBUG_KMS("FIFO entries required for mode: %ld\n", entries_required);
1056
1057         wm_size = fifo_size - (entries_required + wm->guard_size);
1058
1059         DRM_DEBUG_KMS("FIFO watermark level: %ld\n", wm_size);
1060
1061         /* Don't promote wm_size to unsigned... */
1062         if (wm_size > (long)wm->max_wm)
1063                 wm_size = wm->max_wm;
1064         if (wm_size <= 0)
1065                 wm_size = wm->default_wm;
1066         return wm_size;
1067 }
1068
1069 static struct drm_crtc *single_enabled_crtc(struct drm_device *dev)
1070 {
1071         struct drm_crtc *crtc, *enabled = NULL;
1072
1073         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
1074                 if (intel_crtc_active(crtc)) {
1075                         if (enabled)
1076                                 return NULL;
1077                         enabled = crtc;
1078                 }
1079         }
1080
1081         return enabled;
1082 }
1083
1084 static void pineview_update_wm(struct drm_crtc *unused_crtc)
1085 {
1086         struct drm_device *dev = unused_crtc->dev;
1087         struct drm_i915_private *dev_priv = dev->dev_private;
1088         struct drm_crtc *crtc;
1089         const struct cxsr_latency *latency;
1090         u32 reg;
1091         unsigned long wm;
1092
1093         latency = intel_get_cxsr_latency(IS_PINEVIEW_G(dev), dev_priv->is_ddr3,
1094                                          dev_priv->fsb_freq, dev_priv->mem_freq);
1095         if (!latency) {
1096                 DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
1097                 pineview_disable_cxsr(dev);
1098                 return;
1099         }
1100
1101         crtc = single_enabled_crtc(dev);
1102         if (crtc) {
1103                 const struct drm_display_mode *adjusted_mode;
1104                 int pixel_size = crtc->fb->bits_per_pixel / 8;
1105                 int clock;
1106
1107                 adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1108                 clock = adjusted_mode->crtc_clock;
1109
1110                 /* Display SR */
1111                 wm = intel_calculate_wm(clock, &pineview_display_wm,
1112                                         pineview_display_wm.fifo_size,
1113                                         pixel_size, latency->display_sr);
1114                 reg = I915_READ(DSPFW1);
1115                 reg &= ~DSPFW_SR_MASK;
1116                 reg |= wm << DSPFW_SR_SHIFT;
1117                 I915_WRITE(DSPFW1, reg);
1118                 DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
1119
1120                 /* cursor SR */
1121                 wm = intel_calculate_wm(clock, &pineview_cursor_wm,
1122                                         pineview_display_wm.fifo_size,
1123                                         pixel_size, latency->cursor_sr);
1124                 reg = I915_READ(DSPFW3);
1125                 reg &= ~DSPFW_CURSOR_SR_MASK;
1126                 reg |= (wm & 0x3f) << DSPFW_CURSOR_SR_SHIFT;
1127                 I915_WRITE(DSPFW3, reg);
1128
1129                 /* Display HPLL off SR */
1130                 wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
1131                                         pineview_display_hplloff_wm.fifo_size,
1132                                         pixel_size, latency->display_hpll_disable);
1133                 reg = I915_READ(DSPFW3);
1134                 reg &= ~DSPFW_HPLL_SR_MASK;
1135                 reg |= wm & DSPFW_HPLL_SR_MASK;
1136                 I915_WRITE(DSPFW3, reg);
1137
1138                 /* cursor HPLL off SR */
1139                 wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
1140                                         pineview_display_hplloff_wm.fifo_size,
1141                                         pixel_size, latency->cursor_hpll_disable);
1142                 reg = I915_READ(DSPFW3);
1143                 reg &= ~DSPFW_HPLL_CURSOR_MASK;
1144                 reg |= (wm & 0x3f) << DSPFW_HPLL_CURSOR_SHIFT;
1145                 I915_WRITE(DSPFW3, reg);
1146                 DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
1147
1148                 /* activate cxsr */
1149                 I915_WRITE(DSPFW3,
1150                            I915_READ(DSPFW3) | PINEVIEW_SELF_REFRESH_EN);
1151                 DRM_DEBUG_KMS("Self-refresh is enabled\n");
1152         } else {
1153                 pineview_disable_cxsr(dev);
1154                 DRM_DEBUG_KMS("Self-refresh is disabled\n");
1155         }
1156 }
1157
1158 static bool g4x_compute_wm0(struct drm_device *dev,
1159                             int plane,
1160                             const struct intel_watermark_params *display,
1161                             int display_latency_ns,
1162                             const struct intel_watermark_params *cursor,
1163                             int cursor_latency_ns,
1164                             int *plane_wm,
1165                             int *cursor_wm)
1166 {
1167         struct drm_crtc *crtc;
1168         const struct drm_display_mode *adjusted_mode;
1169         int htotal, hdisplay, clock, pixel_size;
1170         int line_time_us, line_count;
1171         int entries, tlb_miss;
1172
1173         crtc = intel_get_crtc_for_plane(dev, plane);
1174         if (!intel_crtc_active(crtc)) {
1175                 *cursor_wm = cursor->guard_size;
1176                 *plane_wm = display->guard_size;
1177                 return false;
1178         }
1179
1180         adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1181         clock = adjusted_mode->crtc_clock;
1182         htotal = adjusted_mode->htotal;
1183         hdisplay = to_intel_crtc(crtc)->config.pipe_src_w;
1184         pixel_size = crtc->fb->bits_per_pixel / 8;
1185
1186         /* Use the small buffer method to calculate plane watermark */
1187         entries = ((clock * pixel_size / 1000) * display_latency_ns) / 1000;
1188         tlb_miss = display->fifo_size*display->cacheline_size - hdisplay * 8;
1189         if (tlb_miss > 0)
1190                 entries += tlb_miss;
1191         entries = DIV_ROUND_UP(entries, display->cacheline_size);
1192         *plane_wm = entries + display->guard_size;
1193         if (*plane_wm > (int)display->max_wm)
1194                 *plane_wm = display->max_wm;
1195
1196         /* Use the large buffer method to calculate cursor watermark */
1197         line_time_us = ((htotal * 1000) / clock);
1198         line_count = (cursor_latency_ns / line_time_us + 1000) / 1000;
1199         entries = line_count * 64 * pixel_size;
1200         tlb_miss = cursor->fifo_size*cursor->cacheline_size - hdisplay * 8;
1201         if (tlb_miss > 0)
1202                 entries += tlb_miss;
1203         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
1204         *cursor_wm = entries + cursor->guard_size;
1205         if (*cursor_wm > (int)cursor->max_wm)
1206                 *cursor_wm = (int)cursor->max_wm;
1207
1208         return true;
1209 }
1210
1211 /*
1212  * Check the wm result.
1213  *
1214  * If any calculated watermark values is larger than the maximum value that
1215  * can be programmed into the associated watermark register, that watermark
1216  * must be disabled.
1217  */
1218 static bool g4x_check_srwm(struct drm_device *dev,
1219                            int display_wm, int cursor_wm,
1220                            const struct intel_watermark_params *display,
1221                            const struct intel_watermark_params *cursor)
1222 {
1223         DRM_DEBUG_KMS("SR watermark: display plane %d, cursor %d\n",
1224                       display_wm, cursor_wm);
1225
1226         if (display_wm > display->max_wm) {
1227                 DRM_DEBUG_KMS("display watermark is too large(%d/%ld), disabling\n",
1228                               display_wm, display->max_wm);
1229                 return false;
1230         }
1231
1232         if (cursor_wm > cursor->max_wm) {
1233                 DRM_DEBUG_KMS("cursor watermark is too large(%d/%ld), disabling\n",
1234                               cursor_wm, cursor->max_wm);
1235                 return false;
1236         }
1237
1238         if (!(display_wm || cursor_wm)) {
1239                 DRM_DEBUG_KMS("SR latency is 0, disabling\n");
1240                 return false;
1241         }
1242
1243         return true;
1244 }
1245
1246 static bool g4x_compute_srwm(struct drm_device *dev,
1247                              int plane,
1248                              int latency_ns,
1249                              const struct intel_watermark_params *display,
1250                              const struct intel_watermark_params *cursor,
1251                              int *display_wm, int *cursor_wm)
1252 {
1253         struct drm_crtc *crtc;
1254         const struct drm_display_mode *adjusted_mode;
1255         int hdisplay, htotal, pixel_size, clock;
1256         unsigned long line_time_us;
1257         int line_count, line_size;
1258         int small, large;
1259         int entries;
1260
1261         if (!latency_ns) {
1262                 *display_wm = *cursor_wm = 0;
1263                 return false;
1264         }
1265
1266         crtc = intel_get_crtc_for_plane(dev, plane);
1267         adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1268         clock = adjusted_mode->crtc_clock;
1269         htotal = adjusted_mode->htotal;
1270         hdisplay = to_intel_crtc(crtc)->config.pipe_src_w;
1271         pixel_size = crtc->fb->bits_per_pixel / 8;
1272
1273         line_time_us = (htotal * 1000) / clock;
1274         line_count = (latency_ns / line_time_us + 1000) / 1000;
1275         line_size = hdisplay * pixel_size;
1276
1277         /* Use the minimum of the small and large buffer method for primary */
1278         small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
1279         large = line_count * line_size;
1280
1281         entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
1282         *display_wm = entries + display->guard_size;
1283
1284         /* calculate the self-refresh watermark for display cursor */
1285         entries = line_count * pixel_size * 64;
1286         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
1287         *cursor_wm = entries + cursor->guard_size;
1288
1289         return g4x_check_srwm(dev,
1290                               *display_wm, *cursor_wm,
1291                               display, cursor);
1292 }
1293
1294 static bool vlv_compute_drain_latency(struct drm_device *dev,
1295                                      int plane,
1296                                      int *plane_prec_mult,
1297                                      int *plane_dl,
1298                                      int *cursor_prec_mult,
1299                                      int *cursor_dl)
1300 {
1301         struct drm_crtc *crtc;
1302         int clock, pixel_size;
1303         int entries;
1304
1305         crtc = intel_get_crtc_for_plane(dev, plane);
1306         if (!intel_crtc_active(crtc))
1307                 return false;
1308
1309         clock = to_intel_crtc(crtc)->config.adjusted_mode.crtc_clock;
1310         pixel_size = crtc->fb->bits_per_pixel / 8;      /* BPP */
1311
1312         entries = (clock / 1000) * pixel_size;
1313         *plane_prec_mult = (entries > 256) ?
1314                 DRAIN_LATENCY_PRECISION_32 : DRAIN_LATENCY_PRECISION_16;
1315         *plane_dl = (64 * (*plane_prec_mult) * 4) / ((clock / 1000) *
1316                                                      pixel_size);
1317
1318         entries = (clock / 1000) * 4;   /* BPP is always 4 for cursor */
1319         *cursor_prec_mult = (entries > 256) ?
1320                 DRAIN_LATENCY_PRECISION_32 : DRAIN_LATENCY_PRECISION_16;
1321         *cursor_dl = (64 * (*cursor_prec_mult) * 4) / ((clock / 1000) * 4);
1322
1323         return true;
1324 }
1325
1326 /*
1327  * Update drain latency registers of memory arbiter
1328  *
1329  * Valleyview SoC has a new memory arbiter and needs drain latency registers
1330  * to be programmed. Each plane has a drain latency multiplier and a drain
1331  * latency value.
1332  */
1333
1334 static void vlv_update_drain_latency(struct drm_device *dev)
1335 {
1336         struct drm_i915_private *dev_priv = dev->dev_private;
1337         int planea_prec, planea_dl, planeb_prec, planeb_dl;
1338         int cursora_prec, cursora_dl, cursorb_prec, cursorb_dl;
1339         int plane_prec_mult, cursor_prec_mult; /* Precision multiplier is
1340                                                         either 16 or 32 */
1341
1342         /* For plane A, Cursor A */
1343         if (vlv_compute_drain_latency(dev, 0, &plane_prec_mult, &planea_dl,
1344                                       &cursor_prec_mult, &cursora_dl)) {
1345                 cursora_prec = (cursor_prec_mult == DRAIN_LATENCY_PRECISION_32) ?
1346                         DDL_CURSORA_PRECISION_32 : DDL_CURSORA_PRECISION_16;
1347                 planea_prec = (plane_prec_mult == DRAIN_LATENCY_PRECISION_32) ?
1348                         DDL_PLANEA_PRECISION_32 : DDL_PLANEA_PRECISION_16;
1349
1350                 I915_WRITE(VLV_DDL1, cursora_prec |
1351                                 (cursora_dl << DDL_CURSORA_SHIFT) |
1352                                 planea_prec | planea_dl);
1353         }
1354
1355         /* For plane B, Cursor B */
1356         if (vlv_compute_drain_latency(dev, 1, &plane_prec_mult, &planeb_dl,
1357                                       &cursor_prec_mult, &cursorb_dl)) {
1358                 cursorb_prec = (cursor_prec_mult == DRAIN_LATENCY_PRECISION_32) ?
1359                         DDL_CURSORB_PRECISION_32 : DDL_CURSORB_PRECISION_16;
1360                 planeb_prec = (plane_prec_mult == DRAIN_LATENCY_PRECISION_32) ?
1361                         DDL_PLANEB_PRECISION_32 : DDL_PLANEB_PRECISION_16;
1362
1363                 I915_WRITE(VLV_DDL2, cursorb_prec |
1364                                 (cursorb_dl << DDL_CURSORB_SHIFT) |
1365                                 planeb_prec | planeb_dl);
1366         }
1367 }
1368
1369 #define single_plane_enabled(mask) is_power_of_2(mask)
1370
1371 static void valleyview_update_wm(struct drm_crtc *crtc)
1372 {
1373         struct drm_device *dev = crtc->dev;
1374         static const int sr_latency_ns = 12000;
1375         struct drm_i915_private *dev_priv = dev->dev_private;
1376         int planea_wm, planeb_wm, cursora_wm, cursorb_wm;
1377         int plane_sr, cursor_sr;
1378         int ignore_plane_sr, ignore_cursor_sr;
1379         unsigned int enabled = 0;
1380
1381         vlv_update_drain_latency(dev);
1382
1383         if (g4x_compute_wm0(dev, PIPE_A,
1384                             &valleyview_wm_info, latency_ns,
1385                             &valleyview_cursor_wm_info, latency_ns,
1386                             &planea_wm, &cursora_wm))
1387                 enabled |= 1 << PIPE_A;
1388
1389         if (g4x_compute_wm0(dev, PIPE_B,
1390                             &valleyview_wm_info, latency_ns,
1391                             &valleyview_cursor_wm_info, latency_ns,
1392                             &planeb_wm, &cursorb_wm))
1393                 enabled |= 1 << PIPE_B;
1394
1395         if (single_plane_enabled(enabled) &&
1396             g4x_compute_srwm(dev, ffs(enabled) - 1,
1397                              sr_latency_ns,
1398                              &valleyview_wm_info,
1399                              &valleyview_cursor_wm_info,
1400                              &plane_sr, &ignore_cursor_sr) &&
1401             g4x_compute_srwm(dev, ffs(enabled) - 1,
1402                              2*sr_latency_ns,
1403                              &valleyview_wm_info,
1404                              &valleyview_cursor_wm_info,
1405                              &ignore_plane_sr, &cursor_sr)) {
1406                 I915_WRITE(FW_BLC_SELF_VLV, FW_CSPWRDWNEN);
1407         } else {
1408                 I915_WRITE(FW_BLC_SELF_VLV,
1409                            I915_READ(FW_BLC_SELF_VLV) & ~FW_CSPWRDWNEN);
1410                 plane_sr = cursor_sr = 0;
1411         }
1412
1413         DRM_DEBUG_KMS("Setting FIFO watermarks - A: plane=%d, cursor=%d, B: plane=%d, cursor=%d, SR: plane=%d, cursor=%d\n",
1414                       planea_wm, cursora_wm,
1415                       planeb_wm, cursorb_wm,
1416                       plane_sr, cursor_sr);
1417
1418         I915_WRITE(DSPFW1,
1419                    (plane_sr << DSPFW_SR_SHIFT) |
1420                    (cursorb_wm << DSPFW_CURSORB_SHIFT) |
1421                    (planeb_wm << DSPFW_PLANEB_SHIFT) |
1422                    planea_wm);
1423         I915_WRITE(DSPFW2,
1424                    (I915_READ(DSPFW2) & ~DSPFW_CURSORA_MASK) |
1425                    (cursora_wm << DSPFW_CURSORA_SHIFT));
1426         I915_WRITE(DSPFW3,
1427                    (I915_READ(DSPFW3) & ~DSPFW_CURSOR_SR_MASK) |
1428                    (cursor_sr << DSPFW_CURSOR_SR_SHIFT));
1429 }
1430
1431 static void g4x_update_wm(struct drm_crtc *crtc)
1432 {
1433         struct drm_device *dev = crtc->dev;
1434         static const int sr_latency_ns = 12000;
1435         struct drm_i915_private *dev_priv = dev->dev_private;
1436         int planea_wm, planeb_wm, cursora_wm, cursorb_wm;
1437         int plane_sr, cursor_sr;
1438         unsigned int enabled = 0;
1439
1440         if (g4x_compute_wm0(dev, PIPE_A,
1441                             &g4x_wm_info, latency_ns,
1442                             &g4x_cursor_wm_info, latency_ns,
1443                             &planea_wm, &cursora_wm))
1444                 enabled |= 1 << PIPE_A;
1445
1446         if (g4x_compute_wm0(dev, PIPE_B,
1447                             &g4x_wm_info, latency_ns,
1448                             &g4x_cursor_wm_info, latency_ns,
1449                             &planeb_wm, &cursorb_wm))
1450                 enabled |= 1 << PIPE_B;
1451
1452         if (single_plane_enabled(enabled) &&
1453             g4x_compute_srwm(dev, ffs(enabled) - 1,
1454                              sr_latency_ns,
1455                              &g4x_wm_info,
1456                              &g4x_cursor_wm_info,
1457                              &plane_sr, &cursor_sr)) {
1458                 I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN);
1459         } else {
1460                 I915_WRITE(FW_BLC_SELF,
1461                            I915_READ(FW_BLC_SELF) & ~FW_BLC_SELF_EN);
1462                 plane_sr = cursor_sr = 0;
1463         }
1464
1465         DRM_DEBUG_KMS("Setting FIFO watermarks - A: plane=%d, cursor=%d, B: plane=%d, cursor=%d, SR: plane=%d, cursor=%d\n",
1466                       planea_wm, cursora_wm,
1467                       planeb_wm, cursorb_wm,
1468                       plane_sr, cursor_sr);
1469
1470         I915_WRITE(DSPFW1,
1471                    (plane_sr << DSPFW_SR_SHIFT) |
1472                    (cursorb_wm << DSPFW_CURSORB_SHIFT) |
1473                    (planeb_wm << DSPFW_PLANEB_SHIFT) |
1474                    planea_wm);
1475         I915_WRITE(DSPFW2,
1476                    (I915_READ(DSPFW2) & ~DSPFW_CURSORA_MASK) |
1477                    (cursora_wm << DSPFW_CURSORA_SHIFT));
1478         /* HPLL off in SR has some issues on G4x... disable it */
1479         I915_WRITE(DSPFW3,
1480                    (I915_READ(DSPFW3) & ~(DSPFW_HPLL_SR_EN | DSPFW_CURSOR_SR_MASK)) |
1481                    (cursor_sr << DSPFW_CURSOR_SR_SHIFT));
1482 }
1483
1484 static void i965_update_wm(struct drm_crtc *unused_crtc)
1485 {
1486         struct drm_device *dev = unused_crtc->dev;
1487         struct drm_i915_private *dev_priv = dev->dev_private;
1488         struct drm_crtc *crtc;
1489         int srwm = 1;
1490         int cursor_sr = 16;
1491
1492         /* Calc sr entries for one plane configs */
1493         crtc = single_enabled_crtc(dev);
1494         if (crtc) {
1495                 /* self-refresh has much higher latency */
1496                 static const int sr_latency_ns = 12000;
1497                 const struct drm_display_mode *adjusted_mode =
1498                         &to_intel_crtc(crtc)->config.adjusted_mode;
1499                 int clock = adjusted_mode->crtc_clock;
1500                 int htotal = adjusted_mode->htotal;
1501                 int hdisplay = to_intel_crtc(crtc)->config.pipe_src_w;
1502                 int pixel_size = crtc->fb->bits_per_pixel / 8;
1503                 unsigned long line_time_us;
1504                 int entries;
1505
1506                 line_time_us = ((htotal * 1000) / clock);
1507
1508                 /* Use ns/us then divide to preserve precision */
1509                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1510                         pixel_size * hdisplay;
1511                 entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
1512                 srwm = I965_FIFO_SIZE - entries;
1513                 if (srwm < 0)
1514                         srwm = 1;
1515                 srwm &= 0x1ff;
1516                 DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
1517                               entries, srwm);
1518
1519                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1520                         pixel_size * 64;
1521                 entries = DIV_ROUND_UP(entries,
1522                                           i965_cursor_wm_info.cacheline_size);
1523                 cursor_sr = i965_cursor_wm_info.fifo_size -
1524                         (entries + i965_cursor_wm_info.guard_size);
1525
1526                 if (cursor_sr > i965_cursor_wm_info.max_wm)
1527                         cursor_sr = i965_cursor_wm_info.max_wm;
1528
1529                 DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
1530                               "cursor %d\n", srwm, cursor_sr);
1531
1532                 if (IS_CRESTLINE(dev))
1533                         I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN);
1534         } else {
1535                 /* Turn off self refresh if both pipes are enabled */
1536                 if (IS_CRESTLINE(dev))
1537                         I915_WRITE(FW_BLC_SELF, I915_READ(FW_BLC_SELF)
1538                                    & ~FW_BLC_SELF_EN);
1539         }
1540
1541         DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
1542                       srwm);
1543
1544         /* 965 has limitations... */
1545         I915_WRITE(DSPFW1, (srwm << DSPFW_SR_SHIFT) |
1546                    (8 << 16) | (8 << 8) | (8 << 0));
1547         I915_WRITE(DSPFW2, (8 << 8) | (8 << 0));
1548         /* update cursor SR watermark */
1549         I915_WRITE(DSPFW3, (cursor_sr << DSPFW_CURSOR_SR_SHIFT));
1550 }
1551
1552 static void i9xx_update_wm(struct drm_crtc *unused_crtc)
1553 {
1554         struct drm_device *dev = unused_crtc->dev;
1555         struct drm_i915_private *dev_priv = dev->dev_private;
1556         const struct intel_watermark_params *wm_info;
1557         uint32_t fwater_lo;
1558         uint32_t fwater_hi;
1559         int cwm, srwm = 1;
1560         int fifo_size;
1561         int planea_wm, planeb_wm;
1562         struct drm_crtc *crtc, *enabled = NULL;
1563
1564         if (IS_I945GM(dev))
1565                 wm_info = &i945_wm_info;
1566         else if (!IS_GEN2(dev))
1567                 wm_info = &i915_wm_info;
1568         else
1569                 wm_info = &i855_wm_info;
1570
1571         fifo_size = dev_priv->display.get_fifo_size(dev, 0);
1572         crtc = intel_get_crtc_for_plane(dev, 0);
1573         if (intel_crtc_active(crtc)) {
1574                 const struct drm_display_mode *adjusted_mode;
1575                 int cpp = crtc->fb->bits_per_pixel / 8;
1576                 if (IS_GEN2(dev))
1577                         cpp = 4;
1578
1579                 adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1580                 planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1581                                                wm_info, fifo_size, cpp,
1582                                                latency_ns);
1583                 enabled = crtc;
1584         } else
1585                 planea_wm = fifo_size - wm_info->guard_size;
1586
1587         fifo_size = dev_priv->display.get_fifo_size(dev, 1);
1588         crtc = intel_get_crtc_for_plane(dev, 1);
1589         if (intel_crtc_active(crtc)) {
1590                 const struct drm_display_mode *adjusted_mode;
1591                 int cpp = crtc->fb->bits_per_pixel / 8;
1592                 if (IS_GEN2(dev))
1593                         cpp = 4;
1594
1595                 adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1596                 planeb_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1597                                                wm_info, fifo_size, cpp,
1598                                                latency_ns);
1599                 if (enabled == NULL)
1600                         enabled = crtc;
1601                 else
1602                         enabled = NULL;
1603         } else
1604                 planeb_wm = fifo_size - wm_info->guard_size;
1605
1606         DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
1607
1608         /*
1609          * Overlay gets an aggressive default since video jitter is bad.
1610          */
1611         cwm = 2;
1612
1613         /* Play safe and disable self-refresh before adjusting watermarks. */
1614         if (IS_I945G(dev) || IS_I945GM(dev))
1615                 I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN_MASK | 0);
1616         else if (IS_I915GM(dev))
1617                 I915_WRITE(INSTPM, I915_READ(INSTPM) & ~INSTPM_SELF_EN);
1618
1619         /* Calc sr entries for one plane configs */
1620         if (HAS_FW_BLC(dev) && enabled) {
1621                 /* self-refresh has much higher latency */
1622                 static const int sr_latency_ns = 6000;
1623                 const struct drm_display_mode *adjusted_mode =
1624                         &to_intel_crtc(enabled)->config.adjusted_mode;
1625                 int clock = adjusted_mode->crtc_clock;
1626                 int htotal = adjusted_mode->htotal;
1627                 int hdisplay = to_intel_crtc(crtc)->config.pipe_src_w;
1628                 int pixel_size = enabled->fb->bits_per_pixel / 8;
1629                 unsigned long line_time_us;
1630                 int entries;
1631
1632                 line_time_us = (htotal * 1000) / clock;
1633
1634                 /* Use ns/us then divide to preserve precision */
1635                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
1636                         pixel_size * hdisplay;
1637                 entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
1638                 DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
1639                 srwm = wm_info->fifo_size - entries;
1640                 if (srwm < 0)
1641                         srwm = 1;
1642
1643                 if (IS_I945G(dev) || IS_I945GM(dev))
1644                         I915_WRITE(FW_BLC_SELF,
1645                                    FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
1646                 else if (IS_I915GM(dev))
1647                         I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
1648         }
1649
1650         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
1651                       planea_wm, planeb_wm, cwm, srwm);
1652
1653         fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
1654         fwater_hi = (cwm & 0x1f);
1655
1656         /* Set request length to 8 cachelines per fetch */
1657         fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
1658         fwater_hi = fwater_hi | (1 << 8);
1659
1660         I915_WRITE(FW_BLC, fwater_lo);
1661         I915_WRITE(FW_BLC2, fwater_hi);
1662
1663         if (HAS_FW_BLC(dev)) {
1664                 if (enabled) {
1665                         if (IS_I945G(dev) || IS_I945GM(dev))
1666                                 I915_WRITE(FW_BLC_SELF,
1667                                            FW_BLC_SELF_EN_MASK | FW_BLC_SELF_EN);
1668                         else if (IS_I915GM(dev))
1669                                 I915_WRITE(INSTPM, I915_READ(INSTPM) | INSTPM_SELF_EN);
1670                         DRM_DEBUG_KMS("memory self refresh enabled\n");
1671                 } else
1672                         DRM_DEBUG_KMS("memory self refresh disabled\n");
1673         }
1674 }
1675
1676 static void i830_update_wm(struct drm_crtc *unused_crtc)
1677 {
1678         struct drm_device *dev = unused_crtc->dev;
1679         struct drm_i915_private *dev_priv = dev->dev_private;
1680         struct drm_crtc *crtc;
1681         const struct drm_display_mode *adjusted_mode;
1682         uint32_t fwater_lo;
1683         int planea_wm;
1684
1685         crtc = single_enabled_crtc(dev);
1686         if (crtc == NULL)
1687                 return;
1688
1689         adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1690         planea_wm = intel_calculate_wm(adjusted_mode->crtc_clock,
1691                                        &i830_wm_info,
1692                                        dev_priv->display.get_fifo_size(dev, 0),
1693                                        4, latency_ns);
1694         fwater_lo = I915_READ(FW_BLC) & ~0xfff;
1695         fwater_lo |= (3<<8) | planea_wm;
1696
1697         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
1698
1699         I915_WRITE(FW_BLC, fwater_lo);
1700 }
1701
1702 /*
1703  * Check the wm result.
1704  *
1705  * If any calculated watermark values is larger than the maximum value that
1706  * can be programmed into the associated watermark register, that watermark
1707  * must be disabled.
1708  */
1709 static bool ironlake_check_srwm(struct drm_device *dev, int level,
1710                                 int fbc_wm, int display_wm, int cursor_wm,
1711                                 const struct intel_watermark_params *display,
1712                                 const struct intel_watermark_params *cursor)
1713 {
1714         struct drm_i915_private *dev_priv = dev->dev_private;
1715
1716         DRM_DEBUG_KMS("watermark %d: display plane %d, fbc lines %d,"
1717                       " cursor %d\n", level, display_wm, fbc_wm, cursor_wm);
1718
1719         if (fbc_wm > SNB_FBC_MAX_SRWM) {
1720                 DRM_DEBUG_KMS("fbc watermark(%d) is too large(%d), disabling wm%d+\n",
1721                               fbc_wm, SNB_FBC_MAX_SRWM, level);
1722
1723                 /* fbc has it's own way to disable FBC WM */
1724                 I915_WRITE(DISP_ARB_CTL,
1725                            I915_READ(DISP_ARB_CTL) | DISP_FBC_WM_DIS);
1726                 return false;
1727         } else if (INTEL_INFO(dev)->gen >= 6) {
1728                 /* enable FBC WM (except on ILK, where it must remain off) */
1729                 I915_WRITE(DISP_ARB_CTL,
1730                            I915_READ(DISP_ARB_CTL) & ~DISP_FBC_WM_DIS);
1731         }
1732
1733         if (display_wm > display->max_wm) {
1734                 DRM_DEBUG_KMS("display watermark(%d) is too large(%d), disabling wm%d+\n",
1735                               display_wm, SNB_DISPLAY_MAX_SRWM, level);
1736                 return false;
1737         }
1738
1739         if (cursor_wm > cursor->max_wm) {
1740                 DRM_DEBUG_KMS("cursor watermark(%d) is too large(%d), disabling wm%d+\n",
1741                               cursor_wm, SNB_CURSOR_MAX_SRWM, level);
1742                 return false;
1743         }
1744
1745         if (!(fbc_wm || display_wm || cursor_wm)) {
1746                 DRM_DEBUG_KMS("latency %d is 0, disabling wm%d+\n", level, level);
1747                 return false;
1748         }
1749
1750         return true;
1751 }
1752
1753 /*
1754  * Compute watermark values of WM[1-3],
1755  */
1756 static bool ironlake_compute_srwm(struct drm_device *dev, int level, int plane,
1757                                   int latency_ns,
1758                                   const struct intel_watermark_params *display,
1759                                   const struct intel_watermark_params *cursor,
1760                                   int *fbc_wm, int *display_wm, int *cursor_wm)
1761 {
1762         struct drm_crtc *crtc;
1763         const struct drm_display_mode *adjusted_mode;
1764         unsigned long line_time_us;
1765         int hdisplay, htotal, pixel_size, clock;
1766         int line_count, line_size;
1767         int small, large;
1768         int entries;
1769
1770         if (!latency_ns) {
1771                 *fbc_wm = *display_wm = *cursor_wm = 0;
1772                 return false;
1773         }
1774
1775         crtc = intel_get_crtc_for_plane(dev, plane);
1776         adjusted_mode = &to_intel_crtc(crtc)->config.adjusted_mode;
1777         clock = adjusted_mode->crtc_clock;
1778         htotal = adjusted_mode->htotal;
1779         hdisplay = to_intel_crtc(crtc)->config.pipe_src_w;
1780         pixel_size = crtc->fb->bits_per_pixel / 8;
1781
1782         line_time_us = (htotal * 1000) / clock;
1783         line_count = (latency_ns / line_time_us + 1000) / 1000;
1784         line_size = hdisplay * pixel_size;
1785
1786         /* Use the minimum of the small and large buffer method for primary */
1787         small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
1788         large = line_count * line_size;
1789
1790         entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
1791         *display_wm = entries + display->guard_size;
1792
1793         /*
1794          * Spec says:
1795          * FBC WM = ((Final Primary WM * 64) / number of bytes per line) + 2
1796          */
1797         *fbc_wm = DIV_ROUND_UP(*display_wm * 64, line_size) + 2;
1798
1799         /* calculate the self-refresh watermark for display cursor */
1800         entries = line_count * pixel_size * 64;
1801         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
1802         *cursor_wm = entries + cursor->guard_size;
1803
1804         return ironlake_check_srwm(dev, level,
1805                                    *fbc_wm, *display_wm, *cursor_wm,
1806                                    display, cursor);
1807 }
1808
1809 static void ironlake_update_wm(struct drm_crtc *crtc)
1810 {
1811         struct drm_device *dev = crtc->dev;
1812         struct drm_i915_private *dev_priv = dev->dev_private;
1813         int fbc_wm, plane_wm, cursor_wm;
1814         unsigned int enabled;
1815
1816         enabled = 0;
1817         if (g4x_compute_wm0(dev, PIPE_A,
1818                             &ironlake_display_wm_info,
1819                             dev_priv->wm.pri_latency[0] * 100,
1820                             &ironlake_cursor_wm_info,
1821                             dev_priv->wm.cur_latency[0] * 100,
1822                             &plane_wm, &cursor_wm)) {
1823                 I915_WRITE(WM0_PIPEA_ILK,
1824                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
1825                 DRM_DEBUG_KMS("FIFO watermarks For pipe A -"
1826                               " plane %d, " "cursor: %d\n",
1827                               plane_wm, cursor_wm);
1828                 enabled |= 1 << PIPE_A;
1829         }
1830
1831         if (g4x_compute_wm0(dev, PIPE_B,
1832                             &ironlake_display_wm_info,
1833                             dev_priv->wm.pri_latency[0] * 100,
1834                             &ironlake_cursor_wm_info,
1835                             dev_priv->wm.cur_latency[0] * 100,
1836                             &plane_wm, &cursor_wm)) {
1837                 I915_WRITE(WM0_PIPEB_ILK,
1838                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
1839                 DRM_DEBUG_KMS("FIFO watermarks For pipe B -"
1840                               " plane %d, cursor: %d\n",
1841                               plane_wm, cursor_wm);
1842                 enabled |= 1 << PIPE_B;
1843         }
1844
1845         /*
1846          * Calculate and update the self-refresh watermark only when one
1847          * display plane is used.
1848          */
1849         I915_WRITE(WM3_LP_ILK, 0);
1850         I915_WRITE(WM2_LP_ILK, 0);
1851         I915_WRITE(WM1_LP_ILK, 0);
1852
1853         if (!single_plane_enabled(enabled))
1854                 return;
1855         enabled = ffs(enabled) - 1;
1856
1857         /* WM1 */
1858         if (!ironlake_compute_srwm(dev, 1, enabled,
1859                                    dev_priv->wm.pri_latency[1] * 500,
1860                                    &ironlake_display_srwm_info,
1861                                    &ironlake_cursor_srwm_info,
1862                                    &fbc_wm, &plane_wm, &cursor_wm))
1863                 return;
1864
1865         I915_WRITE(WM1_LP_ILK,
1866                    WM1_LP_SR_EN |
1867                    (dev_priv->wm.pri_latency[1] << WM1_LP_LATENCY_SHIFT) |
1868                    (fbc_wm << WM1_LP_FBC_SHIFT) |
1869                    (plane_wm << WM1_LP_SR_SHIFT) |
1870                    cursor_wm);
1871
1872         /* WM2 */
1873         if (!ironlake_compute_srwm(dev, 2, enabled,
1874                                    dev_priv->wm.pri_latency[2] * 500,
1875                                    &ironlake_display_srwm_info,
1876                                    &ironlake_cursor_srwm_info,
1877                                    &fbc_wm, &plane_wm, &cursor_wm))
1878                 return;
1879
1880         I915_WRITE(WM2_LP_ILK,
1881                    WM2_LP_EN |
1882                    (dev_priv->wm.pri_latency[2] << WM1_LP_LATENCY_SHIFT) |
1883                    (fbc_wm << WM1_LP_FBC_SHIFT) |
1884                    (plane_wm << WM1_LP_SR_SHIFT) |
1885                    cursor_wm);
1886
1887         /*
1888          * WM3 is unsupported on ILK, probably because we don't have latency
1889          * data for that power state
1890          */
1891 }
1892
1893 static void sandybridge_update_wm(struct drm_crtc *crtc)
1894 {
1895         struct drm_device *dev = crtc->dev;
1896         struct drm_i915_private *dev_priv = dev->dev_private;
1897         int latency = dev_priv->wm.pri_latency[0] * 100;        /* In unit 0.1us */
1898         u32 val;
1899         int fbc_wm, plane_wm, cursor_wm;
1900         unsigned int enabled;
1901
1902         enabled = 0;
1903         if (g4x_compute_wm0(dev, PIPE_A,
1904                             &sandybridge_display_wm_info, latency,
1905                             &sandybridge_cursor_wm_info, latency,
1906                             &plane_wm, &cursor_wm)) {
1907                 val = I915_READ(WM0_PIPEA_ILK);
1908                 val &= ~(WM0_PIPE_PLANE_MASK | WM0_PIPE_CURSOR_MASK);
1909                 I915_WRITE(WM0_PIPEA_ILK, val |
1910                            ((plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm));
1911                 DRM_DEBUG_KMS("FIFO watermarks For pipe A -"
1912                               " plane %d, " "cursor: %d\n",
1913                               plane_wm, cursor_wm);
1914                 enabled |= 1 << PIPE_A;
1915         }
1916
1917         if (g4x_compute_wm0(dev, PIPE_B,
1918                             &sandybridge_display_wm_info, latency,
1919                             &sandybridge_cursor_wm_info, latency,
1920                             &plane_wm, &cursor_wm)) {
1921                 val = I915_READ(WM0_PIPEB_ILK);
1922                 val &= ~(WM0_PIPE_PLANE_MASK | WM0_PIPE_CURSOR_MASK);
1923                 I915_WRITE(WM0_PIPEB_ILK, val |
1924                            ((plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm));
1925                 DRM_DEBUG_KMS("FIFO watermarks For pipe B -"
1926                               " plane %d, cursor: %d\n",
1927                               plane_wm, cursor_wm);
1928                 enabled |= 1 << PIPE_B;
1929         }
1930
1931         /*
1932          * Calculate and update the self-refresh watermark only when one
1933          * display plane is used.
1934          *
1935          * SNB support 3 levels of watermark.
1936          *
1937          * WM1/WM2/WM2 watermarks have to be enabled in the ascending order,
1938          * and disabled in the descending order
1939          *
1940          */
1941         I915_WRITE(WM3_LP_ILK, 0);
1942         I915_WRITE(WM2_LP_ILK, 0);
1943         I915_WRITE(WM1_LP_ILK, 0);
1944
1945         if (!single_plane_enabled(enabled) ||
1946             dev_priv->sprite_scaling_enabled)
1947                 return;
1948         enabled = ffs(enabled) - 1;
1949
1950         /* WM1 */
1951         if (!ironlake_compute_srwm(dev, 1, enabled,
1952                                    dev_priv->wm.pri_latency[1] * 500,
1953                                    &sandybridge_display_srwm_info,
1954                                    &sandybridge_cursor_srwm_info,
1955                                    &fbc_wm, &plane_wm, &cursor_wm))
1956                 return;
1957
1958         I915_WRITE(WM1_LP_ILK,
1959                    WM1_LP_SR_EN |
1960                    (dev_priv->wm.pri_latency[1] << WM1_LP_LATENCY_SHIFT) |
1961                    (fbc_wm << WM1_LP_FBC_SHIFT) |
1962                    (plane_wm << WM1_LP_SR_SHIFT) |
1963                    cursor_wm);
1964
1965         /* WM2 */
1966         if (!ironlake_compute_srwm(dev, 2, enabled,
1967                                    dev_priv->wm.pri_latency[2] * 500,
1968                                    &sandybridge_display_srwm_info,
1969                                    &sandybridge_cursor_srwm_info,
1970                                    &fbc_wm, &plane_wm, &cursor_wm))
1971                 return;
1972
1973         I915_WRITE(WM2_LP_ILK,
1974                    WM2_LP_EN |
1975                    (dev_priv->wm.pri_latency[2] << WM1_LP_LATENCY_SHIFT) |
1976                    (fbc_wm << WM1_LP_FBC_SHIFT) |
1977                    (plane_wm << WM1_LP_SR_SHIFT) |
1978                    cursor_wm);
1979
1980         /* WM3 */
1981         if (!ironlake_compute_srwm(dev, 3, enabled,
1982                                    dev_priv->wm.pri_latency[3] * 500,
1983                                    &sandybridge_display_srwm_info,
1984                                    &sandybridge_cursor_srwm_info,
1985                                    &fbc_wm, &plane_wm, &cursor_wm))
1986                 return;
1987
1988         I915_WRITE(WM3_LP_ILK,
1989                    WM3_LP_EN |
1990                    (dev_priv->wm.pri_latency[3] << WM1_LP_LATENCY_SHIFT) |
1991                    (fbc_wm << WM1_LP_FBC_SHIFT) |
1992                    (plane_wm << WM1_LP_SR_SHIFT) |
1993                    cursor_wm);
1994 }
1995
1996 static void ivybridge_update_wm(struct drm_crtc *crtc)
1997 {
1998         struct drm_device *dev = crtc->dev;
1999         struct drm_i915_private *dev_priv = dev->dev_private;
2000         int latency = dev_priv->wm.pri_latency[0] * 100;        /* In unit 0.1us */
2001         u32 val;
2002         int fbc_wm, plane_wm, cursor_wm;
2003         int ignore_fbc_wm, ignore_plane_wm, ignore_cursor_wm;
2004         unsigned int enabled;
2005
2006         enabled = 0;
2007         if (g4x_compute_wm0(dev, PIPE_A,
2008                             &sandybridge_display_wm_info, latency,
2009                             &sandybridge_cursor_wm_info, latency,
2010                             &plane_wm, &cursor_wm)) {
2011                 val = I915_READ(WM0_PIPEA_ILK);
2012                 val &= ~(WM0_PIPE_PLANE_MASK | WM0_PIPE_CURSOR_MASK);
2013                 I915_WRITE(WM0_PIPEA_ILK, val |
2014                            ((plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm));
2015                 DRM_DEBUG_KMS("FIFO watermarks For pipe A -"
2016                               " plane %d, " "cursor: %d\n",
2017                               plane_wm, cursor_wm);
2018                 enabled |= 1 << PIPE_A;
2019         }
2020
2021         if (g4x_compute_wm0(dev, PIPE_B,
2022                             &sandybridge_display_wm_info, latency,
2023                             &sandybridge_cursor_wm_info, latency,
2024                             &plane_wm, &cursor_wm)) {
2025                 val = I915_READ(WM0_PIPEB_ILK);
2026                 val &= ~(WM0_PIPE_PLANE_MASK | WM0_PIPE_CURSOR_MASK);
2027                 I915_WRITE(WM0_PIPEB_ILK, val |
2028                            ((plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm));
2029                 DRM_DEBUG_KMS("FIFO watermarks For pipe B -"
2030                               " plane %d, cursor: %d\n",
2031                               plane_wm, cursor_wm);
2032                 enabled |= 1 << PIPE_B;
2033         }
2034
2035         if (g4x_compute_wm0(dev, PIPE_C,
2036                             &sandybridge_display_wm_info, latency,
2037                             &sandybridge_cursor_wm_info, latency,
2038                             &plane_wm, &cursor_wm)) {
2039                 val = I915_READ(WM0_PIPEC_IVB);
2040                 val &= ~(WM0_PIPE_PLANE_MASK | WM0_PIPE_CURSOR_MASK);
2041                 I915_WRITE(WM0_PIPEC_IVB, val |
2042                            ((plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm));
2043                 DRM_DEBUG_KMS("FIFO watermarks For pipe C -"
2044                               " plane %d, cursor: %d\n",
2045                               plane_wm, cursor_wm);
2046                 enabled |= 1 << PIPE_C;
2047         }
2048
2049         /*
2050          * Calculate and update the self-refresh watermark only when one
2051          * display plane is used.
2052          *
2053          * SNB support 3 levels of watermark.
2054          *
2055          * WM1/WM2/WM2 watermarks have to be enabled in the ascending order,
2056          * and disabled in the descending order
2057          *
2058          */
2059         I915_WRITE(WM3_LP_ILK, 0);
2060         I915_WRITE(WM2_LP_ILK, 0);
2061         I915_WRITE(WM1_LP_ILK, 0);
2062
2063         if (!single_plane_enabled(enabled) ||
2064             dev_priv->sprite_scaling_enabled)
2065                 return;
2066         enabled = ffs(enabled) - 1;
2067
2068         /* WM1 */
2069         if (!ironlake_compute_srwm(dev, 1, enabled,
2070                                    dev_priv->wm.pri_latency[1] * 500,
2071                                    &sandybridge_display_srwm_info,
2072                                    &sandybridge_cursor_srwm_info,
2073                                    &fbc_wm, &plane_wm, &cursor_wm))
2074                 return;
2075
2076         I915_WRITE(WM1_LP_ILK,
2077                    WM1_LP_SR_EN |
2078                    (dev_priv->wm.pri_latency[1] << WM1_LP_LATENCY_SHIFT) |
2079                    (fbc_wm << WM1_LP_FBC_SHIFT) |
2080                    (plane_wm << WM1_LP_SR_SHIFT) |
2081                    cursor_wm);
2082
2083         /* WM2 */
2084         if (!ironlake_compute_srwm(dev, 2, enabled,
2085                                    dev_priv->wm.pri_latency[2] * 500,
2086                                    &sandybridge_display_srwm_info,
2087                                    &sandybridge_cursor_srwm_info,
2088                                    &fbc_wm, &plane_wm, &cursor_wm))
2089                 return;
2090
2091         I915_WRITE(WM2_LP_ILK,
2092                    WM2_LP_EN |
2093                    (dev_priv->wm.pri_latency[2] << WM1_LP_LATENCY_SHIFT) |
2094                    (fbc_wm << WM1_LP_FBC_SHIFT) |
2095                    (plane_wm << WM1_LP_SR_SHIFT) |
2096                    cursor_wm);
2097
2098         /* WM3, note we have to correct the cursor latency */
2099         if (!ironlake_compute_srwm(dev, 3, enabled,
2100                                    dev_priv->wm.pri_latency[3] * 500,
2101                                    &sandybridge_display_srwm_info,
2102                                    &sandybridge_cursor_srwm_info,
2103                                    &fbc_wm, &plane_wm, &ignore_cursor_wm) ||
2104             !ironlake_compute_srwm(dev, 3, enabled,
2105                                    dev_priv->wm.cur_latency[3] * 500,
2106                                    &sandybridge_display_srwm_info,
2107                                    &sandybridge_cursor_srwm_info,
2108                                    &ignore_fbc_wm, &ignore_plane_wm, &cursor_wm))
2109                 return;
2110
2111         I915_WRITE(WM3_LP_ILK,
2112                    WM3_LP_EN |
2113                    (dev_priv->wm.pri_latency[3] << WM1_LP_LATENCY_SHIFT) |
2114                    (fbc_wm << WM1_LP_FBC_SHIFT) |
2115                    (plane_wm << WM1_LP_SR_SHIFT) |
2116                    cursor_wm);
2117 }
2118
2119 static uint32_t ilk_pipe_pixel_rate(struct drm_device *dev,
2120                                     struct drm_crtc *crtc)
2121 {
2122         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2123         uint32_t pixel_rate;
2124
2125         pixel_rate = intel_crtc->config.adjusted_mode.crtc_clock;
2126
2127         /* We only use IF-ID interlacing. If we ever use PF-ID we'll need to
2128          * adjust the pixel_rate here. */
2129
2130         if (intel_crtc->config.pch_pfit.enabled) {
2131                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
2132                 uint32_t pfit_size = intel_crtc->config.pch_pfit.size;
2133
2134                 pipe_w = intel_crtc->config.pipe_src_w;
2135                 pipe_h = intel_crtc->config.pipe_src_h;
2136                 pfit_w = (pfit_size >> 16) & 0xFFFF;
2137                 pfit_h = pfit_size & 0xFFFF;
2138                 if (pipe_w < pfit_w)
2139                         pipe_w = pfit_w;
2140                 if (pipe_h < pfit_h)
2141                         pipe_h = pfit_h;
2142
2143                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
2144                                      pfit_w * pfit_h);
2145         }
2146
2147         return pixel_rate;
2148 }
2149
2150 /* latency must be in 0.1us units. */
2151 static uint32_t ilk_wm_method1(uint32_t pixel_rate, uint8_t bytes_per_pixel,
2152                                uint32_t latency)
2153 {
2154         uint64_t ret;
2155
2156         if (WARN(latency == 0, "Latency value missing\n"))
2157                 return UINT_MAX;
2158
2159         ret = (uint64_t) pixel_rate * bytes_per_pixel * latency;
2160         ret = DIV_ROUND_UP_ULL(ret, 64 * 10000) + 2;
2161
2162         return ret;
2163 }
2164
2165 /* latency must be in 0.1us units. */
2166 static uint32_t ilk_wm_method2(uint32_t pixel_rate, uint32_t pipe_htotal,
2167                                uint32_t horiz_pixels, uint8_t bytes_per_pixel,
2168                                uint32_t latency)
2169 {
2170         uint32_t ret;
2171
2172         if (WARN(latency == 0, "Latency value missing\n"))
2173                 return UINT_MAX;
2174
2175         ret = (latency * pixel_rate) / (pipe_htotal * 10000);
2176         ret = (ret + 1) * horiz_pixels * bytes_per_pixel;
2177         ret = DIV_ROUND_UP(ret, 64) + 2;
2178         return ret;
2179 }
2180
2181 static uint32_t ilk_wm_fbc(uint32_t pri_val, uint32_t horiz_pixels,
2182                            uint8_t bytes_per_pixel)
2183 {
2184         return DIV_ROUND_UP(pri_val * 64, horiz_pixels * bytes_per_pixel) + 2;
2185 }
2186
2187 struct hsw_pipe_wm_parameters {
2188         bool active;
2189         uint32_t pipe_htotal;
2190         uint32_t pixel_rate;
2191         struct intel_plane_wm_parameters pri;
2192         struct intel_plane_wm_parameters spr;
2193         struct intel_plane_wm_parameters cur;
2194 };
2195
2196 struct hsw_wm_maximums {
2197         uint16_t pri;
2198         uint16_t spr;
2199         uint16_t cur;
2200         uint16_t fbc;
2201 };
2202
2203 struct hsw_wm_values {
2204         uint32_t wm_pipe[3];
2205         uint32_t wm_lp[3];
2206         uint32_t wm_lp_spr[3];
2207         uint32_t wm_linetime[3];
2208         bool enable_fbc_wm;
2209 };
2210
2211 /* used in computing the new watermarks state */
2212 struct intel_wm_config {
2213         unsigned int num_pipes_active;
2214         bool sprites_enabled;
2215         bool sprites_scaled;
2216         bool fbc_wm_enabled;
2217 };
2218
2219 /*
2220  * For both WM_PIPE and WM_LP.
2221  * mem_value must be in 0.1us units.
2222  */
2223 static uint32_t ilk_compute_pri_wm(const struct hsw_pipe_wm_parameters *params,
2224                                    uint32_t mem_value,
2225                                    bool is_lp)
2226 {
2227         uint32_t method1, method2;
2228
2229         if (!params->active || !params->pri.enabled)
2230                 return 0;
2231
2232         method1 = ilk_wm_method1(params->pixel_rate,
2233                                  params->pri.bytes_per_pixel,
2234                                  mem_value);
2235
2236         if (!is_lp)
2237                 return method1;
2238
2239         method2 = ilk_wm_method2(params->pixel_rate,
2240                                  params->pipe_htotal,
2241                                  params->pri.horiz_pixels,
2242                                  params->pri.bytes_per_pixel,
2243                                  mem_value);
2244
2245         return min(method1, method2);
2246 }
2247
2248 /*
2249  * For both WM_PIPE and WM_LP.
2250  * mem_value must be in 0.1us units.
2251  */
2252 static uint32_t ilk_compute_spr_wm(const struct hsw_pipe_wm_parameters *params,
2253                                    uint32_t mem_value)
2254 {
2255         uint32_t method1, method2;
2256
2257         if (!params->active || !params->spr.enabled)
2258                 return 0;
2259
2260         method1 = ilk_wm_method1(params->pixel_rate,
2261                                  params->spr.bytes_per_pixel,
2262                                  mem_value);
2263         method2 = ilk_wm_method2(params->pixel_rate,
2264                                  params->pipe_htotal,
2265                                  params->spr.horiz_pixels,
2266                                  params->spr.bytes_per_pixel,
2267                                  mem_value);
2268         return min(method1, method2);
2269 }
2270
2271 /*
2272  * For both WM_PIPE and WM_LP.
2273  * mem_value must be in 0.1us units.
2274  */
2275 static uint32_t ilk_compute_cur_wm(const struct hsw_pipe_wm_parameters *params,
2276                                    uint32_t mem_value)
2277 {
2278         if (!params->active || !params->cur.enabled)
2279                 return 0;
2280
2281         return ilk_wm_method2(params->pixel_rate,
2282                               params->pipe_htotal,
2283                               params->cur.horiz_pixels,
2284                               params->cur.bytes_per_pixel,
2285                               mem_value);
2286 }
2287
2288 /* Only for WM_LP. */
2289 static uint32_t ilk_compute_fbc_wm(const struct hsw_pipe_wm_parameters *params,
2290                                    uint32_t pri_val)
2291 {
2292         if (!params->active || !params->pri.enabled)
2293                 return 0;
2294
2295         return ilk_wm_fbc(pri_val,
2296                           params->pri.horiz_pixels,
2297                           params->pri.bytes_per_pixel);
2298 }
2299
2300 static unsigned int ilk_display_fifo_size(const struct drm_device *dev)
2301 {
2302         if (INTEL_INFO(dev)->gen >= 7)
2303                 return 768;
2304         else
2305                 return 512;
2306 }
2307
2308 /* Calculate the maximum primary/sprite plane watermark */
2309 static unsigned int ilk_plane_wm_max(const struct drm_device *dev,
2310                                      int level,
2311                                      const struct intel_wm_config *config,
2312                                      enum intel_ddb_partitioning ddb_partitioning,
2313                                      bool is_sprite)
2314 {
2315         unsigned int fifo_size = ilk_display_fifo_size(dev);
2316         unsigned int max;
2317
2318         /* if sprites aren't enabled, sprites get nothing */
2319         if (is_sprite && !config->sprites_enabled)
2320                 return 0;
2321
2322         /* HSW allows LP1+ watermarks even with multiple pipes */
2323         if (level == 0 || config->num_pipes_active > 1) {
2324                 fifo_size /= INTEL_INFO(dev)->num_pipes;
2325
2326                 /*
2327                  * For some reason the non self refresh
2328                  * FIFO size is only half of the self
2329                  * refresh FIFO size on ILK/SNB.
2330                  */
2331                 if (INTEL_INFO(dev)->gen <= 6)
2332                         fifo_size /= 2;
2333         }
2334
2335         if (config->sprites_enabled) {
2336                 /* level 0 is always calculated with 1:1 split */
2337                 if (level > 0 && ddb_partitioning == INTEL_DDB_PART_5_6) {
2338                         if (is_sprite)
2339                                 fifo_size *= 5;
2340                         fifo_size /= 6;
2341                 } else {
2342                         fifo_size /= 2;
2343                 }
2344         }
2345
2346         /* clamp to max that the registers can hold */
2347         if (INTEL_INFO(dev)->gen >= 7)
2348                 /* IVB/HSW primary/sprite plane watermarks */
2349                 max = level == 0 ? 127 : 1023;
2350         else if (!is_sprite)
2351                 /* ILK/SNB primary plane watermarks */
2352                 max = level == 0 ? 127 : 511;
2353         else
2354                 /* ILK/SNB sprite plane watermarks */
2355                 max = level == 0 ? 63 : 255;
2356
2357         return min(fifo_size, max);
2358 }
2359
2360 /* Calculate the maximum cursor plane watermark */
2361 static unsigned int ilk_cursor_wm_max(const struct drm_device *dev,
2362                                       int level,
2363                                       const struct intel_wm_config *config)
2364 {
2365         /* HSW LP1+ watermarks w/ multiple pipes */
2366         if (level > 0 && config->num_pipes_active > 1)
2367                 return 64;
2368
2369         /* otherwise just report max that registers can hold */
2370         if (INTEL_INFO(dev)->gen >= 7)
2371                 return level == 0 ? 63 : 255;
2372         else
2373                 return level == 0 ? 31 : 63;
2374 }
2375
2376 /* Calculate the maximum FBC watermark */
2377 static unsigned int ilk_fbc_wm_max(void)
2378 {
2379         /* max that registers can hold */
2380         return 15;
2381 }
2382
2383 static void ilk_wm_max(struct drm_device *dev,
2384                        int level,
2385                        const struct intel_wm_config *config,
2386                        enum intel_ddb_partitioning ddb_partitioning,
2387                        struct hsw_wm_maximums *max)
2388 {
2389         max->pri = ilk_plane_wm_max(dev, level, config, ddb_partitioning, false);
2390         max->spr = ilk_plane_wm_max(dev, level, config, ddb_partitioning, true);
2391         max->cur = ilk_cursor_wm_max(dev, level, config);
2392         max->fbc = ilk_fbc_wm_max();
2393 }
2394
2395 static bool ilk_check_wm(int level,
2396                          const struct hsw_wm_maximums *max,
2397                          struct intel_wm_level *result)
2398 {
2399         bool ret;
2400
2401         /* already determined to be invalid? */
2402         if (!result->enable)
2403                 return false;
2404
2405         result->enable = result->pri_val <= max->pri &&
2406                          result->spr_val <= max->spr &&
2407                          result->cur_val <= max->cur;
2408
2409         ret = result->enable;
2410
2411         /*
2412          * HACK until we can pre-compute everything,
2413          * and thus fail gracefully if LP0 watermarks
2414          * are exceeded...
2415          */
2416         if (level == 0 && !result->enable) {
2417                 if (result->pri_val > max->pri)
2418                         DRM_DEBUG_KMS("Primary WM%d too large %u (max %u)\n",
2419                                       level, result->pri_val, max->pri);
2420                 if (result->spr_val > max->spr)
2421                         DRM_DEBUG_KMS("Sprite WM%d too large %u (max %u)\n",
2422                                       level, result->spr_val, max->spr);
2423                 if (result->cur_val > max->cur)
2424                         DRM_DEBUG_KMS("Cursor WM%d too large %u (max %u)\n",
2425                                       level, result->cur_val, max->cur);
2426
2427                 result->pri_val = min_t(uint32_t, result->pri_val, max->pri);
2428                 result->spr_val = min_t(uint32_t, result->spr_val, max->spr);
2429                 result->cur_val = min_t(uint32_t, result->cur_val, max->cur);
2430                 result->enable = true;
2431         }
2432
2433         DRM_DEBUG_KMS("WM%d: %sabled\n", level, result->enable ? "en" : "dis");
2434
2435         return ret;
2436 }
2437
2438 static void ilk_compute_wm_level(struct drm_i915_private *dev_priv,
2439                                  int level,
2440                                  const struct hsw_pipe_wm_parameters *p,
2441                                  struct intel_wm_level *result)
2442 {
2443         uint16_t pri_latency = dev_priv->wm.pri_latency[level];
2444         uint16_t spr_latency = dev_priv->wm.spr_latency[level];
2445         uint16_t cur_latency = dev_priv->wm.cur_latency[level];
2446
2447         /* WM1+ latency values stored in 0.5us units */
2448         if (level > 0) {
2449                 pri_latency *= 5;
2450                 spr_latency *= 5;
2451                 cur_latency *= 5;
2452         }
2453
2454         result->pri_val = ilk_compute_pri_wm(p, pri_latency, level);
2455         result->spr_val = ilk_compute_spr_wm(p, spr_latency);
2456         result->cur_val = ilk_compute_cur_wm(p, cur_latency);
2457         result->fbc_val = ilk_compute_fbc_wm(p, result->pri_val);
2458         result->enable = true;
2459 }
2460
2461 static uint32_t
2462 hsw_compute_linetime_wm(struct drm_device *dev, struct drm_crtc *crtc)
2463 {
2464         struct drm_i915_private *dev_priv = dev->dev_private;
2465         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2466         struct drm_display_mode *mode = &intel_crtc->config.adjusted_mode;
2467         u32 linetime, ips_linetime;
2468
2469         if (!intel_crtc_active(crtc))
2470                 return 0;
2471
2472         /* The WM are computed with base on how long it takes to fill a single
2473          * row at the given clock rate, multiplied by 8.
2474          * */
2475         linetime = DIV_ROUND_CLOSEST(mode->htotal * 1000 * 8, mode->clock);
2476         ips_linetime = DIV_ROUND_CLOSEST(mode->htotal * 1000 * 8,
2477                                          intel_ddi_get_cdclk_freq(dev_priv));
2478
2479         return PIPE_WM_LINETIME_IPS_LINETIME(ips_linetime) |
2480                PIPE_WM_LINETIME_TIME(linetime);
2481 }
2482
2483 static void intel_read_wm_latency(struct drm_device *dev, uint16_t wm[5])
2484 {
2485         struct drm_i915_private *dev_priv = dev->dev_private;
2486
2487         if (IS_HASWELL(dev)) {
2488                 uint64_t sskpd = I915_READ64(MCH_SSKPD);
2489
2490                 wm[0] = (sskpd >> 56) & 0xFF;
2491                 if (wm[0] == 0)
2492                         wm[0] = sskpd & 0xF;
2493                 wm[1] = (sskpd >> 4) & 0xFF;
2494                 wm[2] = (sskpd >> 12) & 0xFF;
2495                 wm[3] = (sskpd >> 20) & 0x1FF;
2496                 wm[4] = (sskpd >> 32) & 0x1FF;
2497         } else if (INTEL_INFO(dev)->gen >= 6) {
2498                 uint32_t sskpd = I915_READ(MCH_SSKPD);
2499
2500                 wm[0] = (sskpd >> SSKPD_WM0_SHIFT) & SSKPD_WM_MASK;
2501                 wm[1] = (sskpd >> SSKPD_WM1_SHIFT) & SSKPD_WM_MASK;
2502                 wm[2] = (sskpd >> SSKPD_WM2_SHIFT) & SSKPD_WM_MASK;
2503                 wm[3] = (sskpd >> SSKPD_WM3_SHIFT) & SSKPD_WM_MASK;
2504         } else if (INTEL_INFO(dev)->gen >= 5) {
2505                 uint32_t mltr = I915_READ(MLTR_ILK);
2506
2507                 /* ILK primary LP0 latency is 700 ns */
2508                 wm[0] = 7;
2509                 wm[1] = (mltr >> MLTR_WM1_SHIFT) & ILK_SRLT_MASK;
2510                 wm[2] = (mltr >> MLTR_WM2_SHIFT) & ILK_SRLT_MASK;
2511         }
2512 }
2513
2514 static void intel_fixup_spr_wm_latency(struct drm_device *dev, uint16_t wm[5])
2515 {
2516         /* ILK sprite LP0 latency is 1300 ns */
2517         if (INTEL_INFO(dev)->gen == 5)
2518                 wm[0] = 13;
2519 }
2520
2521 static void intel_fixup_cur_wm_latency(struct drm_device *dev, uint16_t wm[5])
2522 {
2523         /* ILK cursor LP0 latency is 1300 ns */
2524         if (INTEL_INFO(dev)->gen == 5)
2525                 wm[0] = 13;
2526
2527         /* WaDoubleCursorLP3Latency:ivb */
2528         if (IS_IVYBRIDGE(dev))
2529                 wm[3] *= 2;
2530 }
2531
2532 static int ilk_wm_max_level(const struct drm_device *dev)
2533 {
2534         /* how many WM levels are we expecting */
2535         if (IS_HASWELL(dev))
2536                 return 4;
2537         else if (INTEL_INFO(dev)->gen >= 6)
2538                 return 3;
2539         else
2540                 return 2;
2541 }
2542
2543 static void intel_print_wm_latency(struct drm_device *dev,
2544                                    const char *name,
2545                                    const uint16_t wm[5])
2546 {
2547         int level, max_level = ilk_wm_max_level(dev);
2548
2549         for (level = 0; level <= max_level; level++) {
2550                 unsigned int latency = wm[level];
2551
2552                 if (latency == 0) {
2553                         DRM_ERROR("%s WM%d latency not provided\n",
2554                                   name, level);
2555                         continue;
2556                 }
2557
2558                 /* WM1+ latency values in 0.5us units */
2559                 if (level > 0)
2560                         latency *= 5;
2561
2562                 DRM_DEBUG_KMS("%s WM%d latency %u (%u.%u usec)\n",
2563                               name, level, wm[level],
2564                               latency / 10, latency % 10);
2565         }
2566 }
2567
2568 static void intel_setup_wm_latency(struct drm_device *dev)
2569 {
2570         struct drm_i915_private *dev_priv = dev->dev_private;
2571
2572         intel_read_wm_latency(dev, dev_priv->wm.pri_latency);
2573
2574         memcpy(dev_priv->wm.spr_latency, dev_priv->wm.pri_latency,
2575                sizeof(dev_priv->wm.pri_latency));
2576         memcpy(dev_priv->wm.cur_latency, dev_priv->wm.pri_latency,
2577                sizeof(dev_priv->wm.pri_latency));
2578
2579         intel_fixup_spr_wm_latency(dev, dev_priv->wm.spr_latency);
2580         intel_fixup_cur_wm_latency(dev, dev_priv->wm.cur_latency);
2581
2582         intel_print_wm_latency(dev, "Primary", dev_priv->wm.pri_latency);
2583         intel_print_wm_latency(dev, "Sprite", dev_priv->wm.spr_latency);
2584         intel_print_wm_latency(dev, "Cursor", dev_priv->wm.cur_latency);
2585 }
2586
2587 static void hsw_compute_wm_parameters(struct drm_crtc *crtc,
2588                                       struct hsw_pipe_wm_parameters *p,
2589                                       struct intel_wm_config *config)
2590 {
2591         struct drm_device *dev = crtc->dev;
2592         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2593         enum pipe pipe = intel_crtc->pipe;
2594         struct drm_plane *plane;
2595
2596         p->active = intel_crtc_active(crtc);
2597         if (p->active) {
2598                 p->pipe_htotal = intel_crtc->config.adjusted_mode.htotal;
2599                 p->pixel_rate = ilk_pipe_pixel_rate(dev, crtc);
2600                 p->pri.bytes_per_pixel = crtc->fb->bits_per_pixel / 8;
2601                 p->cur.bytes_per_pixel = 4;
2602                 p->pri.horiz_pixels = intel_crtc->config.pipe_src_w;
2603                 p->cur.horiz_pixels = 64;
2604                 /* TODO: for now, assume primary and cursor planes are always enabled. */
2605                 p->pri.enabled = true;
2606                 p->cur.enabled = true;
2607         }
2608
2609         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
2610                 config->num_pipes_active += intel_crtc_active(crtc);
2611
2612         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
2613                 struct intel_plane *intel_plane = to_intel_plane(plane);
2614
2615                 if (intel_plane->pipe == pipe)
2616                         p->spr = intel_plane->wm;
2617
2618                 config->sprites_enabled |= intel_plane->wm.enabled;
2619                 config->sprites_scaled |= intel_plane->wm.scaled;
2620         }
2621 }
2622
2623 /* Compute new watermarks for the pipe */
2624 static bool intel_compute_pipe_wm(struct drm_crtc *crtc,
2625                                   const struct hsw_pipe_wm_parameters *params,
2626                                   struct intel_pipe_wm *pipe_wm)
2627 {
2628         struct drm_device *dev = crtc->dev;
2629         struct drm_i915_private *dev_priv = dev->dev_private;
2630         int level, max_level = ilk_wm_max_level(dev);
2631         /* LP0 watermark maximums depend on this pipe alone */
2632         struct intel_wm_config config = {
2633                 .num_pipes_active = 1,
2634                 .sprites_enabled = params->spr.enabled,
2635                 .sprites_scaled = params->spr.scaled,
2636         };
2637         struct hsw_wm_maximums max;
2638
2639         /* LP0 watermarks always use 1/2 DDB partitioning */
2640         ilk_wm_max(dev, 0, &config, INTEL_DDB_PART_1_2, &max);
2641
2642         for (level = 0; level <= max_level; level++)
2643                 ilk_compute_wm_level(dev_priv, level, params,
2644                                      &pipe_wm->wm[level]);
2645
2646         pipe_wm->linetime = hsw_compute_linetime_wm(dev, crtc);
2647
2648         /* At least LP0 must be valid */
2649         return ilk_check_wm(0, &max, &pipe_wm->wm[0]);
2650 }
2651
2652 /*
2653  * Merge the watermarks from all active pipes for a specific level.
2654  */
2655 static void ilk_merge_wm_level(struct drm_device *dev,
2656                                int level,
2657                                struct intel_wm_level *ret_wm)
2658 {
2659         const struct intel_crtc *intel_crtc;
2660
2661         list_for_each_entry(intel_crtc, &dev->mode_config.crtc_list, base.head) {
2662                 const struct intel_wm_level *wm =
2663                         &intel_crtc->wm.active.wm[level];
2664
2665                 if (!wm->enable)
2666                         return;
2667
2668                 ret_wm->pri_val = max(ret_wm->pri_val, wm->pri_val);
2669                 ret_wm->spr_val = max(ret_wm->spr_val, wm->spr_val);
2670                 ret_wm->cur_val = max(ret_wm->cur_val, wm->cur_val);
2671                 ret_wm->fbc_val = max(ret_wm->fbc_val, wm->fbc_val);
2672         }
2673
2674         ret_wm->enable = true;
2675 }
2676
2677 /*
2678  * Merge all low power watermarks for all active pipes.
2679  */
2680 static void ilk_wm_merge(struct drm_device *dev,
2681                          const struct hsw_wm_maximums *max,
2682                          struct intel_pipe_wm *merged)
2683 {
2684         int level, max_level = ilk_wm_max_level(dev);
2685
2686         merged->fbc_wm_enabled = true;
2687
2688         /* merge each WM1+ level */
2689         for (level = 1; level <= max_level; level++) {
2690                 struct intel_wm_level *wm = &merged->wm[level];
2691
2692                 ilk_merge_wm_level(dev, level, wm);
2693
2694                 if (!ilk_check_wm(level, max, wm))
2695                         break;
2696
2697                 /*
2698                  * The spec says it is preferred to disable
2699                  * FBC WMs instead of disabling a WM level.
2700                  */
2701                 if (wm->fbc_val > max->fbc) {
2702                         merged->fbc_wm_enabled = false;
2703                         wm->fbc_val = 0;
2704                 }
2705         }
2706 }
2707
2708 static int ilk_wm_lp_to_level(int wm_lp, const struct intel_pipe_wm *pipe_wm)
2709 {
2710         /* LP1,LP2,LP3 levels are either 1,2,3 or 1,3,4 */
2711         return wm_lp + (wm_lp >= 2 && pipe_wm->wm[4].enable);
2712 }
2713
2714 static void hsw_compute_wm_results(struct drm_device *dev,
2715                                    const struct intel_pipe_wm *merged,
2716                                    struct hsw_wm_values *results)
2717 {
2718         struct intel_crtc *intel_crtc;
2719         int level, wm_lp;
2720
2721         results->enable_fbc_wm = merged->fbc_wm_enabled;
2722
2723         /* LP1+ register values */
2724         for (wm_lp = 1; wm_lp <= 3; wm_lp++) {
2725                 const struct intel_wm_level *r;
2726
2727                 level = ilk_wm_lp_to_level(wm_lp, merged);
2728
2729                 r = &merged->wm[level];
2730                 if (!r->enable)
2731                         break;
2732
2733                 results->wm_lp[wm_lp - 1] = HSW_WM_LP_VAL(level * 2,
2734                                                           r->fbc_val,
2735                                                           r->pri_val,
2736                                                           r->cur_val);
2737                 results->wm_lp_spr[wm_lp - 1] = r->spr_val;
2738         }
2739
2740         /* LP0 register values */
2741         list_for_each_entry(intel_crtc, &dev->mode_config.crtc_list, base.head) {
2742                 enum pipe pipe = intel_crtc->pipe;
2743                 const struct intel_wm_level *r =
2744                         &intel_crtc->wm.active.wm[0];
2745
2746                 if (WARN_ON(!r->enable))
2747                         continue;
2748
2749                 results->wm_linetime[pipe] = intel_crtc->wm.active.linetime;
2750
2751                 results->wm_pipe[pipe] =
2752                         (r->pri_val << WM0_PIPE_PLANE_SHIFT) |
2753                         (r->spr_val << WM0_PIPE_SPRITE_SHIFT) |
2754                         r->cur_val;
2755         }
2756 }
2757
2758 /* Find the result with the highest level enabled. Check for enable_fbc_wm in
2759  * case both are at the same level. Prefer r1 in case they're the same. */
2760 static struct intel_pipe_wm *hsw_find_best_result(struct drm_device *dev,
2761                                                   struct intel_pipe_wm *r1,
2762                                                   struct intel_pipe_wm *r2)
2763 {
2764         int level, max_level = ilk_wm_max_level(dev);
2765         int level1 = 0, level2 = 0;
2766
2767         for (level = 1; level <= max_level; level++) {
2768                 if (r1->wm[level].enable)
2769                         level1 = level;
2770                 if (r2->wm[level].enable)
2771                         level2 = level;
2772         }
2773
2774         if (level1 == level2) {
2775                 if (r2->fbc_wm_enabled && !r1->fbc_wm_enabled)
2776                         return r2;
2777                 else
2778                         return r1;
2779         } else if (level1 > level2) {
2780                 return r1;
2781         } else {
2782                 return r2;
2783         }
2784 }
2785
2786 /*
2787  * The spec says we shouldn't write when we don't need, because every write
2788  * causes WMs to be re-evaluated, expending some power.
2789  */
2790 static void hsw_write_wm_values(struct drm_i915_private *dev_priv,
2791                                 struct hsw_wm_values *results,
2792                                 enum intel_ddb_partitioning partitioning)
2793 {
2794         struct hsw_wm_values previous;
2795         uint32_t val;
2796         enum intel_ddb_partitioning prev_partitioning;
2797         bool prev_enable_fbc_wm;
2798
2799         previous.wm_pipe[0] = I915_READ(WM0_PIPEA_ILK);
2800         previous.wm_pipe[1] = I915_READ(WM0_PIPEB_ILK);
2801         previous.wm_pipe[2] = I915_READ(WM0_PIPEC_IVB);
2802         previous.wm_lp[0] = I915_READ(WM1_LP_ILK);
2803         previous.wm_lp[1] = I915_READ(WM2_LP_ILK);
2804         previous.wm_lp[2] = I915_READ(WM3_LP_ILK);
2805         previous.wm_lp_spr[0] = I915_READ(WM1S_LP_ILK);
2806         previous.wm_lp_spr[1] = I915_READ(WM2S_LP_IVB);
2807         previous.wm_lp_spr[2] = I915_READ(WM3S_LP_IVB);
2808         previous.wm_linetime[0] = I915_READ(PIPE_WM_LINETIME(PIPE_A));
2809         previous.wm_linetime[1] = I915_READ(PIPE_WM_LINETIME(PIPE_B));
2810         previous.wm_linetime[2] = I915_READ(PIPE_WM_LINETIME(PIPE_C));
2811
2812         prev_partitioning = (I915_READ(WM_MISC) & WM_MISC_DATA_PARTITION_5_6) ?
2813                                 INTEL_DDB_PART_5_6 : INTEL_DDB_PART_1_2;
2814
2815         prev_enable_fbc_wm = !(I915_READ(DISP_ARB_CTL) & DISP_FBC_WM_DIS);
2816
2817         if (memcmp(results->wm_pipe, previous.wm_pipe,
2818                    sizeof(results->wm_pipe)) == 0 &&
2819             memcmp(results->wm_lp, previous.wm_lp,
2820                    sizeof(results->wm_lp)) == 0 &&
2821             memcmp(results->wm_lp_spr, previous.wm_lp_spr,
2822                    sizeof(results->wm_lp_spr)) == 0 &&
2823             memcmp(results->wm_linetime, previous.wm_linetime,
2824                    sizeof(results->wm_linetime)) == 0 &&
2825             partitioning == prev_partitioning &&
2826             results->enable_fbc_wm == prev_enable_fbc_wm)
2827                 return;
2828
2829         if (previous.wm_lp[2] != 0)
2830                 I915_WRITE(WM3_LP_ILK, 0);
2831         if (previous.wm_lp[1] != 0)
2832                 I915_WRITE(WM2_LP_ILK, 0);
2833         if (previous.wm_lp[0] != 0)
2834                 I915_WRITE(WM1_LP_ILK, 0);
2835
2836         if (previous.wm_pipe[0] != results->wm_pipe[0])
2837                 I915_WRITE(WM0_PIPEA_ILK, results->wm_pipe[0]);
2838         if (previous.wm_pipe[1] != results->wm_pipe[1])
2839                 I915_WRITE(WM0_PIPEB_ILK, results->wm_pipe[1]);
2840         if (previous.wm_pipe[2] != results->wm_pipe[2])
2841                 I915_WRITE(WM0_PIPEC_IVB, results->wm_pipe[2]);
2842
2843         if (previous.wm_linetime[0] != results->wm_linetime[0])
2844                 I915_WRITE(PIPE_WM_LINETIME(PIPE_A), results->wm_linetime[0]);
2845         if (previous.wm_linetime[1] != results->wm_linetime[1])
2846                 I915_WRITE(PIPE_WM_LINETIME(PIPE_B), results->wm_linetime[1]);
2847         if (previous.wm_linetime[2] != results->wm_linetime[2])
2848                 I915_WRITE(PIPE_WM_LINETIME(PIPE_C), results->wm_linetime[2]);
2849
2850         if (prev_partitioning != partitioning) {
2851                 val = I915_READ(WM_MISC);
2852                 if (partitioning == INTEL_DDB_PART_1_2)
2853                         val &= ~WM_MISC_DATA_PARTITION_5_6;
2854                 else
2855                         val |= WM_MISC_DATA_PARTITION_5_6;
2856                 I915_WRITE(WM_MISC, val);
2857         }
2858
2859         if (prev_enable_fbc_wm != results->enable_fbc_wm) {
2860                 val = I915_READ(DISP_ARB_CTL);
2861                 if (results->enable_fbc_wm)
2862                         val &= ~DISP_FBC_WM_DIS;
2863                 else
2864                         val |= DISP_FBC_WM_DIS;
2865                 I915_WRITE(DISP_ARB_CTL, val);
2866         }
2867
2868         if (previous.wm_lp_spr[0] != results->wm_lp_spr[0])
2869                 I915_WRITE(WM1S_LP_ILK, results->wm_lp_spr[0]);
2870         if (previous.wm_lp_spr[1] != results->wm_lp_spr[1])
2871                 I915_WRITE(WM2S_LP_IVB, results->wm_lp_spr[1]);
2872         if (previous.wm_lp_spr[2] != results->wm_lp_spr[2])
2873                 I915_WRITE(WM3S_LP_IVB, results->wm_lp_spr[2]);
2874
2875         if (results->wm_lp[0] != 0)
2876                 I915_WRITE(WM1_LP_ILK, results->wm_lp[0]);
2877         if (results->wm_lp[1] != 0)
2878                 I915_WRITE(WM2_LP_ILK, results->wm_lp[1]);
2879         if (results->wm_lp[2] != 0)
2880                 I915_WRITE(WM3_LP_ILK, results->wm_lp[2]);
2881 }
2882
2883 static void haswell_update_wm(struct drm_crtc *crtc)
2884 {
2885         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2886         struct drm_device *dev = crtc->dev;
2887         struct drm_i915_private *dev_priv = dev->dev_private;
2888         struct hsw_wm_maximums max;
2889         struct hsw_pipe_wm_parameters params = {};
2890         struct hsw_wm_values results = {};
2891         enum intel_ddb_partitioning partitioning;
2892         struct intel_pipe_wm pipe_wm = {};
2893         struct intel_pipe_wm lp_wm_1_2 = {}, lp_wm_5_6 = {}, *best_lp_wm;
2894         struct intel_wm_config config = {};
2895
2896         hsw_compute_wm_parameters(crtc, &params, &config);
2897
2898         intel_compute_pipe_wm(crtc, &params, &pipe_wm);
2899
2900         if (!memcmp(&intel_crtc->wm.active, &pipe_wm, sizeof(pipe_wm)))
2901                 return;
2902
2903         intel_crtc->wm.active = pipe_wm;
2904
2905         ilk_wm_max(dev, 1, &config, INTEL_DDB_PART_1_2, &max);
2906         ilk_wm_merge(dev, &max, &lp_wm_1_2);
2907
2908         /* 5/6 split only in single pipe config on IVB+ */
2909         if (INTEL_INFO(dev)->gen >= 7 && config.num_pipes_active == 1) {
2910                 ilk_wm_max(dev, 1, &config, INTEL_DDB_PART_5_6, &max);
2911                 ilk_wm_merge(dev, &max, &lp_wm_5_6);
2912
2913                 best_lp_wm = hsw_find_best_result(dev, &lp_wm_1_2, &lp_wm_5_6);
2914         } else {
2915                 best_lp_wm = &lp_wm_1_2;
2916         }
2917
2918         hsw_compute_wm_results(dev, best_lp_wm, &results);
2919
2920         partitioning = (best_lp_wm == &lp_wm_1_2) ?
2921                        INTEL_DDB_PART_1_2 : INTEL_DDB_PART_5_6;
2922
2923         hsw_write_wm_values(dev_priv, &results, partitioning);
2924 }
2925
2926 static void haswell_update_sprite_wm(struct drm_plane *plane,
2927                                      struct drm_crtc *crtc,
2928                                      uint32_t sprite_width, int pixel_size,
2929                                      bool enabled, bool scaled)
2930 {
2931         struct intel_plane *intel_plane = to_intel_plane(plane);
2932
2933         intel_plane->wm.enabled = enabled;
2934         intel_plane->wm.scaled = scaled;
2935         intel_plane->wm.horiz_pixels = sprite_width;
2936         intel_plane->wm.bytes_per_pixel = pixel_size;
2937
2938         haswell_update_wm(crtc);
2939 }
2940
2941 static bool
2942 sandybridge_compute_sprite_wm(struct drm_device *dev, int plane,
2943                               uint32_t sprite_width, int pixel_size,
2944                               const struct intel_watermark_params *display,
2945                               int display_latency_ns, int *sprite_wm)
2946 {
2947         struct drm_crtc *crtc;
2948         int clock;
2949         int entries, tlb_miss;
2950
2951         crtc = intel_get_crtc_for_plane(dev, plane);
2952         if (!intel_crtc_active(crtc)) {
2953                 *sprite_wm = display->guard_size;
2954                 return false;
2955         }
2956
2957         clock = to_intel_crtc(crtc)->config.adjusted_mode.crtc_clock;
2958
2959         /* Use the small buffer method to calculate the sprite watermark */
2960         entries = ((clock * pixel_size / 1000) * display_latency_ns) / 1000;
2961         tlb_miss = display->fifo_size*display->cacheline_size -
2962                 sprite_width * 8;
2963         if (tlb_miss > 0)
2964                 entries += tlb_miss;
2965         entries = DIV_ROUND_UP(entries, display->cacheline_size);
2966         *sprite_wm = entries + display->guard_size;
2967         if (*sprite_wm > (int)display->max_wm)
2968                 *sprite_wm = display->max_wm;
2969
2970         return true;
2971 }
2972
2973 static bool
2974 sandybridge_compute_sprite_srwm(struct drm_device *dev, int plane,
2975                                 uint32_t sprite_width, int pixel_size,
2976                                 const struct intel_watermark_params *display,
2977                                 int latency_ns, int *sprite_wm)
2978 {
2979         struct drm_crtc *crtc;
2980         unsigned long line_time_us;
2981         int clock;
2982         int line_count, line_size;
2983         int small, large;
2984         int entries;
2985
2986         if (!latency_ns) {
2987                 *sprite_wm = 0;
2988                 return false;
2989         }
2990
2991         crtc = intel_get_crtc_for_plane(dev, plane);
2992         clock = to_intel_crtc(crtc)->config.adjusted_mode.crtc_clock;
2993         if (!clock) {
2994                 *sprite_wm = 0;
2995                 return false;
2996         }
2997
2998         line_time_us = (sprite_width * 1000) / clock;
2999         if (!line_time_us) {
3000                 *sprite_wm = 0;
3001                 return false;
3002         }
3003
3004         line_count = (latency_ns / line_time_us + 1000) / 1000;
3005         line_size = sprite_width * pixel_size;
3006
3007         /* Use the minimum of the small and large buffer method for primary */
3008         small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
3009         large = line_count * line_size;
3010
3011         entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
3012         *sprite_wm = entries + display->guard_size;
3013
3014         return *sprite_wm > 0x3ff ? false : true;
3015 }
3016
3017 static void sandybridge_update_sprite_wm(struct drm_plane *plane,
3018                                          struct drm_crtc *crtc,
3019                                          uint32_t sprite_width, int pixel_size,
3020                                          bool enabled, bool scaled)
3021 {
3022         struct drm_device *dev = plane->dev;
3023         struct drm_i915_private *dev_priv = dev->dev_private;
3024         int pipe = to_intel_plane(plane)->pipe;
3025         int latency = dev_priv->wm.spr_latency[0] * 100;        /* In unit 0.1us */
3026         u32 val;
3027         int sprite_wm, reg;
3028         int ret;
3029
3030         if (!enabled)
3031                 return;
3032
3033         switch (pipe) {
3034         case 0:
3035                 reg = WM0_PIPEA_ILK;
3036                 break;
3037         case 1:
3038                 reg = WM0_PIPEB_ILK;
3039                 break;
3040         case 2:
3041                 reg = WM0_PIPEC_IVB;
3042                 break;
3043         default:
3044                 return; /* bad pipe */
3045         }
3046
3047         ret = sandybridge_compute_sprite_wm(dev, pipe, sprite_width, pixel_size,
3048                                             &sandybridge_display_wm_info,
3049                                             latency, &sprite_wm);
3050         if (!ret) {
3051                 DRM_DEBUG_KMS("failed to compute sprite wm for pipe %c\n",
3052                               pipe_name(pipe));
3053                 return;
3054         }
3055
3056         val = I915_READ(reg);
3057         val &= ~WM0_PIPE_SPRITE_MASK;
3058         I915_WRITE(reg, val | (sprite_wm << WM0_PIPE_SPRITE_SHIFT));
3059         DRM_DEBUG_KMS("sprite watermarks For pipe %c - %d\n", pipe_name(pipe), sprite_wm);
3060
3061
3062         ret = sandybridge_compute_sprite_srwm(dev, pipe, sprite_width,
3063                                               pixel_size,
3064                                               &sandybridge_display_srwm_info,
3065                                               dev_priv->wm.spr_latency[1] * 500,
3066                                               &sprite_wm);
3067         if (!ret) {
3068                 DRM_DEBUG_KMS("failed to compute sprite lp1 wm on pipe %c\n",
3069                               pipe_name(pipe));
3070                 return;
3071         }
3072         I915_WRITE(WM1S_LP_ILK, sprite_wm);
3073
3074         /* Only IVB has two more LP watermarks for sprite */
3075         if (!IS_IVYBRIDGE(dev))
3076                 return;
3077
3078         ret = sandybridge_compute_sprite_srwm(dev, pipe, sprite_width,
3079                                               pixel_size,
3080                                               &sandybridge_display_srwm_info,
3081                                               dev_priv->wm.spr_latency[2] * 500,
3082                                               &sprite_wm);
3083         if (!ret) {
3084                 DRM_DEBUG_KMS("failed to compute sprite lp2 wm on pipe %c\n",
3085                               pipe_name(pipe));
3086                 return;
3087         }
3088         I915_WRITE(WM2S_LP_IVB, sprite_wm);
3089
3090         ret = sandybridge_compute_sprite_srwm(dev, pipe, sprite_width,
3091                                               pixel_size,
3092                                               &sandybridge_display_srwm_info,
3093                                               dev_priv->wm.spr_latency[3] * 500,
3094                                               &sprite_wm);
3095         if (!ret) {
3096                 DRM_DEBUG_KMS("failed to compute sprite lp3 wm on pipe %c\n",
3097                               pipe_name(pipe));
3098                 return;
3099         }
3100         I915_WRITE(WM3S_LP_IVB, sprite_wm);
3101 }
3102
3103 /**
3104  * intel_update_watermarks - update FIFO watermark values based on current modes
3105  *
3106  * Calculate watermark values for the various WM regs based on current mode
3107  * and plane configuration.
3108  *
3109  * There are several cases to deal with here:
3110  *   - normal (i.e. non-self-refresh)
3111  *   - self-refresh (SR) mode
3112  *   - lines are large relative to FIFO size (buffer can hold up to 2)
3113  *   - lines are small relative to FIFO size (buffer can hold more than 2
3114  *     lines), so need to account for TLB latency
3115  *
3116  *   The normal calculation is:
3117  *     watermark = dotclock * bytes per pixel * latency
3118  *   where latency is platform & configuration dependent (we assume pessimal
3119  *   values here).
3120  *
3121  *   The SR calculation is:
3122  *     watermark = (trunc(latency/line time)+1) * surface width *
3123  *       bytes per pixel
3124  *   where
3125  *     line time = htotal / dotclock
3126  *     surface width = hdisplay for normal plane and 64 for cursor
3127  *   and latency is assumed to be high, as above.
3128  *
3129  * The final value programmed to the register should always be rounded up,
3130  * and include an extra 2 entries to account for clock crossings.
3131  *
3132  * We don't use the sprite, so we can ignore that.  And on Crestline we have
3133  * to set the non-SR watermarks to 8.
3134  */
3135 void intel_update_watermarks(struct drm_crtc *crtc)
3136 {
3137         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
3138
3139         if (dev_priv->display.update_wm)
3140                 dev_priv->display.update_wm(crtc);
3141 }
3142
3143 void intel_update_sprite_watermarks(struct drm_plane *plane,
3144                                     struct drm_crtc *crtc,
3145                                     uint32_t sprite_width, int pixel_size,
3146                                     bool enabled, bool scaled)
3147 {
3148         struct drm_i915_private *dev_priv = plane->dev->dev_private;
3149
3150         if (dev_priv->display.update_sprite_wm)
3151                 dev_priv->display.update_sprite_wm(plane, crtc, sprite_width,
3152                                                    pixel_size, enabled, scaled);
3153 }
3154
3155 static struct drm_i915_gem_object *
3156 intel_alloc_context_page(struct drm_device *dev)
3157 {
3158         struct drm_i915_gem_object *ctx;
3159         int ret;
3160
3161         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
3162
3163         ctx = i915_gem_alloc_object(dev, 4096);
3164         if (!ctx) {
3165                 DRM_DEBUG("failed to alloc power context, RC6 disabled\n");
3166                 return NULL;
3167         }
3168
3169         ret = i915_gem_obj_ggtt_pin(ctx, 4096, true, false);
3170         if (ret) {
3171                 DRM_ERROR("failed to pin power context: %d\n", ret);
3172                 goto err_unref;
3173         }
3174
3175         ret = i915_gem_object_set_to_gtt_domain(ctx, 1);
3176         if (ret) {
3177                 DRM_ERROR("failed to set-domain on power context: %d\n", ret);
3178                 goto err_unpin;
3179         }
3180
3181         return ctx;
3182
3183 err_unpin:
3184         i915_gem_object_unpin(ctx);
3185 err_unref:
3186         drm_gem_object_unreference(&ctx->base);
3187         return NULL;
3188 }
3189
3190 /**
3191  * Lock protecting IPS related data structures
3192  */
3193 DEFINE_SPINLOCK(mchdev_lock);
3194
3195 /* Global for IPS driver to get at the current i915 device. Protected by
3196  * mchdev_lock. */
3197 static struct drm_i915_private *i915_mch_dev;
3198
3199 bool ironlake_set_drps(struct drm_device *dev, u8 val)
3200 {
3201         struct drm_i915_private *dev_priv = dev->dev_private;
3202         u16 rgvswctl;
3203
3204         assert_spin_locked(&mchdev_lock);
3205
3206         rgvswctl = I915_READ16(MEMSWCTL);
3207         if (rgvswctl & MEMCTL_CMD_STS) {
3208                 DRM_DEBUG("gpu busy, RCS change rejected\n");
3209                 return false; /* still busy with another command */
3210         }
3211
3212         rgvswctl = (MEMCTL_CMD_CHFREQ << MEMCTL_CMD_SHIFT) |
3213                 (val << MEMCTL_FREQ_SHIFT) | MEMCTL_SFCAVM;
3214         I915_WRITE16(MEMSWCTL, rgvswctl);
3215         POSTING_READ16(MEMSWCTL);
3216
3217         rgvswctl |= MEMCTL_CMD_STS;
3218         I915_WRITE16(MEMSWCTL, rgvswctl);
3219
3220         return true;
3221 }
3222
3223 static void ironlake_enable_drps(struct drm_device *dev)
3224 {
3225         struct drm_i915_private *dev_priv = dev->dev_private;
3226         u32 rgvmodectl = I915_READ(MEMMODECTL);
3227         u8 fmax, fmin, fstart, vstart;
3228
3229         spin_lock_irq(&mchdev_lock);
3230
3231         /* Enable temp reporting */
3232         I915_WRITE16(PMMISC, I915_READ(PMMISC) | MCPPCE_EN);
3233         I915_WRITE16(TSC1, I915_READ(TSC1) | TSE);
3234
3235         /* 100ms RC evaluation intervals */
3236         I915_WRITE(RCUPEI, 100000);
3237         I915_WRITE(RCDNEI, 100000);
3238
3239         /* Set max/min thresholds to 90ms and 80ms respectively */
3240         I915_WRITE(RCBMAXAVG, 90000);
3241         I915_WRITE(RCBMINAVG, 80000);
3242
3243         I915_WRITE(MEMIHYST, 1);
3244
3245         /* Set up min, max, and cur for interrupt handling */
3246         fmax = (rgvmodectl & MEMMODE_FMAX_MASK) >> MEMMODE_FMAX_SHIFT;
3247         fmin = (rgvmodectl & MEMMODE_FMIN_MASK);
3248         fstart = (rgvmodectl & MEMMODE_FSTART_MASK) >>
3249                 MEMMODE_FSTART_SHIFT;
3250
3251         vstart = (I915_READ(PXVFREQ_BASE + (fstart * 4)) & PXVFREQ_PX_MASK) >>
3252                 PXVFREQ_PX_SHIFT;
3253
3254         dev_priv->ips.fmax = fmax; /* IPS callback will increase this */
3255         dev_priv->ips.fstart = fstart;
3256
3257         dev_priv->ips.max_delay = fstart;
3258         dev_priv->ips.min_delay = fmin;
3259         dev_priv->ips.cur_delay = fstart;
3260
3261         DRM_DEBUG_DRIVER("fmax: %d, fmin: %d, fstart: %d\n",
3262                          fmax, fmin, fstart);
3263
3264         I915_WRITE(MEMINTREN, MEMINT_CX_SUPR_EN | MEMINT_EVAL_CHG_EN);
3265
3266         /*
3267          * Interrupts will be enabled in ironlake_irq_postinstall
3268          */
3269
3270         I915_WRITE(VIDSTART, vstart);
3271         POSTING_READ(VIDSTART);
3272
3273         rgvmodectl |= MEMMODE_SWMODE_EN;
3274         I915_WRITE(MEMMODECTL, rgvmodectl);
3275
3276         if (wait_for_atomic((I915_READ(MEMSWCTL) & MEMCTL_CMD_STS) == 0, 10))
3277                 DRM_ERROR("stuck trying to change perf mode\n");
3278         mdelay(1);
3279
3280         ironlake_set_drps(dev, fstart);
3281
3282         dev_priv->ips.last_count1 = I915_READ(0x112e4) + I915_READ(0x112e8) +
3283                 I915_READ(0x112e0);
3284         dev_priv->ips.last_time1 = jiffies_to_msecs(jiffies);
3285         dev_priv->ips.last_count2 = I915_READ(0x112f4);
3286         getrawmonotonic(&dev_priv->ips.last_time2);
3287
3288         spin_unlock_irq(&mchdev_lock);
3289 }
3290
3291 static void ironlake_disable_drps(struct drm_device *dev)
3292 {
3293         struct drm_i915_private *dev_priv = dev->dev_private;
3294         u16 rgvswctl;
3295
3296         spin_lock_irq(&mchdev_lock);
3297
3298         rgvswctl = I915_READ16(MEMSWCTL);
3299
3300         /* Ack interrupts, disable EFC interrupt */
3301         I915_WRITE(MEMINTREN, I915_READ(MEMINTREN) & ~MEMINT_EVAL_CHG_EN);
3302         I915_WRITE(MEMINTRSTS, MEMINT_EVAL_CHG);
3303         I915_WRITE(DEIER, I915_READ(DEIER) & ~DE_PCU_EVENT);
3304         I915_WRITE(DEIIR, DE_PCU_EVENT);
3305         I915_WRITE(DEIMR, I915_READ(DEIMR) | DE_PCU_EVENT);
3306
3307         /* Go back to the starting frequency */
3308         ironlake_set_drps(dev, dev_priv->ips.fstart);
3309         mdelay(1);
3310         rgvswctl |= MEMCTL_CMD_STS;
3311         I915_WRITE(MEMSWCTL, rgvswctl);
3312         mdelay(1);
3313
3314         spin_unlock_irq(&mchdev_lock);
3315 }
3316
3317 /* There's a funny hw issue where the hw returns all 0 when reading from
3318  * GEN6_RP_INTERRUPT_LIMITS. Hence we always need to compute the desired value
3319  * ourselves, instead of doing a rmw cycle (which might result in us clearing
3320  * all limits and the gpu stuck at whatever frequency it is at atm).
3321  */
3322 static u32 gen6_rps_limits(struct drm_i915_private *dev_priv, u8 *val)
3323 {
3324         u32 limits;
3325
3326         limits = 0;
3327
3328         if (*val >= dev_priv->rps.max_delay)
3329                 *val = dev_priv->rps.max_delay;
3330         limits |= dev_priv->rps.max_delay << 24;
3331
3332         /* Only set the down limit when we've reached the lowest level to avoid
3333          * getting more interrupts, otherwise leave this clear. This prevents a
3334          * race in the hw when coming out of rc6: There's a tiny window where
3335          * the hw runs at the minimal clock before selecting the desired
3336          * frequency, if the down threshold expires in that window we will not
3337          * receive a down interrupt. */
3338         if (*val <= dev_priv->rps.min_delay) {
3339                 *val = dev_priv->rps.min_delay;
3340                 limits |= dev_priv->rps.min_delay << 16;
3341         }
3342
3343         return limits;
3344 }
3345
3346 static void gen6_set_rps_thresholds(struct drm_i915_private *dev_priv, u8 val)
3347 {
3348         int new_power;
3349
3350         new_power = dev_priv->rps.power;
3351         switch (dev_priv->rps.power) {
3352         case LOW_POWER:
3353                 if (val > dev_priv->rps.rpe_delay + 1 && val > dev_priv->rps.cur_delay)
3354                         new_power = BETWEEN;
3355                 break;
3356
3357         case BETWEEN:
3358                 if (val <= dev_priv->rps.rpe_delay && val < dev_priv->rps.cur_delay)
3359                         new_power = LOW_POWER;
3360                 else if (val >= dev_priv->rps.rp0_delay && val > dev_priv->rps.cur_delay)
3361                         new_power = HIGH_POWER;
3362                 break;
3363
3364         case HIGH_POWER:
3365                 if (val < (dev_priv->rps.rp1_delay + dev_priv->rps.rp0_delay) >> 1 && val < dev_priv->rps.cur_delay)
3366                         new_power = BETWEEN;
3367                 break;
3368         }
3369         /* Max/min bins are special */
3370         if (val == dev_priv->rps.min_delay)
3371                 new_power = LOW_POWER;
3372         if (val == dev_priv->rps.max_delay)
3373                 new_power = HIGH_POWER;
3374         if (new_power == dev_priv->rps.power)
3375                 return;
3376
3377         /* Note the units here are not exactly 1us, but 1280ns. */
3378         switch (new_power) {
3379         case LOW_POWER:
3380                 /* Upclock if more than 95% busy over 16ms */
3381                 I915_WRITE(GEN6_RP_UP_EI, 12500);
3382                 I915_WRITE(GEN6_RP_UP_THRESHOLD, 11800);
3383
3384                 /* Downclock if less than 85% busy over 32ms */
3385                 I915_WRITE(GEN6_RP_DOWN_EI, 25000);
3386                 I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 21250);
3387
3388                 I915_WRITE(GEN6_RP_CONTROL,
3389                            GEN6_RP_MEDIA_TURBO |
3390                            GEN6_RP_MEDIA_HW_NORMAL_MODE |
3391                            GEN6_RP_MEDIA_IS_GFX |
3392                            GEN6_RP_ENABLE |
3393                            GEN6_RP_UP_BUSY_AVG |
3394                            GEN6_RP_DOWN_IDLE_AVG);
3395                 break;
3396
3397         case BETWEEN:
3398                 /* Upclock if more than 90% busy over 13ms */
3399                 I915_WRITE(GEN6_RP_UP_EI, 10250);
3400                 I915_WRITE(GEN6_RP_UP_THRESHOLD, 9225);
3401
3402                 /* Downclock if less than 75% busy over 32ms */
3403                 I915_WRITE(GEN6_RP_DOWN_EI, 25000);
3404                 I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 18750);
3405
3406                 I915_WRITE(GEN6_RP_CONTROL,
3407                            GEN6_RP_MEDIA_TURBO |
3408                            GEN6_RP_MEDIA_HW_NORMAL_MODE |
3409                            GEN6_RP_MEDIA_IS_GFX |
3410                            GEN6_RP_ENABLE |
3411                            GEN6_RP_UP_BUSY_AVG |
3412                            GEN6_RP_DOWN_IDLE_AVG);
3413                 break;
3414
3415         case HIGH_POWER:
3416                 /* Upclock if more than 85% busy over 10ms */
3417                 I915_WRITE(GEN6_RP_UP_EI, 8000);
3418                 I915_WRITE(GEN6_RP_UP_THRESHOLD, 6800);
3419
3420                 /* Downclock if less than 60% busy over 32ms */
3421                 I915_WRITE(GEN6_RP_DOWN_EI, 25000);
3422                 I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 15000);
3423
3424                 I915_WRITE(GEN6_RP_CONTROL,
3425                            GEN6_RP_MEDIA_TURBO |
3426                            GEN6_RP_MEDIA_HW_NORMAL_MODE |
3427                            GEN6_RP_MEDIA_IS_GFX |
3428                            GEN6_RP_ENABLE |
3429                            GEN6_RP_UP_BUSY_AVG |
3430                            GEN6_RP_DOWN_IDLE_AVG);
3431                 break;
3432         }
3433
3434         dev_priv->rps.power = new_power;
3435         dev_priv->rps.last_adj = 0;
3436 }
3437
3438 void gen6_set_rps(struct drm_device *dev, u8 val)
3439 {
3440         struct drm_i915_private *dev_priv = dev->dev_private;
3441         u32 limits = gen6_rps_limits(dev_priv, &val);
3442
3443         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3444         WARN_ON(val > dev_priv->rps.max_delay);
3445         WARN_ON(val < dev_priv->rps.min_delay);
3446
3447         if (val == dev_priv->rps.cur_delay)
3448                 return;
3449
3450         gen6_set_rps_thresholds(dev_priv, val);
3451
3452         if (IS_HASWELL(dev))
3453                 I915_WRITE(GEN6_RPNSWREQ,
3454                            HSW_FREQUENCY(val));
3455         else
3456                 I915_WRITE(GEN6_RPNSWREQ,
3457                            GEN6_FREQUENCY(val) |
3458                            GEN6_OFFSET(0) |
3459                            GEN6_AGGRESSIVE_TURBO);
3460
3461         /* Make sure we continue to get interrupts
3462          * until we hit the minimum or maximum frequencies.
3463          */
3464         I915_WRITE(GEN6_RP_INTERRUPT_LIMITS, limits);
3465
3466         POSTING_READ(GEN6_RPNSWREQ);
3467
3468         dev_priv->rps.cur_delay = val;
3469
3470         trace_intel_gpu_freq_change(val * 50);
3471 }
3472
3473 void gen6_rps_idle(struct drm_i915_private *dev_priv)
3474 {
3475         mutex_lock(&dev_priv->rps.hw_lock);
3476         if (dev_priv->rps.enabled) {
3477                 if (dev_priv->info->is_valleyview)
3478                         valleyview_set_rps(dev_priv->dev, dev_priv->rps.min_delay);
3479                 else
3480                         gen6_set_rps(dev_priv->dev, dev_priv->rps.min_delay);
3481                 dev_priv->rps.last_adj = 0;
3482         }
3483         mutex_unlock(&dev_priv->rps.hw_lock);
3484 }
3485
3486 void gen6_rps_boost(struct drm_i915_private *dev_priv)
3487 {
3488         mutex_lock(&dev_priv->rps.hw_lock);
3489         if (dev_priv->rps.enabled) {
3490                 if (dev_priv->info->is_valleyview)
3491                         valleyview_set_rps(dev_priv->dev, dev_priv->rps.max_delay);
3492                 else
3493                         gen6_set_rps(dev_priv->dev, dev_priv->rps.max_delay);
3494                 dev_priv->rps.last_adj = 0;
3495         }
3496         mutex_unlock(&dev_priv->rps.hw_lock);
3497 }
3498
3499 /*
3500  * Wait until the previous freq change has completed,
3501  * or the timeout elapsed, and then update our notion
3502  * of the current GPU frequency.
3503  */
3504 static void vlv_update_rps_cur_delay(struct drm_i915_private *dev_priv)
3505 {
3506         u32 pval;
3507
3508         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3509
3510         if (wait_for(((pval = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS)) & GENFREQSTATUS) == 0, 10))
3511                 DRM_DEBUG_DRIVER("timed out waiting for Punit\n");
3512
3513         pval >>= 8;
3514
3515         if (pval != dev_priv->rps.cur_delay)
3516                 DRM_DEBUG_DRIVER("Punit overrode GPU freq: %d MHz (%u) requested, but got %d Mhz (%u)\n",
3517                                  vlv_gpu_freq(dev_priv->mem_freq, dev_priv->rps.cur_delay),
3518                                  dev_priv->rps.cur_delay,
3519                                  vlv_gpu_freq(dev_priv->mem_freq, pval), pval);
3520
3521         dev_priv->rps.cur_delay = pval;
3522 }
3523
3524 void valleyview_set_rps(struct drm_device *dev, u8 val)
3525 {
3526         struct drm_i915_private *dev_priv = dev->dev_private;
3527
3528         gen6_rps_limits(dev_priv, &val);
3529
3530         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3531         WARN_ON(val > dev_priv->rps.max_delay);
3532         WARN_ON(val < dev_priv->rps.min_delay);
3533
3534         vlv_update_rps_cur_delay(dev_priv);
3535
3536         DRM_DEBUG_DRIVER("GPU freq request from %d MHz (%u) to %d MHz (%u)\n",
3537                          vlv_gpu_freq(dev_priv->mem_freq,
3538                                       dev_priv->rps.cur_delay),
3539                          dev_priv->rps.cur_delay,
3540                          vlv_gpu_freq(dev_priv->mem_freq, val), val);
3541
3542         if (val == dev_priv->rps.cur_delay)
3543                 return;
3544
3545         vlv_punit_write(dev_priv, PUNIT_REG_GPU_FREQ_REQ, val);
3546
3547         dev_priv->rps.cur_delay = val;
3548
3549         trace_intel_gpu_freq_change(vlv_gpu_freq(dev_priv->mem_freq, val));
3550 }
3551
3552 static void gen6_disable_rps_interrupts(struct drm_device *dev)
3553 {
3554         struct drm_i915_private *dev_priv = dev->dev_private;
3555
3556         I915_WRITE(GEN6_PMINTRMSK, 0xffffffff);
3557         I915_WRITE(GEN6_PMIER, I915_READ(GEN6_PMIER) & ~GEN6_PM_RPS_EVENTS);
3558         /* Complete PM interrupt masking here doesn't race with the rps work
3559          * item again unmasking PM interrupts because that is using a different
3560          * register (PMIMR) to mask PM interrupts. The only risk is in leaving
3561          * stale bits in PMIIR and PMIMR which gen6_enable_rps will clean up. */
3562
3563         spin_lock_irq(&dev_priv->irq_lock);
3564         dev_priv->rps.pm_iir = 0;
3565         spin_unlock_irq(&dev_priv->irq_lock);
3566
3567         I915_WRITE(GEN6_PMIIR, GEN6_PM_RPS_EVENTS);
3568 }
3569
3570 static void gen6_disable_rps(struct drm_device *dev)
3571 {
3572         struct drm_i915_private *dev_priv = dev->dev_private;
3573
3574         I915_WRITE(GEN6_RC_CONTROL, 0);
3575         I915_WRITE(GEN6_RPNSWREQ, 1 << 31);
3576
3577         gen6_disable_rps_interrupts(dev);
3578 }
3579
3580 static void valleyview_disable_rps(struct drm_device *dev)
3581 {
3582         struct drm_i915_private *dev_priv = dev->dev_private;
3583
3584         I915_WRITE(GEN6_RC_CONTROL, 0);
3585
3586         gen6_disable_rps_interrupts(dev);
3587
3588         if (dev_priv->vlv_pctx) {
3589                 drm_gem_object_unreference(&dev_priv->vlv_pctx->base);
3590                 dev_priv->vlv_pctx = NULL;
3591         }
3592 }
3593
3594 int intel_enable_rc6(const struct drm_device *dev)
3595 {
3596         /* No RC6 before Ironlake */
3597         if (INTEL_INFO(dev)->gen < 5)
3598                 return 0;
3599
3600         /* Respect the kernel parameter if it is set */
3601         if (i915_enable_rc6 >= 0)
3602                 return i915_enable_rc6;
3603
3604         /* Disable RC6 on Ironlake */
3605         if (INTEL_INFO(dev)->gen == 5)
3606                 return 0;
3607
3608         if (IS_HASWELL(dev)) {
3609                 DRM_DEBUG_DRIVER("Haswell: only RC6 available\n");
3610                 return INTEL_RC6_ENABLE;
3611         }
3612
3613         /* snb/ivb have more than one rc6 state. */
3614         if (INTEL_INFO(dev)->gen == 6) {
3615                 DRM_DEBUG_DRIVER("Sandybridge: deep RC6 disabled\n");
3616                 return INTEL_RC6_ENABLE;
3617         }
3618
3619         DRM_DEBUG_DRIVER("RC6 and deep RC6 enabled\n");
3620         return (INTEL_RC6_ENABLE | INTEL_RC6p_ENABLE);
3621 }
3622
3623 static void gen6_enable_rps_interrupts(struct drm_device *dev)
3624 {
3625         struct drm_i915_private *dev_priv = dev->dev_private;
3626         u32 enabled_intrs;
3627
3628         spin_lock_irq(&dev_priv->irq_lock);
3629         WARN_ON(dev_priv->rps.pm_iir);
3630         snb_enable_pm_irq(dev_priv, GEN6_PM_RPS_EVENTS);
3631         I915_WRITE(GEN6_PMIIR, GEN6_PM_RPS_EVENTS);
3632         spin_unlock_irq(&dev_priv->irq_lock);
3633
3634         /* only unmask PM interrupts we need. Mask all others. */
3635         enabled_intrs = GEN6_PM_RPS_EVENTS;
3636
3637         /* IVB and SNB hard hangs on looping batchbuffer
3638          * if GEN6_PM_UP_EI_EXPIRED is masked.
3639          */
3640         if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
3641                 enabled_intrs |= GEN6_PM_RP_UP_EI_EXPIRED;
3642
3643         I915_WRITE(GEN6_PMINTRMSK, ~enabled_intrs);
3644 }
3645
3646 static void gen6_enable_rps(struct drm_device *dev)
3647 {
3648         struct drm_i915_private *dev_priv = dev->dev_private;
3649         struct intel_ring_buffer *ring;
3650         u32 rp_state_cap;
3651         u32 gt_perf_status;
3652         u32 rc6vids, pcu_mbox, rc6_mask = 0;
3653         u32 gtfifodbg;
3654         int rc6_mode;
3655         int i, ret;
3656
3657         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3658
3659         /* Here begins a magic sequence of register writes to enable
3660          * auto-downclocking.
3661          *
3662          * Perhaps there might be some value in exposing these to
3663          * userspace...
3664          */
3665         I915_WRITE(GEN6_RC_STATE, 0);
3666
3667         /* Clear the DBG now so we don't confuse earlier errors */
3668         if ((gtfifodbg = I915_READ(GTFIFODBG))) {
3669                 DRM_ERROR("GT fifo had a previous error %x\n", gtfifodbg);
3670                 I915_WRITE(GTFIFODBG, gtfifodbg);
3671         }
3672
3673         gen6_gt_force_wake_get(dev_priv);
3674
3675         rp_state_cap = I915_READ(GEN6_RP_STATE_CAP);
3676         gt_perf_status = I915_READ(GEN6_GT_PERF_STATUS);
3677
3678         /* In units of 50MHz */
3679         dev_priv->rps.hw_max = dev_priv->rps.max_delay = rp_state_cap & 0xff;
3680         dev_priv->rps.min_delay = (rp_state_cap >> 16) & 0xff;
3681         dev_priv->rps.rp1_delay = (rp_state_cap >>  8) & 0xff;
3682         dev_priv->rps.rp0_delay = (rp_state_cap >>  0) & 0xff;
3683         dev_priv->rps.rpe_delay = dev_priv->rps.rp1_delay;
3684         dev_priv->rps.cur_delay = 0;
3685
3686         /* disable the counters and set deterministic thresholds */
3687         I915_WRITE(GEN6_RC_CONTROL, 0);
3688
3689         I915_WRITE(GEN6_RC1_WAKE_RATE_LIMIT, 1000 << 16);
3690         I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16 | 30);
3691         I915_WRITE(GEN6_RC6pp_WAKE_RATE_LIMIT, 30);
3692         I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
3693         I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
3694
3695         for_each_ring(ring, dev_priv, i)
3696                 I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
3697
3698         I915_WRITE(GEN6_RC_SLEEP, 0);
3699         I915_WRITE(GEN6_RC1e_THRESHOLD, 1000);
3700         if (INTEL_INFO(dev)->gen <= 6 || IS_IVYBRIDGE(dev))
3701                 I915_WRITE(GEN6_RC6_THRESHOLD, 125000);
3702         else
3703                 I915_WRITE(GEN6_RC6_THRESHOLD, 50000);
3704         I915_WRITE(GEN6_RC6p_THRESHOLD, 150000);
3705         I915_WRITE(GEN6_RC6pp_THRESHOLD, 64000); /* unused */
3706
3707         /* Check if we are enabling RC6 */
3708         rc6_mode = intel_enable_rc6(dev_priv->dev);
3709         if (rc6_mode & INTEL_RC6_ENABLE)
3710                 rc6_mask |= GEN6_RC_CTL_RC6_ENABLE;
3711
3712         /* We don't use those on Haswell */
3713         if (!IS_HASWELL(dev)) {
3714                 if (rc6_mode & INTEL_RC6p_ENABLE)
3715                         rc6_mask |= GEN6_RC_CTL_RC6p_ENABLE;
3716
3717                 if (rc6_mode & INTEL_RC6pp_ENABLE)
3718                         rc6_mask |= GEN6_RC_CTL_RC6pp_ENABLE;
3719         }
3720
3721         DRM_INFO("Enabling RC6 states: RC6 %s, RC6p %s, RC6pp %s\n",
3722                         (rc6_mask & GEN6_RC_CTL_RC6_ENABLE) ? "on" : "off",
3723                         (rc6_mask & GEN6_RC_CTL_RC6p_ENABLE) ? "on" : "off",
3724                         (rc6_mask & GEN6_RC_CTL_RC6pp_ENABLE) ? "on" : "off");
3725
3726         I915_WRITE(GEN6_RC_CONTROL,
3727                    rc6_mask |
3728                    GEN6_RC_CTL_EI_MODE(1) |
3729                    GEN6_RC_CTL_HW_ENABLE);
3730
3731         /* Power down if completely idle for over 50ms */
3732         I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 50000);
3733         I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
3734
3735         ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_MIN_FREQ_TABLE, 0);
3736         if (!ret) {
3737                 pcu_mbox = 0;
3738                 ret = sandybridge_pcode_read(dev_priv, GEN6_READ_OC_PARAMS, &pcu_mbox);
3739                 if (!ret && (pcu_mbox & (1<<31))) { /* OC supported */
3740                         DRM_DEBUG_DRIVER("Overclocking supported. Max: %dMHz, Overclock max: %dMHz\n",
3741                                          (dev_priv->rps.max_delay & 0xff) * 50,
3742                                          (pcu_mbox & 0xff) * 50);
3743                         dev_priv->rps.hw_max = pcu_mbox & 0xff;
3744                 }
3745         } else {
3746                 DRM_DEBUG_DRIVER("Failed to set the min frequency\n");
3747         }
3748
3749         dev_priv->rps.power = HIGH_POWER; /* force a reset */
3750         gen6_set_rps(dev_priv->dev, dev_priv->rps.min_delay);
3751
3752         gen6_enable_rps_interrupts(dev);
3753
3754         rc6vids = 0;
3755         ret = sandybridge_pcode_read(dev_priv, GEN6_PCODE_READ_RC6VIDS, &rc6vids);
3756         if (IS_GEN6(dev) && ret) {
3757                 DRM_DEBUG_DRIVER("Couldn't check for BIOS workaround\n");
3758         } else if (IS_GEN6(dev) && (GEN6_DECODE_RC6_VID(rc6vids & 0xff) < 450)) {
3759                 DRM_DEBUG_DRIVER("You should update your BIOS. Correcting minimum rc6 voltage (%dmV->%dmV)\n",
3760                           GEN6_DECODE_RC6_VID(rc6vids & 0xff), 450);
3761                 rc6vids &= 0xffff00;
3762                 rc6vids |= GEN6_ENCODE_RC6_VID(450);
3763                 ret = sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_RC6VIDS, rc6vids);
3764                 if (ret)
3765                         DRM_ERROR("Couldn't fix incorrect rc6 voltage\n");
3766         }
3767
3768         gen6_gt_force_wake_put(dev_priv);
3769 }
3770
3771 void gen6_update_ring_freq(struct drm_device *dev)
3772 {
3773         struct drm_i915_private *dev_priv = dev->dev_private;
3774         int min_freq = 15;
3775         unsigned int gpu_freq;
3776         unsigned int max_ia_freq, min_ring_freq;
3777         int scaling_factor = 180;
3778         struct cpufreq_policy *policy;
3779
3780         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3781
3782         policy = cpufreq_cpu_get(0);
3783         if (policy) {
3784                 max_ia_freq = policy->cpuinfo.max_freq;
3785                 cpufreq_cpu_put(policy);
3786         } else {
3787                 /*
3788                  * Default to measured freq if none found, PCU will ensure we
3789                  * don't go over
3790                  */
3791                 max_ia_freq = tsc_khz;
3792         }
3793
3794         /* Convert from kHz to MHz */
3795         max_ia_freq /= 1000;
3796
3797         min_ring_freq = I915_READ(MCHBAR_MIRROR_BASE_SNB + DCLK) & 0xf;
3798         /* convert DDR frequency from units of 266.6MHz to bandwidth */
3799         min_ring_freq = mult_frac(min_ring_freq, 8, 3);
3800
3801         /*
3802          * For each potential GPU frequency, load a ring frequency we'd like
3803          * to use for memory access.  We do this by specifying the IA frequency
3804          * the PCU should use as a reference to determine the ring frequency.
3805          */
3806         for (gpu_freq = dev_priv->rps.max_delay; gpu_freq >= dev_priv->rps.min_delay;
3807              gpu_freq--) {
3808                 int diff = dev_priv->rps.max_delay - gpu_freq;
3809                 unsigned int ia_freq = 0, ring_freq = 0;
3810
3811                 if (IS_HASWELL(dev)) {
3812                         ring_freq = mult_frac(gpu_freq, 5, 4);
3813                         ring_freq = max(min_ring_freq, ring_freq);
3814                         /* leave ia_freq as the default, chosen by cpufreq */
3815                 } else {
3816                         /* On older processors, there is no separate ring
3817                          * clock domain, so in order to boost the bandwidth
3818                          * of the ring, we need to upclock the CPU (ia_freq).
3819                          *
3820                          * For GPU frequencies less than 750MHz,
3821                          * just use the lowest ring freq.
3822                          */
3823                         if (gpu_freq < min_freq)
3824                                 ia_freq = 800;
3825                         else
3826                                 ia_freq = max_ia_freq - ((diff * scaling_factor) / 2);
3827                         ia_freq = DIV_ROUND_CLOSEST(ia_freq, 100);
3828                 }
3829
3830                 sandybridge_pcode_write(dev_priv,
3831                                         GEN6_PCODE_WRITE_MIN_FREQ_TABLE,
3832                                         ia_freq << GEN6_PCODE_FREQ_IA_RATIO_SHIFT |
3833                                         ring_freq << GEN6_PCODE_FREQ_RING_RATIO_SHIFT |
3834                                         gpu_freq);
3835         }
3836 }
3837
3838 int valleyview_rps_max_freq(struct drm_i915_private *dev_priv)
3839 {
3840         u32 val, rp0;
3841
3842         val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FREQ_FUSE);
3843
3844         rp0 = (val & FB_GFX_MAX_FREQ_FUSE_MASK) >> FB_GFX_MAX_FREQ_FUSE_SHIFT;
3845         /* Clamp to max */
3846         rp0 = min_t(u32, rp0, 0xea);
3847
3848         return rp0;
3849 }
3850
3851 static int valleyview_rps_rpe_freq(struct drm_i915_private *dev_priv)
3852 {
3853         u32 val, rpe;
3854
3855         val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_LO);
3856         rpe = (val & FB_FMAX_VMIN_FREQ_LO_MASK) >> FB_FMAX_VMIN_FREQ_LO_SHIFT;
3857         val = vlv_nc_read(dev_priv, IOSF_NC_FB_GFX_FMAX_FUSE_HI);
3858         rpe |= (val & FB_FMAX_VMIN_FREQ_HI_MASK) << 5;
3859
3860         return rpe;
3861 }
3862
3863 int valleyview_rps_min_freq(struct drm_i915_private *dev_priv)
3864 {
3865         return vlv_punit_read(dev_priv, PUNIT_REG_GPU_LFM) & 0xff;
3866 }
3867
3868 static void valleyview_setup_pctx(struct drm_device *dev)
3869 {
3870         struct drm_i915_private *dev_priv = dev->dev_private;
3871         struct drm_i915_gem_object *pctx;
3872         unsigned long pctx_paddr;
3873         u32 pcbr;
3874         int pctx_size = 24*1024;
3875
3876         pcbr = I915_READ(VLV_PCBR);
3877         if (pcbr) {
3878                 /* BIOS set it up already, grab the pre-alloc'd space */
3879                 int pcbr_offset;
3880
3881                 pcbr_offset = (pcbr & (~4095)) - dev_priv->mm.stolen_base;
3882                 pctx = i915_gem_object_create_stolen_for_preallocated(dev_priv->dev,
3883                                                                       pcbr_offset,
3884                                                                       I915_GTT_OFFSET_NONE,
3885                                                                       pctx_size);
3886                 goto out;
3887         }
3888
3889         /*
3890          * From the Gunit register HAS:
3891          * The Gfx driver is expected to program this register and ensure
3892          * proper allocation within Gfx stolen memory.  For example, this
3893          * register should be programmed such than the PCBR range does not
3894          * overlap with other ranges, such as the frame buffer, protected
3895          * memory, or any other relevant ranges.
3896          */
3897         pctx = i915_gem_object_create_stolen(dev, pctx_size);
3898         if (!pctx) {
3899                 DRM_DEBUG("not enough stolen space for PCTX, disabling\n");
3900                 return;
3901         }
3902
3903         pctx_paddr = dev_priv->mm.stolen_base + pctx->stolen->start;
3904         I915_WRITE(VLV_PCBR, pctx_paddr);
3905
3906 out:
3907         dev_priv->vlv_pctx = pctx;
3908 }
3909
3910 static void valleyview_enable_rps(struct drm_device *dev)
3911 {
3912         struct drm_i915_private *dev_priv = dev->dev_private;
3913         struct intel_ring_buffer *ring;
3914         u32 gtfifodbg, val, rc6_mode = 0;
3915         int i;
3916
3917         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
3918
3919         if ((gtfifodbg = I915_READ(GTFIFODBG))) {
3920                 DRM_DEBUG_DRIVER("GT fifo had a previous error %x\n",
3921                                  gtfifodbg);
3922                 I915_WRITE(GTFIFODBG, gtfifodbg);
3923         }
3924
3925         valleyview_setup_pctx(dev);
3926
3927         gen6_gt_force_wake_get(dev_priv);
3928
3929         I915_WRITE(GEN6_RP_UP_THRESHOLD, 59400);
3930         I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 245000);
3931         I915_WRITE(GEN6_RP_UP_EI, 66000);
3932         I915_WRITE(GEN6_RP_DOWN_EI, 350000);
3933
3934         I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
3935
3936         I915_WRITE(GEN6_RP_CONTROL,
3937                    GEN6_RP_MEDIA_TURBO |
3938                    GEN6_RP_MEDIA_HW_NORMAL_MODE |
3939                    GEN6_RP_MEDIA_IS_GFX |
3940                    GEN6_RP_ENABLE |
3941                    GEN6_RP_UP_BUSY_AVG |
3942                    GEN6_RP_DOWN_IDLE_CONT);
3943
3944         I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 0x00280000);
3945         I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
3946         I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
3947
3948         for_each_ring(ring, dev_priv, i)
3949                 I915_WRITE(RING_MAX_IDLE(ring->mmio_base), 10);
3950
3951         I915_WRITE(GEN6_RC6_THRESHOLD, 0xc350);
3952
3953         /* allows RC6 residency counter to work */
3954         I915_WRITE(VLV_COUNTER_CONTROL,
3955                    _MASKED_BIT_ENABLE(VLV_COUNT_RANGE_HIGH |
3956                                       VLV_MEDIA_RC6_COUNT_EN |
3957                                       VLV_RENDER_RC6_COUNT_EN));
3958         if (intel_enable_rc6(dev) & INTEL_RC6_ENABLE)
3959                 rc6_mode = GEN7_RC_CTL_TO_MODE;
3960         I915_WRITE(GEN6_RC_CONTROL, rc6_mode);
3961
3962         val = vlv_punit_read(dev_priv, PUNIT_REG_GPU_FREQ_STS);
3963         switch ((val >> 6) & 3) {
3964         case 0:
3965         case 1:
3966                 dev_priv->mem_freq = 800;
3967                 break;
3968         case 2:
3969                 dev_priv->mem_freq = 1066;
3970                 break;
3971         case 3:
3972                 dev_priv->mem_freq = 1333;
3973                 break;
3974         }
3975         DRM_DEBUG_DRIVER("DDR speed: %d MHz", dev_priv->mem_freq);
3976
3977         DRM_DEBUG_DRIVER("GPLL enabled? %s\n", val & 0x10 ? "yes" : "no");
3978         DRM_DEBUG_DRIVER("GPU status: 0x%08x\n", val);
3979
3980         dev_priv->rps.cur_delay = (val >> 8) & 0xff;
3981         DRM_DEBUG_DRIVER("current GPU freq: %d MHz (%u)\n",
3982                          vlv_gpu_freq(dev_priv->mem_freq,
3983                                       dev_priv->rps.cur_delay),
3984                          dev_priv->rps.cur_delay);
3985
3986         dev_priv->rps.max_delay = valleyview_rps_max_freq(dev_priv);
3987         dev_priv->rps.hw_max = dev_priv->rps.max_delay;
3988         DRM_DEBUG_DRIVER("max GPU freq: %d MHz (%u)\n",
3989                          vlv_gpu_freq(dev_priv->mem_freq,
3990                                       dev_priv->rps.max_delay),
3991                          dev_priv->rps.max_delay);
3992
3993         dev_priv->rps.rpe_delay = valleyview_rps_rpe_freq(dev_priv);
3994         DRM_DEBUG_DRIVER("RPe GPU freq: %d MHz (%u)\n",
3995                          vlv_gpu_freq(dev_priv->mem_freq,
3996                                       dev_priv->rps.rpe_delay),
3997                          dev_priv->rps.rpe_delay);
3998
3999         dev_priv->rps.min_delay = valleyview_rps_min_freq(dev_priv);
4000         DRM_DEBUG_DRIVER("min GPU freq: %d MHz (%u)\n",
4001                          vlv_gpu_freq(dev_priv->mem_freq,
4002                                       dev_priv->rps.min_delay),
4003                          dev_priv->rps.min_delay);
4004
4005         DRM_DEBUG_DRIVER("setting GPU freq to %d MHz (%u)\n",
4006                          vlv_gpu_freq(dev_priv->mem_freq,
4007                                       dev_priv->rps.rpe_delay),
4008                          dev_priv->rps.rpe_delay);
4009
4010         valleyview_set_rps(dev_priv->dev, dev_priv->rps.rpe_delay);
4011
4012         gen6_enable_rps_interrupts(dev);
4013
4014         gen6_gt_force_wake_put(dev_priv);
4015 }
4016
4017 void ironlake_teardown_rc6(struct drm_device *dev)
4018 {
4019         struct drm_i915_private *dev_priv = dev->dev_private;
4020
4021         if (dev_priv->ips.renderctx) {
4022                 i915_gem_object_unpin(dev_priv->ips.renderctx);
4023                 drm_gem_object_unreference(&dev_priv->ips.renderctx->base);
4024                 dev_priv->ips.renderctx = NULL;
4025         }
4026
4027         if (dev_priv->ips.pwrctx) {
4028                 i915_gem_object_unpin(dev_priv->ips.pwrctx);
4029                 drm_gem_object_unreference(&dev_priv->ips.pwrctx->base);
4030                 dev_priv->ips.pwrctx = NULL;
4031         }
4032 }
4033
4034 static void ironlake_disable_rc6(struct drm_device *dev)
4035 {
4036         struct drm_i915_private *dev_priv = dev->dev_private;
4037
4038         if (I915_READ(PWRCTXA)) {
4039                 /* Wake the GPU, prevent RC6, then restore RSTDBYCTL */
4040                 I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) | RCX_SW_EXIT);
4041                 wait_for(((I915_READ(RSTDBYCTL) & RSX_STATUS_MASK) == RSX_STATUS_ON),
4042                          50);
4043
4044                 I915_WRITE(PWRCTXA, 0);
4045                 POSTING_READ(PWRCTXA);
4046
4047                 I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) & ~RCX_SW_EXIT);
4048                 POSTING_READ(RSTDBYCTL);
4049         }
4050 }
4051
4052 static int ironlake_setup_rc6(struct drm_device *dev)
4053 {
4054         struct drm_i915_private *dev_priv = dev->dev_private;
4055
4056         if (dev_priv->ips.renderctx == NULL)
4057                 dev_priv->ips.renderctx = intel_alloc_context_page(dev);
4058         if (!dev_priv->ips.renderctx)
4059                 return -ENOMEM;
4060
4061         if (dev_priv->ips.pwrctx == NULL)
4062                 dev_priv->ips.pwrctx = intel_alloc_context_page(dev);
4063         if (!dev_priv->ips.pwrctx) {
4064                 ironlake_teardown_rc6(dev);
4065                 return -ENOMEM;
4066         }
4067
4068         return 0;
4069 }
4070
4071 static void ironlake_enable_rc6(struct drm_device *dev)
4072 {
4073         struct drm_i915_private *dev_priv = dev->dev_private;
4074         struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
4075         bool was_interruptible;
4076         int ret;
4077
4078         /* rc6 disabled by default due to repeated reports of hanging during
4079          * boot and resume.
4080          */
4081         if (!intel_enable_rc6(dev))
4082                 return;
4083
4084         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
4085
4086         ret = ironlake_setup_rc6(dev);
4087         if (ret)
4088                 return;
4089
4090         was_interruptible = dev_priv->mm.interruptible;
4091         dev_priv->mm.interruptible = false;
4092
4093         /*
4094          * GPU can automatically power down the render unit if given a page
4095          * to save state.
4096          */
4097         ret = intel_ring_begin(ring, 6);
4098         if (ret) {
4099                 ironlake_teardown_rc6(dev);
4100                 dev_priv->mm.interruptible = was_interruptible;
4101                 return;
4102         }
4103
4104         intel_ring_emit(ring, MI_SUSPEND_FLUSH | MI_SUSPEND_FLUSH_EN);
4105         intel_ring_emit(ring, MI_SET_CONTEXT);
4106         intel_ring_emit(ring, i915_gem_obj_ggtt_offset(dev_priv->ips.renderctx) |
4107                         MI_MM_SPACE_GTT |
4108                         MI_SAVE_EXT_STATE_EN |
4109                         MI_RESTORE_EXT_STATE_EN |
4110                         MI_RESTORE_INHIBIT);
4111         intel_ring_emit(ring, MI_SUSPEND_FLUSH);
4112         intel_ring_emit(ring, MI_NOOP);
4113         intel_ring_emit(ring, MI_FLUSH);
4114         intel_ring_advance(ring);
4115
4116         /*
4117          * Wait for the command parser to advance past MI_SET_CONTEXT. The HW
4118          * does an implicit flush, combined with MI_FLUSH above, it should be
4119          * safe to assume that renderctx is valid
4120          */
4121         ret = intel_ring_idle(ring);
4122         dev_priv->mm.interruptible = was_interruptible;
4123         if (ret) {
4124                 DRM_ERROR("failed to enable ironlake power savings\n");
4125                 ironlake_teardown_rc6(dev);
4126                 return;
4127         }
4128
4129         I915_WRITE(PWRCTXA, i915_gem_obj_ggtt_offset(dev_priv->ips.pwrctx) | PWRCTX_EN);
4130         I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) & ~RCX_SW_EXIT);
4131 }
4132
4133 static unsigned long intel_pxfreq(u32 vidfreq)
4134 {
4135         unsigned long freq;
4136         int div = (vidfreq & 0x3f0000) >> 16;
4137         int post = (vidfreq & 0x3000) >> 12;
4138         int pre = (vidfreq & 0x7);
4139
4140         if (!pre)
4141                 return 0;
4142
4143         freq = ((div * 133333) / ((1<<post) * pre));
4144
4145         return freq;
4146 }
4147
4148 static const struct cparams {
4149         u16 i;
4150         u16 t;
4151         u16 m;
4152         u16 c;
4153 } cparams[] = {
4154         { 1, 1333, 301, 28664 },
4155         { 1, 1066, 294, 24460 },
4156         { 1, 800, 294, 25192 },
4157         { 0, 1333, 276, 27605 },
4158         { 0, 1066, 276, 27605 },
4159         { 0, 800, 231, 23784 },
4160 };
4161
4162 static unsigned long __i915_chipset_val(struct drm_i915_private *dev_priv)
4163 {
4164         u64 total_count, diff, ret;
4165         u32 count1, count2, count3, m = 0, c = 0;
4166         unsigned long now = jiffies_to_msecs(jiffies), diff1;
4167         int i;
4168
4169         assert_spin_locked(&mchdev_lock);
4170
4171         diff1 = now - dev_priv->ips.last_time1;
4172
4173         /* Prevent division-by-zero if we are asking too fast.
4174          * Also, we don't get interesting results if we are polling
4175          * faster than once in 10ms, so just return the saved value
4176          * in such cases.
4177          */
4178         if (diff1 <= 10)
4179                 return dev_priv->ips.chipset_power;
4180
4181         count1 = I915_READ(DMIEC);
4182         count2 = I915_READ(DDREC);
4183         count3 = I915_READ(CSIEC);
4184
4185         total_count = count1 + count2 + count3;
4186
4187         /* FIXME: handle per-counter overflow */
4188         if (total_count < dev_priv->ips.last_count1) {
4189                 diff = ~0UL - dev_priv->ips.last_count1;
4190                 diff += total_count;
4191         } else {
4192                 diff = total_count - dev_priv->ips.last_count1;
4193         }
4194
4195         for (i = 0; i < ARRAY_SIZE(cparams); i++) {
4196                 if (cparams[i].i == dev_priv->ips.c_m &&
4197                     cparams[i].t == dev_priv->ips.r_t) {
4198                         m = cparams[i].m;
4199                         c = cparams[i].c;
4200                         break;
4201                 }
4202         }
4203
4204         diff = div_u64(diff, diff1);
4205         ret = ((m * diff) + c);
4206         ret = div_u64(ret, 10);
4207
4208         dev_priv->ips.last_count1 = total_count;
4209         dev_priv->ips.last_time1 = now;
4210
4211         dev_priv->ips.chipset_power = ret;
4212
4213         return ret;
4214 }
4215
4216 unsigned long i915_chipset_val(struct drm_i915_private *dev_priv)
4217 {
4218         unsigned long val;
4219
4220         if (dev_priv->info->gen != 5)
4221                 return 0;
4222
4223         spin_lock_irq(&mchdev_lock);
4224
4225         val = __i915_chipset_val(dev_priv);
4226
4227         spin_unlock_irq(&mchdev_lock);
4228
4229         return val;
4230 }
4231
4232 unsigned long i915_mch_val(struct drm_i915_private *dev_priv)
4233 {
4234         unsigned long m, x, b;
4235         u32 tsfs;
4236
4237         tsfs = I915_READ(TSFS);
4238
4239         m = ((tsfs & TSFS_SLOPE_MASK) >> TSFS_SLOPE_SHIFT);
4240         x = I915_READ8(TR1);
4241
4242         b = tsfs & TSFS_INTR_MASK;
4243
4244         return ((m * x) / 127) - b;
4245 }
4246
4247 static u16 pvid_to_extvid(struct drm_i915_private *dev_priv, u8 pxvid)
4248 {
4249         static const struct v_table {
4250                 u16 vd; /* in .1 mil */
4251                 u16 vm; /* in .1 mil */
4252         } v_table[] = {
4253                 { 0, 0, },
4254                 { 375, 0, },
4255                 { 500, 0, },
4256                 { 625, 0, },
4257                 { 750, 0, },
4258                 { 875, 0, },
4259                 { 1000, 0, },
4260                 { 1125, 0, },
4261                 { 4125, 3000, },
4262                 { 4125, 3000, },
4263                 { 4125, 3000, },
4264                 { 4125, 3000, },
4265                 { 4125, 3000, },
4266                 { 4125, 3000, },
4267                 { 4125, 3000, },
4268                 { 4125, 3000, },
4269                 { 4125, 3000, },
4270                 { 4125, 3000, },
4271                 { 4125, 3000, },
4272                 { 4125, 3000, },
4273                 { 4125, 3000, },
4274                 { 4125, 3000, },
4275                 { 4125, 3000, },
4276                 { 4125, 3000, },
4277                 { 4125, 3000, },
4278                 { 4125, 3000, },
4279                 { 4125, 3000, },
4280                 { 4125, 3000, },
4281                 { 4125, 3000, },
4282                 { 4125, 3000, },
4283                 { 4125, 3000, },
4284                 { 4125, 3000, },
4285                 { 4250, 3125, },
4286                 { 4375, 3250, },
4287                 { 4500, 3375, },
4288                 { 4625, 3500, },
4289                 { 4750, 3625, },
4290                 { 4875, 3750, },
4291                 { 5000, 3875, },
4292                 { 5125, 4000, },
4293                 { 5250, 4125, },
4294                 { 5375, 4250, },
4295                 { 5500, 4375, },
4296                 { 5625, 4500, },
4297                 { 5750, 4625, },
4298                 { 5875, 4750, },
4299                 { 6000, 4875, },
4300                 { 6125, 5000, },
4301                 { 6250, 5125, },
4302                 { 6375, 5250, },
4303                 { 6500, 5375, },
4304                 { 6625, 5500, },
4305                 { 6750, 5625, },
4306                 { 6875, 5750, },
4307                 { 7000, 5875, },
4308                 { 7125, 6000, },
4309                 { 7250, 6125, },
4310                 { 7375, 6250, },
4311                 { 7500, 6375, },
4312                 { 7625, 6500, },
4313                 { 7750, 6625, },
4314                 { 7875, 6750, },
4315                 { 8000, 6875, },
4316                 { 8125, 7000, },
4317                 { 8250, 7125, },
4318                 { 8375, 7250, },
4319                 { 8500, 7375, },
4320                 { 8625, 7500, },
4321                 { 8750, 7625, },
4322                 { 8875, 7750, },
4323                 { 9000, 7875, },
4324                 { 9125, 8000, },
4325                 { 9250, 8125, },
4326                 { 9375, 8250, },
4327                 { 9500, 8375, },
4328                 { 9625, 8500, },
4329                 { 9750, 8625, },
4330                 { 9875, 8750, },
4331                 { 10000, 8875, },
4332                 { 10125, 9000, },
4333                 { 10250, 9125, },
4334                 { 10375, 9250, },
4335                 { 10500, 9375, },
4336                 { 10625, 9500, },
4337                 { 10750, 9625, },
4338                 { 10875, 9750, },
4339                 { 11000, 9875, },
4340                 { 11125, 10000, },
4341                 { 11250, 10125, },
4342                 { 11375, 10250, },
4343                 { 11500, 10375, },
4344                 { 11625, 10500, },
4345                 { 11750, 10625, },
4346                 { 11875, 10750, },
4347                 { 12000, 10875, },
4348                 { 12125, 11000, },
4349                 { 12250, 11125, },
4350                 { 12375, 11250, },
4351                 { 12500, 11375, },
4352                 { 12625, 11500, },
4353                 { 12750, 11625, },
4354                 { 12875, 11750, },
4355                 { 13000, 11875, },
4356                 { 13125, 12000, },
4357                 { 13250, 12125, },
4358                 { 13375, 12250, },
4359                 { 13500, 12375, },
4360                 { 13625, 12500, },
4361                 { 13750, 12625, },
4362                 { 13875, 12750, },
4363                 { 14000, 12875, },
4364                 { 14125, 13000, },
4365                 { 14250, 13125, },
4366                 { 14375, 13250, },
4367                 { 14500, 13375, },
4368                 { 14625, 13500, },
4369                 { 14750, 13625, },
4370                 { 14875, 13750, },
4371                 { 15000, 13875, },
4372                 { 15125, 14000, },
4373                 { 15250, 14125, },
4374                 { 15375, 14250, },
4375                 { 15500, 14375, },
4376                 { 15625, 14500, },
4377                 { 15750, 14625, },
4378                 { 15875, 14750, },
4379                 { 16000, 14875, },
4380                 { 16125, 15000, },
4381         };
4382         if (dev_priv->info->is_mobile)
4383                 return v_table[pxvid].vm;
4384         else
4385                 return v_table[pxvid].vd;
4386 }
4387
4388 static void __i915_update_gfx_val(struct drm_i915_private *dev_priv)
4389 {
4390         struct timespec now, diff1;
4391         u64 diff;
4392         unsigned long diffms;
4393         u32 count;
4394
4395         assert_spin_locked(&mchdev_lock);
4396
4397         getrawmonotonic(&now);
4398         diff1 = timespec_sub(now, dev_priv->ips.last_time2);
4399
4400         /* Don't divide by 0 */
4401         diffms = diff1.tv_sec * 1000 + diff1.tv_nsec / 1000000;
4402         if (!diffms)
4403                 return;
4404
4405         count = I915_READ(GFXEC);
4406
4407         if (count < dev_priv->ips.last_count2) {
4408                 diff = ~0UL - dev_priv->ips.last_count2;
4409                 diff += count;
4410         } else {
4411                 diff = count - dev_priv->ips.last_count2;
4412         }
4413
4414         dev_priv->ips.last_count2 = count;
4415         dev_priv->ips.last_time2 = now;
4416
4417         /* More magic constants... */
4418         diff = diff * 1181;
4419         diff = div_u64(diff, diffms * 10);
4420         dev_priv->ips.gfx_power = diff;
4421 }
4422
4423 void i915_update_gfx_val(struct drm_i915_private *dev_priv)
4424 {
4425         if (dev_priv->info->gen != 5)
4426                 return;
4427
4428         spin_lock_irq(&mchdev_lock);
4429
4430         __i915_update_gfx_val(dev_priv);
4431
4432         spin_unlock_irq(&mchdev_lock);
4433 }
4434
4435 static unsigned long __i915_gfx_val(struct drm_i915_private *dev_priv)
4436 {
4437         unsigned long t, corr, state1, corr2, state2;
4438         u32 pxvid, ext_v;
4439
4440         assert_spin_locked(&mchdev_lock);
4441
4442         pxvid = I915_READ(PXVFREQ_BASE + (dev_priv->rps.cur_delay * 4));
4443         pxvid = (pxvid >> 24) & 0x7f;
4444         ext_v = pvid_to_extvid(dev_priv, pxvid);
4445
4446         state1 = ext_v;
4447
4448         t = i915_mch_val(dev_priv);
4449
4450         /* Revel in the empirically derived constants */
4451
4452         /* Correction factor in 1/100000 units */
4453         if (t > 80)
4454                 corr = ((t * 2349) + 135940);
4455         else if (t >= 50)
4456                 corr = ((t * 964) + 29317);
4457         else /* < 50 */
4458                 corr = ((t * 301) + 1004);
4459
4460         corr = corr * ((150142 * state1) / 10000 - 78642);
4461         corr /= 100000;
4462         corr2 = (corr * dev_priv->ips.corr);
4463
4464         state2 = (corr2 * state1) / 10000;
4465         state2 /= 100; /* convert to mW */
4466
4467         __i915_update_gfx_val(dev_priv);
4468
4469         return dev_priv->ips.gfx_power + state2;
4470 }
4471
4472 unsigned long i915_gfx_val(struct drm_i915_private *dev_priv)
4473 {
4474         unsigned long val;
4475
4476         if (dev_priv->info->gen != 5)
4477                 return 0;
4478
4479         spin_lock_irq(&mchdev_lock);
4480
4481         val = __i915_gfx_val(dev_priv);
4482
4483         spin_unlock_irq(&mchdev_lock);
4484
4485         return val;
4486 }
4487
4488 /**
4489  * i915_read_mch_val - return value for IPS use
4490  *
4491  * Calculate and return a value for the IPS driver to use when deciding whether
4492  * we have thermal and power headroom to increase CPU or GPU power budget.
4493  */
4494 unsigned long i915_read_mch_val(void)
4495 {
4496         struct drm_i915_private *dev_priv;
4497         unsigned long chipset_val, graphics_val, ret = 0;
4498
4499         spin_lock_irq(&mchdev_lock);
4500         if (!i915_mch_dev)
4501                 goto out_unlock;
4502         dev_priv = i915_mch_dev;
4503
4504         chipset_val = __i915_chipset_val(dev_priv);
4505         graphics_val = __i915_gfx_val(dev_priv);
4506
4507         ret = chipset_val + graphics_val;
4508
4509 out_unlock:
4510         spin_unlock_irq(&mchdev_lock);
4511
4512         return ret;
4513 }
4514 EXPORT_SYMBOL_GPL(i915_read_mch_val);
4515
4516 /**
4517  * i915_gpu_raise - raise GPU frequency limit
4518  *
4519  * Raise the limit; IPS indicates we have thermal headroom.
4520  */
4521 bool i915_gpu_raise(void)
4522 {
4523         struct drm_i915_private *dev_priv;
4524         bool ret = true;
4525
4526         spin_lock_irq(&mchdev_lock);
4527         if (!i915_mch_dev) {
4528                 ret = false;
4529                 goto out_unlock;
4530         }
4531         dev_priv = i915_mch_dev;
4532
4533         if (dev_priv->ips.max_delay > dev_priv->ips.fmax)
4534                 dev_priv->ips.max_delay--;
4535
4536 out_unlock:
4537         spin_unlock_irq(&mchdev_lock);
4538
4539         return ret;
4540 }
4541 EXPORT_SYMBOL_GPL(i915_gpu_raise);
4542
4543 /**
4544  * i915_gpu_lower - lower GPU frequency limit
4545  *
4546  * IPS indicates we're close to a thermal limit, so throttle back the GPU
4547  * frequency maximum.
4548  */
4549 bool i915_gpu_lower(void)
4550 {
4551         struct drm_i915_private *dev_priv;
4552         bool ret = true;
4553
4554         spin_lock_irq(&mchdev_lock);
4555         if (!i915_mch_dev) {
4556                 ret = false;
4557                 goto out_unlock;
4558         }
4559         dev_priv = i915_mch_dev;
4560
4561         if (dev_priv->ips.max_delay < dev_priv->ips.min_delay)
4562                 dev_priv->ips.max_delay++;
4563
4564 out_unlock:
4565         spin_unlock_irq(&mchdev_lock);
4566
4567         return ret;
4568 }
4569 EXPORT_SYMBOL_GPL(i915_gpu_lower);
4570
4571 /**
4572  * i915_gpu_busy - indicate GPU business to IPS
4573  *
4574  * Tell the IPS driver whether or not the GPU is busy.
4575  */
4576 bool i915_gpu_busy(void)
4577 {
4578         struct drm_i915_private *dev_priv;
4579         struct intel_ring_buffer *ring;
4580         bool ret = false;
4581         int i;
4582
4583         spin_lock_irq(&mchdev_lock);
4584         if (!i915_mch_dev)
4585                 goto out_unlock;
4586         dev_priv = i915_mch_dev;
4587
4588         for_each_ring(ring, dev_priv, i)
4589                 ret |= !list_empty(&ring->request_list);
4590
4591 out_unlock:
4592         spin_unlock_irq(&mchdev_lock);
4593
4594         return ret;
4595 }
4596 EXPORT_SYMBOL_GPL(i915_gpu_busy);
4597
4598 /**
4599  * i915_gpu_turbo_disable - disable graphics turbo
4600  *
4601  * Disable graphics turbo by resetting the max frequency and setting the
4602  * current frequency to the default.
4603  */
4604 bool i915_gpu_turbo_disable(void)
4605 {
4606         struct drm_i915_private *dev_priv;
4607         bool ret = true;
4608
4609         spin_lock_irq(&mchdev_lock);
4610         if (!i915_mch_dev) {
4611                 ret = false;
4612                 goto out_unlock;
4613         }
4614         dev_priv = i915_mch_dev;
4615
4616         dev_priv->ips.max_delay = dev_priv->ips.fstart;
4617
4618         if (!ironlake_set_drps(dev_priv->dev, dev_priv->ips.fstart))
4619                 ret = false;
4620
4621 out_unlock:
4622         spin_unlock_irq(&mchdev_lock);
4623
4624         return ret;
4625 }
4626 EXPORT_SYMBOL_GPL(i915_gpu_turbo_disable);
4627
4628 /**
4629  * Tells the intel_ips driver that the i915 driver is now loaded, if
4630  * IPS got loaded first.
4631  *
4632  * This awkward dance is so that neither module has to depend on the
4633  * other in order for IPS to do the appropriate communication of
4634  * GPU turbo limits to i915.
4635  */
4636 static void
4637 ips_ping_for_i915_load(void)
4638 {
4639         void (*link)(void);
4640
4641         link = symbol_get(ips_link_to_i915_driver);
4642         if (link) {
4643                 link();
4644                 symbol_put(ips_link_to_i915_driver);
4645         }
4646 }
4647
4648 void intel_gpu_ips_init(struct drm_i915_private *dev_priv)
4649 {
4650         /* We only register the i915 ips part with intel-ips once everything is
4651          * set up, to avoid intel-ips sneaking in and reading bogus values. */
4652         spin_lock_irq(&mchdev_lock);
4653         i915_mch_dev = dev_priv;
4654         spin_unlock_irq(&mchdev_lock);
4655
4656         ips_ping_for_i915_load();
4657 }
4658
4659 void intel_gpu_ips_teardown(void)
4660 {
4661         spin_lock_irq(&mchdev_lock);
4662         i915_mch_dev = NULL;
4663         spin_unlock_irq(&mchdev_lock);
4664 }
4665 static void intel_init_emon(struct drm_device *dev)
4666 {
4667         struct drm_i915_private *dev_priv = dev->dev_private;
4668         u32 lcfuse;
4669         u8 pxw[16];
4670         int i;
4671
4672         /* Disable to program */
4673         I915_WRITE(ECR, 0);
4674         POSTING_READ(ECR);
4675
4676         /* Program energy weights for various events */
4677         I915_WRITE(SDEW, 0x15040d00);
4678         I915_WRITE(CSIEW0, 0x007f0000);
4679         I915_WRITE(CSIEW1, 0x1e220004);
4680         I915_WRITE(CSIEW2, 0x04000004);
4681
4682         for (i = 0; i < 5; i++)
4683                 I915_WRITE(PEW + (i * 4), 0);
4684         for (i = 0; i < 3; i++)
4685                 I915_WRITE(DEW + (i * 4), 0);
4686
4687         /* Program P-state weights to account for frequency power adjustment */
4688         for (i = 0; i < 16; i++) {
4689                 u32 pxvidfreq = I915_READ(PXVFREQ_BASE + (i * 4));
4690                 unsigned long freq = intel_pxfreq(pxvidfreq);
4691                 unsigned long vid = (pxvidfreq & PXVFREQ_PX_MASK) >>
4692                         PXVFREQ_PX_SHIFT;
4693                 unsigned long val;
4694
4695                 val = vid * vid;
4696                 val *= (freq / 1000);
4697                 val *= 255;
4698                 val /= (127*127*900);
4699                 if (val > 0xff)
4700                         DRM_ERROR("bad pxval: %ld\n", val);
4701                 pxw[i] = val;
4702         }
4703         /* Render standby states get 0 weight */
4704         pxw[14] = 0;
4705         pxw[15] = 0;
4706
4707         for (i = 0; i < 4; i++) {
4708                 u32 val = (pxw[i*4] << 24) | (pxw[(i*4)+1] << 16) |
4709                         (pxw[(i*4)+2] << 8) | (pxw[(i*4)+3]);
4710                 I915_WRITE(PXW + (i * 4), val);
4711         }
4712
4713         /* Adjust magic regs to magic values (more experimental results) */
4714         I915_WRITE(OGW0, 0);
4715         I915_WRITE(OGW1, 0);
4716         I915_WRITE(EG0, 0x00007f00);
4717         I915_WRITE(EG1, 0x0000000e);
4718         I915_WRITE(EG2, 0x000e0000);
4719         I915_WRITE(EG3, 0x68000300);
4720         I915_WRITE(EG4, 0x42000000);
4721         I915_WRITE(EG5, 0x00140031);
4722         I915_WRITE(EG6, 0);
4723         I915_WRITE(EG7, 0);
4724
4725         for (i = 0; i < 8; i++)
4726                 I915_WRITE(PXWL + (i * 4), 0);
4727
4728         /* Enable PMON + select events */
4729         I915_WRITE(ECR, 0x80000019);
4730
4731         lcfuse = I915_READ(LCFUSE02);
4732
4733         dev_priv->ips.corr = (lcfuse & LCFUSE_HIV_MASK);
4734 }
4735
4736 void intel_disable_gt_powersave(struct drm_device *dev)
4737 {
4738         struct drm_i915_private *dev_priv = dev->dev_private;
4739
4740         /* Interrupts should be disabled already to avoid re-arming. */
4741         WARN_ON(dev->irq_enabled);
4742
4743         if (IS_IRONLAKE_M(dev)) {
4744                 ironlake_disable_drps(dev);
4745                 ironlake_disable_rc6(dev);
4746         } else if (INTEL_INFO(dev)->gen >= 6) {
4747                 cancel_delayed_work_sync(&dev_priv->rps.delayed_resume_work);
4748                 cancel_work_sync(&dev_priv->rps.work);
4749                 mutex_lock(&dev_priv->rps.hw_lock);
4750                 if (IS_VALLEYVIEW(dev))
4751                         valleyview_disable_rps(dev);
4752                 else
4753                         gen6_disable_rps(dev);
4754                 dev_priv->rps.enabled = false;
4755                 mutex_unlock(&dev_priv->rps.hw_lock);
4756         }
4757 }
4758
4759 static void intel_gen6_powersave_work(struct work_struct *work)
4760 {
4761         struct drm_i915_private *dev_priv =
4762                 container_of(work, struct drm_i915_private,
4763                              rps.delayed_resume_work.work);
4764         struct drm_device *dev = dev_priv->dev;
4765
4766         mutex_lock(&dev_priv->rps.hw_lock);
4767
4768         if (IS_VALLEYVIEW(dev)) {
4769                 valleyview_enable_rps(dev);
4770         } else {
4771                 gen6_enable_rps(dev);
4772                 gen6_update_ring_freq(dev);
4773         }
4774         dev_priv->rps.enabled = true;
4775         mutex_unlock(&dev_priv->rps.hw_lock);
4776 }
4777
4778 void intel_enable_gt_powersave(struct drm_device *dev)
4779 {
4780         struct drm_i915_private *dev_priv = dev->dev_private;
4781
4782         if (IS_IRONLAKE_M(dev)) {
4783                 ironlake_enable_drps(dev);
4784                 ironlake_enable_rc6(dev);
4785                 intel_init_emon(dev);
4786         } else if (IS_GEN6(dev) || IS_GEN7(dev)) {
4787                 /*
4788                  * PCU communication is slow and this doesn't need to be
4789                  * done at any specific time, so do this out of our fast path
4790                  * to make resume and init faster.
4791                  */
4792                 schedule_delayed_work(&dev_priv->rps.delayed_resume_work,
4793                                       round_jiffies_up_relative(HZ));
4794         }
4795 }
4796
4797 static void ibx_init_clock_gating(struct drm_device *dev)
4798 {
4799         struct drm_i915_private *dev_priv = dev->dev_private;
4800
4801         /*
4802          * On Ibex Peak and Cougar Point, we need to disable clock
4803          * gating for the panel power sequencer or it will fail to
4804          * start up when no ports are active.
4805          */
4806         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
4807 }
4808
4809 static void g4x_disable_trickle_feed(struct drm_device *dev)
4810 {
4811         struct drm_i915_private *dev_priv = dev->dev_private;
4812         int pipe;
4813
4814         for_each_pipe(pipe) {
4815                 I915_WRITE(DSPCNTR(pipe),
4816                            I915_READ(DSPCNTR(pipe)) |
4817                            DISPPLANE_TRICKLE_FEED_DISABLE);
4818                 intel_flush_primary_plane(dev_priv, pipe);
4819         }
4820 }
4821
4822 static void ironlake_init_clock_gating(struct drm_device *dev)
4823 {
4824         struct drm_i915_private *dev_priv = dev->dev_private;
4825         uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
4826
4827         /*
4828          * Required for FBC
4829          * WaFbcDisableDpfcClockGating:ilk
4830          */
4831         dspclk_gate |= ILK_DPFCRUNIT_CLOCK_GATE_DISABLE |
4832                    ILK_DPFCUNIT_CLOCK_GATE_DISABLE |
4833                    ILK_DPFDUNIT_CLOCK_GATE_ENABLE;
4834
4835         I915_WRITE(PCH_3DCGDIS0,
4836                    MARIUNIT_CLOCK_GATE_DISABLE |
4837                    SVSMUNIT_CLOCK_GATE_DISABLE);
4838         I915_WRITE(PCH_3DCGDIS1,
4839                    VFMUNIT_CLOCK_GATE_DISABLE);
4840
4841         /*
4842          * According to the spec the following bits should be set in
4843          * order to enable memory self-refresh
4844          * The bit 22/21 of 0x42004
4845          * The bit 5 of 0x42020
4846          * The bit 15 of 0x45000
4847          */
4848         I915_WRITE(ILK_DISPLAY_CHICKEN2,
4849                    (I915_READ(ILK_DISPLAY_CHICKEN2) |
4850                     ILK_DPARB_GATE | ILK_VSDPFD_FULL));
4851         dspclk_gate |= ILK_DPARBUNIT_CLOCK_GATE_ENABLE;
4852         I915_WRITE(DISP_ARB_CTL,
4853                    (I915_READ(DISP_ARB_CTL) |
4854                     DISP_FBC_WM_DIS));
4855         I915_WRITE(WM3_LP_ILK, 0);
4856         I915_WRITE(WM2_LP_ILK, 0);
4857         I915_WRITE(WM1_LP_ILK, 0);
4858
4859         /*
4860          * Based on the document from hardware guys the following bits
4861          * should be set unconditionally in order to enable FBC.
4862          * The bit 22 of 0x42000
4863          * The bit 22 of 0x42004
4864          * The bit 7,8,9 of 0x42020.
4865          */
4866         if (IS_IRONLAKE_M(dev)) {
4867                 /* WaFbcAsynchFlipDisableFbcQueue:ilk */
4868                 I915_WRITE(ILK_DISPLAY_CHICKEN1,
4869                            I915_READ(ILK_DISPLAY_CHICKEN1) |
4870                            ILK_FBCQ_DIS);
4871                 I915_WRITE(ILK_DISPLAY_CHICKEN2,
4872                            I915_READ(ILK_DISPLAY_CHICKEN2) |
4873                            ILK_DPARB_GATE);
4874         }
4875
4876         I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
4877
4878         I915_WRITE(ILK_DISPLAY_CHICKEN2,
4879                    I915_READ(ILK_DISPLAY_CHICKEN2) |
4880                    ILK_ELPIN_409_SELECT);
4881         I915_WRITE(_3D_CHICKEN2,
4882                    _3D_CHICKEN2_WM_READ_PIPELINED << 16 |
4883                    _3D_CHICKEN2_WM_READ_PIPELINED);
4884
4885         /* WaDisableRenderCachePipelinedFlush:ilk */
4886         I915_WRITE(CACHE_MODE_0,
4887                    _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
4888
4889         g4x_disable_trickle_feed(dev);
4890
4891         ibx_init_clock_gating(dev);
4892 }
4893
4894 static void cpt_init_clock_gating(struct drm_device *dev)
4895 {
4896         struct drm_i915_private *dev_priv = dev->dev_private;
4897         int pipe;
4898         uint32_t val;
4899
4900         /*
4901          * On Ibex Peak and Cougar Point, we need to disable clock
4902          * gating for the panel power sequencer or it will fail to
4903          * start up when no ports are active.
4904          */
4905         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
4906         I915_WRITE(SOUTH_CHICKEN2, I915_READ(SOUTH_CHICKEN2) |
4907                    DPLS_EDP_PPS_FIX_DIS);
4908         /* The below fixes the weird display corruption, a few pixels shifted
4909          * downward, on (only) LVDS of some HP laptops with IVY.
4910          */
4911         for_each_pipe(pipe) {
4912                 val = I915_READ(TRANS_CHICKEN2(pipe));
4913                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
4914                 val &= ~TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
4915                 if (dev_priv->vbt.fdi_rx_polarity_inverted)
4916                         val |= TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
4917                 val &= ~TRANS_CHICKEN2_FRAME_START_DELAY_MASK;
4918                 val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_COUNTER;
4919                 val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_MODESWITCH;
4920                 I915_WRITE(TRANS_CHICKEN2(pipe), val);
4921         }
4922         /* WADP0ClockGatingDisable */
4923         for_each_pipe(pipe) {
4924                 I915_WRITE(TRANS_CHICKEN1(pipe),
4925                            TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
4926         }
4927 }
4928
4929 static void gen6_check_mch_setup(struct drm_device *dev)
4930 {
4931         struct drm_i915_private *dev_priv = dev->dev_private;
4932         uint32_t tmp;
4933
4934         tmp = I915_READ(MCH_SSKPD);
4935         if ((tmp & MCH_SSKPD_WM0_MASK) != MCH_SSKPD_WM0_VAL) {
4936                 DRM_INFO("Wrong MCH_SSKPD value: 0x%08x\n", tmp);
4937                 DRM_INFO("This can cause pipe underruns and display issues.\n");
4938                 DRM_INFO("Please upgrade your BIOS to fix this.\n");
4939         }
4940 }
4941
4942 static void gen6_init_clock_gating(struct drm_device *dev)
4943 {
4944         struct drm_i915_private *dev_priv = dev->dev_private;
4945         uint32_t dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
4946
4947         I915_WRITE(ILK_DSPCLK_GATE_D, dspclk_gate);
4948
4949         I915_WRITE(ILK_DISPLAY_CHICKEN2,
4950                    I915_READ(ILK_DISPLAY_CHICKEN2) |
4951                    ILK_ELPIN_409_SELECT);
4952
4953         /* WaDisableHiZPlanesWhenMSAAEnabled:snb */
4954         I915_WRITE(_3D_CHICKEN,
4955                    _MASKED_BIT_ENABLE(_3D_CHICKEN_HIZ_PLANE_DISABLE_MSAA_4X_SNB));
4956
4957         /* WaSetupGtModeTdRowDispatch:snb */
4958         if (IS_SNB_GT1(dev))
4959                 I915_WRITE(GEN6_GT_MODE,
4960                            _MASKED_BIT_ENABLE(GEN6_TD_FOUR_ROW_DISPATCH_DISABLE));
4961
4962         I915_WRITE(WM3_LP_ILK, 0);
4963         I915_WRITE(WM2_LP_ILK, 0);
4964         I915_WRITE(WM1_LP_ILK, 0);
4965
4966         I915_WRITE(CACHE_MODE_0,
4967                    _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
4968
4969         I915_WRITE(GEN6_UCGCTL1,
4970                    I915_READ(GEN6_UCGCTL1) |
4971                    GEN6_BLBUNIT_CLOCK_GATE_DISABLE |
4972                    GEN6_CSUNIT_CLOCK_GATE_DISABLE);
4973
4974         /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
4975          * gating disable must be set.  Failure to set it results in
4976          * flickering pixels due to Z write ordering failures after
4977          * some amount of runtime in the Mesa "fire" demo, and Unigine
4978          * Sanctuary and Tropics, and apparently anything else with
4979          * alpha test or pixel discard.
4980          *
4981          * According to the spec, bit 11 (RCCUNIT) must also be set,
4982          * but we didn't debug actual testcases to find it out.
4983          *
4984          * Also apply WaDisableVDSUnitClockGating:snb and
4985          * WaDisableRCPBUnitClockGating:snb.
4986          */
4987         I915_WRITE(GEN6_UCGCTL2,
4988                    GEN7_VDSUNIT_CLOCK_GATE_DISABLE |
4989                    GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
4990                    GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
4991
4992         /* Bspec says we need to always set all mask bits. */
4993         I915_WRITE(_3D_CHICKEN3, (0xFFFF << 16) |
4994                    _3D_CHICKEN3_SF_DISABLE_FASTCLIP_CULL);
4995
4996         /*
4997          * According to the spec the following bits should be
4998          * set in order to enable memory self-refresh and fbc:
4999          * The bit21 and bit22 of 0x42000
5000          * The bit21 and bit22 of 0x42004
5001          * The bit5 and bit7 of 0x42020
5002          * The bit14 of 0x70180
5003          * The bit14 of 0x71180
5004          *
5005          * WaFbcAsynchFlipDisableFbcQueue:snb
5006          */
5007         I915_WRITE(ILK_DISPLAY_CHICKEN1,
5008                    I915_READ(ILK_DISPLAY_CHICKEN1) |
5009                    ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
5010         I915_WRITE(ILK_DISPLAY_CHICKEN2,
5011                    I915_READ(ILK_DISPLAY_CHICKEN2) |
5012                    ILK_DPARB_GATE | ILK_VSDPFD_FULL);
5013         I915_WRITE(ILK_DSPCLK_GATE_D,
5014                    I915_READ(ILK_DSPCLK_GATE_D) |
5015                    ILK_DPARBUNIT_CLOCK_GATE_ENABLE  |
5016                    ILK_DPFDUNIT_CLOCK_GATE_ENABLE);
5017
5018         g4x_disable_trickle_feed(dev);
5019
5020         /* The default value should be 0x200 according to docs, but the two
5021          * platforms I checked have a 0 for this. (Maybe BIOS overrides?) */
5022         I915_WRITE(GEN6_GT_MODE, _MASKED_BIT_DISABLE(0xffff));
5023         I915_WRITE(GEN6_GT_MODE, _MASKED_BIT_ENABLE(GEN6_GT_MODE_HI));
5024
5025         cpt_init_clock_gating(dev);
5026
5027         gen6_check_mch_setup(dev);
5028 }
5029
5030 static void gen7_setup_fixed_func_scheduler(struct drm_i915_private *dev_priv)
5031 {
5032         uint32_t reg = I915_READ(GEN7_FF_THREAD_MODE);
5033
5034         reg &= ~GEN7_FF_SCHED_MASK;
5035         reg |= GEN7_FF_TS_SCHED_HW;
5036         reg |= GEN7_FF_VS_SCHED_HW;
5037         reg |= GEN7_FF_DS_SCHED_HW;
5038
5039         if (IS_HASWELL(dev_priv->dev))
5040                 reg &= ~GEN7_FF_VS_REF_CNT_FFME;
5041
5042         I915_WRITE(GEN7_FF_THREAD_MODE, reg);
5043 }
5044
5045 static void lpt_init_clock_gating(struct drm_device *dev)
5046 {
5047         struct drm_i915_private *dev_priv = dev->dev_private;
5048
5049         /*
5050          * TODO: this bit should only be enabled when really needed, then
5051          * disabled when not needed anymore in order to save power.
5052          */
5053         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE)
5054                 I915_WRITE(SOUTH_DSPCLK_GATE_D,
5055                            I915_READ(SOUTH_DSPCLK_GATE_D) |
5056                            PCH_LP_PARTITION_LEVEL_DISABLE);
5057
5058         /* WADPOClockGatingDisable:hsw */
5059         I915_WRITE(_TRANSA_CHICKEN1,
5060                    I915_READ(_TRANSA_CHICKEN1) |
5061                    TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
5062 }
5063
5064 static void lpt_suspend_hw(struct drm_device *dev)
5065 {
5066         struct drm_i915_private *dev_priv = dev->dev_private;
5067
5068         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
5069                 uint32_t val = I915_READ(SOUTH_DSPCLK_GATE_D);
5070
5071                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
5072                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
5073         }
5074 }
5075
5076 static void haswell_init_clock_gating(struct drm_device *dev)
5077 {
5078         struct drm_i915_private *dev_priv = dev->dev_private;
5079
5080         I915_WRITE(WM3_LP_ILK, 0);
5081         I915_WRITE(WM2_LP_ILK, 0);
5082         I915_WRITE(WM1_LP_ILK, 0);
5083
5084         /* According to the spec, bit 13 (RCZUNIT) must be set on IVB.
5085          * This implements the WaDisableRCZUnitClockGating:hsw workaround.
5086          */
5087         I915_WRITE(GEN6_UCGCTL2, GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
5088
5089         /* Apply the WaDisableRHWOOptimizationForRenderHang:hsw workaround. */
5090         I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
5091                    GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
5092
5093         /* WaApplyL3ControlAndL3ChickenMode:hsw */
5094         I915_WRITE(GEN7_L3CNTLREG1,
5095                         GEN7_WA_FOR_GEN7_L3_CONTROL);
5096         I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
5097                         GEN7_WA_L3_CHICKEN_MODE);
5098
5099         /* This is required by WaCatErrorRejectionIssue:hsw */
5100         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
5101                         I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
5102                         GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
5103
5104         /* WaVSRefCountFullforceMissDisable:hsw */
5105         gen7_setup_fixed_func_scheduler(dev_priv);
5106
5107         /* WaDisable4x2SubspanOptimization:hsw */
5108         I915_WRITE(CACHE_MODE_1,
5109                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
5110
5111         /* WaSwitchSolVfFArbitrationPriority:hsw */
5112         I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) | HSW_ECOCHK_ARB_PRIO_SOL);
5113
5114         /* WaRsPkgCStateDisplayPMReq:hsw */
5115         I915_WRITE(CHICKEN_PAR1_1,
5116                    I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
5117
5118         lpt_init_clock_gating(dev);
5119 }
5120
5121 static void ivybridge_init_clock_gating(struct drm_device *dev)
5122 {
5123         struct drm_i915_private *dev_priv = dev->dev_private;
5124         uint32_t snpcr;
5125
5126         I915_WRITE(WM3_LP_ILK, 0);
5127         I915_WRITE(WM2_LP_ILK, 0);
5128         I915_WRITE(WM1_LP_ILK, 0);
5129
5130         I915_WRITE(ILK_DSPCLK_GATE_D, ILK_VRHUNIT_CLOCK_GATE_DISABLE);
5131
5132         /* WaDisableEarlyCull:ivb */
5133         I915_WRITE(_3D_CHICKEN3,
5134                    _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
5135
5136         /* WaDisableBackToBackFlipFix:ivb */
5137         I915_WRITE(IVB_CHICKEN3,
5138                    CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
5139                    CHICKEN3_DGMG_DONE_FIX_DISABLE);
5140
5141         /* WaDisablePSDDualDispatchEnable:ivb */
5142         if (IS_IVB_GT1(dev))
5143                 I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
5144                            _MASKED_BIT_ENABLE(GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
5145         else
5146                 I915_WRITE(GEN7_HALF_SLICE_CHICKEN1_GT2,
5147                            _MASKED_BIT_ENABLE(GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
5148
5149         /* Apply the WaDisableRHWOOptimizationForRenderHang:ivb workaround. */
5150         I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
5151                    GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
5152
5153         /* WaApplyL3ControlAndL3ChickenMode:ivb */
5154         I915_WRITE(GEN7_L3CNTLREG1,
5155                         GEN7_WA_FOR_GEN7_L3_CONTROL);
5156         I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
5157                    GEN7_WA_L3_CHICKEN_MODE);
5158         if (IS_IVB_GT1(dev))
5159                 I915_WRITE(GEN7_ROW_CHICKEN2,
5160                            _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
5161         else
5162                 I915_WRITE(GEN7_ROW_CHICKEN2_GT2,
5163                            _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
5164
5165
5166         /* WaForceL3Serialization:ivb */
5167         I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
5168                    ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
5169
5170         /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
5171          * gating disable must be set.  Failure to set it results in
5172          * flickering pixels due to Z write ordering failures after
5173          * some amount of runtime in the Mesa "fire" demo, and Unigine
5174          * Sanctuary and Tropics, and apparently anything else with
5175          * alpha test or pixel discard.
5176          *
5177          * According to the spec, bit 11 (RCCUNIT) must also be set,
5178          * but we didn't debug actual testcases to find it out.
5179          *
5180          * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
5181          * This implements the WaDisableRCZUnitClockGating:ivb workaround.
5182          */
5183         I915_WRITE(GEN6_UCGCTL2,
5184                    GEN6_RCZUNIT_CLOCK_GATE_DISABLE |
5185                    GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
5186
5187         /* This is required by WaCatErrorRejectionIssue:ivb */
5188         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
5189                         I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
5190                         GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
5191
5192         g4x_disable_trickle_feed(dev);
5193
5194         /* WaVSRefCountFullforceMissDisable:ivb */
5195         gen7_setup_fixed_func_scheduler(dev_priv);
5196
5197         /* WaDisable4x2SubspanOptimization:ivb */
5198         I915_WRITE(CACHE_MODE_1,
5199                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
5200
5201         snpcr = I915_READ(GEN6_MBCUNIT_SNPCR);
5202         snpcr &= ~GEN6_MBC_SNPCR_MASK;
5203         snpcr |= GEN6_MBC_SNPCR_MED;
5204         I915_WRITE(GEN6_MBCUNIT_SNPCR, snpcr);
5205
5206         if (!HAS_PCH_NOP(dev))
5207                 cpt_init_clock_gating(dev);
5208
5209         gen6_check_mch_setup(dev);
5210 }
5211
5212 static void valleyview_init_clock_gating(struct drm_device *dev)
5213 {
5214         struct drm_i915_private *dev_priv = dev->dev_private;
5215
5216         I915_WRITE(DSPCLK_GATE_D, VRHUNIT_CLOCK_GATE_DISABLE);
5217
5218         /* WaDisableEarlyCull:vlv */
5219         I915_WRITE(_3D_CHICKEN3,
5220                    _MASKED_BIT_ENABLE(_3D_CHICKEN_SF_DISABLE_OBJEND_CULL));
5221
5222         /* WaDisableBackToBackFlipFix:vlv */
5223         I915_WRITE(IVB_CHICKEN3,
5224                    CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
5225                    CHICKEN3_DGMG_DONE_FIX_DISABLE);
5226
5227         /* WaDisablePSDDualDispatchEnable:vlv */
5228         I915_WRITE(GEN7_HALF_SLICE_CHICKEN1,
5229                    _MASKED_BIT_ENABLE(GEN7_MAX_PS_THREAD_DEP |
5230                                       GEN7_PSD_SINGLE_PORT_DISPATCH_ENABLE));
5231
5232         /* Apply the WaDisableRHWOOptimizationForRenderHang:vlv workaround. */
5233         I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
5234                    GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
5235
5236         /* WaApplyL3ControlAndL3ChickenMode:vlv */
5237         I915_WRITE(GEN7_L3CNTLREG1, I915_READ(GEN7_L3CNTLREG1) | GEN7_L3AGDIS);
5238         I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER, GEN7_WA_L3_CHICKEN_MODE);
5239
5240         /* WaForceL3Serialization:vlv */
5241         I915_WRITE(GEN7_L3SQCREG4, I915_READ(GEN7_L3SQCREG4) &
5242                    ~L3SQ_URB_READ_CAM_MATCH_DISABLE);
5243
5244         /* WaDisableDopClockGating:vlv */
5245         I915_WRITE(GEN7_ROW_CHICKEN2,
5246                    _MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
5247
5248         /* This is required by WaCatErrorRejectionIssue:vlv */
5249         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
5250                    I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
5251                    GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
5252
5253         /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
5254          * gating disable must be set.  Failure to set it results in
5255          * flickering pixels due to Z write ordering failures after
5256          * some amount of runtime in the Mesa "fire" demo, and Unigine
5257          * Sanctuary and Tropics, and apparently anything else with
5258          * alpha test or pixel discard.
5259          *
5260          * According to the spec, bit 11 (RCCUNIT) must also be set,
5261          * but we didn't debug actual testcases to find it out.
5262          *
5263          * According to the spec, bit 13 (RCZUNIT) must be set on IVB.
5264          * This implements the WaDisableRCZUnitClockGating:vlv workaround.
5265          *
5266          * Also apply WaDisableVDSUnitClockGating:vlv and
5267          * WaDisableRCPBUnitClockGating:vlv.
5268          */
5269         I915_WRITE(GEN6_UCGCTL2,
5270                    GEN7_VDSUNIT_CLOCK_GATE_DISABLE |
5271                    GEN7_TDLUNIT_CLOCK_GATE_DISABLE |
5272                    GEN6_RCZUNIT_CLOCK_GATE_DISABLE |
5273                    GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
5274                    GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
5275
5276         I915_WRITE(GEN7_UCGCTL4, GEN7_L3BANK2X_CLOCK_GATE_DISABLE);
5277
5278         I915_WRITE(MI_ARB_VLV, MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE);
5279
5280         I915_WRITE(CACHE_MODE_1,
5281                    _MASKED_BIT_ENABLE(PIXEL_SUBSPAN_COLLECT_OPT_DISABLE));
5282
5283         /*
5284          * WaDisableVLVClockGating_VBIIssue:vlv
5285          * Disable clock gating on th GCFG unit to prevent a delay
5286          * in the reporting of vblank events.
5287          */
5288         I915_WRITE(VLV_GUNIT_CLOCK_GATE, 0xffffffff);
5289
5290         /* Conservative clock gating settings for now */
5291         I915_WRITE(0x9400, 0xffffffff);
5292         I915_WRITE(0x9404, 0xffffffff);
5293         I915_WRITE(0x9408, 0xffffffff);
5294         I915_WRITE(0x940c, 0xffffffff);
5295         I915_WRITE(0x9410, 0xffffffff);
5296         I915_WRITE(0x9414, 0xffffffff);
5297         I915_WRITE(0x9418, 0xffffffff);
5298 }
5299
5300 static void g4x_init_clock_gating(struct drm_device *dev)
5301 {
5302         struct drm_i915_private *dev_priv = dev->dev_private;
5303         uint32_t dspclk_gate;
5304
5305         I915_WRITE(RENCLK_GATE_D1, 0);
5306         I915_WRITE(RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
5307                    GS_UNIT_CLOCK_GATE_DISABLE |
5308                    CL_UNIT_CLOCK_GATE_DISABLE);
5309         I915_WRITE(RAMCLK_GATE_D, 0);
5310         dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
5311                 OVRUNIT_CLOCK_GATE_DISABLE |
5312                 OVCUNIT_CLOCK_GATE_DISABLE;
5313         if (IS_GM45(dev))
5314                 dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
5315         I915_WRITE(DSPCLK_GATE_D, dspclk_gate);
5316
5317         /* WaDisableRenderCachePipelinedFlush */
5318         I915_WRITE(CACHE_MODE_0,
5319                    _MASKED_BIT_ENABLE(CM0_PIPELINED_RENDER_FLUSH_DISABLE));
5320
5321         g4x_disable_trickle_feed(dev);
5322 }
5323
5324 static void crestline_init_clock_gating(struct drm_device *dev)
5325 {
5326         struct drm_i915_private *dev_priv = dev->dev_private;
5327
5328         I915_WRITE(RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
5329         I915_WRITE(RENCLK_GATE_D2, 0);
5330         I915_WRITE(DSPCLK_GATE_D, 0);
5331         I915_WRITE(RAMCLK_GATE_D, 0);
5332         I915_WRITE16(DEUC, 0);
5333         I915_WRITE(MI_ARB_STATE,
5334                    _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
5335 }
5336
5337 static void broadwater_init_clock_gating(struct drm_device *dev)
5338 {
5339         struct drm_i915_private *dev_priv = dev->dev_private;
5340
5341         I915_WRITE(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
5342                    I965_RCC_CLOCK_GATE_DISABLE |
5343                    I965_RCPB_CLOCK_GATE_DISABLE |
5344                    I965_ISC_CLOCK_GATE_DISABLE |
5345                    I965_FBC_CLOCK_GATE_DISABLE);
5346         I915_WRITE(RENCLK_GATE_D2, 0);
5347         I915_WRITE(MI_ARB_STATE,
5348                    _MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
5349 }
5350
5351 static void gen3_init_clock_gating(struct drm_device *dev)
5352 {
5353         struct drm_i915_private *dev_priv = dev->dev_private;
5354         u32 dstate = I915_READ(D_STATE);
5355
5356         dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
5357                 DSTATE_DOT_CLOCK_GATING;
5358         I915_WRITE(D_STATE, dstate);
5359
5360         if (IS_PINEVIEW(dev))
5361                 I915_WRITE(ECOSKPD, _MASKED_BIT_ENABLE(ECO_GATING_CX_ONLY));
5362
5363         /* IIR "flip pending" means done if this bit is set */
5364         I915_WRITE(ECOSKPD, _MASKED_BIT_DISABLE(ECO_FLIP_DONE));
5365 }
5366
5367 static void i85x_init_clock_gating(struct drm_device *dev)
5368 {
5369         struct drm_i915_private *dev_priv = dev->dev_private;
5370
5371         I915_WRITE(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
5372 }
5373
5374 static void i830_init_clock_gating(struct drm_device *dev)
5375 {
5376         struct drm_i915_private *dev_priv = dev->dev_private;
5377
5378         I915_WRITE(DSPCLK_GATE_D, OVRUNIT_CLOCK_GATE_DISABLE);
5379 }
5380
5381 void intel_init_clock_gating(struct drm_device *dev)
5382 {
5383         struct drm_i915_private *dev_priv = dev->dev_private;
5384
5385         dev_priv->display.init_clock_gating(dev);
5386 }
5387
5388 void intel_suspend_hw(struct drm_device *dev)
5389 {
5390         if (HAS_PCH_LPT(dev))
5391                 lpt_suspend_hw(dev);
5392 }
5393
5394 /**
5395  * We should only use the power well if we explicitly asked the hardware to
5396  * enable it, so check if it's enabled and also check if we've requested it to
5397  * be enabled.
5398  */
5399 bool intel_display_power_enabled(struct drm_device *dev,
5400                                  enum intel_display_power_domain domain)
5401 {
5402         struct drm_i915_private *dev_priv = dev->dev_private;
5403
5404         if (!HAS_POWER_WELL(dev))
5405                 return true;
5406
5407         switch (domain) {
5408         case POWER_DOMAIN_PIPE_A:
5409         case POWER_DOMAIN_TRANSCODER_EDP:
5410                 return true;
5411         case POWER_DOMAIN_VGA:
5412         case POWER_DOMAIN_PIPE_B:
5413         case POWER_DOMAIN_PIPE_C:
5414         case POWER_DOMAIN_PIPE_A_PANEL_FITTER:
5415         case POWER_DOMAIN_PIPE_B_PANEL_FITTER:
5416         case POWER_DOMAIN_PIPE_C_PANEL_FITTER:
5417         case POWER_DOMAIN_TRANSCODER_A:
5418         case POWER_DOMAIN_TRANSCODER_B:
5419         case POWER_DOMAIN_TRANSCODER_C:
5420                 return I915_READ(HSW_PWR_WELL_DRIVER) ==
5421                      (HSW_PWR_WELL_ENABLE_REQUEST | HSW_PWR_WELL_STATE_ENABLED);
5422         default:
5423                 BUG();
5424         }
5425 }
5426
5427 static void __intel_set_power_well(struct drm_device *dev, bool enable)
5428 {
5429         struct drm_i915_private *dev_priv = dev->dev_private;
5430         bool is_enabled, enable_requested;
5431         uint32_t tmp;
5432
5433         tmp = I915_READ(HSW_PWR_WELL_DRIVER);
5434         is_enabled = tmp & HSW_PWR_WELL_STATE_ENABLED;
5435         enable_requested = tmp & HSW_PWR_WELL_ENABLE_REQUEST;
5436
5437         if (enable) {
5438                 if (!enable_requested)
5439                         I915_WRITE(HSW_PWR_WELL_DRIVER,
5440                                    HSW_PWR_WELL_ENABLE_REQUEST);
5441
5442                 if (!is_enabled) {
5443                         DRM_DEBUG_KMS("Enabling power well\n");
5444                         if (wait_for((I915_READ(HSW_PWR_WELL_DRIVER) &
5445                                       HSW_PWR_WELL_STATE_ENABLED), 20))
5446                                 DRM_ERROR("Timeout enabling power well\n");
5447                 }
5448         } else {
5449                 if (enable_requested) {
5450                         unsigned long irqflags;
5451                         enum pipe p;
5452
5453                         I915_WRITE(HSW_PWR_WELL_DRIVER, 0);
5454                         POSTING_READ(HSW_PWR_WELL_DRIVER);
5455                         DRM_DEBUG_KMS("Requesting to disable the power well\n");
5456
5457                         /*
5458                          * After this, the registers on the pipes that are part
5459                          * of the power well will become zero, so we have to
5460                          * adjust our counters according to that.
5461                          *
5462                          * FIXME: Should we do this in general in
5463                          * drm_vblank_post_modeset?
5464                          */
5465                         spin_lock_irqsave(&dev->vbl_lock, irqflags);
5466                         for_each_pipe(p)
5467                                 if (p != PIPE_A)
5468                                         dev->vblank[p].last = 0;
5469                         spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
5470                 }
5471         }
5472 }
5473
5474 static void __intel_power_well_get(struct i915_power_well *power_well)
5475 {
5476         if (!power_well->count++)
5477                 __intel_set_power_well(power_well->device, true);
5478 }
5479
5480 static void __intel_power_well_put(struct i915_power_well *power_well)
5481 {
5482         WARN_ON(!power_well->count);
5483         if (!--power_well->count)
5484                 __intel_set_power_well(power_well->device, false);
5485 }
5486
5487 void intel_display_power_get(struct drm_device *dev,
5488                              enum intel_display_power_domain domain)
5489 {
5490         struct drm_i915_private *dev_priv = dev->dev_private;
5491         struct i915_power_well *power_well = &dev_priv->power_well;
5492
5493         if (!HAS_POWER_WELL(dev))
5494                 return;
5495
5496         switch (domain) {
5497         case POWER_DOMAIN_PIPE_A:
5498         case POWER_DOMAIN_TRANSCODER_EDP:
5499                 return;
5500         case POWER_DOMAIN_VGA:
5501         case POWER_DOMAIN_PIPE_B:
5502         case POWER_DOMAIN_PIPE_C:
5503         case POWER_DOMAIN_PIPE_A_PANEL_FITTER:
5504         case POWER_DOMAIN_PIPE_B_PANEL_FITTER:
5505         case POWER_DOMAIN_PIPE_C_PANEL_FITTER:
5506         case POWER_DOMAIN_TRANSCODER_A:
5507         case POWER_DOMAIN_TRANSCODER_B:
5508         case POWER_DOMAIN_TRANSCODER_C:
5509                 spin_lock_irq(&power_well->lock);
5510                 __intel_power_well_get(power_well);
5511                 spin_unlock_irq(&power_well->lock);
5512                 return;
5513         default:
5514                 BUG();
5515         }
5516 }
5517
5518 void intel_display_power_put(struct drm_device *dev,
5519                              enum intel_display_power_domain domain)
5520 {
5521         struct drm_i915_private *dev_priv = dev->dev_private;
5522         struct i915_power_well *power_well = &dev_priv->power_well;
5523
5524         if (!HAS_POWER_WELL(dev))
5525                 return;
5526
5527         switch (domain) {
5528         case POWER_DOMAIN_PIPE_A:
5529         case POWER_DOMAIN_TRANSCODER_EDP:
5530                 return;
5531         case POWER_DOMAIN_VGA:
5532         case POWER_DOMAIN_PIPE_B:
5533         case POWER_DOMAIN_PIPE_C:
5534         case POWER_DOMAIN_PIPE_A_PANEL_FITTER:
5535         case POWER_DOMAIN_PIPE_B_PANEL_FITTER:
5536         case POWER_DOMAIN_PIPE_C_PANEL_FITTER:
5537         case POWER_DOMAIN_TRANSCODER_A:
5538         case POWER_DOMAIN_TRANSCODER_B:
5539         case POWER_DOMAIN_TRANSCODER_C:
5540                 spin_lock_irq(&power_well->lock);
5541                 __intel_power_well_put(power_well);
5542                 spin_unlock_irq(&power_well->lock);
5543                 return;
5544         default:
5545                 BUG();
5546         }
5547 }
5548
5549 static struct i915_power_well *hsw_pwr;
5550
5551 /* Display audio driver power well request */
5552 void i915_request_power_well(void)
5553 {
5554         if (WARN_ON(!hsw_pwr))
5555                 return;
5556
5557         spin_lock_irq(&hsw_pwr->lock);
5558         __intel_power_well_get(hsw_pwr);
5559         spin_unlock_irq(&hsw_pwr->lock);
5560 }
5561 EXPORT_SYMBOL_GPL(i915_request_power_well);
5562
5563 /* Display audio driver power well release */
5564 void i915_release_power_well(void)
5565 {
5566         if (WARN_ON(!hsw_pwr))
5567                 return;
5568
5569         spin_lock_irq(&hsw_pwr->lock);
5570         __intel_power_well_put(hsw_pwr);
5571         spin_unlock_irq(&hsw_pwr->lock);
5572 }
5573 EXPORT_SYMBOL_GPL(i915_release_power_well);
5574
5575 int i915_init_power_well(struct drm_device *dev)
5576 {
5577         struct drm_i915_private *dev_priv = dev->dev_private;
5578
5579         hsw_pwr = &dev_priv->power_well;
5580
5581         hsw_pwr->device = dev;
5582         spin_lock_init(&hsw_pwr->lock);
5583         hsw_pwr->count = 0;
5584
5585         return 0;
5586 }
5587
5588 void i915_remove_power_well(struct drm_device *dev)
5589 {
5590         hsw_pwr = NULL;
5591 }
5592
5593 void intel_set_power_well(struct drm_device *dev, bool enable)
5594 {
5595         struct drm_i915_private *dev_priv = dev->dev_private;
5596         struct i915_power_well *power_well = &dev_priv->power_well;
5597
5598         if (!HAS_POWER_WELL(dev))
5599                 return;
5600
5601         if (!i915_disable_power_well && !enable)
5602                 return;
5603
5604         spin_lock_irq(&power_well->lock);
5605
5606         /*
5607          * This function will only ever contribute one
5608          * to the power well reference count. i915_request
5609          * is what tracks whether we have or have not
5610          * added the one to the reference count.
5611          */
5612         if (power_well->i915_request == enable)
5613                 goto out;
5614
5615         power_well->i915_request = enable;
5616
5617         if (enable)
5618                 __intel_power_well_get(power_well);
5619         else
5620                 __intel_power_well_put(power_well);
5621
5622  out:
5623         spin_unlock_irq(&power_well->lock);
5624 }
5625
5626 static void intel_resume_power_well(struct drm_device *dev)
5627 {
5628         struct drm_i915_private *dev_priv = dev->dev_private;
5629         struct i915_power_well *power_well = &dev_priv->power_well;
5630
5631         if (!HAS_POWER_WELL(dev))
5632                 return;
5633
5634         spin_lock_irq(&power_well->lock);
5635         __intel_set_power_well(dev, power_well->count > 0);
5636         spin_unlock_irq(&power_well->lock);
5637 }
5638
5639 /*
5640  * Starting with Haswell, we have a "Power Down Well" that can be turned off
5641  * when not needed anymore. We have 4 registers that can request the power well
5642  * to be enabled, and it will only be disabled if none of the registers is
5643  * requesting it to be enabled.
5644  */
5645 void intel_init_power_well(struct drm_device *dev)
5646 {
5647         struct drm_i915_private *dev_priv = dev->dev_private;
5648
5649         if (!HAS_POWER_WELL(dev))
5650                 return;
5651
5652         /* For now, we need the power well to be always enabled. */
5653         intel_set_power_well(dev, true);
5654         intel_resume_power_well(dev);
5655
5656         /* We're taking over the BIOS, so clear any requests made by it since
5657          * the driver is in charge now. */
5658         if (I915_READ(HSW_PWR_WELL_BIOS) & HSW_PWR_WELL_ENABLE_REQUEST)
5659                 I915_WRITE(HSW_PWR_WELL_BIOS, 0);
5660 }
5661
5662 /* Disables PC8 so we can use the GMBUS and DP AUX interrupts. */
5663 void intel_aux_display_runtime_get(struct drm_i915_private *dev_priv)
5664 {
5665         hsw_disable_package_c8(dev_priv);
5666 }
5667
5668 void intel_aux_display_runtime_put(struct drm_i915_private *dev_priv)
5669 {
5670         hsw_enable_package_c8(dev_priv);
5671 }
5672
5673 /* Set up chip specific power management-related functions */
5674 void intel_init_pm(struct drm_device *dev)
5675 {
5676         struct drm_i915_private *dev_priv = dev->dev_private;
5677
5678         if (I915_HAS_FBC(dev)) {
5679                 if (HAS_PCH_SPLIT(dev)) {
5680                         dev_priv->display.fbc_enabled = ironlake_fbc_enabled;
5681                         if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
5682                                 dev_priv->display.enable_fbc =
5683                                         gen7_enable_fbc;
5684                         else
5685                                 dev_priv->display.enable_fbc =
5686                                         ironlake_enable_fbc;
5687                         dev_priv->display.disable_fbc = ironlake_disable_fbc;
5688                 } else if (IS_GM45(dev)) {
5689                         dev_priv->display.fbc_enabled = g4x_fbc_enabled;
5690                         dev_priv->display.enable_fbc = g4x_enable_fbc;
5691                         dev_priv->display.disable_fbc = g4x_disable_fbc;
5692                 } else if (IS_CRESTLINE(dev)) {
5693                         dev_priv->display.fbc_enabled = i8xx_fbc_enabled;
5694                         dev_priv->display.enable_fbc = i8xx_enable_fbc;
5695                         dev_priv->display.disable_fbc = i8xx_disable_fbc;
5696                 }
5697                 /* 855GM needs testing */
5698         }
5699
5700         /* For cxsr */
5701         if (IS_PINEVIEW(dev))
5702                 i915_pineview_get_mem_freq(dev);
5703         else if (IS_GEN5(dev))
5704                 i915_ironlake_get_mem_freq(dev);
5705
5706         /* For FIFO watermark updates */
5707         if (HAS_PCH_SPLIT(dev)) {
5708                 intel_setup_wm_latency(dev);
5709
5710                 if (IS_GEN5(dev)) {
5711                         if (dev_priv->wm.pri_latency[1] &&
5712                             dev_priv->wm.spr_latency[1] &&
5713                             dev_priv->wm.cur_latency[1])
5714                                 dev_priv->display.update_wm = ironlake_update_wm;
5715                         else {
5716                                 DRM_DEBUG_KMS("Failed to get proper latency. "
5717                                               "Disable CxSR\n");
5718                                 dev_priv->display.update_wm = NULL;
5719                         }
5720                         dev_priv->display.init_clock_gating = ironlake_init_clock_gating;
5721                 } else if (IS_GEN6(dev)) {
5722                         if (dev_priv->wm.pri_latency[0] &&
5723                             dev_priv->wm.spr_latency[0] &&
5724                             dev_priv->wm.cur_latency[0]) {
5725                                 dev_priv->display.update_wm = sandybridge_update_wm;
5726                                 dev_priv->display.update_sprite_wm = sandybridge_update_sprite_wm;
5727                         } else {
5728                                 DRM_DEBUG_KMS("Failed to read display plane latency. "
5729                                               "Disable CxSR\n");
5730                                 dev_priv->display.update_wm = NULL;
5731                         }
5732                         dev_priv->display.init_clock_gating = gen6_init_clock_gating;
5733                 } else if (IS_IVYBRIDGE(dev)) {
5734                         if (dev_priv->wm.pri_latency[0] &&
5735                             dev_priv->wm.spr_latency[0] &&
5736                             dev_priv->wm.cur_latency[0]) {
5737                                 dev_priv->display.update_wm = ivybridge_update_wm;
5738                                 dev_priv->display.update_sprite_wm = sandybridge_update_sprite_wm;
5739                         } else {
5740                                 DRM_DEBUG_KMS("Failed to read display plane latency. "
5741                                               "Disable CxSR\n");
5742                                 dev_priv->display.update_wm = NULL;
5743                         }
5744                         dev_priv->display.init_clock_gating = ivybridge_init_clock_gating;
5745                 } else if (IS_HASWELL(dev)) {
5746                         if (dev_priv->wm.pri_latency[0] &&
5747                             dev_priv->wm.spr_latency[0] &&
5748                             dev_priv->wm.cur_latency[0]) {
5749                                 dev_priv->display.update_wm = haswell_update_wm;
5750                                 dev_priv->display.update_sprite_wm =
5751                                         haswell_update_sprite_wm;
5752                         } else {
5753                                 DRM_DEBUG_KMS("Failed to read display plane latency. "
5754                                               "Disable CxSR\n");
5755                                 dev_priv->display.update_wm = NULL;
5756                         }
5757                         dev_priv->display.init_clock_gating = haswell_init_clock_gating;
5758                 } else
5759                         dev_priv->display.update_wm = NULL;
5760         } else if (IS_VALLEYVIEW(dev)) {
5761                 dev_priv->display.update_wm = valleyview_update_wm;
5762                 dev_priv->display.init_clock_gating =
5763                         valleyview_init_clock_gating;
5764         } else if (IS_PINEVIEW(dev)) {
5765                 if (!intel_get_cxsr_latency(IS_PINEVIEW_G(dev),
5766                                             dev_priv->is_ddr3,
5767                                             dev_priv->fsb_freq,
5768                                             dev_priv->mem_freq)) {
5769                         DRM_INFO("failed to find known CxSR latency "
5770                                  "(found ddr%s fsb freq %d, mem freq %d), "
5771                                  "disabling CxSR\n",
5772                                  (dev_priv->is_ddr3 == 1) ? "3" : "2",
5773                                  dev_priv->fsb_freq, dev_priv->mem_freq);
5774                         /* Disable CxSR and never update its watermark again */
5775                         pineview_disable_cxsr(dev);
5776                         dev_priv->display.update_wm = NULL;
5777                 } else
5778                         dev_priv->display.update_wm = pineview_update_wm;
5779                 dev_priv->display.init_clock_gating = gen3_init_clock_gating;
5780         } else if (IS_G4X(dev)) {
5781                 dev_priv->display.update_wm = g4x_update_wm;
5782                 dev_priv->display.init_clock_gating = g4x_init_clock_gating;
5783         } else if (IS_GEN4(dev)) {
5784                 dev_priv->display.update_wm = i965_update_wm;
5785                 if (IS_CRESTLINE(dev))
5786                         dev_priv->display.init_clock_gating = crestline_init_clock_gating;
5787                 else if (IS_BROADWATER(dev))
5788                         dev_priv->display.init_clock_gating = broadwater_init_clock_gating;
5789         } else if (IS_GEN3(dev)) {
5790                 dev_priv->display.update_wm = i9xx_update_wm;
5791                 dev_priv->display.get_fifo_size = i9xx_get_fifo_size;
5792                 dev_priv->display.init_clock_gating = gen3_init_clock_gating;
5793         } else if (IS_I865G(dev)) {
5794                 dev_priv->display.update_wm = i830_update_wm;
5795                 dev_priv->display.init_clock_gating = i85x_init_clock_gating;
5796                 dev_priv->display.get_fifo_size = i830_get_fifo_size;
5797         } else if (IS_I85X(dev)) {
5798                 dev_priv->display.update_wm = i9xx_update_wm;
5799                 dev_priv->display.get_fifo_size = i85x_get_fifo_size;
5800                 dev_priv->display.init_clock_gating = i85x_init_clock_gating;
5801         } else {
5802                 dev_priv->display.update_wm = i830_update_wm;
5803                 dev_priv->display.init_clock_gating = i830_init_clock_gating;
5804                 if (IS_845G(dev))
5805                         dev_priv->display.get_fifo_size = i845_get_fifo_size;
5806                 else
5807                         dev_priv->display.get_fifo_size = i830_get_fifo_size;
5808         }
5809 }
5810
5811 int sandybridge_pcode_read(struct drm_i915_private *dev_priv, u8 mbox, u32 *val)
5812 {
5813         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5814
5815         if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
5816                 DRM_DEBUG_DRIVER("warning: pcode (read) mailbox access failed\n");
5817                 return -EAGAIN;
5818         }
5819
5820         I915_WRITE(GEN6_PCODE_DATA, *val);
5821         I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
5822
5823         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
5824                      500)) {
5825                 DRM_ERROR("timeout waiting for pcode read (%d) to finish\n", mbox);
5826                 return -ETIMEDOUT;
5827         }
5828
5829         *val = I915_READ(GEN6_PCODE_DATA);
5830         I915_WRITE(GEN6_PCODE_DATA, 0);
5831
5832         return 0;
5833 }
5834
5835 int sandybridge_pcode_write(struct drm_i915_private *dev_priv, u8 mbox, u32 val)
5836 {
5837         WARN_ON(!mutex_is_locked(&dev_priv->rps.hw_lock));
5838
5839         if (I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) {
5840                 DRM_DEBUG_DRIVER("warning: pcode (write) mailbox access failed\n");
5841                 return -EAGAIN;
5842         }
5843
5844         I915_WRITE(GEN6_PCODE_DATA, val);
5845         I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
5846
5847         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
5848                      500)) {
5849                 DRM_ERROR("timeout waiting for pcode write (%d) to finish\n", mbox);
5850                 return -ETIMEDOUT;
5851         }
5852
5853         I915_WRITE(GEN6_PCODE_DATA, 0);
5854
5855         return 0;
5856 }
5857
5858 int vlv_gpu_freq(int ddr_freq, int val)
5859 {
5860         int mult, base;
5861
5862         switch (ddr_freq) {
5863         case 800:
5864                 mult = 20;
5865                 base = 120;
5866                 break;
5867         case 1066:
5868                 mult = 22;
5869                 base = 133;
5870                 break;
5871         case 1333:
5872                 mult = 21;
5873                 base = 125;
5874                 break;
5875         default:
5876                 return -1;
5877         }
5878
5879         return ((val - 0xbd) * mult) + base;
5880 }
5881
5882 int vlv_freq_opcode(int ddr_freq, int val)
5883 {
5884         int mult, base;
5885
5886         switch (ddr_freq) {
5887         case 800:
5888                 mult = 20;
5889                 base = 120;
5890                 break;
5891         case 1066:
5892                 mult = 22;
5893                 base = 133;
5894                 break;
5895         case 1333:
5896                 mult = 21;
5897                 base = 125;
5898                 break;
5899         default:
5900                 return -1;
5901         }
5902
5903         val /= mult;
5904         val -= base / mult;
5905         val += 0xbd;
5906
5907         if (val > 0xea)
5908                 val = 0xea;
5909
5910         return val;
5911 }
5912
5913 void intel_pm_init(struct drm_device *dev)
5914 {
5915         struct drm_i915_private *dev_priv = dev->dev_private;
5916
5917         INIT_DELAYED_WORK(&dev_priv->rps.delayed_resume_work,
5918                           intel_gen6_powersave_work);
5919 }
5920