c75aa4348a9c61b80315c573a24b3176350d9296
[pandora-kernel.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 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
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/cpufreq.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include "drmP.h"
36 #include "intel_drv.h"
37 #include "i915_drm.h"
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include "drm_dp_helper.h"
41 #include "drm_crtc_helper.h"
42 #include <linux/dma_remapping.h>
43
44 #define HAS_eDP (intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
45
46 bool intel_pipe_has_type(struct drm_crtc *crtc, int type);
47 static void intel_update_watermarks(struct drm_device *dev);
48 static void intel_increase_pllclock(struct drm_crtc *crtc);
49 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
50
51 typedef struct {
52         /* given values */
53         int n;
54         int m1, m2;
55         int p1, p2;
56         /* derived values */
57         int     dot;
58         int     vco;
59         int     m;
60         int     p;
61 } intel_clock_t;
62
63 typedef struct {
64         int     min, max;
65 } intel_range_t;
66
67 typedef struct {
68         int     dot_limit;
69         int     p2_slow, p2_fast;
70 } intel_p2_t;
71
72 #define INTEL_P2_NUM                  2
73 typedef struct intel_limit intel_limit_t;
74 struct intel_limit {
75         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
76         intel_p2_t          p2;
77         bool (* find_pll)(const intel_limit_t *, struct drm_crtc *,
78                         int, int, intel_clock_t *);
79 };
80
81 /* FDI */
82 #define IRONLAKE_FDI_FREQ               2700000 /* in kHz for mode->clock */
83
84 static bool
85 intel_find_best_PLL(const intel_limit_t *limit, struct drm_crtc *crtc,
86                     int target, int refclk, intel_clock_t *best_clock);
87 static bool
88 intel_g4x_find_best_PLL(const intel_limit_t *limit, struct drm_crtc *crtc,
89                         int target, int refclk, intel_clock_t *best_clock);
90
91 static bool
92 intel_find_pll_g4x_dp(const intel_limit_t *, struct drm_crtc *crtc,
93                       int target, int refclk, intel_clock_t *best_clock);
94 static bool
95 intel_find_pll_ironlake_dp(const intel_limit_t *, struct drm_crtc *crtc,
96                            int target, int refclk, intel_clock_t *best_clock);
97
98 static inline u32 /* units of 100MHz */
99 intel_fdi_link_freq(struct drm_device *dev)
100 {
101         if (IS_GEN5(dev)) {
102                 struct drm_i915_private *dev_priv = dev->dev_private;
103                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
104         } else
105                 return 27;
106 }
107
108 static const intel_limit_t intel_limits_i8xx_dvo = {
109         .dot = { .min = 25000, .max = 350000 },
110         .vco = { .min = 930000, .max = 1400000 },
111         .n = { .min = 3, .max = 16 },
112         .m = { .min = 96, .max = 140 },
113         .m1 = { .min = 18, .max = 26 },
114         .m2 = { .min = 6, .max = 16 },
115         .p = { .min = 4, .max = 128 },
116         .p1 = { .min = 2, .max = 33 },
117         .p2 = { .dot_limit = 165000,
118                 .p2_slow = 4, .p2_fast = 2 },
119         .find_pll = intel_find_best_PLL,
120 };
121
122 static const intel_limit_t intel_limits_i8xx_lvds = {
123         .dot = { .min = 25000, .max = 350000 },
124         .vco = { .min = 930000, .max = 1400000 },
125         .n = { .min = 3, .max = 16 },
126         .m = { .min = 96, .max = 140 },
127         .m1 = { .min = 18, .max = 26 },
128         .m2 = { .min = 6, .max = 16 },
129         .p = { .min = 4, .max = 128 },
130         .p1 = { .min = 1, .max = 6 },
131         .p2 = { .dot_limit = 165000,
132                 .p2_slow = 14, .p2_fast = 7 },
133         .find_pll = intel_find_best_PLL,
134 };
135
136 static const intel_limit_t intel_limits_i9xx_sdvo = {
137         .dot = { .min = 20000, .max = 400000 },
138         .vco = { .min = 1400000, .max = 2800000 },
139         .n = { .min = 1, .max = 6 },
140         .m = { .min = 70, .max = 120 },
141         .m1 = { .min = 10, .max = 22 },
142         .m2 = { .min = 5, .max = 9 },
143         .p = { .min = 5, .max = 80 },
144         .p1 = { .min = 1, .max = 8 },
145         .p2 = { .dot_limit = 200000,
146                 .p2_slow = 10, .p2_fast = 5 },
147         .find_pll = intel_find_best_PLL,
148 };
149
150 static const intel_limit_t intel_limits_i9xx_lvds = {
151         .dot = { .min = 20000, .max = 400000 },
152         .vco = { .min = 1400000, .max = 2800000 },
153         .n = { .min = 1, .max = 6 },
154         .m = { .min = 70, .max = 120 },
155         .m1 = { .min = 10, .max = 22 },
156         .m2 = { .min = 5, .max = 9 },
157         .p = { .min = 7, .max = 98 },
158         .p1 = { .min = 1, .max = 8 },
159         .p2 = { .dot_limit = 112000,
160                 .p2_slow = 14, .p2_fast = 7 },
161         .find_pll = intel_find_best_PLL,
162 };
163
164
165 static const intel_limit_t intel_limits_g4x_sdvo = {
166         .dot = { .min = 25000, .max = 270000 },
167         .vco = { .min = 1750000, .max = 3500000},
168         .n = { .min = 1, .max = 4 },
169         .m = { .min = 104, .max = 138 },
170         .m1 = { .min = 17, .max = 23 },
171         .m2 = { .min = 5, .max = 11 },
172         .p = { .min = 10, .max = 30 },
173         .p1 = { .min = 1, .max = 3},
174         .p2 = { .dot_limit = 270000,
175                 .p2_slow = 10,
176                 .p2_fast = 10
177         },
178         .find_pll = intel_g4x_find_best_PLL,
179 };
180
181 static const intel_limit_t intel_limits_g4x_hdmi = {
182         .dot = { .min = 22000, .max = 400000 },
183         .vco = { .min = 1750000, .max = 3500000},
184         .n = { .min = 1, .max = 4 },
185         .m = { .min = 104, .max = 138 },
186         .m1 = { .min = 16, .max = 23 },
187         .m2 = { .min = 5, .max = 11 },
188         .p = { .min = 5, .max = 80 },
189         .p1 = { .min = 1, .max = 8},
190         .p2 = { .dot_limit = 165000,
191                 .p2_slow = 10, .p2_fast = 5 },
192         .find_pll = intel_g4x_find_best_PLL,
193 };
194
195 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
196         .dot = { .min = 20000, .max = 115000 },
197         .vco = { .min = 1750000, .max = 3500000 },
198         .n = { .min = 1, .max = 3 },
199         .m = { .min = 104, .max = 138 },
200         .m1 = { .min = 17, .max = 23 },
201         .m2 = { .min = 5, .max = 11 },
202         .p = { .min = 28, .max = 112 },
203         .p1 = { .min = 2, .max = 8 },
204         .p2 = { .dot_limit = 0,
205                 .p2_slow = 14, .p2_fast = 14
206         },
207         .find_pll = intel_g4x_find_best_PLL,
208 };
209
210 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
211         .dot = { .min = 80000, .max = 224000 },
212         .vco = { .min = 1750000, .max = 3500000 },
213         .n = { .min = 1, .max = 3 },
214         .m = { .min = 104, .max = 138 },
215         .m1 = { .min = 17, .max = 23 },
216         .m2 = { .min = 5, .max = 11 },
217         .p = { .min = 14, .max = 42 },
218         .p1 = { .min = 2, .max = 6 },
219         .p2 = { .dot_limit = 0,
220                 .p2_slow = 7, .p2_fast = 7
221         },
222         .find_pll = intel_g4x_find_best_PLL,
223 };
224
225 static const intel_limit_t intel_limits_g4x_display_port = {
226         .dot = { .min = 161670, .max = 227000 },
227         .vco = { .min = 1750000, .max = 3500000},
228         .n = { .min = 1, .max = 2 },
229         .m = { .min = 97, .max = 108 },
230         .m1 = { .min = 0x10, .max = 0x12 },
231         .m2 = { .min = 0x05, .max = 0x06 },
232         .p = { .min = 10, .max = 20 },
233         .p1 = { .min = 1, .max = 2},
234         .p2 = { .dot_limit = 0,
235                 .p2_slow = 10, .p2_fast = 10 },
236         .find_pll = intel_find_pll_g4x_dp,
237 };
238
239 static const intel_limit_t intel_limits_pineview_sdvo = {
240         .dot = { .min = 20000, .max = 400000},
241         .vco = { .min = 1700000, .max = 3500000 },
242         /* Pineview's Ncounter is a ring counter */
243         .n = { .min = 3, .max = 6 },
244         .m = { .min = 2, .max = 256 },
245         /* Pineview only has one combined m divider, which we treat as m2. */
246         .m1 = { .min = 0, .max = 0 },
247         .m2 = { .min = 0, .max = 254 },
248         .p = { .min = 5, .max = 80 },
249         .p1 = { .min = 1, .max = 8 },
250         .p2 = { .dot_limit = 200000,
251                 .p2_slow = 10, .p2_fast = 5 },
252         .find_pll = intel_find_best_PLL,
253 };
254
255 static const intel_limit_t intel_limits_pineview_lvds = {
256         .dot = { .min = 20000, .max = 400000 },
257         .vco = { .min = 1700000, .max = 3500000 },
258         .n = { .min = 3, .max = 6 },
259         .m = { .min = 2, .max = 256 },
260         .m1 = { .min = 0, .max = 0 },
261         .m2 = { .min = 0, .max = 254 },
262         .p = { .min = 7, .max = 112 },
263         .p1 = { .min = 1, .max = 8 },
264         .p2 = { .dot_limit = 112000,
265                 .p2_slow = 14, .p2_fast = 14 },
266         .find_pll = intel_find_best_PLL,
267 };
268
269 /* Ironlake / Sandybridge
270  *
271  * We calculate clock using (register_value + 2) for N/M1/M2, so here
272  * the range value for them is (actual_value - 2).
273  */
274 static const intel_limit_t intel_limits_ironlake_dac = {
275         .dot = { .min = 25000, .max = 350000 },
276         .vco = { .min = 1760000, .max = 3510000 },
277         .n = { .min = 1, .max = 5 },
278         .m = { .min = 79, .max = 127 },
279         .m1 = { .min = 12, .max = 22 },
280         .m2 = { .min = 5, .max = 9 },
281         .p = { .min = 5, .max = 80 },
282         .p1 = { .min = 1, .max = 8 },
283         .p2 = { .dot_limit = 225000,
284                 .p2_slow = 10, .p2_fast = 5 },
285         .find_pll = intel_g4x_find_best_PLL,
286 };
287
288 static const intel_limit_t intel_limits_ironlake_single_lvds = {
289         .dot = { .min = 25000, .max = 350000 },
290         .vco = { .min = 1760000, .max = 3510000 },
291         .n = { .min = 1, .max = 3 },
292         .m = { .min = 79, .max = 118 },
293         .m1 = { .min = 12, .max = 22 },
294         .m2 = { .min = 5, .max = 9 },
295         .p = { .min = 28, .max = 112 },
296         .p1 = { .min = 2, .max = 8 },
297         .p2 = { .dot_limit = 225000,
298                 .p2_slow = 14, .p2_fast = 14 },
299         .find_pll = intel_g4x_find_best_PLL,
300 };
301
302 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
303         .dot = { .min = 25000, .max = 350000 },
304         .vco = { .min = 1760000, .max = 3510000 },
305         .n = { .min = 1, .max = 3 },
306         .m = { .min = 79, .max = 127 },
307         .m1 = { .min = 12, .max = 22 },
308         .m2 = { .min = 5, .max = 9 },
309         .p = { .min = 14, .max = 56 },
310         .p1 = { .min = 2, .max = 8 },
311         .p2 = { .dot_limit = 225000,
312                 .p2_slow = 7, .p2_fast = 7 },
313         .find_pll = intel_g4x_find_best_PLL,
314 };
315
316 /* LVDS 100mhz refclk limits. */
317 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
318         .dot = { .min = 25000, .max = 350000 },
319         .vco = { .min = 1760000, .max = 3510000 },
320         .n = { .min = 1, .max = 2 },
321         .m = { .min = 79, .max = 126 },
322         .m1 = { .min = 12, .max = 22 },
323         .m2 = { .min = 5, .max = 9 },
324         .p = { .min = 28, .max = 112 },
325         .p1 = { .min = 2, .max = 8 },
326         .p2 = { .dot_limit = 225000,
327                 .p2_slow = 14, .p2_fast = 14 },
328         .find_pll = intel_g4x_find_best_PLL,
329 };
330
331 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
332         .dot = { .min = 25000, .max = 350000 },
333         .vco = { .min = 1760000, .max = 3510000 },
334         .n = { .min = 1, .max = 3 },
335         .m = { .min = 79, .max = 126 },
336         .m1 = { .min = 12, .max = 22 },
337         .m2 = { .min = 5, .max = 9 },
338         .p = { .min = 14, .max = 42 },
339         .p1 = { .min = 2, .max = 6 },
340         .p2 = { .dot_limit = 225000,
341                 .p2_slow = 7, .p2_fast = 7 },
342         .find_pll = intel_g4x_find_best_PLL,
343 };
344
345 static const intel_limit_t intel_limits_ironlake_display_port = {
346         .dot = { .min = 25000, .max = 350000 },
347         .vco = { .min = 1760000, .max = 3510000},
348         .n = { .min = 1, .max = 2 },
349         .m = { .min = 81, .max = 90 },
350         .m1 = { .min = 12, .max = 22 },
351         .m2 = { .min = 5, .max = 9 },
352         .p = { .min = 10, .max = 20 },
353         .p1 = { .min = 1, .max = 2},
354         .p2 = { .dot_limit = 0,
355                 .p2_slow = 10, .p2_fast = 10 },
356         .find_pll = intel_find_pll_ironlake_dp,
357 };
358
359 static bool is_dual_link_lvds(struct drm_i915_private *dev_priv,
360                               unsigned int reg)
361 {
362         unsigned int val;
363
364         if (dev_priv->lvds_val)
365                 val = dev_priv->lvds_val;
366         else {
367                 /* BIOS should set the proper LVDS register value at boot, but
368                  * in reality, it doesn't set the value when the lid is closed;
369                  * we need to check "the value to be set" in VBT when LVDS
370                  * register is uninitialized.
371                  */
372                 val = I915_READ(reg);
373                 if (!(val & ~LVDS_DETECTED))
374                         val = dev_priv->bios_lvds_val;
375                 dev_priv->lvds_val = val;
376         }
377         return (val & LVDS_CLKB_POWER_MASK) == LVDS_CLKB_POWER_UP;
378 }
379
380 static const intel_limit_t *intel_ironlake_limit(struct drm_crtc *crtc,
381                                                 int refclk)
382 {
383         struct drm_device *dev = crtc->dev;
384         struct drm_i915_private *dev_priv = dev->dev_private;
385         const intel_limit_t *limit;
386
387         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
388                 if (is_dual_link_lvds(dev_priv, PCH_LVDS)) {
389                         /* LVDS dual channel */
390                         if (refclk == 100000)
391                                 limit = &intel_limits_ironlake_dual_lvds_100m;
392                         else
393                                 limit = &intel_limits_ironlake_dual_lvds;
394                 } else {
395                         if (refclk == 100000)
396                                 limit = &intel_limits_ironlake_single_lvds_100m;
397                         else
398                                 limit = &intel_limits_ironlake_single_lvds;
399                 }
400         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
401                         HAS_eDP)
402                 limit = &intel_limits_ironlake_display_port;
403         else
404                 limit = &intel_limits_ironlake_dac;
405
406         return limit;
407 }
408
409 static const intel_limit_t *intel_g4x_limit(struct drm_crtc *crtc)
410 {
411         struct drm_device *dev = crtc->dev;
412         struct drm_i915_private *dev_priv = dev->dev_private;
413         const intel_limit_t *limit;
414
415         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
416                 if (is_dual_link_lvds(dev_priv, LVDS))
417                         /* LVDS with dual channel */
418                         limit = &intel_limits_g4x_dual_channel_lvds;
419                 else
420                         /* LVDS with dual channel */
421                         limit = &intel_limits_g4x_single_channel_lvds;
422         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI) ||
423                    intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG)) {
424                 limit = &intel_limits_g4x_hdmi;
425         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_SDVO)) {
426                 limit = &intel_limits_g4x_sdvo;
427         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT)) {
428                 limit = &intel_limits_g4x_display_port;
429         } else /* The option is for other outputs */
430                 limit = &intel_limits_i9xx_sdvo;
431
432         return limit;
433 }
434
435 static const intel_limit_t *intel_limit(struct drm_crtc *crtc, int refclk)
436 {
437         struct drm_device *dev = crtc->dev;
438         const intel_limit_t *limit;
439
440         if (HAS_PCH_SPLIT(dev))
441                 limit = intel_ironlake_limit(crtc, refclk);
442         else if (IS_G4X(dev)) {
443                 limit = intel_g4x_limit(crtc);
444         } else if (IS_PINEVIEW(dev)) {
445                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
446                         limit = &intel_limits_pineview_lvds;
447                 else
448                         limit = &intel_limits_pineview_sdvo;
449         } else if (!IS_GEN2(dev)) {
450                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
451                         limit = &intel_limits_i9xx_lvds;
452                 else
453                         limit = &intel_limits_i9xx_sdvo;
454         } else {
455                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
456                         limit = &intel_limits_i8xx_lvds;
457                 else
458                         limit = &intel_limits_i8xx_dvo;
459         }
460         return limit;
461 }
462
463 /* m1 is reserved as 0 in Pineview, n is a ring counter */
464 static void pineview_clock(int refclk, intel_clock_t *clock)
465 {
466         clock->m = clock->m2 + 2;
467         clock->p = clock->p1 * clock->p2;
468         clock->vco = refclk * clock->m / clock->n;
469         clock->dot = clock->vco / clock->p;
470 }
471
472 static void intel_clock(struct drm_device *dev, int refclk, intel_clock_t *clock)
473 {
474         if (IS_PINEVIEW(dev)) {
475                 pineview_clock(refclk, clock);
476                 return;
477         }
478         clock->m = 5 * (clock->m1 + 2) + (clock->m2 + 2);
479         clock->p = clock->p1 * clock->p2;
480         clock->vco = refclk * clock->m / (clock->n + 2);
481         clock->dot = clock->vco / clock->p;
482 }
483
484 /**
485  * Returns whether any output on the specified pipe is of the specified type
486  */
487 bool intel_pipe_has_type(struct drm_crtc *crtc, int type)
488 {
489         struct drm_device *dev = crtc->dev;
490         struct drm_mode_config *mode_config = &dev->mode_config;
491         struct intel_encoder *encoder;
492
493         list_for_each_entry(encoder, &mode_config->encoder_list, base.head)
494                 if (encoder->base.crtc == crtc && encoder->type == type)
495                         return true;
496
497         return false;
498 }
499
500 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
501 /**
502  * Returns whether the given set of divisors are valid for a given refclk with
503  * the given connectors.
504  */
505
506 static bool intel_PLL_is_valid(struct drm_device *dev,
507                                const intel_limit_t *limit,
508                                const intel_clock_t *clock)
509 {
510         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
511                 INTELPllInvalid("p1 out of range\n");
512         if (clock->p   < limit->p.min   || limit->p.max   < clock->p)
513                 INTELPllInvalid("p out of range\n");
514         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
515                 INTELPllInvalid("m2 out of range\n");
516         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
517                 INTELPllInvalid("m1 out of range\n");
518         if (clock->m1 <= clock->m2 && !IS_PINEVIEW(dev))
519                 INTELPllInvalid("m1 <= m2\n");
520         if (clock->m   < limit->m.min   || limit->m.max   < clock->m)
521                 INTELPllInvalid("m out of range\n");
522         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
523                 INTELPllInvalid("n out of range\n");
524         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
525                 INTELPllInvalid("vco out of range\n");
526         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
527          * connector, etc., rather than just a single range.
528          */
529         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
530                 INTELPllInvalid("dot out of range\n");
531
532         return true;
533 }
534
535 static bool
536 intel_find_best_PLL(const intel_limit_t *limit, struct drm_crtc *crtc,
537                     int target, int refclk, intel_clock_t *best_clock)
538
539 {
540         struct drm_device *dev = crtc->dev;
541         struct drm_i915_private *dev_priv = dev->dev_private;
542         intel_clock_t clock;
543         int err = target;
544
545         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
546             (I915_READ(LVDS)) != 0) {
547                 /*
548                  * For LVDS, if the panel is on, just rely on its current
549                  * settings for dual-channel.  We haven't figured out how to
550                  * reliably set up different single/dual channel state, if we
551                  * even can.
552                  */
553                 if (is_dual_link_lvds(dev_priv, LVDS))
554                         clock.p2 = limit->p2.p2_fast;
555                 else
556                         clock.p2 = limit->p2.p2_slow;
557         } else {
558                 if (target < limit->p2.dot_limit)
559                         clock.p2 = limit->p2.p2_slow;
560                 else
561                         clock.p2 = limit->p2.p2_fast;
562         }
563
564         memset(best_clock, 0, sizeof(*best_clock));
565
566         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
567              clock.m1++) {
568                 for (clock.m2 = limit->m2.min;
569                      clock.m2 <= limit->m2.max; clock.m2++) {
570                         /* m1 is always 0 in Pineview */
571                         if (clock.m2 >= clock.m1 && !IS_PINEVIEW(dev))
572                                 break;
573                         for (clock.n = limit->n.min;
574                              clock.n <= limit->n.max; clock.n++) {
575                                 for (clock.p1 = limit->p1.min;
576                                         clock.p1 <= limit->p1.max; clock.p1++) {
577                                         int this_err;
578
579                                         intel_clock(dev, refclk, &clock);
580                                         if (!intel_PLL_is_valid(dev, limit,
581                                                                 &clock))
582                                                 continue;
583
584                                         this_err = abs(clock.dot - target);
585                                         if (this_err < err) {
586                                                 *best_clock = clock;
587                                                 err = this_err;
588                                         }
589                                 }
590                         }
591                 }
592         }
593
594         return (err != target);
595 }
596
597 static bool
598 intel_g4x_find_best_PLL(const intel_limit_t *limit, struct drm_crtc *crtc,
599                         int target, int refclk, intel_clock_t *best_clock)
600 {
601         struct drm_device *dev = crtc->dev;
602         struct drm_i915_private *dev_priv = dev->dev_private;
603         intel_clock_t clock;
604         int max_n;
605         bool found;
606         /* approximately equals target * 0.00585 */
607         int err_most = (target >> 8) + (target >> 9);
608         found = false;
609
610         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
611                 int lvds_reg;
612
613                 if (HAS_PCH_SPLIT(dev))
614                         lvds_reg = PCH_LVDS;
615                 else
616                         lvds_reg = LVDS;
617                 if ((I915_READ(lvds_reg) & LVDS_CLKB_POWER_MASK) ==
618                     LVDS_CLKB_POWER_UP)
619                         clock.p2 = limit->p2.p2_fast;
620                 else
621                         clock.p2 = limit->p2.p2_slow;
622         } else {
623                 if (target < limit->p2.dot_limit)
624                         clock.p2 = limit->p2.p2_slow;
625                 else
626                         clock.p2 = limit->p2.p2_fast;
627         }
628
629         memset(best_clock, 0, sizeof(*best_clock));
630         max_n = limit->n.max;
631         /* based on hardware requirement, prefer smaller n to precision */
632         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
633                 /* based on hardware requirement, prefere larger m1,m2 */
634                 for (clock.m1 = limit->m1.max;
635                      clock.m1 >= limit->m1.min; clock.m1--) {
636                         for (clock.m2 = limit->m2.max;
637                              clock.m2 >= limit->m2.min; clock.m2--) {
638                                 for (clock.p1 = limit->p1.max;
639                                      clock.p1 >= limit->p1.min; clock.p1--) {
640                                         int this_err;
641
642                                         intel_clock(dev, refclk, &clock);
643                                         if (!intel_PLL_is_valid(dev, limit,
644                                                                 &clock))
645                                                 continue;
646
647                                         this_err = abs(clock.dot - target);
648                                         if (this_err < err_most) {
649                                                 *best_clock = clock;
650                                                 err_most = this_err;
651                                                 max_n = clock.n;
652                                                 found = true;
653                                         }
654                                 }
655                         }
656                 }
657         }
658         return found;
659 }
660
661 static bool
662 intel_find_pll_ironlake_dp(const intel_limit_t *limit, struct drm_crtc *crtc,
663                            int target, int refclk, intel_clock_t *best_clock)
664 {
665         struct drm_device *dev = crtc->dev;
666         intel_clock_t clock;
667
668         if (target < 200000) {
669                 clock.n = 1;
670                 clock.p1 = 2;
671                 clock.p2 = 10;
672                 clock.m1 = 12;
673                 clock.m2 = 9;
674         } else {
675                 clock.n = 2;
676                 clock.p1 = 1;
677                 clock.p2 = 10;
678                 clock.m1 = 14;
679                 clock.m2 = 8;
680         }
681         intel_clock(dev, refclk, &clock);
682         memcpy(best_clock, &clock, sizeof(intel_clock_t));
683         return true;
684 }
685
686 /* DisplayPort has only two frequencies, 162MHz and 270MHz */
687 static bool
688 intel_find_pll_g4x_dp(const intel_limit_t *limit, struct drm_crtc *crtc,
689                       int target, int refclk, intel_clock_t *best_clock)
690 {
691         intel_clock_t clock;
692         if (target < 200000) {
693                 clock.p1 = 2;
694                 clock.p2 = 10;
695                 clock.n = 2;
696                 clock.m1 = 23;
697                 clock.m2 = 8;
698         } else {
699                 clock.p1 = 1;
700                 clock.p2 = 10;
701                 clock.n = 1;
702                 clock.m1 = 14;
703                 clock.m2 = 2;
704         }
705         clock.m = 5 * (clock.m1 + 2) + (clock.m2 + 2);
706         clock.p = (clock.p1 * clock.p2);
707         clock.dot = 96000 * clock.m / (clock.n + 2) / clock.p;
708         clock.vco = 0;
709         memcpy(best_clock, &clock, sizeof(intel_clock_t));
710         return true;
711 }
712
713 /**
714  * intel_wait_for_vblank - wait for vblank on a given pipe
715  * @dev: drm device
716  * @pipe: pipe to wait for
717  *
718  * Wait for vblank to occur on a given pipe.  Needed for various bits of
719  * mode setting code.
720  */
721 void intel_wait_for_vblank(struct drm_device *dev, int pipe)
722 {
723         struct drm_i915_private *dev_priv = dev->dev_private;
724         int pipestat_reg = PIPESTAT(pipe);
725
726         /* Clear existing vblank status. Note this will clear any other
727          * sticky status fields as well.
728          *
729          * This races with i915_driver_irq_handler() with the result
730          * that either function could miss a vblank event.  Here it is not
731          * fatal, as we will either wait upon the next vblank interrupt or
732          * timeout.  Generally speaking intel_wait_for_vblank() is only
733          * called during modeset at which time the GPU should be idle and
734          * should *not* be performing page flips and thus not waiting on
735          * vblanks...
736          * Currently, the result of us stealing a vblank from the irq
737          * handler is that a single frame will be skipped during swapbuffers.
738          */
739         I915_WRITE(pipestat_reg,
740                    I915_READ(pipestat_reg) | PIPE_VBLANK_INTERRUPT_STATUS);
741
742         /* Wait for vblank interrupt bit to set */
743         if (wait_for(I915_READ(pipestat_reg) &
744                      PIPE_VBLANK_INTERRUPT_STATUS,
745                      50))
746                 DRM_DEBUG_KMS("vblank wait timed out\n");
747 }
748
749 /*
750  * intel_wait_for_pipe_off - wait for pipe to turn off
751  * @dev: drm device
752  * @pipe: pipe to wait for
753  *
754  * After disabling a pipe, we can't wait for vblank in the usual way,
755  * spinning on the vblank interrupt status bit, since we won't actually
756  * see an interrupt when the pipe is disabled.
757  *
758  * On Gen4 and above:
759  *   wait for the pipe register state bit to turn off
760  *
761  * Otherwise:
762  *   wait for the display line value to settle (it usually
763  *   ends up stopping at the start of the next frame).
764  *
765  */
766 void intel_wait_for_pipe_off(struct drm_device *dev, int pipe)
767 {
768         struct drm_i915_private *dev_priv = dev->dev_private;
769
770         if (INTEL_INFO(dev)->gen >= 4) {
771                 int reg = PIPECONF(pipe);
772
773                 /* Wait for the Pipe State to go off */
774                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
775                              100))
776                         DRM_DEBUG_KMS("pipe_off wait timed out\n");
777         } else {
778                 u32 last_line;
779                 int reg = PIPEDSL(pipe);
780                 unsigned long timeout = jiffies + msecs_to_jiffies(100);
781
782                 /* Wait for the display line to settle */
783                 do {
784                         last_line = I915_READ(reg) & DSL_LINEMASK;
785                         mdelay(5);
786                 } while (((I915_READ(reg) & DSL_LINEMASK) != last_line) &&
787                          time_after(timeout, jiffies));
788                 if (time_after(jiffies, timeout))
789                         DRM_DEBUG_KMS("pipe_off wait timed out\n");
790         }
791 }
792
793 static const char *state_string(bool enabled)
794 {
795         return enabled ? "on" : "off";
796 }
797
798 /* Only for pre-ILK configs */
799 static void assert_pll(struct drm_i915_private *dev_priv,
800                        enum pipe pipe, bool state)
801 {
802         int reg;
803         u32 val;
804         bool cur_state;
805
806         reg = DPLL(pipe);
807         val = I915_READ(reg);
808         cur_state = !!(val & DPLL_VCO_ENABLE);
809         WARN(cur_state != state,
810              "PLL state assertion failure (expected %s, current %s)\n",
811              state_string(state), state_string(cur_state));
812 }
813 #define assert_pll_enabled(d, p) assert_pll(d, p, true)
814 #define assert_pll_disabled(d, p) assert_pll(d, p, false)
815
816 /* For ILK+ */
817 static void assert_pch_pll(struct drm_i915_private *dev_priv,
818                            enum pipe pipe, bool state)
819 {
820         int reg;
821         u32 val;
822         bool cur_state;
823
824         if (HAS_PCH_CPT(dev_priv->dev)) {
825                 u32 pch_dpll;
826
827                 pch_dpll = I915_READ(PCH_DPLL_SEL);
828
829                 /* Make sure the selected PLL is enabled to the transcoder */
830                 WARN(!((pch_dpll >> (4 * pipe)) & 8),
831                      "transcoder %d PLL not enabled\n", pipe);
832
833                 /* Convert the transcoder pipe number to a pll pipe number */
834                 pipe = (pch_dpll >> (4 * pipe)) & 1;
835         }
836
837         reg = PCH_DPLL(pipe);
838         val = I915_READ(reg);
839         cur_state = !!(val & DPLL_VCO_ENABLE);
840         WARN(cur_state != state,
841              "PCH PLL state assertion failure (expected %s, current %s)\n",
842              state_string(state), state_string(cur_state));
843 }
844 #define assert_pch_pll_enabled(d, p) assert_pch_pll(d, p, true)
845 #define assert_pch_pll_disabled(d, p) assert_pch_pll(d, p, false)
846
847 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
848                           enum pipe pipe, bool state)
849 {
850         int reg;
851         u32 val;
852         bool cur_state;
853
854         reg = FDI_TX_CTL(pipe);
855         val = I915_READ(reg);
856         cur_state = !!(val & FDI_TX_ENABLE);
857         WARN(cur_state != state,
858              "FDI TX state assertion failure (expected %s, current %s)\n",
859              state_string(state), state_string(cur_state));
860 }
861 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
862 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
863
864 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
865                           enum pipe pipe, bool state)
866 {
867         int reg;
868         u32 val;
869         bool cur_state;
870
871         reg = FDI_RX_CTL(pipe);
872         val = I915_READ(reg);
873         cur_state = !!(val & FDI_RX_ENABLE);
874         WARN(cur_state != state,
875              "FDI RX state assertion failure (expected %s, current %s)\n",
876              state_string(state), state_string(cur_state));
877 }
878 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
879 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
880
881 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
882                                       enum pipe pipe)
883 {
884         int reg;
885         u32 val;
886
887         /* ILK FDI PLL is always enabled */
888         if (dev_priv->info->gen == 5)
889                 return;
890
891         reg = FDI_TX_CTL(pipe);
892         val = I915_READ(reg);
893         WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
894 }
895
896 static void assert_fdi_rx_pll_enabled(struct drm_i915_private *dev_priv,
897                                       enum pipe pipe)
898 {
899         int reg;
900         u32 val;
901
902         reg = FDI_RX_CTL(pipe);
903         val = I915_READ(reg);
904         WARN(!(val & FDI_RX_PLL_ENABLE), "FDI RX PLL assertion failure, should be active but is disabled\n");
905 }
906
907 static void assert_panel_unlocked(struct drm_i915_private *dev_priv,
908                                   enum pipe pipe)
909 {
910         int pp_reg, lvds_reg;
911         u32 val;
912         enum pipe panel_pipe = PIPE_A;
913         bool locked = true;
914
915         if (HAS_PCH_SPLIT(dev_priv->dev)) {
916                 pp_reg = PCH_PP_CONTROL;
917                 lvds_reg = PCH_LVDS;
918         } else {
919                 pp_reg = PP_CONTROL;
920                 lvds_reg = LVDS;
921         }
922
923         val = I915_READ(pp_reg);
924         if (!(val & PANEL_POWER_ON) ||
925             ((val & PANEL_UNLOCK_REGS) == PANEL_UNLOCK_REGS))
926                 locked = false;
927
928         if (I915_READ(lvds_reg) & LVDS_PIPEB_SELECT)
929                 panel_pipe = PIPE_B;
930
931         WARN(panel_pipe == pipe && locked,
932              "panel assertion failure, pipe %c regs locked\n",
933              pipe_name(pipe));
934 }
935
936 static void assert_pipe(struct drm_i915_private *dev_priv,
937                         enum pipe pipe, bool state)
938 {
939         int reg;
940         u32 val;
941         bool cur_state;
942
943         reg = PIPECONF(pipe);
944         val = I915_READ(reg);
945         cur_state = !!(val & PIPECONF_ENABLE);
946         WARN(cur_state != state,
947              "pipe %c assertion failure (expected %s, current %s)\n",
948              pipe_name(pipe), state_string(state), state_string(cur_state));
949 }
950 #define assert_pipe_enabled(d, p) assert_pipe(d, p, true)
951 #define assert_pipe_disabled(d, p) assert_pipe(d, p, false)
952
953 static void assert_plane_enabled(struct drm_i915_private *dev_priv,
954                                  enum plane plane)
955 {
956         int reg;
957         u32 val;
958
959         reg = DSPCNTR(plane);
960         val = I915_READ(reg);
961         WARN(!(val & DISPLAY_PLANE_ENABLE),
962              "plane %c assertion failure, should be active but is disabled\n",
963              plane_name(plane));
964 }
965
966 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
967                                    enum pipe pipe)
968 {
969         int reg, i;
970         u32 val;
971         int cur_pipe;
972
973         /* Planes are fixed to pipes on ILK+ */
974         if (HAS_PCH_SPLIT(dev_priv->dev))
975                 return;
976
977         /* Need to check both planes against the pipe */
978         for (i = 0; i < 2; i++) {
979                 reg = DSPCNTR(i);
980                 val = I915_READ(reg);
981                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
982                         DISPPLANE_SEL_PIPE_SHIFT;
983                 WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
984                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
985                      plane_name(i), pipe_name(pipe));
986         }
987 }
988
989 static void assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
990 {
991         u32 val;
992         bool enabled;
993
994         val = I915_READ(PCH_DREF_CONTROL);
995         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
996                             DREF_SUPERSPREAD_SOURCE_MASK));
997         WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
998 }
999
1000 static void assert_transcoder_disabled(struct drm_i915_private *dev_priv,
1001                                        enum pipe pipe)
1002 {
1003         int reg;
1004         u32 val;
1005         bool enabled;
1006
1007         reg = TRANSCONF(pipe);
1008         val = I915_READ(reg);
1009         enabled = !!(val & TRANS_ENABLE);
1010         WARN(enabled,
1011              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1012              pipe_name(pipe));
1013 }
1014
1015 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1016                             enum pipe pipe, u32 port_sel, u32 val)
1017 {
1018         if ((val & DP_PORT_EN) == 0)
1019                 return false;
1020
1021         if (HAS_PCH_CPT(dev_priv->dev)) {
1022                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1023                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1024                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1025                         return false;
1026         } else {
1027                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1028                         return false;
1029         }
1030         return true;
1031 }
1032
1033 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1034                               enum pipe pipe, u32 val)
1035 {
1036         if ((val & PORT_ENABLE) == 0)
1037                 return false;
1038
1039         if (HAS_PCH_CPT(dev_priv->dev)) {
1040                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1041                         return false;
1042         } else {
1043                 if ((val & TRANSCODER_MASK) != TRANSCODER(pipe))
1044                         return false;
1045         }
1046         return true;
1047 }
1048
1049 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1050                               enum pipe pipe, u32 val)
1051 {
1052         if ((val & LVDS_PORT_EN) == 0)
1053                 return false;
1054
1055         if (HAS_PCH_CPT(dev_priv->dev)) {
1056                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1057                         return false;
1058         } else {
1059                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1060                         return false;
1061         }
1062         return true;
1063 }
1064
1065 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1066                               enum pipe pipe, u32 val)
1067 {
1068         if ((val & ADPA_DAC_ENABLE) == 0)
1069                 return false;
1070         if (HAS_PCH_CPT(dev_priv->dev)) {
1071                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1072                         return false;
1073         } else {
1074                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1075                         return false;
1076         }
1077         return true;
1078 }
1079
1080 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1081                                    enum pipe pipe, int reg, u32 port_sel)
1082 {
1083         u32 val = I915_READ(reg);
1084         WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1085              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1086              reg, pipe_name(pipe));
1087 }
1088
1089 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1090                                      enum pipe pipe, int reg)
1091 {
1092         u32 val = I915_READ(reg);
1093         WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1094              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1095              reg, pipe_name(pipe));
1096 }
1097
1098 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1099                                       enum pipe pipe)
1100 {
1101         int reg;
1102         u32 val;
1103
1104         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1105         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1106         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1107
1108         reg = PCH_ADPA;
1109         val = I915_READ(reg);
1110         WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1111              "PCH VGA enabled on transcoder %c, should be disabled\n",
1112              pipe_name(pipe));
1113
1114         reg = PCH_LVDS;
1115         val = I915_READ(reg);
1116         WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1117              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1118              pipe_name(pipe));
1119
1120         assert_pch_hdmi_disabled(dev_priv, pipe, HDMIB);
1121         assert_pch_hdmi_disabled(dev_priv, pipe, HDMIC);
1122         assert_pch_hdmi_disabled(dev_priv, pipe, HDMID);
1123 }
1124
1125 /**
1126  * intel_enable_pll - enable a PLL
1127  * @dev_priv: i915 private structure
1128  * @pipe: pipe PLL to enable
1129  *
1130  * Enable @pipe's PLL so we can start pumping pixels from a plane.  Check to
1131  * make sure the PLL reg is writable first though, since the panel write
1132  * protect mechanism may be enabled.
1133  *
1134  * Note!  This is for pre-ILK only.
1135  */
1136 static void intel_enable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1137 {
1138         int reg;
1139         u32 val;
1140
1141         /* No really, not for ILK+ */
1142         BUG_ON(dev_priv->info->gen >= 5);
1143
1144         /* PLL is protected by panel, make sure we can write it */
1145         if (IS_MOBILE(dev_priv->dev) && !IS_I830(dev_priv->dev))
1146                 assert_panel_unlocked(dev_priv, pipe);
1147
1148         reg = DPLL(pipe);
1149         val = I915_READ(reg);
1150         val |= DPLL_VCO_ENABLE;
1151
1152         /* We do this three times for luck */
1153         I915_WRITE(reg, val);
1154         POSTING_READ(reg);
1155         udelay(150); /* wait for warmup */
1156         I915_WRITE(reg, val);
1157         POSTING_READ(reg);
1158         udelay(150); /* wait for warmup */
1159         I915_WRITE(reg, val);
1160         POSTING_READ(reg);
1161         udelay(150); /* wait for warmup */
1162 }
1163
1164 /**
1165  * intel_disable_pll - disable a PLL
1166  * @dev_priv: i915 private structure
1167  * @pipe: pipe PLL to disable
1168  *
1169  * Disable the PLL for @pipe, making sure the pipe is off first.
1170  *
1171  * Note!  This is for pre-ILK only.
1172  */
1173 static void intel_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1174 {
1175         int reg;
1176         u32 val;
1177
1178         /* Don't disable pipe A or pipe A PLLs if needed */
1179         if (pipe == PIPE_A && (dev_priv->quirks & QUIRK_PIPEA_FORCE))
1180                 return;
1181
1182         /* Make sure the pipe isn't still relying on us */
1183         assert_pipe_disabled(dev_priv, pipe);
1184
1185         reg = DPLL(pipe);
1186         val = I915_READ(reg);
1187         val &= ~DPLL_VCO_ENABLE;
1188         I915_WRITE(reg, val);
1189         POSTING_READ(reg);
1190 }
1191
1192 /**
1193  * intel_enable_pch_pll - enable PCH PLL
1194  * @dev_priv: i915 private structure
1195  * @pipe: pipe PLL to enable
1196  *
1197  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1198  * drives the transcoder clock.
1199  */
1200 static void intel_enable_pch_pll(struct drm_i915_private *dev_priv,
1201                                  enum pipe pipe)
1202 {
1203         int reg;
1204         u32 val;
1205
1206         if (pipe > 1)
1207                 return;
1208
1209         /* PCH only available on ILK+ */
1210         BUG_ON(dev_priv->info->gen < 5);
1211
1212         /* PCH refclock must be enabled first */
1213         assert_pch_refclk_enabled(dev_priv);
1214
1215         reg = PCH_DPLL(pipe);
1216         val = I915_READ(reg);
1217         val |= DPLL_VCO_ENABLE;
1218         I915_WRITE(reg, val);
1219         POSTING_READ(reg);
1220         udelay(200);
1221 }
1222
1223 static void intel_disable_pch_pll(struct drm_i915_private *dev_priv,
1224                                   enum pipe pipe)
1225 {
1226         int reg;
1227         u32 val;
1228
1229         if (pipe > 1)
1230                 return;
1231
1232         /* PCH only available on ILK+ */
1233         BUG_ON(dev_priv->info->gen < 5);
1234
1235         /* Make sure transcoder isn't still depending on us */
1236         assert_transcoder_disabled(dev_priv, pipe);
1237
1238         reg = PCH_DPLL(pipe);
1239         val = I915_READ(reg);
1240         val &= ~DPLL_VCO_ENABLE;
1241         I915_WRITE(reg, val);
1242         POSTING_READ(reg);
1243         udelay(200);
1244 }
1245
1246 static void intel_enable_transcoder(struct drm_i915_private *dev_priv,
1247                                     enum pipe pipe)
1248 {
1249         int reg;
1250         u32 val;
1251
1252         /* PCH only available on ILK+ */
1253         BUG_ON(dev_priv->info->gen < 5);
1254
1255         /* Make sure PCH DPLL is enabled */
1256         assert_pch_pll_enabled(dev_priv, pipe);
1257
1258         /* FDI must be feeding us bits for PCH ports */
1259         assert_fdi_tx_enabled(dev_priv, pipe);
1260         assert_fdi_rx_enabled(dev_priv, pipe);
1261
1262         reg = TRANSCONF(pipe);
1263         val = I915_READ(reg);
1264
1265         if (HAS_PCH_IBX(dev_priv->dev)) {
1266                 /*
1267                  * make the BPC in transcoder be consistent with
1268                  * that in pipeconf reg.
1269                  */
1270                 val &= ~PIPE_BPC_MASK;
1271                 val |= I915_READ(PIPECONF(pipe)) & PIPE_BPC_MASK;
1272         }
1273         I915_WRITE(reg, val | TRANS_ENABLE);
1274         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1275                 DRM_ERROR("failed to enable transcoder %d\n", pipe);
1276 }
1277
1278 static void intel_disable_transcoder(struct drm_i915_private *dev_priv,
1279                                      enum pipe pipe)
1280 {
1281         int reg;
1282         u32 val;
1283
1284         /* FDI relies on the transcoder */
1285         assert_fdi_tx_disabled(dev_priv, pipe);
1286         assert_fdi_rx_disabled(dev_priv, pipe);
1287
1288         /* Ports must be off as well */
1289         assert_pch_ports_disabled(dev_priv, pipe);
1290
1291         reg = TRANSCONF(pipe);
1292         val = I915_READ(reg);
1293         val &= ~TRANS_ENABLE;
1294         I915_WRITE(reg, val);
1295         /* wait for PCH transcoder off, transcoder state */
1296         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1297                 DRM_ERROR("failed to disable transcoder %d\n", pipe);
1298 }
1299
1300 /**
1301  * intel_enable_pipe - enable a pipe, asserting requirements
1302  * @dev_priv: i915 private structure
1303  * @pipe: pipe to enable
1304  * @pch_port: on ILK+, is this pipe driving a PCH port or not
1305  *
1306  * Enable @pipe, making sure that various hardware specific requirements
1307  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1308  *
1309  * @pipe should be %PIPE_A or %PIPE_B.
1310  *
1311  * Will wait until the pipe is actually running (i.e. first vblank) before
1312  * returning.
1313  */
1314 static void intel_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe,
1315                               bool pch_port)
1316 {
1317         int reg;
1318         u32 val;
1319
1320         /*
1321          * A pipe without a PLL won't actually be able to drive bits from
1322          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1323          * need the check.
1324          */
1325         if (!HAS_PCH_SPLIT(dev_priv->dev))
1326                 assert_pll_enabled(dev_priv, pipe);
1327         else {
1328                 if (pch_port) {
1329                         /* if driving the PCH, we need FDI enabled */
1330                         assert_fdi_rx_pll_enabled(dev_priv, pipe);
1331                         assert_fdi_tx_pll_enabled(dev_priv, pipe);
1332                 }
1333                 /* FIXME: assert CPU port conditions for SNB+ */
1334         }
1335
1336         reg = PIPECONF(pipe);
1337         val = I915_READ(reg);
1338         if (val & PIPECONF_ENABLE)
1339                 return;
1340
1341         I915_WRITE(reg, val | PIPECONF_ENABLE);
1342         intel_wait_for_vblank(dev_priv->dev, pipe);
1343 }
1344
1345 /**
1346  * intel_disable_pipe - disable a pipe, asserting requirements
1347  * @dev_priv: i915 private structure
1348  * @pipe: pipe to disable
1349  *
1350  * Disable @pipe, making sure that various hardware specific requirements
1351  * are met, if applicable, e.g. plane disabled, panel fitter off, etc.
1352  *
1353  * @pipe should be %PIPE_A or %PIPE_B.
1354  *
1355  * Will wait until the pipe has shut down before returning.
1356  */
1357 static void intel_disable_pipe(struct drm_i915_private *dev_priv,
1358                                enum pipe pipe)
1359 {
1360         int reg;
1361         u32 val;
1362
1363         /*
1364          * Make sure planes won't keep trying to pump pixels to us,
1365          * or we might hang the display.
1366          */
1367         assert_planes_disabled(dev_priv, pipe);
1368
1369         /* Don't disable pipe A or pipe A PLLs if needed */
1370         if (pipe == PIPE_A && (dev_priv->quirks & QUIRK_PIPEA_FORCE))
1371                 return;
1372
1373         reg = PIPECONF(pipe);
1374         val = I915_READ(reg);
1375         if ((val & PIPECONF_ENABLE) == 0)
1376                 return;
1377
1378         I915_WRITE(reg, val & ~PIPECONF_ENABLE);
1379         intel_wait_for_pipe_off(dev_priv->dev, pipe);
1380 }
1381
1382 /*
1383  * Plane regs are double buffered, going from enabled->disabled needs a
1384  * trigger in order to latch.  The display address reg provides this.
1385  */
1386 static void intel_flush_display_plane(struct drm_i915_private *dev_priv,
1387                                       enum plane plane)
1388 {
1389         I915_WRITE(DSPADDR(plane), I915_READ(DSPADDR(plane)));
1390         I915_WRITE(DSPSURF(plane), I915_READ(DSPSURF(plane)));
1391 }
1392
1393 /**
1394  * intel_enable_plane - enable a display plane on a given pipe
1395  * @dev_priv: i915 private structure
1396  * @plane: plane to enable
1397  * @pipe: pipe being fed
1398  *
1399  * Enable @plane on @pipe, making sure that @pipe is running first.
1400  */
1401 static void intel_enable_plane(struct drm_i915_private *dev_priv,
1402                                enum plane plane, enum pipe pipe)
1403 {
1404         int reg;
1405         u32 val;
1406
1407         /* If the pipe isn't enabled, we can't pump pixels and may hang */
1408         assert_pipe_enabled(dev_priv, pipe);
1409
1410         reg = DSPCNTR(plane);
1411         val = I915_READ(reg);
1412         if (val & DISPLAY_PLANE_ENABLE)
1413                 return;
1414
1415         I915_WRITE(reg, val | DISPLAY_PLANE_ENABLE);
1416         intel_flush_display_plane(dev_priv, plane);
1417         intel_wait_for_vblank(dev_priv->dev, pipe);
1418 }
1419
1420 /**
1421  * intel_disable_plane - disable a display plane
1422  * @dev_priv: i915 private structure
1423  * @plane: plane to disable
1424  * @pipe: pipe consuming the data
1425  *
1426  * Disable @plane; should be an independent operation.
1427  */
1428 static void intel_disable_plane(struct drm_i915_private *dev_priv,
1429                                 enum plane plane, enum pipe pipe)
1430 {
1431         int reg;
1432         u32 val;
1433
1434         reg = DSPCNTR(plane);
1435         val = I915_READ(reg);
1436         if ((val & DISPLAY_PLANE_ENABLE) == 0)
1437                 return;
1438
1439         I915_WRITE(reg, val & ~DISPLAY_PLANE_ENABLE);
1440         intel_flush_display_plane(dev_priv, plane);
1441         intel_wait_for_vblank(dev_priv->dev, pipe);
1442 }
1443
1444 static void disable_pch_dp(struct drm_i915_private *dev_priv,
1445                            enum pipe pipe, int reg, u32 port_sel)
1446 {
1447         u32 val = I915_READ(reg);
1448         if (dp_pipe_enabled(dev_priv, pipe, port_sel, val)) {
1449                 DRM_DEBUG_KMS("Disabling pch dp %x on pipe %d\n", reg, pipe);
1450                 I915_WRITE(reg, val & ~DP_PORT_EN);
1451         }
1452 }
1453
1454 static void disable_pch_hdmi(struct drm_i915_private *dev_priv,
1455                              enum pipe pipe, int reg)
1456 {
1457         u32 val = I915_READ(reg);
1458         if (hdmi_pipe_enabled(dev_priv, pipe, val)) {
1459                 DRM_DEBUG_KMS("Disabling pch HDMI %x on pipe %d\n",
1460                               reg, pipe);
1461                 I915_WRITE(reg, val & ~PORT_ENABLE);
1462         }
1463 }
1464
1465 /* Disable any ports connected to this transcoder */
1466 static void intel_disable_pch_ports(struct drm_i915_private *dev_priv,
1467                                     enum pipe pipe)
1468 {
1469         u32 reg, val;
1470
1471         val = I915_READ(PCH_PP_CONTROL);
1472         I915_WRITE(PCH_PP_CONTROL, val | PANEL_UNLOCK_REGS);
1473
1474         disable_pch_dp(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1475         disable_pch_dp(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1476         disable_pch_dp(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1477
1478         reg = PCH_ADPA;
1479         val = I915_READ(reg);
1480         if (adpa_pipe_enabled(dev_priv, pipe, val))
1481                 I915_WRITE(reg, val & ~ADPA_DAC_ENABLE);
1482
1483         reg = PCH_LVDS;
1484         val = I915_READ(reg);
1485         if (lvds_pipe_enabled(dev_priv, pipe, val)) {
1486                 DRM_DEBUG_KMS("disable lvds on pipe %d val 0x%08x\n", pipe, val);
1487                 I915_WRITE(reg, val & ~LVDS_PORT_EN);
1488                 POSTING_READ(reg);
1489                 udelay(100);
1490         }
1491
1492         disable_pch_hdmi(dev_priv, pipe, HDMIB);
1493         disable_pch_hdmi(dev_priv, pipe, HDMIC);
1494         disable_pch_hdmi(dev_priv, pipe, HDMID);
1495 }
1496
1497 static void i8xx_disable_fbc(struct drm_device *dev)
1498 {
1499         struct drm_i915_private *dev_priv = dev->dev_private;
1500         u32 fbc_ctl;
1501
1502         /* Disable compression */
1503         fbc_ctl = I915_READ(FBC_CONTROL);
1504         if ((fbc_ctl & FBC_CTL_EN) == 0)
1505                 return;
1506
1507         fbc_ctl &= ~FBC_CTL_EN;
1508         I915_WRITE(FBC_CONTROL, fbc_ctl);
1509
1510         /* Wait for compressing bit to clear */
1511         if (wait_for((I915_READ(FBC_STATUS) & FBC_STAT_COMPRESSING) == 0, 10)) {
1512                 DRM_DEBUG_KMS("FBC idle timed out\n");
1513                 return;
1514         }
1515
1516         DRM_DEBUG_KMS("disabled FBC\n");
1517 }
1518
1519 static void i8xx_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
1520 {
1521         struct drm_device *dev = crtc->dev;
1522         struct drm_i915_private *dev_priv = dev->dev_private;
1523         struct drm_framebuffer *fb = crtc->fb;
1524         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
1525         struct drm_i915_gem_object *obj = intel_fb->obj;
1526         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1527         int cfb_pitch;
1528         int plane, i;
1529         u32 fbc_ctl, fbc_ctl2;
1530
1531         cfb_pitch = dev_priv->cfb_size / FBC_LL_SIZE;
1532         if (fb->pitch < cfb_pitch)
1533                 cfb_pitch = fb->pitch;
1534
1535         /* FBC_CTL wants 64B units */
1536         cfb_pitch = (cfb_pitch / 64) - 1;
1537         plane = intel_crtc->plane == 0 ? FBC_CTL_PLANEA : FBC_CTL_PLANEB;
1538
1539         /* Clear old tags */
1540         for (i = 0; i < (FBC_LL_SIZE / 32) + 1; i++)
1541                 I915_WRITE(FBC_TAG + (i * 4), 0);
1542
1543         /* Set it up... */
1544         fbc_ctl2 = FBC_CTL_FENCE_DBL | FBC_CTL_IDLE_IMM | FBC_CTL_CPU_FENCE;
1545         fbc_ctl2 |= plane;
1546         I915_WRITE(FBC_CONTROL2, fbc_ctl2);
1547         I915_WRITE(FBC_FENCE_OFF, crtc->y);
1548
1549         /* enable it... */
1550         fbc_ctl = FBC_CTL_EN | FBC_CTL_PERIODIC;
1551         if (IS_I945GM(dev))
1552                 fbc_ctl |= FBC_CTL_C3_IDLE; /* 945 needs special SR handling */
1553         fbc_ctl |= (cfb_pitch & 0xff) << FBC_CTL_STRIDE_SHIFT;
1554         fbc_ctl |= (interval & 0x2fff) << FBC_CTL_INTERVAL_SHIFT;
1555         fbc_ctl |= obj->fence_reg;
1556         I915_WRITE(FBC_CONTROL, fbc_ctl);
1557
1558         DRM_DEBUG_KMS("enabled FBC, pitch %d, yoff %d, plane %d, ",
1559                       cfb_pitch, crtc->y, intel_crtc->plane);
1560 }
1561
1562 static bool i8xx_fbc_enabled(struct drm_device *dev)
1563 {
1564         struct drm_i915_private *dev_priv = dev->dev_private;
1565
1566         return I915_READ(FBC_CONTROL) & FBC_CTL_EN;
1567 }
1568
1569 static void g4x_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
1570 {
1571         struct drm_device *dev = crtc->dev;
1572         struct drm_i915_private *dev_priv = dev->dev_private;
1573         struct drm_framebuffer *fb = crtc->fb;
1574         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
1575         struct drm_i915_gem_object *obj = intel_fb->obj;
1576         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1577         int plane = intel_crtc->plane == 0 ? DPFC_CTL_PLANEA : DPFC_CTL_PLANEB;
1578         unsigned long stall_watermark = 200;
1579         u32 dpfc_ctl;
1580
1581         dpfc_ctl = plane | DPFC_SR_EN | DPFC_CTL_LIMIT_1X;
1582         dpfc_ctl |= DPFC_CTL_FENCE_EN | obj->fence_reg;
1583         I915_WRITE(DPFC_CHICKEN, DPFC_HT_MODIFY);
1584
1585         I915_WRITE(DPFC_RECOMP_CTL, DPFC_RECOMP_STALL_EN |
1586                    (stall_watermark << DPFC_RECOMP_STALL_WM_SHIFT) |
1587                    (interval << DPFC_RECOMP_TIMER_COUNT_SHIFT));
1588         I915_WRITE(DPFC_FENCE_YOFF, crtc->y);
1589
1590         /* enable it... */
1591         I915_WRITE(DPFC_CONTROL, I915_READ(DPFC_CONTROL) | DPFC_CTL_EN);
1592
1593         DRM_DEBUG_KMS("enabled fbc on plane %d\n", intel_crtc->plane);
1594 }
1595
1596 static void g4x_disable_fbc(struct drm_device *dev)
1597 {
1598         struct drm_i915_private *dev_priv = dev->dev_private;
1599         u32 dpfc_ctl;
1600
1601         /* Disable compression */
1602         dpfc_ctl = I915_READ(DPFC_CONTROL);
1603         if (dpfc_ctl & DPFC_CTL_EN) {
1604                 dpfc_ctl &= ~DPFC_CTL_EN;
1605                 I915_WRITE(DPFC_CONTROL, dpfc_ctl);
1606
1607                 DRM_DEBUG_KMS("disabled FBC\n");
1608         }
1609 }
1610
1611 static bool g4x_fbc_enabled(struct drm_device *dev)
1612 {
1613         struct drm_i915_private *dev_priv = dev->dev_private;
1614
1615         return I915_READ(DPFC_CONTROL) & DPFC_CTL_EN;
1616 }
1617
1618 static void sandybridge_blit_fbc_update(struct drm_device *dev)
1619 {
1620         struct drm_i915_private *dev_priv = dev->dev_private;
1621         u32 blt_ecoskpd;
1622
1623         /* Make sure blitter notifies FBC of writes */
1624         gen6_gt_force_wake_get(dev_priv);
1625         blt_ecoskpd = I915_READ(GEN6_BLITTER_ECOSKPD);
1626         blt_ecoskpd |= GEN6_BLITTER_FBC_NOTIFY <<
1627                 GEN6_BLITTER_LOCK_SHIFT;
1628         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
1629         blt_ecoskpd |= GEN6_BLITTER_FBC_NOTIFY;
1630         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
1631         blt_ecoskpd &= ~(GEN6_BLITTER_FBC_NOTIFY <<
1632                          GEN6_BLITTER_LOCK_SHIFT);
1633         I915_WRITE(GEN6_BLITTER_ECOSKPD, blt_ecoskpd);
1634         POSTING_READ(GEN6_BLITTER_ECOSKPD);
1635         gen6_gt_force_wake_put(dev_priv);
1636 }
1637
1638 static void ironlake_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
1639 {
1640         struct drm_device *dev = crtc->dev;
1641         struct drm_i915_private *dev_priv = dev->dev_private;
1642         struct drm_framebuffer *fb = crtc->fb;
1643         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
1644         struct drm_i915_gem_object *obj = intel_fb->obj;
1645         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1646         int plane = intel_crtc->plane == 0 ? DPFC_CTL_PLANEA : DPFC_CTL_PLANEB;
1647         unsigned long stall_watermark = 200;
1648         u32 dpfc_ctl;
1649
1650         dpfc_ctl = I915_READ(ILK_DPFC_CONTROL);
1651         dpfc_ctl &= DPFC_RESERVED;
1652         dpfc_ctl |= (plane | DPFC_CTL_LIMIT_1X);
1653         /* Set persistent mode for front-buffer rendering, ala X. */
1654         dpfc_ctl |= DPFC_CTL_PERSISTENT_MODE;
1655         dpfc_ctl |= (DPFC_CTL_FENCE_EN | obj->fence_reg);
1656         I915_WRITE(ILK_DPFC_CHICKEN, DPFC_HT_MODIFY);
1657
1658         I915_WRITE(ILK_DPFC_RECOMP_CTL, DPFC_RECOMP_STALL_EN |
1659                    (stall_watermark << DPFC_RECOMP_STALL_WM_SHIFT) |
1660                    (interval << DPFC_RECOMP_TIMER_COUNT_SHIFT));
1661         I915_WRITE(ILK_DPFC_FENCE_YOFF, crtc->y);
1662         I915_WRITE(ILK_FBC_RT_BASE, obj->gtt_offset | ILK_FBC_RT_VALID);
1663         /* enable it... */
1664         I915_WRITE(ILK_DPFC_CONTROL, dpfc_ctl | DPFC_CTL_EN);
1665
1666         if (IS_GEN6(dev)) {
1667                 I915_WRITE(SNB_DPFC_CTL_SA,
1668                            SNB_CPU_FENCE_ENABLE | obj->fence_reg);
1669                 I915_WRITE(DPFC_CPU_FENCE_OFFSET, crtc->y);
1670                 sandybridge_blit_fbc_update(dev);
1671         }
1672
1673         DRM_DEBUG_KMS("enabled fbc on plane %d\n", intel_crtc->plane);
1674 }
1675
1676 static void ironlake_disable_fbc(struct drm_device *dev)
1677 {
1678         struct drm_i915_private *dev_priv = dev->dev_private;
1679         u32 dpfc_ctl;
1680
1681         /* Disable compression */
1682         dpfc_ctl = I915_READ(ILK_DPFC_CONTROL);
1683         if (dpfc_ctl & DPFC_CTL_EN) {
1684                 dpfc_ctl &= ~DPFC_CTL_EN;
1685                 I915_WRITE(ILK_DPFC_CONTROL, dpfc_ctl);
1686
1687                 DRM_DEBUG_KMS("disabled FBC\n");
1688         }
1689 }
1690
1691 static bool ironlake_fbc_enabled(struct drm_device *dev)
1692 {
1693         struct drm_i915_private *dev_priv = dev->dev_private;
1694
1695         return I915_READ(ILK_DPFC_CONTROL) & DPFC_CTL_EN;
1696 }
1697
1698 bool intel_fbc_enabled(struct drm_device *dev)
1699 {
1700         struct drm_i915_private *dev_priv = dev->dev_private;
1701
1702         if (!dev_priv->display.fbc_enabled)
1703                 return false;
1704
1705         return dev_priv->display.fbc_enabled(dev);
1706 }
1707
1708 static void intel_fbc_work_fn(struct work_struct *__work)
1709 {
1710         struct intel_fbc_work *work =
1711                 container_of(to_delayed_work(__work),
1712                              struct intel_fbc_work, work);
1713         struct drm_device *dev = work->crtc->dev;
1714         struct drm_i915_private *dev_priv = dev->dev_private;
1715
1716         mutex_lock(&dev->struct_mutex);
1717         if (work == dev_priv->fbc_work) {
1718                 /* Double check that we haven't switched fb without cancelling
1719                  * the prior work.
1720                  */
1721                 if (work->crtc->fb == work->fb) {
1722                         dev_priv->display.enable_fbc(work->crtc,
1723                                                      work->interval);
1724
1725                         dev_priv->cfb_plane = to_intel_crtc(work->crtc)->plane;
1726                         dev_priv->cfb_fb = work->crtc->fb->base.id;
1727                         dev_priv->cfb_y = work->crtc->y;
1728                 }
1729
1730                 dev_priv->fbc_work = NULL;
1731         }
1732         mutex_unlock(&dev->struct_mutex);
1733
1734         kfree(work);
1735 }
1736
1737 static void intel_cancel_fbc_work(struct drm_i915_private *dev_priv)
1738 {
1739         if (dev_priv->fbc_work == NULL)
1740                 return;
1741
1742         DRM_DEBUG_KMS("cancelling pending FBC enable\n");
1743
1744         /* Synchronisation is provided by struct_mutex and checking of
1745          * dev_priv->fbc_work, so we can perform the cancellation
1746          * entirely asynchronously.
1747          */
1748         if (cancel_delayed_work(&dev_priv->fbc_work->work))
1749                 /* tasklet was killed before being run, clean up */
1750                 kfree(dev_priv->fbc_work);
1751
1752         /* Mark the work as no longer wanted so that if it does
1753          * wake-up (because the work was already running and waiting
1754          * for our mutex), it will discover that is no longer
1755          * necessary to run.
1756          */
1757         dev_priv->fbc_work = NULL;
1758 }
1759
1760 static void intel_enable_fbc(struct drm_crtc *crtc, unsigned long interval)
1761 {
1762         struct intel_fbc_work *work;
1763         struct drm_device *dev = crtc->dev;
1764         struct drm_i915_private *dev_priv = dev->dev_private;
1765
1766         if (!dev_priv->display.enable_fbc)
1767                 return;
1768
1769         intel_cancel_fbc_work(dev_priv);
1770
1771         work = kzalloc(sizeof *work, GFP_KERNEL);
1772         if (work == NULL) {
1773                 dev_priv->display.enable_fbc(crtc, interval);
1774                 return;
1775         }
1776
1777         work->crtc = crtc;
1778         work->fb = crtc->fb;
1779         work->interval = interval;
1780         INIT_DELAYED_WORK(&work->work, intel_fbc_work_fn);
1781
1782         dev_priv->fbc_work = work;
1783
1784         DRM_DEBUG_KMS("scheduling delayed FBC enable\n");
1785
1786         /* Delay the actual enabling to let pageflipping cease and the
1787          * display to settle before starting the compression. Note that
1788          * this delay also serves a second purpose: it allows for a
1789          * vblank to pass after disabling the FBC before we attempt
1790          * to modify the control registers.
1791          *
1792          * A more complicated solution would involve tracking vblanks
1793          * following the termination of the page-flipping sequence
1794          * and indeed performing the enable as a co-routine and not
1795          * waiting synchronously upon the vblank.
1796          */
1797         schedule_delayed_work(&work->work, msecs_to_jiffies(50));
1798 }
1799
1800 void intel_disable_fbc(struct drm_device *dev)
1801 {
1802         struct drm_i915_private *dev_priv = dev->dev_private;
1803
1804         intel_cancel_fbc_work(dev_priv);
1805
1806         if (!dev_priv->display.disable_fbc)
1807                 return;
1808
1809         dev_priv->display.disable_fbc(dev);
1810         dev_priv->cfb_plane = -1;
1811 }
1812
1813 /**
1814  * intel_update_fbc - enable/disable FBC as needed
1815  * @dev: the drm_device
1816  *
1817  * Set up the framebuffer compression hardware at mode set time.  We
1818  * enable it if possible:
1819  *   - plane A only (on pre-965)
1820  *   - no pixel mulitply/line duplication
1821  *   - no alpha buffer discard
1822  *   - no dual wide
1823  *   - framebuffer <= 2048 in width, 1536 in height
1824  *
1825  * We can't assume that any compression will take place (worst case),
1826  * so the compressed buffer has to be the same size as the uncompressed
1827  * one.  It also must reside (along with the line length buffer) in
1828  * stolen memory.
1829  *
1830  * We need to enable/disable FBC on a global basis.
1831  */
1832 static void intel_update_fbc(struct drm_device *dev)
1833 {
1834         struct drm_i915_private *dev_priv = dev->dev_private;
1835         struct drm_crtc *crtc = NULL, *tmp_crtc;
1836         struct intel_crtc *intel_crtc;
1837         struct drm_framebuffer *fb;
1838         struct intel_framebuffer *intel_fb;
1839         struct drm_i915_gem_object *obj;
1840         int enable_fbc;
1841
1842         DRM_DEBUG_KMS("\n");
1843
1844         if (!i915_powersave)
1845                 return;
1846
1847         if (!I915_HAS_FBC(dev))
1848                 return;
1849
1850         /*
1851          * If FBC is already on, we just have to verify that we can
1852          * keep it that way...
1853          * Need to disable if:
1854          *   - more than one pipe is active
1855          *   - changing FBC params (stride, fence, mode)
1856          *   - new fb is too large to fit in compressed buffer
1857          *   - going to an unsupported config (interlace, pixel multiply, etc.)
1858          */
1859         list_for_each_entry(tmp_crtc, &dev->mode_config.crtc_list, head) {
1860                 if (tmp_crtc->enabled && tmp_crtc->fb) {
1861                         if (crtc) {
1862                                 DRM_DEBUG_KMS("more than one pipe active, disabling compression\n");
1863                                 dev_priv->no_fbc_reason = FBC_MULTIPLE_PIPES;
1864                                 goto out_disable;
1865                         }
1866                         crtc = tmp_crtc;
1867                 }
1868         }
1869
1870         if (!crtc || crtc->fb == NULL) {
1871                 DRM_DEBUG_KMS("no output, disabling\n");
1872                 dev_priv->no_fbc_reason = FBC_NO_OUTPUT;
1873                 goto out_disable;
1874         }
1875
1876         intel_crtc = to_intel_crtc(crtc);
1877         fb = crtc->fb;
1878         intel_fb = to_intel_framebuffer(fb);
1879         obj = intel_fb->obj;
1880
1881         enable_fbc = i915_enable_fbc;
1882         if (enable_fbc < 0) {
1883                 DRM_DEBUG_KMS("fbc set to per-chip default\n");
1884                 enable_fbc = 1;
1885                 if (INTEL_INFO(dev)->gen <= 6)
1886                         enable_fbc = 0;
1887         }
1888         if (!enable_fbc) {
1889                 DRM_DEBUG_KMS("fbc disabled per module param\n");
1890                 dev_priv->no_fbc_reason = FBC_MODULE_PARAM;
1891                 goto out_disable;
1892         }
1893         if (intel_fb->obj->base.size > dev_priv->cfb_size) {
1894                 DRM_DEBUG_KMS("framebuffer too large, disabling "
1895                               "compression\n");
1896                 dev_priv->no_fbc_reason = FBC_STOLEN_TOO_SMALL;
1897                 goto out_disable;
1898         }
1899         if ((crtc->mode.flags & DRM_MODE_FLAG_INTERLACE) ||
1900             (crtc->mode.flags & DRM_MODE_FLAG_DBLSCAN)) {
1901                 DRM_DEBUG_KMS("mode incompatible with compression, "
1902                               "disabling\n");
1903                 dev_priv->no_fbc_reason = FBC_UNSUPPORTED_MODE;
1904                 goto out_disable;
1905         }
1906         if ((crtc->mode.hdisplay > 2048) ||
1907             (crtc->mode.vdisplay > 1536)) {
1908                 DRM_DEBUG_KMS("mode too large for compression, disabling\n");
1909                 dev_priv->no_fbc_reason = FBC_MODE_TOO_LARGE;
1910                 goto out_disable;
1911         }
1912         if ((IS_I915GM(dev) || IS_I945GM(dev)) && intel_crtc->plane != 0) {
1913                 DRM_DEBUG_KMS("plane not 0, disabling compression\n");
1914                 dev_priv->no_fbc_reason = FBC_BAD_PLANE;
1915                 goto out_disable;
1916         }
1917
1918         /* The use of a CPU fence is mandatory in order to detect writes
1919          * by the CPU to the scanout and trigger updates to the FBC.
1920          */
1921         if (obj->tiling_mode != I915_TILING_X ||
1922             obj->fence_reg == I915_FENCE_REG_NONE) {
1923                 DRM_DEBUG_KMS("framebuffer not tiled or fenced, disabling compression\n");
1924                 dev_priv->no_fbc_reason = FBC_NOT_TILED;
1925                 goto out_disable;
1926         }
1927
1928         /* If the kernel debugger is active, always disable compression */
1929         if (in_dbg_master())
1930                 goto out_disable;
1931
1932         /* If the scanout has not changed, don't modify the FBC settings.
1933          * Note that we make the fundamental assumption that the fb->obj
1934          * cannot be unpinned (and have its GTT offset and fence revoked)
1935          * without first being decoupled from the scanout and FBC disabled.
1936          */
1937         if (dev_priv->cfb_plane == intel_crtc->plane &&
1938             dev_priv->cfb_fb == fb->base.id &&
1939             dev_priv->cfb_y == crtc->y)
1940                 return;
1941
1942         if (intel_fbc_enabled(dev)) {
1943                 /* We update FBC along two paths, after changing fb/crtc
1944                  * configuration (modeswitching) and after page-flipping
1945                  * finishes. For the latter, we know that not only did
1946                  * we disable the FBC at the start of the page-flip
1947                  * sequence, but also more than one vblank has passed.
1948                  *
1949                  * For the former case of modeswitching, it is possible
1950                  * to switch between two FBC valid configurations
1951                  * instantaneously so we do need to disable the FBC
1952                  * before we can modify its control registers. We also
1953                  * have to wait for the next vblank for that to take
1954                  * effect. However, since we delay enabling FBC we can
1955                  * assume that a vblank has passed since disabling and
1956                  * that we can safely alter the registers in the deferred
1957                  * callback.
1958                  *
1959                  * In the scenario that we go from a valid to invalid
1960                  * and then back to valid FBC configuration we have
1961                  * no strict enforcement that a vblank occurred since
1962                  * disabling the FBC. However, along all current pipe
1963                  * disabling paths we do need to wait for a vblank at
1964                  * some point. And we wait before enabling FBC anyway.
1965                  */
1966                 DRM_DEBUG_KMS("disabling active FBC for update\n");
1967                 intel_disable_fbc(dev);
1968         }
1969
1970         intel_enable_fbc(crtc, 500);
1971         return;
1972
1973 out_disable:
1974         /* Multiple disables should be harmless */
1975         if (intel_fbc_enabled(dev)) {
1976                 DRM_DEBUG_KMS("unsupported config, disabling FBC\n");
1977                 intel_disable_fbc(dev);
1978         }
1979 }
1980
1981 int
1982 intel_pin_and_fence_fb_obj(struct drm_device *dev,
1983                            struct drm_i915_gem_object *obj,
1984                            struct intel_ring_buffer *pipelined)
1985 {
1986         struct drm_i915_private *dev_priv = dev->dev_private;
1987         u32 alignment;
1988         int ret;
1989
1990         switch (obj->tiling_mode) {
1991         case I915_TILING_NONE:
1992                 if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
1993                         alignment = 128 * 1024;
1994                 else if (INTEL_INFO(dev)->gen >= 4)
1995                         alignment = 4 * 1024;
1996                 else
1997                         alignment = 64 * 1024;
1998                 break;
1999         case I915_TILING_X:
2000                 /* pin() will align the object as required by fence */
2001                 alignment = 0;
2002                 break;
2003         case I915_TILING_Y:
2004                 /* FIXME: Is this true? */
2005                 DRM_ERROR("Y tiled not allowed for scan out buffers\n");
2006                 return -EINVAL;
2007         default:
2008                 BUG();
2009         }
2010
2011         dev_priv->mm.interruptible = false;
2012         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined);
2013         if (ret)
2014                 goto err_interruptible;
2015
2016         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2017          * fence, whereas 965+ only requires a fence if using
2018          * framebuffer compression.  For simplicity, we always install
2019          * a fence as the cost is not that onerous.
2020          */
2021         if (obj->tiling_mode != I915_TILING_NONE) {
2022                 ret = i915_gem_object_get_fence(obj, pipelined);
2023                 if (ret)
2024                         goto err_unpin;
2025         }
2026
2027         dev_priv->mm.interruptible = true;
2028         return 0;
2029
2030 err_unpin:
2031         i915_gem_object_unpin(obj);
2032 err_interruptible:
2033         dev_priv->mm.interruptible = true;
2034         return ret;
2035 }
2036
2037 static int i9xx_update_plane(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2038                              int x, int y)
2039 {
2040         struct drm_device *dev = crtc->dev;
2041         struct drm_i915_private *dev_priv = dev->dev_private;
2042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2043         struct intel_framebuffer *intel_fb;
2044         struct drm_i915_gem_object *obj;
2045         int plane = intel_crtc->plane;
2046         unsigned long Start, Offset;
2047         u32 dspcntr;
2048         u32 reg;
2049
2050         switch (plane) {
2051         case 0:
2052         case 1:
2053                 break;
2054         default:
2055                 DRM_ERROR("Can't update plane %d in SAREA\n", plane);
2056                 return -EINVAL;
2057         }
2058
2059         intel_fb = to_intel_framebuffer(fb);
2060         obj = intel_fb->obj;
2061
2062         reg = DSPCNTR(plane);
2063         dspcntr = I915_READ(reg);
2064         /* Mask out pixel format bits in case we change it */
2065         dspcntr &= ~DISPPLANE_PIXFORMAT_MASK;
2066         switch (fb->bits_per_pixel) {
2067         case 8:
2068                 dspcntr |= DISPPLANE_8BPP;
2069                 break;
2070         case 16:
2071                 if (fb->depth == 15)
2072                         dspcntr |= DISPPLANE_15_16BPP;
2073                 else
2074                         dspcntr |= DISPPLANE_16BPP;
2075                 break;
2076         case 24:
2077         case 32:
2078                 dspcntr |= DISPPLANE_32BPP_NO_ALPHA;
2079                 break;
2080         default:
2081                 DRM_ERROR("Unknown color depth %d\n", fb->bits_per_pixel);
2082                 return -EINVAL;
2083         }
2084         if (INTEL_INFO(dev)->gen >= 4) {
2085                 if (obj->tiling_mode != I915_TILING_NONE)
2086                         dspcntr |= DISPPLANE_TILED;
2087                 else
2088                         dspcntr &= ~DISPPLANE_TILED;
2089         }
2090
2091         I915_WRITE(reg, dspcntr);
2092
2093         Start = obj->gtt_offset;
2094         Offset = y * fb->pitch + x * (fb->bits_per_pixel / 8);
2095
2096         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2097                       Start, Offset, x, y, fb->pitch);
2098         I915_WRITE(DSPSTRIDE(plane), fb->pitch);
2099         if (INTEL_INFO(dev)->gen >= 4) {
2100                 I915_WRITE(DSPSURF(plane), Start);
2101                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2102                 I915_WRITE(DSPADDR(plane), Offset);
2103         } else
2104                 I915_WRITE(DSPADDR(plane), Start + Offset);
2105         POSTING_READ(reg);
2106
2107         return 0;
2108 }
2109
2110 static int ironlake_update_plane(struct drm_crtc *crtc,
2111                                  struct drm_framebuffer *fb, int x, int y)
2112 {
2113         struct drm_device *dev = crtc->dev;
2114         struct drm_i915_private *dev_priv = dev->dev_private;
2115         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2116         struct intel_framebuffer *intel_fb;
2117         struct drm_i915_gem_object *obj;
2118         int plane = intel_crtc->plane;
2119         unsigned long Start, Offset;
2120         u32 dspcntr;
2121         u32 reg;
2122
2123         switch (plane) {
2124         case 0:
2125         case 1:
2126         case 2:
2127                 break;
2128         default:
2129                 DRM_ERROR("Can't update plane %d in SAREA\n", plane);
2130                 return -EINVAL;
2131         }
2132
2133         intel_fb = to_intel_framebuffer(fb);
2134         obj = intel_fb->obj;
2135
2136         reg = DSPCNTR(plane);
2137         dspcntr = I915_READ(reg);
2138         /* Mask out pixel format bits in case we change it */
2139         dspcntr &= ~DISPPLANE_PIXFORMAT_MASK;
2140         switch (fb->bits_per_pixel) {
2141         case 8:
2142                 dspcntr |= DISPPLANE_8BPP;
2143                 break;
2144         case 16:
2145                 if (fb->depth != 16)
2146                         return -EINVAL;
2147
2148                 dspcntr |= DISPPLANE_16BPP;
2149                 break;
2150         case 24:
2151         case 32:
2152                 if (fb->depth == 24)
2153                         dspcntr |= DISPPLANE_32BPP_NO_ALPHA;
2154                 else if (fb->depth == 30)
2155                         dspcntr |= DISPPLANE_32BPP_30BIT_NO_ALPHA;
2156                 else
2157                         return -EINVAL;
2158                 break;
2159         default:
2160                 DRM_ERROR("Unknown color depth %d\n", fb->bits_per_pixel);
2161                 return -EINVAL;
2162         }
2163
2164         if (obj->tiling_mode != I915_TILING_NONE)
2165                 dspcntr |= DISPPLANE_TILED;
2166         else
2167                 dspcntr &= ~DISPPLANE_TILED;
2168
2169         /* must disable */
2170         dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2171
2172         I915_WRITE(reg, dspcntr);
2173
2174         Start = obj->gtt_offset;
2175         Offset = y * fb->pitch + x * (fb->bits_per_pixel / 8);
2176
2177         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2178                       Start, Offset, x, y, fb->pitch);
2179         I915_WRITE(DSPSTRIDE(plane), fb->pitch);
2180         I915_WRITE(DSPSURF(plane), Start);
2181         I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2182         I915_WRITE(DSPADDR(plane), Offset);
2183         POSTING_READ(reg);
2184
2185         return 0;
2186 }
2187
2188 /* Assume fb object is pinned & idle & fenced and just update base pointers */
2189 static int
2190 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2191                            int x, int y, enum mode_set_atomic state)
2192 {
2193         struct drm_device *dev = crtc->dev;
2194         struct drm_i915_private *dev_priv = dev->dev_private;
2195         int ret;
2196
2197         ret = dev_priv->display.update_plane(crtc, fb, x, y);
2198         if (ret)
2199                 return ret;
2200
2201         intel_update_fbc(dev);
2202         intel_increase_pllclock(crtc);
2203
2204         return 0;
2205 }
2206
2207 static int
2208 intel_finish_fb(struct drm_framebuffer *old_fb)
2209 {
2210         struct drm_i915_gem_object *obj = to_intel_framebuffer(old_fb)->obj;
2211         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2212         bool was_interruptible = dev_priv->mm.interruptible;
2213         int ret;
2214
2215         wait_event(dev_priv->pending_flip_queue,
2216                    atomic_read(&dev_priv->mm.wedged) ||
2217                    atomic_read(&obj->pending_flip) == 0);
2218
2219         /* Big Hammer, we also need to ensure that any pending
2220          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
2221          * current scanout is retired before unpinning the old
2222          * framebuffer.
2223          *
2224          * This should only fail upon a hung GPU, in which case we
2225          * can safely continue.
2226          */
2227         dev_priv->mm.interruptible = false;
2228         ret = i915_gem_object_finish_gpu(obj);
2229         dev_priv->mm.interruptible = was_interruptible;
2230
2231         return ret;
2232 }
2233
2234 static int
2235 intel_pipe_set_base(struct drm_crtc *crtc, int x, int y,
2236                     struct drm_framebuffer *old_fb)
2237 {
2238         struct drm_device *dev = crtc->dev;
2239         struct drm_i915_master_private *master_priv;
2240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2241         int ret;
2242
2243         /* no fb bound */
2244         if (!crtc->fb) {
2245                 DRM_ERROR("No FB bound\n");
2246                 return 0;
2247         }
2248
2249         switch (intel_crtc->plane) {
2250         case 0:
2251         case 1:
2252                 break;
2253         case 2:
2254                 if (IS_IVYBRIDGE(dev))
2255                         break;
2256                 /* fall through otherwise */
2257         default:
2258                 DRM_ERROR("no plane for crtc\n");
2259                 return -EINVAL;
2260         }
2261
2262         mutex_lock(&dev->struct_mutex);
2263         ret = intel_pin_and_fence_fb_obj(dev,
2264                                          to_intel_framebuffer(crtc->fb)->obj,
2265                                          NULL);
2266         if (ret != 0) {
2267                 mutex_unlock(&dev->struct_mutex);
2268                 DRM_ERROR("pin & fence failed\n");
2269                 return ret;
2270         }
2271
2272         if (old_fb)
2273                 intel_finish_fb(old_fb);
2274
2275         ret = intel_pipe_set_base_atomic(crtc, crtc->fb, x, y,
2276                                          LEAVE_ATOMIC_MODE_SET);
2277         if (ret) {
2278                 i915_gem_object_unpin(to_intel_framebuffer(crtc->fb)->obj);
2279                 mutex_unlock(&dev->struct_mutex);
2280                 DRM_ERROR("failed to update base address\n");
2281                 return ret;
2282         }
2283
2284         if (old_fb) {
2285                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2286                 i915_gem_object_unpin(to_intel_framebuffer(old_fb)->obj);
2287         }
2288
2289         mutex_unlock(&dev->struct_mutex);
2290
2291         if (!dev->primary->master)
2292                 return 0;
2293
2294         master_priv = dev->primary->master->driver_priv;
2295         if (!master_priv->sarea_priv)
2296                 return 0;
2297
2298         if (intel_crtc->pipe) {
2299                 master_priv->sarea_priv->pipeB_x = x;
2300                 master_priv->sarea_priv->pipeB_y = y;
2301         } else {
2302                 master_priv->sarea_priv->pipeA_x = x;
2303                 master_priv->sarea_priv->pipeA_y = y;
2304         }
2305
2306         return 0;
2307 }
2308
2309 static void ironlake_set_pll_edp(struct drm_crtc *crtc, int clock)
2310 {
2311         struct drm_device *dev = crtc->dev;
2312         struct drm_i915_private *dev_priv = dev->dev_private;
2313         u32 dpa_ctl;
2314
2315         DRM_DEBUG_KMS("eDP PLL enable for clock %d\n", clock);
2316         dpa_ctl = I915_READ(DP_A);
2317         dpa_ctl &= ~DP_PLL_FREQ_MASK;
2318
2319         if (clock < 200000) {
2320                 u32 temp;
2321                 dpa_ctl |= DP_PLL_FREQ_160MHZ;
2322                 /* workaround for 160Mhz:
2323                    1) program 0x4600c bits 15:0 = 0x8124
2324                    2) program 0x46010 bit 0 = 1
2325                    3) program 0x46034 bit 24 = 1
2326                    4) program 0x64000 bit 14 = 1
2327                    */
2328                 temp = I915_READ(0x4600c);
2329                 temp &= 0xffff0000;
2330                 I915_WRITE(0x4600c, temp | 0x8124);
2331
2332                 temp = I915_READ(0x46010);
2333                 I915_WRITE(0x46010, temp | 1);
2334
2335                 temp = I915_READ(0x46034);
2336                 I915_WRITE(0x46034, temp | (1 << 24));
2337         } else {
2338                 dpa_ctl |= DP_PLL_FREQ_270MHZ;
2339         }
2340         I915_WRITE(DP_A, dpa_ctl);
2341
2342         POSTING_READ(DP_A);
2343         udelay(500);
2344 }
2345
2346 static void intel_fdi_normal_train(struct drm_crtc *crtc)
2347 {
2348         struct drm_device *dev = crtc->dev;
2349         struct drm_i915_private *dev_priv = dev->dev_private;
2350         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2351         int pipe = intel_crtc->pipe;
2352         u32 reg, temp;
2353
2354         /* enable normal train */
2355         reg = FDI_TX_CTL(pipe);
2356         temp = I915_READ(reg);
2357         if (IS_IVYBRIDGE(dev)) {
2358                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
2359                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
2360         } else {
2361                 temp &= ~FDI_LINK_TRAIN_NONE;
2362                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
2363         }
2364         I915_WRITE(reg, temp);
2365
2366         reg = FDI_RX_CTL(pipe);
2367         temp = I915_READ(reg);
2368         if (HAS_PCH_CPT(dev)) {
2369                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2370                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
2371         } else {
2372                 temp &= ~FDI_LINK_TRAIN_NONE;
2373                 temp |= FDI_LINK_TRAIN_NONE;
2374         }
2375         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
2376
2377         /* wait one idle pattern time */
2378         POSTING_READ(reg);
2379         udelay(1000);
2380
2381         /* IVB wants error correction enabled */
2382         if (IS_IVYBRIDGE(dev))
2383                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
2384                            FDI_FE_ERRC_ENABLE);
2385 }
2386
2387 static void cpt_phase_pointer_enable(struct drm_device *dev, int pipe)
2388 {
2389         struct drm_i915_private *dev_priv = dev->dev_private;
2390         u32 flags = I915_READ(SOUTH_CHICKEN1);
2391
2392         flags |= FDI_PHASE_SYNC_OVR(pipe);
2393         I915_WRITE(SOUTH_CHICKEN1, flags); /* once to unlock... */
2394         flags |= FDI_PHASE_SYNC_EN(pipe);
2395         I915_WRITE(SOUTH_CHICKEN1, flags); /* then again to enable */
2396         POSTING_READ(SOUTH_CHICKEN1);
2397 }
2398
2399 /* The FDI link training functions for ILK/Ibexpeak. */
2400 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
2401 {
2402         struct drm_device *dev = crtc->dev;
2403         struct drm_i915_private *dev_priv = dev->dev_private;
2404         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2405         int pipe = intel_crtc->pipe;
2406         int plane = intel_crtc->plane;
2407         u32 reg, temp, tries;
2408
2409         /* FDI needs bits from pipe & plane first */
2410         assert_pipe_enabled(dev_priv, pipe);
2411         assert_plane_enabled(dev_priv, plane);
2412
2413         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
2414            for train result */
2415         reg = FDI_RX_IMR(pipe);
2416         temp = I915_READ(reg);
2417         temp &= ~FDI_RX_SYMBOL_LOCK;
2418         temp &= ~FDI_RX_BIT_LOCK;
2419         I915_WRITE(reg, temp);
2420         I915_READ(reg);
2421         udelay(150);
2422
2423         /* enable CPU FDI TX and PCH FDI RX */
2424         reg = FDI_TX_CTL(pipe);
2425         temp = I915_READ(reg);
2426         temp &= ~(7 << 19);
2427         temp |= (intel_crtc->fdi_lanes - 1) << 19;
2428         temp &= ~FDI_LINK_TRAIN_NONE;
2429         temp |= FDI_LINK_TRAIN_PATTERN_1;
2430         I915_WRITE(reg, temp | FDI_TX_ENABLE);
2431
2432         reg = FDI_RX_CTL(pipe);
2433         temp = I915_READ(reg);
2434         temp &= ~FDI_LINK_TRAIN_NONE;
2435         temp |= FDI_LINK_TRAIN_PATTERN_1;
2436         I915_WRITE(reg, temp | FDI_RX_ENABLE);
2437
2438         POSTING_READ(reg);
2439         udelay(150);
2440
2441         /* Ironlake workaround, enable clock pointer after FDI enable*/
2442         if (HAS_PCH_IBX(dev)) {
2443                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
2444                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
2445                            FDI_RX_PHASE_SYNC_POINTER_EN);
2446         }
2447
2448         reg = FDI_RX_IIR(pipe);
2449         for (tries = 0; tries < 5; tries++) {
2450                 temp = I915_READ(reg);
2451                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2452
2453                 if ((temp & FDI_RX_BIT_LOCK)) {
2454                         DRM_DEBUG_KMS("FDI train 1 done.\n");
2455                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
2456                         break;
2457                 }
2458         }
2459         if (tries == 5)
2460                 DRM_ERROR("FDI train 1 fail!\n");
2461
2462         /* Train 2 */
2463         reg = FDI_TX_CTL(pipe);
2464         temp = I915_READ(reg);
2465         temp &= ~FDI_LINK_TRAIN_NONE;
2466         temp |= FDI_LINK_TRAIN_PATTERN_2;
2467         I915_WRITE(reg, temp);
2468
2469         reg = FDI_RX_CTL(pipe);
2470         temp = I915_READ(reg);
2471         temp &= ~FDI_LINK_TRAIN_NONE;
2472         temp |= FDI_LINK_TRAIN_PATTERN_2;
2473         I915_WRITE(reg, temp);
2474
2475         POSTING_READ(reg);
2476         udelay(150);
2477
2478         reg = FDI_RX_IIR(pipe);
2479         for (tries = 0; tries < 5; tries++) {
2480                 temp = I915_READ(reg);
2481                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2482
2483                 if (temp & FDI_RX_SYMBOL_LOCK) {
2484                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
2485                         DRM_DEBUG_KMS("FDI train 2 done.\n");
2486                         break;
2487                 }
2488         }
2489         if (tries == 5)
2490                 DRM_ERROR("FDI train 2 fail!\n");
2491
2492         DRM_DEBUG_KMS("FDI train done\n");
2493
2494 }
2495
2496 static const int snb_b_fdi_train_param[] = {
2497         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
2498         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
2499         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
2500         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
2501 };
2502
2503 /* The FDI link training functions for SNB/Cougarpoint. */
2504 static void gen6_fdi_link_train(struct drm_crtc *crtc)
2505 {
2506         struct drm_device *dev = crtc->dev;
2507         struct drm_i915_private *dev_priv = dev->dev_private;
2508         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2509         int pipe = intel_crtc->pipe;
2510         u32 reg, temp, i;
2511
2512         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
2513            for train result */
2514         reg = FDI_RX_IMR(pipe);
2515         temp = I915_READ(reg);
2516         temp &= ~FDI_RX_SYMBOL_LOCK;
2517         temp &= ~FDI_RX_BIT_LOCK;
2518         I915_WRITE(reg, temp);
2519
2520         POSTING_READ(reg);
2521         udelay(150);
2522
2523         /* enable CPU FDI TX and PCH FDI RX */
2524         reg = FDI_TX_CTL(pipe);
2525         temp = I915_READ(reg);
2526         temp &= ~(7 << 19);
2527         temp |= (intel_crtc->fdi_lanes - 1) << 19;
2528         temp &= ~FDI_LINK_TRAIN_NONE;
2529         temp |= FDI_LINK_TRAIN_PATTERN_1;
2530         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2531         /* SNB-B */
2532         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2533         I915_WRITE(reg, temp | FDI_TX_ENABLE);
2534
2535         reg = FDI_RX_CTL(pipe);
2536         temp = I915_READ(reg);
2537         if (HAS_PCH_CPT(dev)) {
2538                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2539                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
2540         } else {
2541                 temp &= ~FDI_LINK_TRAIN_NONE;
2542                 temp |= FDI_LINK_TRAIN_PATTERN_1;
2543         }
2544         I915_WRITE(reg, temp | FDI_RX_ENABLE);
2545
2546         POSTING_READ(reg);
2547         udelay(150);
2548
2549         if (HAS_PCH_CPT(dev))
2550                 cpt_phase_pointer_enable(dev, pipe);
2551
2552         for (i = 0; i < 4; i++) {
2553                 reg = FDI_TX_CTL(pipe);
2554                 temp = I915_READ(reg);
2555                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2556                 temp |= snb_b_fdi_train_param[i];
2557                 I915_WRITE(reg, temp);
2558
2559                 POSTING_READ(reg);
2560                 udelay(500);
2561
2562                 reg = FDI_RX_IIR(pipe);
2563                 temp = I915_READ(reg);
2564                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2565
2566                 if (temp & FDI_RX_BIT_LOCK) {
2567                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
2568                         DRM_DEBUG_KMS("FDI train 1 done.\n");
2569                         break;
2570                 }
2571         }
2572         if (i == 4)
2573                 DRM_ERROR("FDI train 1 fail!\n");
2574
2575         /* Train 2 */
2576         reg = FDI_TX_CTL(pipe);
2577         temp = I915_READ(reg);
2578         temp &= ~FDI_LINK_TRAIN_NONE;
2579         temp |= FDI_LINK_TRAIN_PATTERN_2;
2580         if (IS_GEN6(dev)) {
2581                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2582                 /* SNB-B */
2583                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2584         }
2585         I915_WRITE(reg, temp);
2586
2587         reg = FDI_RX_CTL(pipe);
2588         temp = I915_READ(reg);
2589         if (HAS_PCH_CPT(dev)) {
2590                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2591                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
2592         } else {
2593                 temp &= ~FDI_LINK_TRAIN_NONE;
2594                 temp |= FDI_LINK_TRAIN_PATTERN_2;
2595         }
2596         I915_WRITE(reg, temp);
2597
2598         POSTING_READ(reg);
2599         udelay(150);
2600
2601         for (i = 0; i < 4; i++) {
2602                 reg = FDI_TX_CTL(pipe);
2603                 temp = I915_READ(reg);
2604                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2605                 temp |= snb_b_fdi_train_param[i];
2606                 I915_WRITE(reg, temp);
2607
2608                 POSTING_READ(reg);
2609                 udelay(500);
2610
2611                 reg = FDI_RX_IIR(pipe);
2612                 temp = I915_READ(reg);
2613                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2614
2615                 if (temp & FDI_RX_SYMBOL_LOCK) {
2616                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
2617                         DRM_DEBUG_KMS("FDI train 2 done.\n");
2618                         break;
2619                 }
2620         }
2621         if (i == 4)
2622                 DRM_ERROR("FDI train 2 fail!\n");
2623
2624         DRM_DEBUG_KMS("FDI train done.\n");
2625 }
2626
2627 /* Manual link training for Ivy Bridge A0 parts */
2628 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
2629 {
2630         struct drm_device *dev = crtc->dev;
2631         struct drm_i915_private *dev_priv = dev->dev_private;
2632         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2633         int pipe = intel_crtc->pipe;
2634         u32 reg, temp, i;
2635
2636         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
2637            for train result */
2638         reg = FDI_RX_IMR(pipe);
2639         temp = I915_READ(reg);
2640         temp &= ~FDI_RX_SYMBOL_LOCK;
2641         temp &= ~FDI_RX_BIT_LOCK;
2642         I915_WRITE(reg, temp);
2643
2644         POSTING_READ(reg);
2645         udelay(150);
2646
2647         /* enable CPU FDI TX and PCH FDI RX */
2648         reg = FDI_TX_CTL(pipe);
2649         temp = I915_READ(reg);
2650         temp &= ~(7 << 19);
2651         temp |= (intel_crtc->fdi_lanes - 1) << 19;
2652         temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
2653         temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
2654         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2655         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2656         temp |= FDI_COMPOSITE_SYNC;
2657         I915_WRITE(reg, temp | FDI_TX_ENABLE);
2658
2659         reg = FDI_RX_CTL(pipe);
2660         temp = I915_READ(reg);
2661         temp &= ~FDI_LINK_TRAIN_AUTO;
2662         temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2663         temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
2664         temp |= FDI_COMPOSITE_SYNC;
2665         I915_WRITE(reg, temp | FDI_RX_ENABLE);
2666
2667         POSTING_READ(reg);
2668         udelay(150);
2669
2670         if (HAS_PCH_CPT(dev))
2671                 cpt_phase_pointer_enable(dev, pipe);
2672
2673         for (i = 0; i < 4; i++) {
2674                 reg = FDI_TX_CTL(pipe);
2675                 temp = I915_READ(reg);
2676                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2677                 temp |= snb_b_fdi_train_param[i];
2678                 I915_WRITE(reg, temp);
2679
2680                 POSTING_READ(reg);
2681                 udelay(500);
2682
2683                 reg = FDI_RX_IIR(pipe);
2684                 temp = I915_READ(reg);
2685                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2686
2687                 if (temp & FDI_RX_BIT_LOCK ||
2688                     (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
2689                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
2690                         DRM_DEBUG_KMS("FDI train 1 done.\n");
2691                         break;
2692                 }
2693         }
2694         if (i == 4)
2695                 DRM_ERROR("FDI train 1 fail!\n");
2696
2697         /* Train 2 */
2698         reg = FDI_TX_CTL(pipe);
2699         temp = I915_READ(reg);
2700         temp &= ~FDI_LINK_TRAIN_NONE_IVB;
2701         temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
2702         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2703         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2704         I915_WRITE(reg, temp);
2705
2706         reg = FDI_RX_CTL(pipe);
2707         temp = I915_READ(reg);
2708         temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2709         temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
2710         I915_WRITE(reg, temp);
2711
2712         POSTING_READ(reg);
2713         udelay(150);
2714
2715         for (i = 0; i < 4; i++) {
2716                 reg = FDI_TX_CTL(pipe);
2717                 temp = I915_READ(reg);
2718                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2719                 temp |= snb_b_fdi_train_param[i];
2720                 I915_WRITE(reg, temp);
2721
2722                 POSTING_READ(reg);
2723                 udelay(500);
2724
2725                 reg = FDI_RX_IIR(pipe);
2726                 temp = I915_READ(reg);
2727                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2728
2729                 if (temp & FDI_RX_SYMBOL_LOCK) {
2730                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
2731                         DRM_DEBUG_KMS("FDI train 2 done.\n");
2732                         break;
2733                 }
2734         }
2735         if (i == 4)
2736                 DRM_ERROR("FDI train 2 fail!\n");
2737
2738         DRM_DEBUG_KMS("FDI train done.\n");
2739 }
2740
2741 static void ironlake_fdi_pll_enable(struct drm_crtc *crtc)
2742 {
2743         struct drm_device *dev = crtc->dev;
2744         struct drm_i915_private *dev_priv = dev->dev_private;
2745         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2746         int pipe = intel_crtc->pipe;
2747         u32 reg, temp;
2748
2749         /* Write the TU size bits so error detection works */
2750         I915_WRITE(FDI_RX_TUSIZE1(pipe),
2751                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
2752
2753         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
2754         reg = FDI_RX_CTL(pipe);
2755         temp = I915_READ(reg);
2756         temp &= ~((0x7 << 19) | (0x7 << 16));
2757         temp |= (intel_crtc->fdi_lanes - 1) << 19;
2758         temp |= (I915_READ(PIPECONF(pipe)) & PIPE_BPC_MASK) << 11;
2759         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
2760
2761         POSTING_READ(reg);
2762         udelay(200);
2763
2764         /* Switch from Rawclk to PCDclk */
2765         temp = I915_READ(reg);
2766         I915_WRITE(reg, temp | FDI_PCDCLK);
2767
2768         POSTING_READ(reg);
2769         udelay(200);
2770
2771         /* Enable CPU FDI TX PLL, always on for Ironlake */
2772         reg = FDI_TX_CTL(pipe);
2773         temp = I915_READ(reg);
2774         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
2775                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
2776
2777                 POSTING_READ(reg);
2778                 udelay(100);
2779         }
2780 }
2781
2782 static void cpt_phase_pointer_disable(struct drm_device *dev, int pipe)
2783 {
2784         struct drm_i915_private *dev_priv = dev->dev_private;
2785         u32 flags = I915_READ(SOUTH_CHICKEN1);
2786
2787         flags &= ~(FDI_PHASE_SYNC_EN(pipe));
2788         I915_WRITE(SOUTH_CHICKEN1, flags); /* once to disable... */
2789         flags &= ~(FDI_PHASE_SYNC_OVR(pipe));
2790         I915_WRITE(SOUTH_CHICKEN1, flags); /* then again to lock */
2791         POSTING_READ(SOUTH_CHICKEN1);
2792 }
2793 static void ironlake_fdi_disable(struct drm_crtc *crtc)
2794 {
2795         struct drm_device *dev = crtc->dev;
2796         struct drm_i915_private *dev_priv = dev->dev_private;
2797         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2798         int pipe = intel_crtc->pipe;
2799         u32 reg, temp;
2800
2801         /* disable CPU FDI tx and PCH FDI rx */
2802         reg = FDI_TX_CTL(pipe);
2803         temp = I915_READ(reg);
2804         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
2805         POSTING_READ(reg);
2806
2807         reg = FDI_RX_CTL(pipe);
2808         temp = I915_READ(reg);
2809         temp &= ~(0x7 << 16);
2810         temp |= (I915_READ(PIPECONF(pipe)) & PIPE_BPC_MASK) << 11;
2811         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
2812
2813         POSTING_READ(reg);
2814         udelay(100);
2815
2816         /* Ironlake workaround, disable clock pointer after downing FDI */
2817         if (HAS_PCH_IBX(dev)) {
2818                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
2819                 I915_WRITE(FDI_RX_CHICKEN(pipe),
2820                            I915_READ(FDI_RX_CHICKEN(pipe) &
2821                                      ~FDI_RX_PHASE_SYNC_POINTER_EN));
2822         } else if (HAS_PCH_CPT(dev)) {
2823                 cpt_phase_pointer_disable(dev, pipe);
2824         }
2825
2826         /* still set train pattern 1 */
2827         reg = FDI_TX_CTL(pipe);
2828         temp = I915_READ(reg);
2829         temp &= ~FDI_LINK_TRAIN_NONE;
2830         temp |= FDI_LINK_TRAIN_PATTERN_1;
2831         I915_WRITE(reg, temp);
2832
2833         reg = FDI_RX_CTL(pipe);
2834         temp = I915_READ(reg);
2835         if (HAS_PCH_CPT(dev)) {
2836                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2837                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
2838         } else {
2839                 temp &= ~FDI_LINK_TRAIN_NONE;
2840                 temp |= FDI_LINK_TRAIN_PATTERN_1;
2841         }
2842         /* BPC in FDI rx is consistent with that in PIPECONF */
2843         temp &= ~(0x07 << 16);
2844         temp |= (I915_READ(PIPECONF(pipe)) & PIPE_BPC_MASK) << 11;
2845         I915_WRITE(reg, temp);
2846
2847         POSTING_READ(reg);
2848         udelay(100);
2849 }
2850
2851 /*
2852  * When we disable a pipe, we need to clear any pending scanline wait events
2853  * to avoid hanging the ring, which we assume we are waiting on.
2854  */
2855 static void intel_clear_scanline_wait(struct drm_device *dev)
2856 {
2857         struct drm_i915_private *dev_priv = dev->dev_private;
2858         struct intel_ring_buffer *ring;
2859         u32 tmp;
2860
2861         if (IS_GEN2(dev))
2862                 /* Can't break the hang on i8xx */
2863                 return;
2864
2865         ring = LP_RING(dev_priv);
2866         tmp = I915_READ_CTL(ring);
2867         if (tmp & RING_WAIT)
2868                 I915_WRITE_CTL(ring, tmp);
2869 }
2870
2871 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
2872 {
2873         struct drm_device *dev = crtc->dev;
2874         struct drm_i915_private *dev_priv = dev->dev_private;
2875         unsigned long flags;
2876         bool pending;
2877
2878         if (atomic_read(&dev_priv->mm.wedged))
2879                 return false;
2880
2881         spin_lock_irqsave(&dev->event_lock, flags);
2882         pending = to_intel_crtc(crtc)->unpin_work != NULL;
2883         spin_unlock_irqrestore(&dev->event_lock, flags);
2884
2885         return pending;
2886 }
2887
2888 static void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
2889 {
2890         struct drm_device *dev = crtc->dev;
2891         struct drm_i915_private *dev_priv = dev->dev_private;
2892
2893         if (crtc->fb == NULL)
2894                 return;
2895
2896         wait_event(dev_priv->pending_flip_queue,
2897                    !intel_crtc_has_pending_flip(crtc));
2898
2899         mutex_lock(&dev->struct_mutex);
2900         intel_finish_fb(crtc->fb);
2901         mutex_unlock(&dev->struct_mutex);
2902 }
2903
2904 static bool intel_crtc_driving_pch(struct drm_crtc *crtc)
2905 {
2906         struct drm_device *dev = crtc->dev;
2907         struct drm_mode_config *mode_config = &dev->mode_config;
2908         struct intel_encoder *encoder;
2909
2910         /*
2911          * If there's a non-PCH eDP on this crtc, it must be DP_A, and that
2912          * must be driven by its own crtc; no sharing is possible.
2913          */
2914         list_for_each_entry(encoder, &mode_config->encoder_list, base.head) {
2915                 if (encoder->base.crtc != crtc)
2916                         continue;
2917
2918                 switch (encoder->type) {
2919                 case INTEL_OUTPUT_EDP:
2920                         if (!intel_encoder_is_pch_edp(&encoder->base))
2921                                 return false;
2922                         continue;
2923                 }
2924         }
2925
2926         return true;
2927 }
2928
2929 /*
2930  * Enable PCH resources required for PCH ports:
2931  *   - PCH PLLs
2932  *   - FDI training & RX/TX
2933  *   - update transcoder timings
2934  *   - DP transcoding bits
2935  *   - transcoder
2936  */
2937 static void ironlake_pch_enable(struct drm_crtc *crtc)
2938 {
2939         struct drm_device *dev = crtc->dev;
2940         struct drm_i915_private *dev_priv = dev->dev_private;
2941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2942         int pipe = intel_crtc->pipe;
2943         u32 reg, temp, transc_sel;
2944
2945         /* For PCH output, training FDI link */
2946         dev_priv->display.fdi_link_train(crtc);
2947
2948         intel_enable_pch_pll(dev_priv, pipe);
2949
2950         if (HAS_PCH_CPT(dev)) {
2951                 transc_sel = intel_crtc->use_pll_a ? TRANSC_DPLLA_SEL :
2952                         TRANSC_DPLLB_SEL;
2953
2954                 /* Be sure PCH DPLL SEL is set */
2955                 temp = I915_READ(PCH_DPLL_SEL);
2956                 if (pipe == 0) {
2957                         temp &= ~(TRANSA_DPLLB_SEL);
2958                         temp |= (TRANSA_DPLL_ENABLE | TRANSA_DPLLA_SEL);
2959                 } else if (pipe == 1) {
2960                         temp &= ~(TRANSB_DPLLB_SEL);
2961                         temp |= (TRANSB_DPLL_ENABLE | TRANSB_DPLLB_SEL);
2962                 } else if (pipe == 2) {
2963                         temp &= ~(TRANSC_DPLLB_SEL);
2964                         temp |= (TRANSC_DPLL_ENABLE | transc_sel);
2965                 }
2966                 I915_WRITE(PCH_DPLL_SEL, temp);
2967         }
2968
2969         /* set transcoder timing, panel must allow it */
2970         assert_panel_unlocked(dev_priv, pipe);
2971         I915_WRITE(TRANS_HTOTAL(pipe), I915_READ(HTOTAL(pipe)));
2972         I915_WRITE(TRANS_HBLANK(pipe), I915_READ(HBLANK(pipe)));
2973         I915_WRITE(TRANS_HSYNC(pipe),  I915_READ(HSYNC(pipe)));
2974
2975         I915_WRITE(TRANS_VTOTAL(pipe), I915_READ(VTOTAL(pipe)));
2976         I915_WRITE(TRANS_VBLANK(pipe), I915_READ(VBLANK(pipe)));
2977         I915_WRITE(TRANS_VSYNC(pipe),  I915_READ(VSYNC(pipe)));
2978
2979         intel_fdi_normal_train(crtc);
2980
2981         /* For PCH DP, enable TRANS_DP_CTL */
2982         if (HAS_PCH_CPT(dev) &&
2983             (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
2984              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
2985                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPE_BPC_MASK) >> 5;
2986                 reg = TRANS_DP_CTL(pipe);
2987                 temp = I915_READ(reg);
2988                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
2989                           TRANS_DP_SYNC_MASK |
2990                           TRANS_DP_BPC_MASK);
2991                 temp |= (TRANS_DP_OUTPUT_ENABLE |
2992                          TRANS_DP_ENH_FRAMING);
2993                 temp |= bpc << 9; /* same format but at 11:9 */
2994
2995                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
2996                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
2997                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
2998                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
2999
3000                 switch (intel_trans_dp_port_sel(crtc)) {
3001                 case PCH_DP_B:
3002                         temp |= TRANS_DP_PORT_SEL_B;
3003                         break;
3004                 case PCH_DP_C:
3005                         temp |= TRANS_DP_PORT_SEL_C;
3006                         break;
3007                 case PCH_DP_D:
3008                         temp |= TRANS_DP_PORT_SEL_D;
3009                         break;
3010                 default:
3011                         DRM_DEBUG_KMS("Wrong PCH DP port return. Guess port B\n");
3012                         temp |= TRANS_DP_PORT_SEL_B;
3013                         break;
3014                 }
3015
3016                 I915_WRITE(reg, temp);
3017         }
3018
3019         intel_enable_transcoder(dev_priv, pipe);
3020 }
3021
3022 void intel_cpt_verify_modeset(struct drm_device *dev, int pipe)
3023 {
3024         struct drm_i915_private *dev_priv = dev->dev_private;
3025         int dslreg = PIPEDSL(pipe), tc2reg = TRANS_CHICKEN2(pipe);
3026         u32 temp;
3027
3028         temp = I915_READ(dslreg);
3029         udelay(500);
3030         if (wait_for(I915_READ(dslreg) != temp, 5)) {
3031                 /* Without this, mode sets may fail silently on FDI */
3032                 I915_WRITE(tc2reg, TRANS_AUTOTRAIN_GEN_STALL_DIS);
3033                 udelay(250);
3034                 I915_WRITE(tc2reg, 0);
3035                 if (wait_for(I915_READ(dslreg) != temp, 5))
3036                         DRM_ERROR("mode set failed: pipe %d stuck\n", pipe);
3037         }
3038 }
3039
3040 static void ironlake_crtc_enable(struct drm_crtc *crtc)
3041 {
3042         struct drm_device *dev = crtc->dev;
3043         struct drm_i915_private *dev_priv = dev->dev_private;
3044         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3045         int pipe = intel_crtc->pipe;
3046         int plane = intel_crtc->plane;
3047         u32 temp;
3048         bool is_pch_port;
3049
3050         if (intel_crtc->active)
3051                 return;
3052
3053         intel_crtc->active = true;
3054         intel_update_watermarks(dev);
3055
3056         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
3057                 temp = I915_READ(PCH_LVDS);
3058                 if ((temp & LVDS_PORT_EN) == 0)
3059                         I915_WRITE(PCH_LVDS, temp | LVDS_PORT_EN);
3060         }
3061
3062         is_pch_port = intel_crtc_driving_pch(crtc);
3063
3064         if (is_pch_port)
3065                 ironlake_fdi_pll_enable(crtc);
3066         else
3067                 ironlake_fdi_disable(crtc);
3068
3069         /* Enable panel fitting for LVDS */
3070         if (dev_priv->pch_pf_size &&
3071             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) || HAS_eDP)) {
3072                 /* Force use of hard-coded filter coefficients
3073                  * as some pre-programmed values are broken,
3074                  * e.g. x201.
3075                  */
3076                 if (IS_IVYBRIDGE(dev))
3077                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
3078                                                  PF_PIPE_SEL_IVB(pipe));
3079                 else
3080                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
3081                 I915_WRITE(PF_WIN_POS(pipe), dev_priv->pch_pf_pos);
3082                 I915_WRITE(PF_WIN_SZ(pipe), dev_priv->pch_pf_size);
3083         }
3084
3085         /*
3086          * On ILK+ LUT must be loaded before the pipe is running but with
3087          * clocks enabled
3088          */
3089         intel_crtc_load_lut(crtc);
3090
3091         intel_enable_pipe(dev_priv, pipe, is_pch_port);
3092         intel_enable_plane(dev_priv, plane, pipe);
3093
3094         if (is_pch_port)
3095                 ironlake_pch_enable(crtc);
3096
3097         mutex_lock(&dev->struct_mutex);
3098         intel_update_fbc(dev);
3099         mutex_unlock(&dev->struct_mutex);
3100
3101         intel_crtc_update_cursor(crtc, true);
3102 }
3103
3104 static void ironlake_crtc_disable(struct drm_crtc *crtc)
3105 {
3106         struct drm_device *dev = crtc->dev;
3107         struct drm_i915_private *dev_priv = dev->dev_private;
3108         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3109         int pipe = intel_crtc->pipe;
3110         int plane = intel_crtc->plane;
3111         u32 reg, temp;
3112
3113         if (!intel_crtc->active)
3114                 return;
3115
3116         intel_crtc_wait_for_pending_flips(crtc);
3117         drm_vblank_off(dev, pipe);
3118         intel_crtc_update_cursor(crtc, false);
3119
3120         intel_disable_plane(dev_priv, plane, pipe);
3121
3122         if (dev_priv->cfb_plane == plane)
3123                 intel_disable_fbc(dev);
3124
3125         intel_disable_pipe(dev_priv, pipe);
3126
3127         /* Disable PF */
3128         I915_WRITE(PF_CTL(pipe), 0);
3129         I915_WRITE(PF_WIN_SZ(pipe), 0);
3130
3131         ironlake_fdi_disable(crtc);
3132
3133         /* This is a horrible layering violation; we should be doing this in
3134          * the connector/encoder ->prepare instead, but we don't always have
3135          * enough information there about the config to know whether it will
3136          * actually be necessary or just cause undesired flicker.
3137          */
3138         intel_disable_pch_ports(dev_priv, pipe);
3139
3140         intel_disable_transcoder(dev_priv, pipe);
3141
3142         if (HAS_PCH_CPT(dev)) {
3143                 /* disable TRANS_DP_CTL */
3144                 reg = TRANS_DP_CTL(pipe);
3145                 temp = I915_READ(reg);
3146                 temp &= ~(TRANS_DP_OUTPUT_ENABLE | TRANS_DP_PORT_SEL_MASK);
3147                 temp |= TRANS_DP_PORT_SEL_NONE;
3148                 I915_WRITE(reg, temp);
3149
3150                 /* disable DPLL_SEL */
3151                 temp = I915_READ(PCH_DPLL_SEL);
3152                 switch (pipe) {
3153                 case 0:
3154                         temp &= ~(TRANSA_DPLL_ENABLE | TRANSA_DPLLB_SEL);
3155                         break;
3156                 case 1:
3157                         temp &= ~(TRANSB_DPLL_ENABLE | TRANSB_DPLLB_SEL);
3158                         break;
3159                 case 2:
3160                         /* C shares PLL A or B */
3161                         temp &= ~(TRANSC_DPLL_ENABLE | TRANSC_DPLLB_SEL);
3162                         break;
3163                 default:
3164                         BUG(); /* wtf */
3165                 }
3166                 I915_WRITE(PCH_DPLL_SEL, temp);
3167         }
3168
3169         /* disable PCH DPLL */
3170         if (!intel_crtc->no_pll)
3171                 intel_disable_pch_pll(dev_priv, pipe);
3172
3173         /* Switch from PCDclk to Rawclk */
3174         reg = FDI_RX_CTL(pipe);
3175         temp = I915_READ(reg);
3176         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3177
3178         /* Disable CPU FDI TX PLL */
3179         reg = FDI_TX_CTL(pipe);
3180         temp = I915_READ(reg);
3181         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3182
3183         POSTING_READ(reg);
3184         udelay(100);
3185
3186         reg = FDI_RX_CTL(pipe);
3187         temp = I915_READ(reg);
3188         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3189
3190         /* Wait for the clocks to turn off. */
3191         POSTING_READ(reg);
3192         udelay(100);
3193
3194         intel_crtc->active = false;
3195         intel_update_watermarks(dev);
3196
3197         mutex_lock(&dev->struct_mutex);
3198         intel_update_fbc(dev);
3199         intel_clear_scanline_wait(dev);
3200         mutex_unlock(&dev->struct_mutex);
3201 }
3202
3203 static void ironlake_crtc_dpms(struct drm_crtc *crtc, int mode)
3204 {
3205         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3206         int pipe = intel_crtc->pipe;
3207         int plane = intel_crtc->plane;
3208
3209         /* XXX: When our outputs are all unaware of DPMS modes other than off
3210          * and on, we should map those modes to DRM_MODE_DPMS_OFF in the CRTC.
3211          */
3212         switch (mode) {
3213         case DRM_MODE_DPMS_ON:
3214         case DRM_MODE_DPMS_STANDBY:
3215         case DRM_MODE_DPMS_SUSPEND:
3216                 DRM_DEBUG_KMS("crtc %d/%d dpms on\n", pipe, plane);
3217                 ironlake_crtc_enable(crtc);
3218                 break;
3219
3220         case DRM_MODE_DPMS_OFF:
3221                 DRM_DEBUG_KMS("crtc %d/%d dpms off\n", pipe, plane);
3222                 ironlake_crtc_disable(crtc);
3223                 break;
3224         }
3225 }
3226
3227 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
3228 {
3229         if (!enable && intel_crtc->overlay) {
3230                 struct drm_device *dev = intel_crtc->base.dev;
3231                 struct drm_i915_private *dev_priv = dev->dev_private;
3232
3233                 mutex_lock(&dev->struct_mutex);
3234                 dev_priv->mm.interruptible = false;
3235                 (void) intel_overlay_switch_off(intel_crtc->overlay);
3236                 dev_priv->mm.interruptible = true;
3237                 mutex_unlock(&dev->struct_mutex);
3238         }
3239
3240         /* Let userspace switch the overlay on again. In most cases userspace
3241          * has to recompute where to put it anyway.
3242          */
3243 }
3244
3245 static void i9xx_crtc_enable(struct drm_crtc *crtc)
3246 {
3247         struct drm_device *dev = crtc->dev;
3248         struct drm_i915_private *dev_priv = dev->dev_private;
3249         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3250         int pipe = intel_crtc->pipe;
3251         int plane = intel_crtc->plane;
3252
3253         if (intel_crtc->active)
3254                 return;
3255
3256         intel_crtc->active = true;
3257         intel_update_watermarks(dev);
3258
3259         intel_enable_pll(dev_priv, pipe);
3260         intel_enable_pipe(dev_priv, pipe, false);
3261         intel_enable_plane(dev_priv, plane, pipe);
3262
3263         intel_crtc_load_lut(crtc);
3264         intel_update_fbc(dev);
3265
3266         /* Give the overlay scaler a chance to enable if it's on this pipe */
3267         intel_crtc_dpms_overlay(intel_crtc, true);
3268         intel_crtc_update_cursor(crtc, true);
3269 }
3270
3271 static void i9xx_crtc_disable(struct drm_crtc *crtc)
3272 {
3273         struct drm_device *dev = crtc->dev;
3274         struct drm_i915_private *dev_priv = dev->dev_private;
3275         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3276         int pipe = intel_crtc->pipe;
3277         int plane = intel_crtc->plane;
3278
3279         if (!intel_crtc->active)
3280                 return;
3281
3282         /* Give the overlay scaler a chance to disable if it's on this pipe */
3283         intel_crtc_wait_for_pending_flips(crtc);
3284         drm_vblank_off(dev, pipe);
3285         intel_crtc_dpms_overlay(intel_crtc, false);
3286         intel_crtc_update_cursor(crtc, false);
3287
3288         if (dev_priv->cfb_plane == plane)
3289                 intel_disable_fbc(dev);
3290
3291         intel_disable_plane(dev_priv, plane, pipe);
3292         intel_disable_pipe(dev_priv, pipe);
3293         intel_disable_pll(dev_priv, pipe);
3294
3295         intel_crtc->active = false;
3296         intel_update_fbc(dev);
3297         intel_update_watermarks(dev);
3298         intel_clear_scanline_wait(dev);
3299 }
3300
3301 static void i9xx_crtc_dpms(struct drm_crtc *crtc, int mode)
3302 {
3303         /* XXX: When our outputs are all unaware of DPMS modes other than off
3304          * and on, we should map those modes to DRM_MODE_DPMS_OFF in the CRTC.
3305          */
3306         switch (mode) {
3307         case DRM_MODE_DPMS_ON:
3308         case DRM_MODE_DPMS_STANDBY:
3309         case DRM_MODE_DPMS_SUSPEND:
3310                 i9xx_crtc_enable(crtc);
3311                 break;
3312         case DRM_MODE_DPMS_OFF:
3313                 i9xx_crtc_disable(crtc);
3314                 break;
3315         }
3316 }
3317
3318 /**
3319  * Sets the power management mode of the pipe and plane.
3320  */
3321 static void intel_crtc_dpms(struct drm_crtc *crtc, int mode)
3322 {
3323         struct drm_device *dev = crtc->dev;
3324         struct drm_i915_private *dev_priv = dev->dev_private;
3325         struct drm_i915_master_private *master_priv;
3326         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3327         int pipe = intel_crtc->pipe;
3328         bool enabled;
3329
3330         if (intel_crtc->dpms_mode == mode)
3331                 return;
3332
3333         intel_crtc->dpms_mode = mode;
3334
3335         dev_priv->display.dpms(crtc, mode);
3336
3337         if (!dev->primary->master)
3338                 return;
3339
3340         master_priv = dev->primary->master->driver_priv;
3341         if (!master_priv->sarea_priv)
3342                 return;
3343
3344         enabled = crtc->enabled && mode != DRM_MODE_DPMS_OFF;
3345
3346         switch (pipe) {
3347         case 0:
3348                 master_priv->sarea_priv->pipeA_w = enabled ? crtc->mode.hdisplay : 0;
3349                 master_priv->sarea_priv->pipeA_h = enabled ? crtc->mode.vdisplay : 0;
3350                 break;
3351         case 1:
3352                 master_priv->sarea_priv->pipeB_w = enabled ? crtc->mode.hdisplay : 0;
3353                 master_priv->sarea_priv->pipeB_h = enabled ? crtc->mode.vdisplay : 0;
3354                 break;
3355         default:
3356                 DRM_ERROR("Can't update pipe %c in SAREA\n", pipe_name(pipe));
3357                 break;
3358         }
3359 }
3360
3361 static void intel_crtc_disable(struct drm_crtc *crtc)
3362 {
3363         struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private;
3364         struct drm_device *dev = crtc->dev;
3365
3366         crtc_funcs->dpms(crtc, DRM_MODE_DPMS_OFF);
3367
3368         if (crtc->fb) {
3369                 mutex_lock(&dev->struct_mutex);
3370                 i915_gem_object_unpin(to_intel_framebuffer(crtc->fb)->obj);
3371                 mutex_unlock(&dev->struct_mutex);
3372         }
3373 }
3374
3375 /* Prepare for a mode set.
3376  *
3377  * Note we could be a lot smarter here.  We need to figure out which outputs
3378  * will be enabled, which disabled (in short, how the config will changes)
3379  * and perform the minimum necessary steps to accomplish that, e.g. updating
3380  * watermarks, FBC configuration, making sure PLLs are programmed correctly,
3381  * panel fitting is in the proper state, etc.
3382  */
3383 static void i9xx_crtc_prepare(struct drm_crtc *crtc)
3384 {
3385         i9xx_crtc_disable(crtc);
3386 }
3387
3388 static void i9xx_crtc_commit(struct drm_crtc *crtc)
3389 {
3390         i9xx_crtc_enable(crtc);
3391 }
3392
3393 static void ironlake_crtc_prepare(struct drm_crtc *crtc)
3394 {
3395         ironlake_crtc_disable(crtc);
3396 }
3397
3398 static void ironlake_crtc_commit(struct drm_crtc *crtc)
3399 {
3400         ironlake_crtc_enable(crtc);
3401 }
3402
3403 void intel_encoder_prepare(struct drm_encoder *encoder)
3404 {
3405         struct drm_encoder_helper_funcs *encoder_funcs = encoder->helper_private;
3406         /* lvds has its own version of prepare see intel_lvds_prepare */
3407         encoder_funcs->dpms(encoder, DRM_MODE_DPMS_OFF);
3408 }
3409
3410 void intel_encoder_commit(struct drm_encoder *encoder)
3411 {
3412         struct drm_encoder_helper_funcs *encoder_funcs = encoder->helper_private;
3413         struct drm_device *dev = encoder->dev;
3414         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
3415         struct intel_crtc *intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
3416
3417         /* lvds has its own version of commit see intel_lvds_commit */
3418         encoder_funcs->dpms(encoder, DRM_MODE_DPMS_ON);
3419
3420         if (HAS_PCH_CPT(dev))
3421                 intel_cpt_verify_modeset(dev, intel_crtc->pipe);
3422 }
3423
3424 void intel_encoder_destroy(struct drm_encoder *encoder)
3425 {
3426         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
3427
3428         drm_encoder_cleanup(encoder);
3429         kfree(intel_encoder);
3430 }
3431
3432 static bool intel_crtc_mode_fixup(struct drm_crtc *crtc,
3433                                   struct drm_display_mode *mode,
3434                                   struct drm_display_mode *adjusted_mode)
3435 {
3436         struct drm_device *dev = crtc->dev;
3437
3438         if (HAS_PCH_SPLIT(dev)) {
3439                 /* FDI link clock is fixed at 2.7G */
3440                 if (mode->clock * 3 > IRONLAKE_FDI_FREQ * 4)
3441                         return false;
3442         }
3443
3444         /* XXX some encoders set the crtcinfo, others don't.
3445          * Obviously we need some form of conflict resolution here...
3446          */
3447         if (adjusted_mode->crtc_htotal == 0)
3448                 drm_mode_set_crtcinfo(adjusted_mode, 0);
3449
3450         return true;
3451 }
3452
3453 static int i945_get_display_clock_speed(struct drm_device *dev)
3454 {
3455         return 400000;
3456 }
3457
3458 static int i915_get_display_clock_speed(struct drm_device *dev)
3459 {
3460         return 333000;
3461 }
3462
3463 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
3464 {
3465         return 200000;
3466 }
3467
3468 static int i915gm_get_display_clock_speed(struct drm_device *dev)
3469 {
3470         u16 gcfgc = 0;
3471
3472         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
3473
3474         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
3475                 return 133000;
3476         else {
3477                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
3478                 case GC_DISPLAY_CLOCK_333_MHZ:
3479                         return 333000;
3480                 default:
3481                 case GC_DISPLAY_CLOCK_190_200_MHZ:
3482                         return 190000;
3483                 }
3484         }
3485 }
3486
3487 static int i865_get_display_clock_speed(struct drm_device *dev)
3488 {
3489         return 266000;
3490 }
3491
3492 static int i855_get_display_clock_speed(struct drm_device *dev)
3493 {
3494         u16 hpllcc = 0;
3495         /* Assume that the hardware is in the high speed state.  This
3496          * should be the default.
3497          */
3498         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
3499         case GC_CLOCK_133_200:
3500         case GC_CLOCK_100_200:
3501                 return 200000;
3502         case GC_CLOCK_166_250:
3503                 return 250000;
3504         case GC_CLOCK_100_133:
3505                 return 133000;
3506         }
3507
3508         /* Shouldn't happen */
3509         return 0;
3510 }
3511
3512 static int i830_get_display_clock_speed(struct drm_device *dev)
3513 {
3514         return 133000;
3515 }
3516
3517 struct fdi_m_n {
3518         u32        tu;
3519         u32        gmch_m;
3520         u32        gmch_n;
3521         u32        link_m;
3522         u32        link_n;
3523 };
3524
3525 static void
3526 fdi_reduce_ratio(u32 *num, u32 *den)
3527 {
3528         while (*num > 0xffffff || *den > 0xffffff) {
3529                 *num >>= 1;
3530                 *den >>= 1;
3531         }
3532 }
3533
3534 static void
3535 ironlake_compute_m_n(int bits_per_pixel, int nlanes, int pixel_clock,
3536                      int link_clock, struct fdi_m_n *m_n)
3537 {
3538         m_n->tu = 64; /* default size */
3539
3540         /* BUG_ON(pixel_clock > INT_MAX / 36); */
3541         m_n->gmch_m = bits_per_pixel * pixel_clock;
3542         m_n->gmch_n = link_clock * nlanes * 8;
3543         fdi_reduce_ratio(&m_n->gmch_m, &m_n->gmch_n);
3544
3545         m_n->link_m = pixel_clock;
3546         m_n->link_n = link_clock;
3547         fdi_reduce_ratio(&m_n->link_m, &m_n->link_n);
3548 }
3549
3550
3551 struct intel_watermark_params {
3552         unsigned long fifo_size;
3553         unsigned long max_wm;
3554         unsigned long default_wm;
3555         unsigned long guard_size;
3556         unsigned long cacheline_size;
3557 };
3558
3559 /* Pineview has different values for various configs */
3560 static const struct intel_watermark_params pineview_display_wm = {
3561         PINEVIEW_DISPLAY_FIFO,
3562         PINEVIEW_MAX_WM,
3563         PINEVIEW_DFT_WM,
3564         PINEVIEW_GUARD_WM,
3565         PINEVIEW_FIFO_LINE_SIZE
3566 };
3567 static const struct intel_watermark_params pineview_display_hplloff_wm = {
3568         PINEVIEW_DISPLAY_FIFO,
3569         PINEVIEW_MAX_WM,
3570         PINEVIEW_DFT_HPLLOFF_WM,
3571         PINEVIEW_GUARD_WM,
3572         PINEVIEW_FIFO_LINE_SIZE
3573 };
3574 static const struct intel_watermark_params pineview_cursor_wm = {
3575         PINEVIEW_CURSOR_FIFO,
3576         PINEVIEW_CURSOR_MAX_WM,
3577         PINEVIEW_CURSOR_DFT_WM,
3578         PINEVIEW_CURSOR_GUARD_WM,
3579         PINEVIEW_FIFO_LINE_SIZE,
3580 };
3581 static const struct intel_watermark_params pineview_cursor_hplloff_wm = {
3582         PINEVIEW_CURSOR_FIFO,
3583         PINEVIEW_CURSOR_MAX_WM,
3584         PINEVIEW_CURSOR_DFT_WM,
3585         PINEVIEW_CURSOR_GUARD_WM,
3586         PINEVIEW_FIFO_LINE_SIZE
3587 };
3588 static const struct intel_watermark_params g4x_wm_info = {
3589         G4X_FIFO_SIZE,
3590         G4X_MAX_WM,
3591         G4X_MAX_WM,
3592         2,
3593         G4X_FIFO_LINE_SIZE,
3594 };
3595 static const struct intel_watermark_params g4x_cursor_wm_info = {
3596         I965_CURSOR_FIFO,
3597         I965_CURSOR_MAX_WM,
3598         I965_CURSOR_DFT_WM,
3599         2,
3600         G4X_FIFO_LINE_SIZE,
3601 };
3602 static const struct intel_watermark_params i965_cursor_wm_info = {
3603         I965_CURSOR_FIFO,
3604         I965_CURSOR_MAX_WM,
3605         I965_CURSOR_DFT_WM,
3606         2,
3607         I915_FIFO_LINE_SIZE,
3608 };
3609 static const struct intel_watermark_params i945_wm_info = {
3610         I945_FIFO_SIZE,
3611         I915_MAX_WM,
3612         1,
3613         2,
3614         I915_FIFO_LINE_SIZE
3615 };
3616 static const struct intel_watermark_params i915_wm_info = {
3617         I915_FIFO_SIZE,
3618         I915_MAX_WM,
3619         1,
3620         2,
3621         I915_FIFO_LINE_SIZE
3622 };
3623 static const struct intel_watermark_params i855_wm_info = {
3624         I855GM_FIFO_SIZE,
3625         I915_MAX_WM,
3626         1,
3627         2,
3628         I830_FIFO_LINE_SIZE
3629 };
3630 static const struct intel_watermark_params i830_wm_info = {
3631         I830_FIFO_SIZE,
3632         I915_MAX_WM,
3633         1,
3634         2,
3635         I830_FIFO_LINE_SIZE
3636 };
3637
3638 static const struct intel_watermark_params ironlake_display_wm_info = {
3639         ILK_DISPLAY_FIFO,
3640         ILK_DISPLAY_MAXWM,
3641         ILK_DISPLAY_DFTWM,
3642         2,
3643         ILK_FIFO_LINE_SIZE
3644 };
3645 static const struct intel_watermark_params ironlake_cursor_wm_info = {
3646         ILK_CURSOR_FIFO,
3647         ILK_CURSOR_MAXWM,
3648         ILK_CURSOR_DFTWM,
3649         2,
3650         ILK_FIFO_LINE_SIZE
3651 };
3652 static const struct intel_watermark_params ironlake_display_srwm_info = {
3653         ILK_DISPLAY_SR_FIFO,
3654         ILK_DISPLAY_MAX_SRWM,
3655         ILK_DISPLAY_DFT_SRWM,
3656         2,
3657         ILK_FIFO_LINE_SIZE
3658 };
3659 static const struct intel_watermark_params ironlake_cursor_srwm_info = {
3660         ILK_CURSOR_SR_FIFO,
3661         ILK_CURSOR_MAX_SRWM,
3662         ILK_CURSOR_DFT_SRWM,
3663         2,
3664         ILK_FIFO_LINE_SIZE
3665 };
3666
3667 static const struct intel_watermark_params sandybridge_display_wm_info = {
3668         SNB_DISPLAY_FIFO,
3669         SNB_DISPLAY_MAXWM,
3670         SNB_DISPLAY_DFTWM,
3671         2,
3672         SNB_FIFO_LINE_SIZE
3673 };
3674 static const struct intel_watermark_params sandybridge_cursor_wm_info = {
3675         SNB_CURSOR_FIFO,
3676         SNB_CURSOR_MAXWM,
3677         SNB_CURSOR_DFTWM,
3678         2,
3679         SNB_FIFO_LINE_SIZE
3680 };
3681 static const struct intel_watermark_params sandybridge_display_srwm_info = {
3682         SNB_DISPLAY_SR_FIFO,
3683         SNB_DISPLAY_MAX_SRWM,
3684         SNB_DISPLAY_DFT_SRWM,
3685         2,
3686         SNB_FIFO_LINE_SIZE
3687 };
3688 static const struct intel_watermark_params sandybridge_cursor_srwm_info = {
3689         SNB_CURSOR_SR_FIFO,
3690         SNB_CURSOR_MAX_SRWM,
3691         SNB_CURSOR_DFT_SRWM,
3692         2,
3693         SNB_FIFO_LINE_SIZE
3694 };
3695
3696
3697 /**
3698  * intel_calculate_wm - calculate watermark level
3699  * @clock_in_khz: pixel clock
3700  * @wm: chip FIFO params
3701  * @pixel_size: display pixel size
3702  * @latency_ns: memory latency for the platform
3703  *
3704  * Calculate the watermark level (the level at which the display plane will
3705  * start fetching from memory again).  Each chip has a different display
3706  * FIFO size and allocation, so the caller needs to figure that out and pass
3707  * in the correct intel_watermark_params structure.
3708  *
3709  * As the pixel clock runs, the FIFO will be drained at a rate that depends
3710  * on the pixel size.  When it reaches the watermark level, it'll start
3711  * fetching FIFO line sized based chunks from memory until the FIFO fills
3712  * past the watermark point.  If the FIFO drains completely, a FIFO underrun
3713  * will occur, and a display engine hang could result.
3714  */
3715 static unsigned long intel_calculate_wm(unsigned long clock_in_khz,
3716                                         const struct intel_watermark_params *wm,
3717                                         int fifo_size,
3718                                         int pixel_size,
3719                                         unsigned long latency_ns)
3720 {
3721         long entries_required, wm_size;
3722
3723         /*
3724          * Note: we need to make sure we don't overflow for various clock &
3725          * latency values.
3726          * clocks go from a few thousand to several hundred thousand.
3727          * latency is usually a few thousand
3728          */
3729         entries_required = ((clock_in_khz / 1000) * pixel_size * latency_ns) /
3730                 1000;
3731         entries_required = DIV_ROUND_UP(entries_required, wm->cacheline_size);
3732
3733         DRM_DEBUG_KMS("FIFO entries required for mode: %ld\n", entries_required);
3734
3735         wm_size = fifo_size - (entries_required + wm->guard_size);
3736
3737         DRM_DEBUG_KMS("FIFO watermark level: %ld\n", wm_size);
3738
3739         /* Don't promote wm_size to unsigned... */
3740         if (wm_size > (long)wm->max_wm)
3741                 wm_size = wm->max_wm;
3742         if (wm_size <= 0)
3743                 wm_size = wm->default_wm;
3744         return wm_size;
3745 }
3746
3747 struct cxsr_latency {
3748         int is_desktop;
3749         int is_ddr3;
3750         unsigned long fsb_freq;
3751         unsigned long mem_freq;
3752         unsigned long display_sr;
3753         unsigned long display_hpll_disable;
3754         unsigned long cursor_sr;
3755         unsigned long cursor_hpll_disable;
3756 };
3757
3758 static const struct cxsr_latency cxsr_latency_table[] = {
3759         {1, 0, 800, 400, 3382, 33382, 3983, 33983},    /* DDR2-400 SC */
3760         {1, 0, 800, 667, 3354, 33354, 3807, 33807},    /* DDR2-667 SC */
3761         {1, 0, 800, 800, 3347, 33347, 3763, 33763},    /* DDR2-800 SC */
3762         {1, 1, 800, 667, 6420, 36420, 6873, 36873},    /* DDR3-667 SC */
3763         {1, 1, 800, 800, 5902, 35902, 6318, 36318},    /* DDR3-800 SC */
3764
3765         {1, 0, 667, 400, 3400, 33400, 4021, 34021},    /* DDR2-400 SC */
3766         {1, 0, 667, 667, 3372, 33372, 3845, 33845},    /* DDR2-667 SC */
3767         {1, 0, 667, 800, 3386, 33386, 3822, 33822},    /* DDR2-800 SC */
3768         {1, 1, 667, 667, 6438, 36438, 6911, 36911},    /* DDR3-667 SC */
3769         {1, 1, 667, 800, 5941, 35941, 6377, 36377},    /* DDR3-800 SC */
3770
3771         {1, 0, 400, 400, 3472, 33472, 4173, 34173},    /* DDR2-400 SC */
3772         {1, 0, 400, 667, 3443, 33443, 3996, 33996},    /* DDR2-667 SC */
3773         {1, 0, 400, 800, 3430, 33430, 3946, 33946},    /* DDR2-800 SC */
3774         {1, 1, 400, 667, 6509, 36509, 7062, 37062},    /* DDR3-667 SC */
3775         {1, 1, 400, 800, 5985, 35985, 6501, 36501},    /* DDR3-800 SC */
3776
3777         {0, 0, 800, 400, 3438, 33438, 4065, 34065},    /* DDR2-400 SC */
3778         {0, 0, 800, 667, 3410, 33410, 3889, 33889},    /* DDR2-667 SC */
3779         {0, 0, 800, 800, 3403, 33403, 3845, 33845},    /* DDR2-800 SC */
3780         {0, 1, 800, 667, 6476, 36476, 6955, 36955},    /* DDR3-667 SC */
3781         {0, 1, 800, 800, 5958, 35958, 6400, 36400},    /* DDR3-800 SC */
3782
3783         {0, 0, 667, 400, 3456, 33456, 4103, 34106},    /* DDR2-400 SC */
3784         {0, 0, 667, 667, 3428, 33428, 3927, 33927},    /* DDR2-667 SC */
3785         {0, 0, 667, 800, 3443, 33443, 3905, 33905},    /* DDR2-800 SC */
3786         {0, 1, 667, 667, 6494, 36494, 6993, 36993},    /* DDR3-667 SC */
3787         {0, 1, 667, 800, 5998, 35998, 6460, 36460},    /* DDR3-800 SC */
3788
3789         {0, 0, 400, 400, 3528, 33528, 4255, 34255},    /* DDR2-400 SC */
3790         {0, 0, 400, 667, 3500, 33500, 4079, 34079},    /* DDR2-667 SC */
3791         {0, 0, 400, 800, 3487, 33487, 4029, 34029},    /* DDR2-800 SC */
3792         {0, 1, 400, 667, 6566, 36566, 7145, 37145},    /* DDR3-667 SC */
3793         {0, 1, 400, 800, 6042, 36042, 6584, 36584},    /* DDR3-800 SC */
3794 };
3795
3796 static const struct cxsr_latency *intel_get_cxsr_latency(int is_desktop,
3797                                                          int is_ddr3,
3798                                                          int fsb,
3799                                                          int mem)
3800 {
3801         const struct cxsr_latency *latency;
3802         int i;
3803
3804         if (fsb == 0 || mem == 0)
3805                 return NULL;
3806
3807         for (i = 0; i < ARRAY_SIZE(cxsr_latency_table); i++) {
3808                 latency = &cxsr_latency_table[i];
3809                 if (is_desktop == latency->is_desktop &&
3810                     is_ddr3 == latency->is_ddr3 &&
3811                     fsb == latency->fsb_freq && mem == latency->mem_freq)
3812                         return latency;
3813         }
3814
3815         DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
3816
3817         return NULL;
3818 }
3819
3820 static void pineview_disable_cxsr(struct drm_device *dev)
3821 {
3822         struct drm_i915_private *dev_priv = dev->dev_private;
3823
3824         /* deactivate cxsr */
3825         I915_WRITE(DSPFW3, I915_READ(DSPFW3) & ~PINEVIEW_SELF_REFRESH_EN);
3826 }
3827
3828 /*
3829  * Latency for FIFO fetches is dependent on several factors:
3830  *   - memory configuration (speed, channels)
3831  *   - chipset
3832  *   - current MCH state
3833  * It can be fairly high in some situations, so here we assume a fairly
3834  * pessimal value.  It's a tradeoff between extra memory fetches (if we
3835  * set this value too high, the FIFO will fetch frequently to stay full)
3836  * and power consumption (set it too low to save power and we might see
3837  * FIFO underruns and display "flicker").
3838  *
3839  * A value of 5us seems to be a good balance; safe for very low end
3840  * platforms but not overly aggressive on lower latency configs.
3841  */
3842 static const int latency_ns = 5000;
3843
3844 static int i9xx_get_fifo_size(struct drm_device *dev, int plane)
3845 {
3846         struct drm_i915_private *dev_priv = dev->dev_private;
3847         uint32_t dsparb = I915_READ(DSPARB);
3848         int size;
3849
3850         size = dsparb & 0x7f;
3851         if (plane)
3852                 size = ((dsparb >> DSPARB_CSTART_SHIFT) & 0x7f) - size;
3853
3854         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
3855                       plane ? "B" : "A", size);
3856
3857         return size;
3858 }
3859
3860 static int i85x_get_fifo_size(struct drm_device *dev, int plane)
3861 {
3862         struct drm_i915_private *dev_priv = dev->dev_private;
3863         uint32_t dsparb = I915_READ(DSPARB);
3864         int size;
3865
3866         size = dsparb & 0x1ff;
3867         if (plane)
3868                 size = ((dsparb >> DSPARB_BEND_SHIFT) & 0x1ff) - size;
3869         size >>= 1; /* Convert to cachelines */
3870
3871         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
3872                       plane ? "B" : "A", size);
3873
3874         return size;
3875 }
3876
3877 static int i845_get_fifo_size(struct drm_device *dev, int plane)
3878 {
3879         struct drm_i915_private *dev_priv = dev->dev_private;
3880         uint32_t dsparb = I915_READ(DSPARB);
3881         int size;
3882
3883         size = dsparb & 0x7f;
3884         size >>= 2; /* Convert to cachelines */
3885
3886         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
3887                       plane ? "B" : "A",
3888                       size);
3889
3890         return size;
3891 }
3892
3893 static int i830_get_fifo_size(struct drm_device *dev, int plane)
3894 {
3895         struct drm_i915_private *dev_priv = dev->dev_private;
3896         uint32_t dsparb = I915_READ(DSPARB);
3897         int size;
3898
3899         size = dsparb & 0x7f;
3900         size >>= 1; /* Convert to cachelines */
3901
3902         DRM_DEBUG_KMS("FIFO size - (0x%08x) %s: %d\n", dsparb,
3903                       plane ? "B" : "A", size);
3904
3905         return size;
3906 }
3907
3908 static struct drm_crtc *single_enabled_crtc(struct drm_device *dev)
3909 {
3910         struct drm_crtc *crtc, *enabled = NULL;
3911
3912         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
3913                 if (crtc->enabled && crtc->fb) {
3914                         if (enabled)
3915                                 return NULL;
3916                         enabled = crtc;
3917                 }
3918         }
3919
3920         return enabled;
3921 }
3922
3923 static void pineview_update_wm(struct drm_device *dev)
3924 {
3925         struct drm_i915_private *dev_priv = dev->dev_private;
3926         struct drm_crtc *crtc;
3927         const struct cxsr_latency *latency;
3928         u32 reg;
3929         unsigned long wm;
3930
3931         latency = intel_get_cxsr_latency(IS_PINEVIEW_G(dev), dev_priv->is_ddr3,
3932                                          dev_priv->fsb_freq, dev_priv->mem_freq);
3933         if (!latency) {
3934                 DRM_DEBUG_KMS("Unknown FSB/MEM found, disable CxSR\n");
3935                 pineview_disable_cxsr(dev);
3936                 return;
3937         }
3938
3939         crtc = single_enabled_crtc(dev);
3940         if (crtc) {
3941                 int clock = crtc->mode.clock;
3942                 int pixel_size = crtc->fb->bits_per_pixel / 8;
3943
3944                 /* Display SR */
3945                 wm = intel_calculate_wm(clock, &pineview_display_wm,
3946                                         pineview_display_wm.fifo_size,
3947                                         pixel_size, latency->display_sr);
3948                 reg = I915_READ(DSPFW1);
3949                 reg &= ~DSPFW_SR_MASK;
3950                 reg |= wm << DSPFW_SR_SHIFT;
3951                 I915_WRITE(DSPFW1, reg);
3952                 DRM_DEBUG_KMS("DSPFW1 register is %x\n", reg);
3953
3954                 /* cursor SR */
3955                 wm = intel_calculate_wm(clock, &pineview_cursor_wm,
3956                                         pineview_display_wm.fifo_size,
3957                                         pixel_size, latency->cursor_sr);
3958                 reg = I915_READ(DSPFW3);
3959                 reg &= ~DSPFW_CURSOR_SR_MASK;
3960                 reg |= (wm & 0x3f) << DSPFW_CURSOR_SR_SHIFT;
3961                 I915_WRITE(DSPFW3, reg);
3962
3963                 /* Display HPLL off SR */
3964                 wm = intel_calculate_wm(clock, &pineview_display_hplloff_wm,
3965                                         pineview_display_hplloff_wm.fifo_size,
3966                                         pixel_size, latency->display_hpll_disable);
3967                 reg = I915_READ(DSPFW3);
3968                 reg &= ~DSPFW_HPLL_SR_MASK;
3969                 reg |= wm & DSPFW_HPLL_SR_MASK;
3970                 I915_WRITE(DSPFW3, reg);
3971
3972                 /* cursor HPLL off SR */
3973                 wm = intel_calculate_wm(clock, &pineview_cursor_hplloff_wm,
3974                                         pineview_display_hplloff_wm.fifo_size,
3975                                         pixel_size, latency->cursor_hpll_disable);
3976                 reg = I915_READ(DSPFW3);
3977                 reg &= ~DSPFW_HPLL_CURSOR_MASK;
3978                 reg |= (wm & 0x3f) << DSPFW_HPLL_CURSOR_SHIFT;
3979                 I915_WRITE(DSPFW3, reg);
3980                 DRM_DEBUG_KMS("DSPFW3 register is %x\n", reg);
3981
3982                 /* activate cxsr */
3983                 I915_WRITE(DSPFW3,
3984                            I915_READ(DSPFW3) | PINEVIEW_SELF_REFRESH_EN);
3985                 DRM_DEBUG_KMS("Self-refresh is enabled\n");
3986         } else {
3987                 pineview_disable_cxsr(dev);
3988                 DRM_DEBUG_KMS("Self-refresh is disabled\n");
3989         }
3990 }
3991
3992 static bool g4x_compute_wm0(struct drm_device *dev,
3993                             int plane,
3994                             const struct intel_watermark_params *display,
3995                             int display_latency_ns,
3996                             const struct intel_watermark_params *cursor,
3997                             int cursor_latency_ns,
3998                             int *plane_wm,
3999                             int *cursor_wm)
4000 {
4001         struct drm_crtc *crtc;
4002         int htotal, hdisplay, clock, pixel_size;
4003         int line_time_us, line_count;
4004         int entries, tlb_miss;
4005
4006         crtc = intel_get_crtc_for_plane(dev, plane);
4007         if (crtc->fb == NULL || !crtc->enabled) {
4008                 *cursor_wm = cursor->guard_size;
4009                 *plane_wm = display->guard_size;
4010                 return false;
4011         }
4012
4013         htotal = crtc->mode.htotal;
4014         hdisplay = crtc->mode.hdisplay;
4015         clock = crtc->mode.clock;
4016         pixel_size = crtc->fb->bits_per_pixel / 8;
4017
4018         /* Use the small buffer method to calculate plane watermark */
4019         entries = ((clock * pixel_size / 1000) * display_latency_ns) / 1000;
4020         tlb_miss = display->fifo_size*display->cacheline_size - hdisplay * 8;
4021         if (tlb_miss > 0)
4022                 entries += tlb_miss;
4023         entries = DIV_ROUND_UP(entries, display->cacheline_size);
4024         *plane_wm = entries + display->guard_size;
4025         if (*plane_wm > (int)display->max_wm)
4026                 *plane_wm = display->max_wm;
4027
4028         /* Use the large buffer method to calculate cursor watermark */
4029         line_time_us = ((htotal * 1000) / clock);
4030         line_count = (cursor_latency_ns / line_time_us + 1000) / 1000;
4031         entries = line_count * 64 * pixel_size;
4032         tlb_miss = cursor->fifo_size*cursor->cacheline_size - hdisplay * 8;
4033         if (tlb_miss > 0)
4034                 entries += tlb_miss;
4035         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
4036         *cursor_wm = entries + cursor->guard_size;
4037         if (*cursor_wm > (int)cursor->max_wm)
4038                 *cursor_wm = (int)cursor->max_wm;
4039
4040         return true;
4041 }
4042
4043 /*
4044  * Check the wm result.
4045  *
4046  * If any calculated watermark values is larger than the maximum value that
4047  * can be programmed into the associated watermark register, that watermark
4048  * must be disabled.
4049  */
4050 static bool g4x_check_srwm(struct drm_device *dev,
4051                            int display_wm, int cursor_wm,
4052                            const struct intel_watermark_params *display,
4053                            const struct intel_watermark_params *cursor)
4054 {
4055         DRM_DEBUG_KMS("SR watermark: display plane %d, cursor %d\n",
4056                       display_wm, cursor_wm);
4057
4058         if (display_wm > display->max_wm) {
4059                 DRM_DEBUG_KMS("display watermark is too large(%d/%ld), disabling\n",
4060                               display_wm, display->max_wm);
4061                 return false;
4062         }
4063
4064         if (cursor_wm > cursor->max_wm) {
4065                 DRM_DEBUG_KMS("cursor watermark is too large(%d/%ld), disabling\n",
4066                               cursor_wm, cursor->max_wm);
4067                 return false;
4068         }
4069
4070         if (!(display_wm || cursor_wm)) {
4071                 DRM_DEBUG_KMS("SR latency is 0, disabling\n");
4072                 return false;
4073         }
4074
4075         return true;
4076 }
4077
4078 static bool g4x_compute_srwm(struct drm_device *dev,
4079                              int plane,
4080                              int latency_ns,
4081                              const struct intel_watermark_params *display,
4082                              const struct intel_watermark_params *cursor,
4083                              int *display_wm, int *cursor_wm)
4084 {
4085         struct drm_crtc *crtc;
4086         int hdisplay, htotal, pixel_size, clock;
4087         unsigned long line_time_us;
4088         int line_count, line_size;
4089         int small, large;
4090         int entries;
4091
4092         if (!latency_ns) {
4093                 *display_wm = *cursor_wm = 0;
4094                 return false;
4095         }
4096
4097         crtc = intel_get_crtc_for_plane(dev, plane);
4098         hdisplay = crtc->mode.hdisplay;
4099         htotal = crtc->mode.htotal;
4100         clock = crtc->mode.clock;
4101         pixel_size = crtc->fb->bits_per_pixel / 8;
4102
4103         line_time_us = (htotal * 1000) / clock;
4104         line_count = (latency_ns / line_time_us + 1000) / 1000;
4105         line_size = hdisplay * pixel_size;
4106
4107         /* Use the minimum of the small and large buffer method for primary */
4108         small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
4109         large = line_count * line_size;
4110
4111         entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
4112         *display_wm = entries + display->guard_size;
4113
4114         /* calculate the self-refresh watermark for display cursor */
4115         entries = line_count * pixel_size * 64;
4116         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
4117         *cursor_wm = entries + cursor->guard_size;
4118
4119         return g4x_check_srwm(dev,
4120                               *display_wm, *cursor_wm,
4121                               display, cursor);
4122 }
4123
4124 #define single_plane_enabled(mask) is_power_of_2(mask)
4125
4126 static void g4x_update_wm(struct drm_device *dev)
4127 {
4128         static const int sr_latency_ns = 12000;
4129         struct drm_i915_private *dev_priv = dev->dev_private;
4130         int planea_wm, planeb_wm, cursora_wm, cursorb_wm;
4131         int plane_sr, cursor_sr;
4132         unsigned int enabled = 0;
4133
4134         if (g4x_compute_wm0(dev, 0,
4135                             &g4x_wm_info, latency_ns,
4136                             &g4x_cursor_wm_info, latency_ns,
4137                             &planea_wm, &cursora_wm))
4138                 enabled |= 1;
4139
4140         if (g4x_compute_wm0(dev, 1,
4141                             &g4x_wm_info, latency_ns,
4142                             &g4x_cursor_wm_info, latency_ns,
4143                             &planeb_wm, &cursorb_wm))
4144                 enabled |= 2;
4145
4146         plane_sr = cursor_sr = 0;
4147         if (single_plane_enabled(enabled) &&
4148             g4x_compute_srwm(dev, ffs(enabled) - 1,
4149                              sr_latency_ns,
4150                              &g4x_wm_info,
4151                              &g4x_cursor_wm_info,
4152                              &plane_sr, &cursor_sr))
4153                 I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN);
4154         else
4155                 I915_WRITE(FW_BLC_SELF,
4156                            I915_READ(FW_BLC_SELF) & ~FW_BLC_SELF_EN);
4157
4158         DRM_DEBUG_KMS("Setting FIFO watermarks - A: plane=%d, cursor=%d, B: plane=%d, cursor=%d, SR: plane=%d, cursor=%d\n",
4159                       planea_wm, cursora_wm,
4160                       planeb_wm, cursorb_wm,
4161                       plane_sr, cursor_sr);
4162
4163         I915_WRITE(DSPFW1,
4164                    (plane_sr << DSPFW_SR_SHIFT) |
4165                    (cursorb_wm << DSPFW_CURSORB_SHIFT) |
4166                    (planeb_wm << DSPFW_PLANEB_SHIFT) |
4167                    planea_wm);
4168         I915_WRITE(DSPFW2,
4169                    (I915_READ(DSPFW2) & DSPFW_CURSORA_MASK) |
4170                    (cursora_wm << DSPFW_CURSORA_SHIFT));
4171         /* HPLL off in SR has some issues on G4x... disable it */
4172         I915_WRITE(DSPFW3,
4173                    (I915_READ(DSPFW3) & ~DSPFW_HPLL_SR_EN) |
4174                    (cursor_sr << DSPFW_CURSOR_SR_SHIFT));
4175 }
4176
4177 static void i965_update_wm(struct drm_device *dev)
4178 {
4179         struct drm_i915_private *dev_priv = dev->dev_private;
4180         struct drm_crtc *crtc;
4181         int srwm = 1;
4182         int cursor_sr = 16;
4183
4184         /* Calc sr entries for one plane configs */
4185         crtc = single_enabled_crtc(dev);
4186         if (crtc) {
4187                 /* self-refresh has much higher latency */
4188                 static const int sr_latency_ns = 12000;
4189                 int clock = crtc->mode.clock;
4190                 int htotal = crtc->mode.htotal;
4191                 int hdisplay = crtc->mode.hdisplay;
4192                 int pixel_size = crtc->fb->bits_per_pixel / 8;
4193                 unsigned long line_time_us;
4194                 int entries;
4195
4196                 line_time_us = ((htotal * 1000) / clock);
4197
4198                 /* Use ns/us then divide to preserve precision */
4199                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
4200                         pixel_size * hdisplay;
4201                 entries = DIV_ROUND_UP(entries, I915_FIFO_LINE_SIZE);
4202                 srwm = I965_FIFO_SIZE - entries;
4203                 if (srwm < 0)
4204                         srwm = 1;
4205                 srwm &= 0x1ff;
4206                 DRM_DEBUG_KMS("self-refresh entries: %d, wm: %d\n",
4207                               entries, srwm);
4208
4209                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
4210                         pixel_size * 64;
4211                 entries = DIV_ROUND_UP(entries,
4212                                           i965_cursor_wm_info.cacheline_size);
4213                 cursor_sr = i965_cursor_wm_info.fifo_size -
4214                         (entries + i965_cursor_wm_info.guard_size);
4215
4216                 if (cursor_sr > i965_cursor_wm_info.max_wm)
4217                         cursor_sr = i965_cursor_wm_info.max_wm;
4218
4219                 DRM_DEBUG_KMS("self-refresh watermark: display plane %d "
4220                               "cursor %d\n", srwm, cursor_sr);
4221
4222                 if (IS_CRESTLINE(dev))
4223                         I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN);
4224         } else {
4225                 /* Turn off self refresh if both pipes are enabled */
4226                 if (IS_CRESTLINE(dev))
4227                         I915_WRITE(FW_BLC_SELF, I915_READ(FW_BLC_SELF)
4228                                    & ~FW_BLC_SELF_EN);
4229         }
4230
4231         DRM_DEBUG_KMS("Setting FIFO watermarks - A: 8, B: 8, C: 8, SR %d\n",
4232                       srwm);
4233
4234         /* 965 has limitations... */
4235         I915_WRITE(DSPFW1, (srwm << DSPFW_SR_SHIFT) |
4236                    (8 << 16) | (8 << 8) | (8 << 0));
4237         I915_WRITE(DSPFW2, (8 << 8) | (8 << 0));
4238         /* update cursor SR watermark */
4239         I915_WRITE(DSPFW3, (cursor_sr << DSPFW_CURSOR_SR_SHIFT));
4240 }
4241
4242 static void i9xx_update_wm(struct drm_device *dev)
4243 {
4244         struct drm_i915_private *dev_priv = dev->dev_private;
4245         const struct intel_watermark_params *wm_info;
4246         uint32_t fwater_lo;
4247         uint32_t fwater_hi;
4248         int cwm, srwm = 1;
4249         int fifo_size;
4250         int planea_wm, planeb_wm;
4251         struct drm_crtc *crtc, *enabled = NULL;
4252
4253         if (IS_I945GM(dev))
4254                 wm_info = &i945_wm_info;
4255         else if (!IS_GEN2(dev))
4256                 wm_info = &i915_wm_info;
4257         else
4258                 wm_info = &i855_wm_info;
4259
4260         fifo_size = dev_priv->display.get_fifo_size(dev, 0);
4261         crtc = intel_get_crtc_for_plane(dev, 0);
4262         if (crtc->enabled && crtc->fb) {
4263                 planea_wm = intel_calculate_wm(crtc->mode.clock,
4264                                                wm_info, fifo_size,
4265                                                crtc->fb->bits_per_pixel / 8,
4266                                                latency_ns);
4267                 enabled = crtc;
4268         } else
4269                 planea_wm = fifo_size - wm_info->guard_size;
4270
4271         fifo_size = dev_priv->display.get_fifo_size(dev, 1);
4272         crtc = intel_get_crtc_for_plane(dev, 1);
4273         if (crtc->enabled && crtc->fb) {
4274                 planeb_wm = intel_calculate_wm(crtc->mode.clock,
4275                                                wm_info, fifo_size,
4276                                                crtc->fb->bits_per_pixel / 8,
4277                                                latency_ns);
4278                 if (enabled == NULL)
4279                         enabled = crtc;
4280                 else
4281                         enabled = NULL;
4282         } else
4283                 planeb_wm = fifo_size - wm_info->guard_size;
4284
4285         DRM_DEBUG_KMS("FIFO watermarks - A: %d, B: %d\n", planea_wm, planeb_wm);
4286
4287         /*
4288          * Overlay gets an aggressive default since video jitter is bad.
4289          */
4290         cwm = 2;
4291
4292         /* Play safe and disable self-refresh before adjusting watermarks. */
4293         if (IS_I945G(dev) || IS_I945GM(dev))
4294                 I915_WRITE(FW_BLC_SELF, FW_BLC_SELF_EN_MASK | 0);
4295         else if (IS_I915GM(dev))
4296                 I915_WRITE(INSTPM, I915_READ(INSTPM) & ~INSTPM_SELF_EN);
4297
4298         /* Calc sr entries for one plane configs */
4299         if (HAS_FW_BLC(dev) && enabled) {
4300                 /* self-refresh has much higher latency */
4301                 static const int sr_latency_ns = 6000;
4302                 int clock = enabled->mode.clock;
4303                 int htotal = enabled->mode.htotal;
4304                 int hdisplay = enabled->mode.hdisplay;
4305                 int pixel_size = enabled->fb->bits_per_pixel / 8;
4306                 unsigned long line_time_us;
4307                 int entries;
4308
4309                 line_time_us = (htotal * 1000) / clock;
4310
4311                 /* Use ns/us then divide to preserve precision */
4312                 entries = (((sr_latency_ns / line_time_us) + 1000) / 1000) *
4313                         pixel_size * hdisplay;
4314                 entries = DIV_ROUND_UP(entries, wm_info->cacheline_size);
4315                 DRM_DEBUG_KMS("self-refresh entries: %d\n", entries);
4316                 srwm = wm_info->fifo_size - entries;
4317                 if (srwm < 0)
4318                         srwm = 1;
4319
4320                 if (IS_I945G(dev) || IS_I945GM(dev))
4321                         I915_WRITE(FW_BLC_SELF,
4322                                    FW_BLC_SELF_FIFO_MASK | (srwm & 0xff));
4323                 else if (IS_I915GM(dev))
4324                         I915_WRITE(FW_BLC_SELF, srwm & 0x3f);
4325         }
4326
4327         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d, B: %d, C: %d, SR %d\n",
4328                       planea_wm, planeb_wm, cwm, srwm);
4329
4330         fwater_lo = ((planeb_wm & 0x3f) << 16) | (planea_wm & 0x3f);
4331         fwater_hi = (cwm & 0x1f);
4332
4333         /* Set request length to 8 cachelines per fetch */
4334         fwater_lo = fwater_lo | (1 << 24) | (1 << 8);
4335         fwater_hi = fwater_hi | (1 << 8);
4336
4337         I915_WRITE(FW_BLC, fwater_lo);
4338         I915_WRITE(FW_BLC2, fwater_hi);
4339
4340         if (HAS_FW_BLC(dev)) {
4341                 if (enabled) {
4342                         if (IS_I945G(dev) || IS_I945GM(dev))
4343                                 I915_WRITE(FW_BLC_SELF,
4344                                            FW_BLC_SELF_EN_MASK | FW_BLC_SELF_EN);
4345                         else if (IS_I915GM(dev))
4346                                 I915_WRITE(INSTPM, I915_READ(INSTPM) | INSTPM_SELF_EN);
4347                         DRM_DEBUG_KMS("memory self refresh enabled\n");
4348                 } else
4349                         DRM_DEBUG_KMS("memory self refresh disabled\n");
4350         }
4351 }
4352
4353 static void i830_update_wm(struct drm_device *dev)
4354 {
4355         struct drm_i915_private *dev_priv = dev->dev_private;
4356         struct drm_crtc *crtc;
4357         uint32_t fwater_lo;
4358         int planea_wm;
4359
4360         crtc = single_enabled_crtc(dev);
4361         if (crtc == NULL)
4362                 return;
4363
4364         planea_wm = intel_calculate_wm(crtc->mode.clock, &i830_wm_info,
4365                                        dev_priv->display.get_fifo_size(dev, 0),
4366                                        crtc->fb->bits_per_pixel / 8,
4367                                        latency_ns);
4368         fwater_lo = I915_READ(FW_BLC) & ~0xfff;
4369         fwater_lo |= (3<<8) | planea_wm;
4370
4371         DRM_DEBUG_KMS("Setting FIFO watermarks - A: %d\n", planea_wm);
4372
4373         I915_WRITE(FW_BLC, fwater_lo);
4374 }
4375
4376 #define ILK_LP0_PLANE_LATENCY           700
4377 #define ILK_LP0_CURSOR_LATENCY          1300
4378
4379 /*
4380  * Check the wm result.
4381  *
4382  * If any calculated watermark values is larger than the maximum value that
4383  * can be programmed into the associated watermark register, that watermark
4384  * must be disabled.
4385  */
4386 static bool ironlake_check_srwm(struct drm_device *dev, int level,
4387                                 int fbc_wm, int display_wm, int cursor_wm,
4388                                 const struct intel_watermark_params *display,
4389                                 const struct intel_watermark_params *cursor)
4390 {
4391         struct drm_i915_private *dev_priv = dev->dev_private;
4392
4393         DRM_DEBUG_KMS("watermark %d: display plane %d, fbc lines %d,"
4394                       " cursor %d\n", level, display_wm, fbc_wm, cursor_wm);
4395
4396         if (fbc_wm > SNB_FBC_MAX_SRWM) {
4397                 DRM_DEBUG_KMS("fbc watermark(%d) is too large(%d), disabling wm%d+\n",
4398                               fbc_wm, SNB_FBC_MAX_SRWM, level);
4399
4400                 /* fbc has it's own way to disable FBC WM */
4401                 I915_WRITE(DISP_ARB_CTL,
4402                            I915_READ(DISP_ARB_CTL) | DISP_FBC_WM_DIS);
4403                 return false;
4404         }
4405
4406         if (display_wm > display->max_wm) {
4407                 DRM_DEBUG_KMS("display watermark(%d) is too large(%d), disabling wm%d+\n",
4408                               display_wm, SNB_DISPLAY_MAX_SRWM, level);
4409                 return false;
4410         }
4411
4412         if (cursor_wm > cursor->max_wm) {
4413                 DRM_DEBUG_KMS("cursor watermark(%d) is too large(%d), disabling wm%d+\n",
4414                               cursor_wm, SNB_CURSOR_MAX_SRWM, level);
4415                 return false;
4416         }
4417
4418         if (!(fbc_wm || display_wm || cursor_wm)) {
4419                 DRM_DEBUG_KMS("latency %d is 0, disabling wm%d+\n", level, level);
4420                 return false;
4421         }
4422
4423         return true;
4424 }
4425
4426 /*
4427  * Compute watermark values of WM[1-3],
4428  */
4429 static bool ironlake_compute_srwm(struct drm_device *dev, int level, int plane,
4430                                   int latency_ns,
4431                                   const struct intel_watermark_params *display,
4432                                   const struct intel_watermark_params *cursor,
4433                                   int *fbc_wm, int *display_wm, int *cursor_wm)
4434 {
4435         struct drm_crtc *crtc;
4436         unsigned long line_time_us;
4437         int hdisplay, htotal, pixel_size, clock;
4438         int line_count, line_size;
4439         int small, large;
4440         int entries;
4441
4442         if (!latency_ns) {
4443                 *fbc_wm = *display_wm = *cursor_wm = 0;
4444                 return false;
4445         }
4446
4447         crtc = intel_get_crtc_for_plane(dev, plane);
4448         hdisplay = crtc->mode.hdisplay;
4449         htotal = crtc->mode.htotal;
4450         clock = crtc->mode.clock;
4451         pixel_size = crtc->fb->bits_per_pixel / 8;
4452
4453         line_time_us = (htotal * 1000) / clock;
4454         line_count = (latency_ns / line_time_us + 1000) / 1000;
4455         line_size = hdisplay * pixel_size;
4456
4457         /* Use the minimum of the small and large buffer method for primary */
4458         small = ((clock * pixel_size / 1000) * latency_ns) / 1000;
4459         large = line_count * line_size;
4460
4461         entries = DIV_ROUND_UP(min(small, large), display->cacheline_size);
4462         *display_wm = entries + display->guard_size;
4463
4464         /*
4465          * Spec says:
4466          * FBC WM = ((Final Primary WM * 64) / number of bytes per line) + 2
4467          */
4468         *fbc_wm = DIV_ROUND_UP(*display_wm * 64, line_size) + 2;
4469
4470         /* calculate the self-refresh watermark for display cursor */
4471         entries = line_count * pixel_size * 64;
4472         entries = DIV_ROUND_UP(entries, cursor->cacheline_size);
4473         *cursor_wm = entries + cursor->guard_size;
4474
4475         return ironlake_check_srwm(dev, level,
4476                                    *fbc_wm, *display_wm, *cursor_wm,
4477                                    display, cursor);
4478 }
4479
4480 static void ironlake_update_wm(struct drm_device *dev)
4481 {
4482         struct drm_i915_private *dev_priv = dev->dev_private;
4483         int fbc_wm, plane_wm, cursor_wm;
4484         unsigned int enabled;
4485
4486         enabled = 0;
4487         if (g4x_compute_wm0(dev, 0,
4488                             &ironlake_display_wm_info,
4489                             ILK_LP0_PLANE_LATENCY,
4490                             &ironlake_cursor_wm_info,
4491                             ILK_LP0_CURSOR_LATENCY,
4492                             &plane_wm, &cursor_wm)) {
4493                 I915_WRITE(WM0_PIPEA_ILK,
4494                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
4495                 DRM_DEBUG_KMS("FIFO watermarks For pipe A -"
4496                               " plane %d, " "cursor: %d\n",
4497                               plane_wm, cursor_wm);
4498                 enabled |= 1;
4499         }
4500
4501         if (g4x_compute_wm0(dev, 1,
4502                             &ironlake_display_wm_info,
4503                             ILK_LP0_PLANE_LATENCY,
4504                             &ironlake_cursor_wm_info,
4505                             ILK_LP0_CURSOR_LATENCY,
4506                             &plane_wm, &cursor_wm)) {
4507                 I915_WRITE(WM0_PIPEB_ILK,
4508                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
4509                 DRM_DEBUG_KMS("FIFO watermarks For pipe B -"
4510                               " plane %d, cursor: %d\n",
4511                               plane_wm, cursor_wm);
4512                 enabled |= 2;
4513         }
4514
4515         /*
4516          * Calculate and update the self-refresh watermark only when one
4517          * display plane is used.
4518          */
4519         I915_WRITE(WM3_LP_ILK, 0);
4520         I915_WRITE(WM2_LP_ILK, 0);
4521         I915_WRITE(WM1_LP_ILK, 0);
4522
4523         if (!single_plane_enabled(enabled))
4524                 return;
4525         enabled = ffs(enabled) - 1;
4526
4527         /* WM1 */
4528         if (!ironlake_compute_srwm(dev, 1, enabled,
4529                                    ILK_READ_WM1_LATENCY() * 500,
4530                                    &ironlake_display_srwm_info,
4531                                    &ironlake_cursor_srwm_info,
4532                                    &fbc_wm, &plane_wm, &cursor_wm))
4533                 return;
4534
4535         I915_WRITE(WM1_LP_ILK,
4536                    WM1_LP_SR_EN |
4537                    (ILK_READ_WM1_LATENCY() << WM1_LP_LATENCY_SHIFT) |
4538                    (fbc_wm << WM1_LP_FBC_SHIFT) |
4539                    (plane_wm << WM1_LP_SR_SHIFT) |
4540                    cursor_wm);
4541
4542         /* WM2 */
4543         if (!ironlake_compute_srwm(dev, 2, enabled,
4544                                    ILK_READ_WM2_LATENCY() * 500,
4545                                    &ironlake_display_srwm_info,
4546                                    &ironlake_cursor_srwm_info,
4547                                    &fbc_wm, &plane_wm, &cursor_wm))
4548                 return;
4549
4550         I915_WRITE(WM2_LP_ILK,
4551                    WM2_LP_EN |
4552                    (ILK_READ_WM2_LATENCY() << WM1_LP_LATENCY_SHIFT) |
4553                    (fbc_wm << WM1_LP_FBC_SHIFT) |
4554                    (plane_wm << WM1_LP_SR_SHIFT) |
4555                    cursor_wm);
4556
4557         /*
4558          * WM3 is unsupported on ILK, probably because we don't have latency
4559          * data for that power state
4560          */
4561 }
4562
4563 static void sandybridge_update_wm(struct drm_device *dev)
4564 {
4565         struct drm_i915_private *dev_priv = dev->dev_private;
4566         int latency = SNB_READ_WM0_LATENCY() * 100;     /* In unit 0.1us */
4567         int fbc_wm, plane_wm, cursor_wm;
4568         unsigned int enabled;
4569
4570         enabled = 0;
4571         if (g4x_compute_wm0(dev, 0,
4572                             &sandybridge_display_wm_info, latency,
4573                             &sandybridge_cursor_wm_info, latency,
4574                             &plane_wm, &cursor_wm)) {
4575                 I915_WRITE(WM0_PIPEA_ILK,
4576                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
4577                 DRM_DEBUG_KMS("FIFO watermarks For pipe A -"
4578                               " plane %d, " "cursor: %d\n",
4579                               plane_wm, cursor_wm);
4580                 enabled |= 1;
4581         }
4582
4583         if (g4x_compute_wm0(dev, 1,
4584                             &sandybridge_display_wm_info, latency,
4585                             &sandybridge_cursor_wm_info, latency,
4586                             &plane_wm, &cursor_wm)) {
4587                 I915_WRITE(WM0_PIPEB_ILK,
4588                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
4589                 DRM_DEBUG_KMS("FIFO watermarks For pipe B -"
4590                               " plane %d, cursor: %d\n",
4591                               plane_wm, cursor_wm);
4592                 enabled |= 2;
4593         }
4594
4595         /* IVB has 3 pipes */
4596         if (IS_IVYBRIDGE(dev) &&
4597             g4x_compute_wm0(dev, 2,
4598                             &sandybridge_display_wm_info, latency,
4599                             &sandybridge_cursor_wm_info, latency,
4600                             &plane_wm, &cursor_wm)) {
4601                 I915_WRITE(WM0_PIPEC_IVB,
4602                            (plane_wm << WM0_PIPE_PLANE_SHIFT) | cursor_wm);
4603                 DRM_DEBUG_KMS("FIFO watermarks For pipe C -"
4604                               " plane %d, cursor: %d\n",
4605                               plane_wm, cursor_wm);
4606                 enabled |= 3;
4607         }
4608
4609         /*
4610          * Calculate and update the self-refresh watermark only when one
4611          * display plane is used.
4612          *
4613          * SNB support 3 levels of watermark.
4614          *
4615          * WM1/WM2/WM2 watermarks have to be enabled in the ascending order,
4616          * and disabled in the descending order
4617          *
4618          */
4619         I915_WRITE(WM3_LP_ILK, 0);
4620         I915_WRITE(WM2_LP_ILK, 0);
4621         I915_WRITE(WM1_LP_ILK, 0);
4622
4623         if (!single_plane_enabled(enabled))
4624                 return;
4625         enabled = ffs(enabled) - 1;
4626
4627         /* WM1 */
4628         if (!ironlake_compute_srwm(dev, 1, enabled,
4629                                    SNB_READ_WM1_LATENCY() * 500,
4630                                    &sandybridge_display_srwm_info,
4631                                    &sandybridge_cursor_srwm_info,
4632                                    &fbc_wm, &plane_wm, &cursor_wm))
4633                 return;
4634
4635         I915_WRITE(WM1_LP_ILK,
4636                    WM1_LP_SR_EN |
4637                    (SNB_READ_WM1_LATENCY() << WM1_LP_LATENCY_SHIFT) |
4638                    (fbc_wm << WM1_LP_FBC_SHIFT) |
4639                    (plane_wm << WM1_LP_SR_SHIFT) |
4640                    cursor_wm);
4641
4642         /* WM2 */
4643         if (!ironlake_compute_srwm(dev, 2, enabled,
4644                                    SNB_READ_WM2_LATENCY() * 500,
4645                                    &sandybridge_display_srwm_info,
4646                                    &sandybridge_cursor_srwm_info,
4647                                    &fbc_wm, &plane_wm, &cursor_wm))
4648                 return;
4649
4650         I915_WRITE(WM2_LP_ILK,
4651                    WM2_LP_EN |
4652                    (SNB_READ_WM2_LATENCY() << WM1_LP_LATENCY_SHIFT) |
4653                    (fbc_wm << WM1_LP_FBC_SHIFT) |
4654                    (plane_wm << WM1_LP_SR_SHIFT) |
4655                    cursor_wm);
4656
4657         /* WM3 */
4658         if (!ironlake_compute_srwm(dev, 3, enabled,
4659                                    SNB_READ_WM3_LATENCY() * 500,
4660                                    &sandybridge_display_srwm_info,
4661                                    &sandybridge_cursor_srwm_info,
4662                                    &fbc_wm, &plane_wm, &cursor_wm))
4663                 return;
4664
4665         I915_WRITE(WM3_LP_ILK,
4666                    WM3_LP_EN |
4667                    (SNB_READ_WM3_LATENCY() << WM1_LP_LATENCY_SHIFT) |
4668                    (fbc_wm << WM1_LP_FBC_SHIFT) |
4669                    (plane_wm << WM1_LP_SR_SHIFT) |
4670                    cursor_wm);
4671 }
4672
4673 /**
4674  * intel_update_watermarks - update FIFO watermark values based on current modes
4675  *
4676  * Calculate watermark values for the various WM regs based on current mode
4677  * and plane configuration.
4678  *
4679  * There are several cases to deal with here:
4680  *   - normal (i.e. non-self-refresh)
4681  *   - self-refresh (SR) mode
4682  *   - lines are large relative to FIFO size (buffer can hold up to 2)
4683  *   - lines are small relative to FIFO size (buffer can hold more than 2
4684  *     lines), so need to account for TLB latency
4685  *
4686  *   The normal calculation is:
4687  *     watermark = dotclock * bytes per pixel * latency
4688  *   where latency is platform & configuration dependent (we assume pessimal
4689  *   values here).
4690  *
4691  *   The SR calculation is:
4692  *     watermark = (trunc(latency/line time)+1) * surface width *
4693  *       bytes per pixel
4694  *   where
4695  *     line time = htotal / dotclock
4696  *     surface width = hdisplay for normal plane and 64 for cursor
4697  *   and latency is assumed to be high, as above.
4698  *
4699  * The final value programmed to the register should always be rounded up,
4700  * and include an extra 2 entries to account for clock crossings.
4701  *
4702  * We don't use the sprite, so we can ignore that.  And on Crestline we have
4703  * to set the non-SR watermarks to 8.
4704  */
4705 static void intel_update_watermarks(struct drm_device *dev)
4706 {
4707         struct drm_i915_private *dev_priv = dev->dev_private;
4708
4709         if (dev_priv->display.update_wm)
4710                 dev_priv->display.update_wm(dev);
4711 }
4712
4713 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
4714 {
4715         if (i915_panel_use_ssc >= 0)
4716                 return i915_panel_use_ssc != 0;
4717         return dev_priv->lvds_use_ssc
4718                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
4719 }
4720
4721 /**
4722  * intel_choose_pipe_bpp_dither - figure out what color depth the pipe should send
4723  * @crtc: CRTC structure
4724  * @mode: requested mode
4725  *
4726  * A pipe may be connected to one or more outputs.  Based on the depth of the
4727  * attached framebuffer, choose a good color depth to use on the pipe.
4728  *
4729  * If possible, match the pipe depth to the fb depth.  In some cases, this
4730  * isn't ideal, because the connected output supports a lesser or restricted
4731  * set of depths.  Resolve that here:
4732  *    LVDS typically supports only 6bpc, so clamp down in that case
4733  *    HDMI supports only 8bpc or 12bpc, so clamp to 8bpc with dither for 10bpc
4734  *    Displays may support a restricted set as well, check EDID and clamp as
4735  *      appropriate.
4736  *    DP may want to dither down to 6bpc to fit larger modes
4737  *
4738  * RETURNS:
4739  * Dithering requirement (i.e. false if display bpc and pipe bpc match,
4740  * true if they don't match).
4741  */
4742 static bool intel_choose_pipe_bpp_dither(struct drm_crtc *crtc,
4743                                          unsigned int *pipe_bpp,
4744                                          struct drm_display_mode *mode)
4745 {
4746         struct drm_device *dev = crtc->dev;
4747         struct drm_i915_private *dev_priv = dev->dev_private;
4748         struct drm_encoder *encoder;
4749         struct drm_connector *connector;
4750         unsigned int display_bpc = UINT_MAX, bpc;
4751
4752         /* Walk the encoders & connectors on this crtc, get min bpc */
4753         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
4754                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
4755
4756                 if (encoder->crtc != crtc)
4757                         continue;
4758
4759                 if (intel_encoder->type == INTEL_OUTPUT_LVDS) {
4760                         unsigned int lvds_bpc;
4761
4762                         if ((I915_READ(PCH_LVDS) & LVDS_A3_POWER_MASK) ==
4763                             LVDS_A3_POWER_UP)
4764                                 lvds_bpc = 8;
4765                         else
4766                                 lvds_bpc = 6;
4767
4768                         if (lvds_bpc < display_bpc) {
4769                                 DRM_DEBUG_KMS("clamping display bpc (was %d) to LVDS (%d)\n", display_bpc, lvds_bpc);
4770                                 display_bpc = lvds_bpc;
4771                         }
4772                         continue;
4773                 }
4774
4775                 /* Not one of the known troublemakers, check the EDID */
4776                 list_for_each_entry(connector, &dev->mode_config.connector_list,
4777                                     head) {
4778                         if (connector->encoder != encoder)
4779                                 continue;
4780
4781                         /* Don't use an invalid EDID bpc value */
4782                         if (connector->display_info.bpc &&
4783                             connector->display_info.bpc < display_bpc) {
4784                                 DRM_DEBUG_KMS("clamping display bpc (was %d) to EDID reported max of %d\n", display_bpc, connector->display_info.bpc);
4785                                 display_bpc = connector->display_info.bpc;
4786                         }
4787                 }
4788
4789                 /*
4790                  * HDMI is either 12 or 8, so if the display lets 10bpc sneak
4791                  * through, clamp it down.  (Note: >12bpc will be caught below.)
4792                  */
4793                 if (intel_encoder->type == INTEL_OUTPUT_HDMI) {
4794                         if (display_bpc > 8 && display_bpc < 12) {
4795                                 DRM_DEBUG_KMS("forcing bpc to 12 for HDMI\n");
4796                                 display_bpc = 12;
4797                         } else {
4798                                 DRM_DEBUG_KMS("forcing bpc to 8 for HDMI\n");
4799                                 display_bpc = 8;
4800                         }
4801                 }
4802         }
4803
4804         if (mode->private_flags & INTEL_MODE_DP_FORCE_6BPC) {
4805                 DRM_DEBUG_KMS("Dithering DP to 6bpc\n");
4806                 display_bpc = 6;
4807         }
4808
4809         /*
4810          * We could just drive the pipe at the highest bpc all the time and
4811          * enable dithering as needed, but that costs bandwidth.  So choose
4812          * the minimum value that expresses the full color range of the fb but
4813          * also stays within the max display bpc discovered above.
4814          */
4815
4816         switch (crtc->fb->depth) {
4817         case 8:
4818                 bpc = 8; /* since we go through a colormap */
4819                 break;
4820         case 15:
4821         case 16:
4822                 bpc = 6; /* min is 18bpp */
4823                 break;
4824         case 24:
4825                 bpc = 8;
4826                 break;
4827         case 30:
4828                 bpc = 10;
4829                 break;
4830         case 48:
4831                 bpc = 12;
4832                 break;
4833         default:
4834                 DRM_DEBUG("unsupported depth, assuming 24 bits\n");
4835                 bpc = min((unsigned int)8, display_bpc);
4836                 break;
4837         }
4838
4839         display_bpc = min(display_bpc, bpc);
4840
4841         DRM_DEBUG_KMS("setting pipe bpc to %d (max display bpc %d)\n",
4842                       bpc, display_bpc);
4843
4844         *pipe_bpp = display_bpc * 3;
4845
4846         return display_bpc != bpc;
4847 }
4848
4849 static int i9xx_crtc_mode_set(struct drm_crtc *crtc,
4850                               struct drm_display_mode *mode,
4851                               struct drm_display_mode *adjusted_mode,
4852                               int x, int y,
4853                               struct drm_framebuffer *old_fb)
4854 {
4855         struct drm_device *dev = crtc->dev;
4856         struct drm_i915_private *dev_priv = dev->dev_private;
4857         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4858         int pipe = intel_crtc->pipe;
4859         int plane = intel_crtc->plane;
4860         int refclk, num_connectors = 0;
4861         intel_clock_t clock, reduced_clock;
4862         u32 dpll, fp = 0, fp2 = 0, dspcntr, pipeconf;
4863         bool ok, has_reduced_clock = false, is_sdvo = false, is_dvo = false;
4864         bool is_crt = false, is_lvds = false, is_tv = false, is_dp = false;
4865         struct drm_mode_config *mode_config = &dev->mode_config;
4866         struct intel_encoder *encoder;
4867         const intel_limit_t *limit;
4868         int ret;
4869         u32 temp;
4870         u32 lvds_sync = 0;
4871
4872         list_for_each_entry(encoder, &mode_config->encoder_list, base.head) {
4873                 if (encoder->base.crtc != crtc)
4874                         continue;
4875
4876                 switch (encoder->type) {
4877                 case INTEL_OUTPUT_LVDS:
4878                         is_lvds = true;
4879                         break;
4880                 case INTEL_OUTPUT_SDVO:
4881                 case INTEL_OUTPUT_HDMI:
4882                         is_sdvo = true;
4883                         if (encoder->needs_tv_clock)
4884                                 is_tv = true;
4885                         break;
4886                 case INTEL_OUTPUT_DVO:
4887                         is_dvo = true;
4888                         break;
4889                 case INTEL_OUTPUT_TVOUT:
4890                         is_tv = true;
4891                         break;
4892                 case INTEL_OUTPUT_ANALOG:
4893                         is_crt = true;
4894                         break;
4895                 case INTEL_OUTPUT_DISPLAYPORT:
4896                         is_dp = true;
4897                         break;
4898                 }
4899
4900                 num_connectors++;
4901         }
4902
4903         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
4904                 refclk = dev_priv->lvds_ssc_freq * 1000;
4905                 DRM_DEBUG_KMS("using SSC reference clock of %d MHz\n",
4906                               refclk / 1000);
4907         } else if (!IS_GEN2(dev)) {
4908                 refclk = 96000;
4909         } else {
4910                 refclk = 48000;
4911         }
4912
4913         /*
4914          * Returns a set of divisors for the desired target clock with the given
4915          * refclk, or FALSE.  The returned values represent the clock equation:
4916          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
4917          */
4918         limit = intel_limit(crtc, refclk);
4919         ok = limit->find_pll(limit, crtc, adjusted_mode->clock, refclk, &clock);
4920         if (!ok) {
4921                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
4922                 return -EINVAL;
4923         }
4924
4925         /* Ensure that the cursor is valid for the new mode before changing... */
4926         intel_crtc_update_cursor(crtc, true);
4927
4928         if (is_lvds && dev_priv->lvds_downclock_avail) {
4929                 has_reduced_clock = limit->find_pll(limit, crtc,
4930                                                     dev_priv->lvds_downclock,
4931                                                     refclk,
4932                                                     &reduced_clock);
4933                 if (has_reduced_clock && (clock.p != reduced_clock.p)) {
4934                         /*
4935                          * If the different P is found, it means that we can't
4936                          * switch the display clock by using the FP0/FP1.
4937                          * In such case we will disable the LVDS downclock
4938                          * feature.
4939                          */
4940                         DRM_DEBUG_KMS("Different P is found for "
4941                                       "LVDS clock/downclock\n");
4942                         has_reduced_clock = 0;
4943                 }
4944         }
4945         /* SDVO TV has fixed PLL values depend on its clock range,
4946            this mirrors vbios setting. */
4947         if (is_sdvo && is_tv) {
4948                 if (adjusted_mode->clock >= 100000
4949                     && adjusted_mode->clock < 140500) {
4950                         clock.p1 = 2;
4951                         clock.p2 = 10;
4952                         clock.n = 3;
4953                         clock.m1 = 16;
4954                         clock.m2 = 8;
4955                 } else if (adjusted_mode->clock >= 140500
4956                            && adjusted_mode->clock <= 200000) {
4957                         clock.p1 = 1;
4958                         clock.p2 = 10;
4959                         clock.n = 6;
4960                         clock.m1 = 12;
4961                         clock.m2 = 8;
4962                 }
4963         }
4964
4965         if (IS_PINEVIEW(dev)) {
4966                 fp = (1 << clock.n) << 16 | clock.m1 << 8 | clock.m2;
4967                 if (has_reduced_clock)
4968                         fp2 = (1 << reduced_clock.n) << 16 |
4969                                 reduced_clock.m1 << 8 | reduced_clock.m2;
4970         } else {
4971                 fp = clock.n << 16 | clock.m1 << 8 | clock.m2;
4972                 if (has_reduced_clock)
4973                         fp2 = reduced_clock.n << 16 | reduced_clock.m1 << 8 |
4974                                 reduced_clock.m2;
4975         }
4976
4977         dpll = DPLL_VGA_MODE_DIS;
4978
4979         if (!IS_GEN2(dev)) {
4980                 if (is_lvds)
4981                         dpll |= DPLLB_MODE_LVDS;
4982                 else
4983                         dpll |= DPLLB_MODE_DAC_SERIAL;
4984                 if (is_sdvo) {
4985                         int pixel_multiplier = intel_mode_get_pixel_multiplier(adjusted_mode);
4986                         if (pixel_multiplier > 1) {
4987                                 if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4988                                         dpll |= (pixel_multiplier - 1) << SDVO_MULTIPLIER_SHIFT_HIRES;
4989                         }
4990                         dpll |= DPLL_DVO_HIGH_SPEED;
4991                 }
4992                 if (is_dp)
4993                         dpll |= DPLL_DVO_HIGH_SPEED;
4994
4995                 /* compute bitmask from p1 value */
4996                 if (IS_PINEVIEW(dev))
4997                         dpll |= (1 << (clock.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
4998                 else {
4999                         dpll |= (1 << (clock.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5000                         if (IS_G4X(dev) && has_reduced_clock)
5001                                 dpll |= (1 << (reduced_clock.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
5002                 }
5003                 switch (clock.p2) {
5004                 case 5:
5005                         dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
5006                         break;
5007                 case 7:
5008                         dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
5009                         break;
5010                 case 10:
5011                         dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
5012                         break;
5013                 case 14:
5014                         dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
5015                         break;
5016                 }
5017                 if (INTEL_INFO(dev)->gen >= 4)
5018                         dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
5019         } else {
5020                 if (is_lvds) {
5021                         dpll |= (1 << (clock.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5022                 } else {
5023                         if (clock.p1 == 2)
5024                                 dpll |= PLL_P1_DIVIDE_BY_TWO;
5025                         else
5026                                 dpll |= (clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5027                         if (clock.p2 == 4)
5028                                 dpll |= PLL_P2_DIVIDE_BY_4;
5029                 }
5030         }
5031
5032         if (is_sdvo && is_tv)
5033                 dpll |= PLL_REF_INPUT_TVCLKINBC;
5034         else if (is_tv)
5035                 /* XXX: just matching BIOS for now */
5036                 /*      dpll |= PLL_REF_INPUT_TVCLKINBC; */
5037                 dpll |= 3;
5038         else if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
5039                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
5040         else
5041                 dpll |= PLL_REF_INPUT_DREFCLK;
5042
5043         /* setup pipeconf */
5044         pipeconf = I915_READ(PIPECONF(pipe));
5045
5046         /* Set up the display plane register */
5047         dspcntr = DISPPLANE_GAMMA_ENABLE;
5048
5049         /* Ironlake's plane is forced to pipe, bit 24 is to
5050            enable color space conversion */
5051         if (pipe == 0)
5052                 dspcntr &= ~DISPPLANE_SEL_PIPE_MASK;
5053         else
5054                 dspcntr |= DISPPLANE_SEL_PIPE_B;
5055
5056         if (pipe == 0 && INTEL_INFO(dev)->gen < 4) {
5057                 /* Enable pixel doubling when the dot clock is > 90% of the (display)
5058                  * core speed.
5059                  *
5060                  * XXX: No double-wide on 915GM pipe B. Is that the only reason for the
5061                  * pipe == 0 check?
5062                  */
5063                 if (mode->clock >
5064                     dev_priv->display.get_display_clock_speed(dev) * 9 / 10)
5065                         pipeconf |= PIPECONF_DOUBLE_WIDE;
5066                 else
5067                         pipeconf &= ~PIPECONF_DOUBLE_WIDE;
5068         }
5069
5070         /* default to 8bpc */
5071         pipeconf &= ~(PIPECONF_BPP_MASK | PIPECONF_DITHER_EN);
5072         if (is_dp) {
5073                 if (adjusted_mode->private_flags & INTEL_MODE_DP_FORCE_6BPC) {
5074                         pipeconf |= PIPECONF_BPP_6 |
5075                                     PIPECONF_DITHER_EN |
5076                                     PIPECONF_DITHER_TYPE_SP;
5077                 }
5078         }
5079
5080         dpll |= DPLL_VCO_ENABLE;
5081
5082         DRM_DEBUG_KMS("Mode for pipe %c:\n", pipe == 0 ? 'A' : 'B');
5083         drm_mode_debug_printmodeline(mode);
5084
5085         I915_WRITE(FP0(pipe), fp);
5086         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VCO_ENABLE);
5087
5088         POSTING_READ(DPLL(pipe));
5089         udelay(150);
5090
5091         /* The LVDS pin pair needs to be on before the DPLLs are enabled.
5092          * This is an exception to the general rule that mode_set doesn't turn
5093          * things on.
5094          */
5095         if (is_lvds) {
5096                 temp = I915_READ(LVDS);
5097                 temp |= LVDS_PORT_EN | LVDS_A0A2_CLKA_POWER_UP;
5098                 if (pipe == 1) {
5099                         temp |= LVDS_PIPEB_SELECT;
5100                 } else {
5101                         temp &= ~LVDS_PIPEB_SELECT;
5102                 }
5103                 /* set the corresponsding LVDS_BORDER bit */
5104                 temp |= dev_priv->lvds_border_bits;
5105                 /* Set the B0-B3 data pairs corresponding to whether we're going to
5106                  * set the DPLLs for dual-channel mode or not.
5107                  */
5108                 if (clock.p2 == 7)
5109                         temp |= LVDS_B0B3_POWER_UP | LVDS_CLKB_POWER_UP;
5110                 else
5111                         temp &= ~(LVDS_B0B3_POWER_UP | LVDS_CLKB_POWER_UP);
5112
5113                 /* It would be nice to set 24 vs 18-bit mode (LVDS_A3_POWER_UP)
5114                  * appropriately here, but we need to look more thoroughly into how
5115                  * panels behave in the two modes.
5116                  */
5117                 /* set the dithering flag on LVDS as needed */
5118                 if (INTEL_INFO(dev)->gen >= 4) {
5119                         if (dev_priv->lvds_dither)
5120                                 temp |= LVDS_ENABLE_DITHER;
5121                         else
5122                                 temp &= ~LVDS_ENABLE_DITHER;
5123                 }
5124                 if (adjusted_mode->flags & DRM_MODE_FLAG_NHSYNC)
5125                         lvds_sync |= LVDS_HSYNC_POLARITY;
5126                 if (adjusted_mode->flags & DRM_MODE_FLAG_NVSYNC)
5127                         lvds_sync |= LVDS_VSYNC_POLARITY;
5128                 if ((temp & (LVDS_HSYNC_POLARITY | LVDS_VSYNC_POLARITY))
5129                     != lvds_sync) {
5130                         char flags[2] = "-+";
5131                         DRM_INFO("Changing LVDS panel from "
5132                                  "(%chsync, %cvsync) to (%chsync, %cvsync)\n",
5133                                  flags[!(temp & LVDS_HSYNC_POLARITY)],
5134                                  flags[!(temp & LVDS_VSYNC_POLARITY)],
5135                                  flags[!(lvds_sync & LVDS_HSYNC_POLARITY)],
5136                                  flags[!(lvds_sync & LVDS_VSYNC_POLARITY)]);
5137                         temp &= ~(LVDS_HSYNC_POLARITY | LVDS_VSYNC_POLARITY);
5138                         temp |= lvds_sync;
5139                 }
5140                 I915_WRITE(LVDS, temp);
5141         }
5142
5143         if (is_dp) {
5144                 intel_dp_set_m_n(crtc, mode, adjusted_mode);
5145         }
5146
5147         I915_WRITE(DPLL(pipe), dpll);
5148
5149         /* Wait for the clocks to stabilize. */
5150         POSTING_READ(DPLL(pipe));
5151         udelay(150);
5152
5153         if (INTEL_INFO(dev)->gen >= 4) {
5154                 temp = 0;
5155                 if (is_sdvo) {
5156                         temp = intel_mode_get_pixel_multiplier(adjusted_mode);
5157                         if (temp > 1)
5158                                 temp = (temp - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5159                         else
5160                                 temp = 0;
5161                 }
5162                 I915_WRITE(DPLL_MD(pipe), temp);
5163         } else {
5164                 /* The pixel multiplier can only be updated once the
5165                  * DPLL is enabled and the clocks are stable.
5166                  *
5167                  * So write it again.
5168                  */
5169                 I915_WRITE(DPLL(pipe), dpll);
5170         }
5171
5172         intel_crtc->lowfreq_avail = false;
5173         if (is_lvds && has_reduced_clock && i915_powersave) {
5174                 I915_WRITE(FP1(pipe), fp2);
5175                 intel_crtc->lowfreq_avail = true;
5176                 if (HAS_PIPE_CXSR(dev)) {
5177                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
5178                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
5179                 }
5180         } else {
5181                 I915_WRITE(FP1(pipe), fp);
5182                 if (HAS_PIPE_CXSR(dev)) {
5183                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
5184                         pipeconf &= ~PIPECONF_CXSR_DOWNCLOCK;
5185                 }
5186         }
5187
5188         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5189                 pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
5190                 /* the chip adds 2 halflines automatically */
5191                 adjusted_mode->crtc_vdisplay -= 1;
5192                 adjusted_mode->crtc_vtotal -= 1;
5193                 adjusted_mode->crtc_vblank_start -= 1;
5194                 adjusted_mode->crtc_vblank_end -= 1;
5195                 adjusted_mode->crtc_vsync_end -= 1;
5196                 adjusted_mode->crtc_vsync_start -= 1;
5197         } else
5198                 pipeconf &= ~PIPECONF_INTERLACE_W_FIELD_INDICATION; /* progressive */
5199
5200         I915_WRITE(HTOTAL(pipe),
5201                    (adjusted_mode->crtc_hdisplay - 1) |
5202                    ((adjusted_mode->crtc_htotal - 1) << 16));
5203         I915_WRITE(HBLANK(pipe),
5204                    (adjusted_mode->crtc_hblank_start - 1) |
5205                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
5206         I915_WRITE(HSYNC(pipe),
5207                    (adjusted_mode->crtc_hsync_start - 1) |
5208                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
5209
5210         I915_WRITE(VTOTAL(pipe),
5211                    (adjusted_mode->crtc_vdisplay - 1) |
5212                    ((adjusted_mode->crtc_vtotal - 1) << 16));
5213         I915_WRITE(VBLANK(pipe),
5214                    (adjusted_mode->crtc_vblank_start - 1) |
5215                    ((adjusted_mode->crtc_vblank_end - 1) << 16));
5216         I915_WRITE(VSYNC(pipe),
5217                    (adjusted_mode->crtc_vsync_start - 1) |
5218                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
5219
5220         /* pipesrc and dspsize control the size that is scaled from,
5221          * which should always be the user's requested size.
5222          */
5223         I915_WRITE(DSPSIZE(plane),
5224                    ((mode->vdisplay - 1) << 16) |
5225                    (mode->hdisplay - 1));
5226         I915_WRITE(DSPPOS(plane), 0);
5227         I915_WRITE(PIPESRC(pipe),
5228                    ((mode->hdisplay - 1) << 16) | (mode->vdisplay - 1));
5229
5230         I915_WRITE(PIPECONF(pipe), pipeconf);
5231         POSTING_READ(PIPECONF(pipe));
5232         intel_enable_pipe(dev_priv, pipe, false);
5233
5234         intel_wait_for_vblank(dev, pipe);
5235
5236         I915_WRITE(DSPCNTR(plane), dspcntr);
5237         POSTING_READ(DSPCNTR(plane));
5238         intel_enable_plane(dev_priv, plane, pipe);
5239
5240         ret = intel_pipe_set_base(crtc, x, y, old_fb);
5241
5242         intel_update_watermarks(dev);
5243
5244         return ret;
5245 }
5246
5247 /*
5248  * Initialize reference clocks when the driver loads
5249  */
5250 void ironlake_init_pch_refclk(struct drm_device *dev)
5251 {
5252         struct drm_i915_private *dev_priv = dev->dev_private;
5253         struct drm_mode_config *mode_config = &dev->mode_config;
5254         struct intel_encoder *encoder;
5255         u32 temp;
5256         bool has_lvds = false;
5257         bool has_cpu_edp = false;
5258         bool has_pch_edp = false;
5259         bool has_panel = false;
5260         bool has_ck505 = false;
5261         bool can_ssc = false;
5262
5263         /* We need to take the global config into account */
5264         list_for_each_entry(encoder, &mode_config->encoder_list,
5265                             base.head) {
5266                 switch (encoder->type) {
5267                 case INTEL_OUTPUT_LVDS:
5268                         has_panel = true;
5269                         has_lvds = true;
5270                         break;
5271                 case INTEL_OUTPUT_EDP:
5272                         has_panel = true;
5273                         if (intel_encoder_is_pch_edp(&encoder->base))
5274                                 has_pch_edp = true;
5275                         else
5276                                 has_cpu_edp = true;
5277                         break;
5278                 }
5279         }
5280
5281         if (HAS_PCH_IBX(dev)) {
5282                 has_ck505 = dev_priv->display_clock_mode;
5283                 can_ssc = has_ck505;
5284         } else {
5285                 has_ck505 = false;
5286                 can_ssc = true;
5287         }
5288
5289         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_pch_edp %d has_cpu_edp %d has_ck505 %d\n",
5290                       has_panel, has_lvds, has_pch_edp, has_cpu_edp,
5291                       has_ck505);
5292
5293         /* Ironlake: try to setup display ref clock before DPLL
5294          * enabling. This is only under driver's control after
5295          * PCH B stepping, previous chipset stepping should be
5296          * ignoring this setting.
5297          */
5298         temp = I915_READ(PCH_DREF_CONTROL);
5299         /* Always enable nonspread source */
5300         temp &= ~DREF_NONSPREAD_SOURCE_MASK;
5301
5302         if (has_ck505)
5303                 temp |= DREF_NONSPREAD_CK505_ENABLE;
5304         else
5305                 temp |= DREF_NONSPREAD_SOURCE_ENABLE;
5306
5307         if (has_panel) {
5308                 temp &= ~DREF_SSC_SOURCE_MASK;
5309                 temp |= DREF_SSC_SOURCE_ENABLE;
5310
5311                 /* SSC must be turned on before enabling the CPU output  */
5312                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
5313                         DRM_DEBUG_KMS("Using SSC on panel\n");
5314                         temp |= DREF_SSC1_ENABLE;
5315                 }
5316
5317                 /* Get SSC going before enabling the outputs */
5318                 I915_WRITE(PCH_DREF_CONTROL, temp);
5319                 POSTING_READ(PCH_DREF_CONTROL);
5320                 udelay(200);
5321
5322                 temp &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
5323
5324                 /* Enable CPU source on CPU attached eDP */
5325                 if (has_cpu_edp) {
5326                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
5327                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
5328                                 temp |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
5329                         }
5330                         else
5331                                 temp |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
5332                 } else
5333                         temp |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
5334
5335                 I915_WRITE(PCH_DREF_CONTROL, temp);
5336                 POSTING_READ(PCH_DREF_CONTROL);
5337                 udelay(200);
5338         } else {
5339                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
5340
5341                 temp &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
5342
5343                 /* Turn off CPU output */
5344                 temp |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
5345
5346                 I915_WRITE(PCH_DREF_CONTROL, temp);
5347                 POSTING_READ(PCH_DREF_CONTROL);
5348                 udelay(200);
5349
5350                 /* Turn off the SSC source */
5351                 temp &= ~DREF_SSC_SOURCE_MASK;
5352                 temp |= DREF_SSC_SOURCE_DISABLE;
5353
5354                 /* Turn off SSC1 */
5355                 temp &= ~ DREF_SSC1_ENABLE;
5356
5357                 I915_WRITE(PCH_DREF_CONTROL, temp);
5358                 POSTING_READ(PCH_DREF_CONTROL);
5359                 udelay(200);
5360         }
5361 }
5362
5363 static int ironlake_get_refclk(struct drm_crtc *crtc)
5364 {
5365         struct drm_device *dev = crtc->dev;
5366         struct drm_i915_private *dev_priv = dev->dev_private;
5367         struct intel_encoder *encoder;
5368         struct drm_mode_config *mode_config = &dev->mode_config;
5369         struct intel_encoder *edp_encoder = NULL;
5370         int num_connectors = 0;
5371         bool is_lvds = false;
5372
5373         list_for_each_entry(encoder, &mode_config->encoder_list, base.head) {
5374                 if (encoder->base.crtc != crtc)
5375                         continue;
5376
5377                 switch (encoder->type) {
5378                 case INTEL_OUTPUT_LVDS:
5379                         is_lvds = true;
5380                         break;
5381                 case INTEL_OUTPUT_EDP:
5382                         edp_encoder = encoder;
5383                         break;
5384                 }
5385                 num_connectors++;
5386         }
5387
5388         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
5389                 DRM_DEBUG_KMS("using SSC reference clock of %d MHz\n",
5390                               dev_priv->lvds_ssc_freq);
5391                 return dev_priv->lvds_ssc_freq * 1000;
5392         }
5393
5394         return 120000;
5395 }
5396
5397 static int ironlake_crtc_mode_set(struct drm_crtc *crtc,
5398                                   struct drm_display_mode *mode,
5399                                   struct drm_display_mode *adjusted_mode,
5400                                   int x, int y,
5401                                   struct drm_framebuffer *old_fb)
5402 {
5403         struct drm_device *dev = crtc->dev;
5404         struct drm_i915_private *dev_priv = dev->dev_private;
5405         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5406         int pipe = intel_crtc->pipe;
5407         int plane = intel_crtc->plane;
5408         int refclk, num_connectors = 0;
5409         intel_clock_t clock, reduced_clock;
5410         u32 dpll, fp = 0, fp2 = 0, dspcntr, pipeconf;
5411         bool ok, has_reduced_clock = false, is_sdvo = false;
5412         bool is_crt = false, is_lvds = false, is_tv = false, is_dp = false;
5413         struct intel_encoder *has_edp_encoder = NULL;
5414         struct drm_mode_config *mode_config = &dev->mode_config;
5415         struct intel_encoder *encoder;
5416         const intel_limit_t *limit;
5417         int ret;
5418         struct fdi_m_n m_n = {0};
5419         u32 temp;
5420         u32 lvds_sync = 0;
5421         int target_clock, pixel_multiplier, lane, link_bw, factor;
5422         unsigned int pipe_bpp;
5423         bool dither;
5424
5425         list_for_each_entry(encoder, &mode_config->encoder_list, base.head) {
5426                 if (encoder->base.crtc != crtc)
5427                         continue;
5428
5429                 switch (encoder->type) {
5430                 case INTEL_OUTPUT_LVDS:
5431                         is_lvds = true;
5432                         break;
5433                 case INTEL_OUTPUT_SDVO:
5434                 case INTEL_OUTPUT_HDMI:
5435                         is_sdvo = true;
5436                         if (encoder->needs_tv_clock)
5437                                 is_tv = true;
5438                         break;
5439                 case INTEL_OUTPUT_TVOUT:
5440                         is_tv = true;
5441                         break;
5442                 case INTEL_OUTPUT_ANALOG:
5443                         is_crt = true;
5444                         break;
5445                 case INTEL_OUTPUT_DISPLAYPORT:
5446                         is_dp = true;
5447                         break;
5448                 case INTEL_OUTPUT_EDP:
5449                         has_edp_encoder = encoder;
5450                         break;
5451                 }
5452
5453                 num_connectors++;
5454         }
5455
5456         refclk = ironlake_get_refclk(crtc);
5457
5458         /*
5459          * Returns a set of divisors for the desired target clock with the given
5460          * refclk, or FALSE.  The returned values represent the clock equation:
5461          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
5462          */
5463         limit = intel_limit(crtc, refclk);
5464         ok = limit->find_pll(limit, crtc, adjusted_mode->clock, refclk, &clock);
5465         if (!ok) {
5466                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
5467                 return -EINVAL;
5468         }
5469
5470         /* Ensure that the cursor is valid for the new mode before changing... */
5471         intel_crtc_update_cursor(crtc, true);
5472
5473         if (is_lvds && dev_priv->lvds_downclock_avail) {
5474                 has_reduced_clock = limit->find_pll(limit, crtc,
5475                                                     dev_priv->lvds_downclock,
5476                                                     refclk,
5477                                                     &reduced_clock);
5478                 if (has_reduced_clock && (clock.p != reduced_clock.p)) {
5479                         /*
5480                          * If the different P is found, it means that we can't
5481                          * switch the display clock by using the FP0/FP1.
5482                          * In such case we will disable the LVDS downclock
5483                          * feature.
5484                          */
5485                         DRM_DEBUG_KMS("Different P is found for "
5486                                       "LVDS clock/downclock\n");
5487                         has_reduced_clock = 0;
5488                 }
5489         }
5490         /* SDVO TV has fixed PLL values depend on its clock range,
5491            this mirrors vbios setting. */
5492         if (is_sdvo && is_tv) {
5493                 if (adjusted_mode->clock >= 100000
5494                     && adjusted_mode->clock < 140500) {
5495                         clock.p1 = 2;
5496                         clock.p2 = 10;
5497                         clock.n = 3;
5498                         clock.m1 = 16;
5499                         clock.m2 = 8;
5500                 } else if (adjusted_mode->clock >= 140500
5501                            && adjusted_mode->clock <= 200000) {
5502                         clock.p1 = 1;
5503                         clock.p2 = 10;
5504                         clock.n = 6;
5505                         clock.m1 = 12;
5506                         clock.m2 = 8;
5507                 }
5508         }
5509
5510         /* FDI link */
5511         pixel_multiplier = intel_mode_get_pixel_multiplier(adjusted_mode);
5512         lane = 0;
5513         /* CPU eDP doesn't require FDI link, so just set DP M/N
5514            according to current link config */
5515         if (has_edp_encoder &&
5516             !intel_encoder_is_pch_edp(&has_edp_encoder->base)) {
5517                 target_clock = mode->clock;
5518                 intel_edp_link_config(has_edp_encoder,
5519                                       &lane, &link_bw);
5520         } else {
5521                 /* [e]DP over FDI requires target mode clock
5522                    instead of link clock */
5523                 if (is_dp || intel_encoder_is_pch_edp(&has_edp_encoder->base))
5524                         target_clock = mode->clock;
5525                 else
5526                         target_clock = adjusted_mode->clock;
5527
5528                 /* FDI is a binary signal running at ~2.7GHz, encoding
5529                  * each output octet as 10 bits. The actual frequency
5530                  * is stored as a divider into a 100MHz clock, and the
5531                  * mode pixel clock is stored in units of 1KHz.
5532                  * Hence the bw of each lane in terms of the mode signal
5533                  * is:
5534                  */
5535                 link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
5536         }
5537
5538         /* determine panel color depth */
5539         temp = I915_READ(PIPECONF(pipe));
5540         temp &= ~PIPE_BPC_MASK;
5541         dither = intel_choose_pipe_bpp_dither(crtc, &pipe_bpp, adjusted_mode);
5542         switch (pipe_bpp) {
5543         case 18:
5544                 temp |= PIPE_6BPC;
5545                 break;
5546         case 24:
5547                 temp |= PIPE_8BPC;
5548                 break;
5549         case 30:
5550                 temp |= PIPE_10BPC;
5551                 break;
5552         case 36:
5553                 temp |= PIPE_12BPC;
5554                 break;
5555         default:
5556                 WARN(1, "intel_choose_pipe_bpp returned invalid value %d\n",
5557                         pipe_bpp);
5558                 temp |= PIPE_8BPC;
5559                 pipe_bpp = 24;
5560                 break;
5561         }
5562
5563         intel_crtc->bpp = pipe_bpp;
5564         I915_WRITE(PIPECONF(pipe), temp);
5565
5566         if (!lane) {
5567                 /*
5568                  * Account for spread spectrum to avoid
5569                  * oversubscribing the link. Max center spread
5570                  * is 2.5%; use 5% for safety's sake.
5571                  */
5572                 u32 bps = target_clock * intel_crtc->bpp * 21 / 20;
5573                 lane = bps / (link_bw * 8) + 1;
5574         }
5575
5576         intel_crtc->fdi_lanes = lane;
5577
5578         if (pixel_multiplier > 1)
5579                 link_bw *= pixel_multiplier;
5580         ironlake_compute_m_n(intel_crtc->bpp, lane, target_clock, link_bw,
5581                              &m_n);
5582
5583         fp = clock.n << 16 | clock.m1 << 8 | clock.m2;
5584         if (has_reduced_clock)
5585                 fp2 = reduced_clock.n << 16 | reduced_clock.m1 << 8 |
5586                         reduced_clock.m2;
5587
5588         /* Enable autotuning of the PLL clock (if permissible) */
5589         factor = 21;
5590         if (is_lvds) {
5591                 if ((intel_panel_use_ssc(dev_priv) &&
5592                      dev_priv->lvds_ssc_freq == 100) ||
5593                     (I915_READ(PCH_LVDS) & LVDS_CLKB_POWER_MASK) == LVDS_CLKB_POWER_UP)
5594                         factor = 25;
5595         } else if (is_sdvo && is_tv)
5596                 factor = 20;
5597
5598         if (clock.m < factor * clock.n)
5599                 fp |= FP_CB_TUNE;
5600
5601         dpll = 0;
5602
5603         if (is_lvds)
5604                 dpll |= DPLLB_MODE_LVDS;
5605         else
5606                 dpll |= DPLLB_MODE_DAC_SERIAL;
5607         if (is_sdvo) {
5608                 int pixel_multiplier = intel_mode_get_pixel_multiplier(adjusted_mode);
5609                 if (pixel_multiplier > 1) {
5610                         dpll |= (pixel_multiplier - 1) << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
5611                 }
5612                 dpll |= DPLL_DVO_HIGH_SPEED;
5613         }
5614         if (is_dp || intel_encoder_is_pch_edp(&has_edp_encoder->base))
5615                 dpll |= DPLL_DVO_HIGH_SPEED;
5616
5617         /* compute bitmask from p1 value */
5618         dpll |= (1 << (clock.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5619         /* also FPA1 */
5620         dpll |= (1 << (clock.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
5621
5622         switch (clock.p2) {
5623         case 5:
5624                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
5625                 break;
5626         case 7:
5627                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
5628                 break;
5629         case 10:
5630                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
5631                 break;
5632         case 14:
5633                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
5634                 break;
5635         }
5636
5637         if (is_sdvo && is_tv)
5638                 dpll |= PLL_REF_INPUT_TVCLKINBC;
5639         else if (is_tv)
5640                 /* XXX: just matching BIOS for now */
5641                 /*      dpll |= PLL_REF_INPUT_TVCLKINBC; */
5642                 dpll |= 3;
5643         else if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
5644                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
5645         else
5646                 dpll |= PLL_REF_INPUT_DREFCLK;
5647
5648         /* setup pipeconf */
5649         pipeconf = I915_READ(PIPECONF(pipe));
5650
5651         /* Set up the display plane register */
5652         dspcntr = DISPPLANE_GAMMA_ENABLE;
5653
5654         DRM_DEBUG_KMS("Mode for pipe %d:\n", pipe);
5655         drm_mode_debug_printmodeline(mode);
5656
5657         /* PCH eDP needs FDI, but CPU eDP does not */
5658         if (!intel_crtc->no_pll) {
5659                 if (!has_edp_encoder ||
5660                     intel_encoder_is_pch_edp(&has_edp_encoder->base)) {
5661                         I915_WRITE(PCH_FP0(pipe), fp);
5662                         I915_WRITE(PCH_DPLL(pipe), dpll & ~DPLL_VCO_ENABLE);
5663
5664                         POSTING_READ(PCH_DPLL(pipe));
5665                         udelay(150);
5666                 }
5667         } else {
5668                 if (dpll == (I915_READ(PCH_DPLL(0)) & 0x7fffffff) &&
5669                     fp == I915_READ(PCH_FP0(0))) {
5670                         intel_crtc->use_pll_a = true;
5671                         DRM_DEBUG_KMS("using pipe a dpll\n");
5672                 } else if (dpll == (I915_READ(PCH_DPLL(1)) & 0x7fffffff) &&
5673                            fp == I915_READ(PCH_FP0(1))) {
5674                         intel_crtc->use_pll_a = false;
5675                         DRM_DEBUG_KMS("using pipe b dpll\n");
5676                 } else {
5677                         DRM_DEBUG_KMS("no matching PLL configuration for pipe 2\n");
5678                         return -EINVAL;
5679                 }
5680         }
5681
5682         /* The LVDS pin pair needs to be on before the DPLLs are enabled.
5683          * This is an exception to the general rule that mode_set doesn't turn
5684          * things on.
5685          */
5686         if (is_lvds) {
5687                 temp = I915_READ(PCH_LVDS);
5688                 temp |= LVDS_PORT_EN | LVDS_A0A2_CLKA_POWER_UP;
5689                 if (HAS_PCH_CPT(dev)) {
5690                         temp &= ~PORT_TRANS_SEL_MASK;
5691                         temp |= PORT_TRANS_SEL_CPT(pipe);
5692                 } else {
5693                         if (pipe == 1)
5694                                 temp |= LVDS_PIPEB_SELECT;
5695                         else
5696                                 temp &= ~LVDS_PIPEB_SELECT;
5697                 }
5698
5699                 /* set the corresponsding LVDS_BORDER bit */
5700                 temp |= dev_priv->lvds_border_bits;
5701                 /* Set the B0-B3 data pairs corresponding to whether we're going to
5702                  * set the DPLLs for dual-channel mode or not.
5703                  */
5704                 if (clock.p2 == 7)
5705                         temp |= LVDS_B0B3_POWER_UP | LVDS_CLKB_POWER_UP;
5706                 else
5707                         temp &= ~(LVDS_B0B3_POWER_UP | LVDS_CLKB_POWER_UP);
5708
5709                 /* It would be nice to set 24 vs 18-bit mode (LVDS_A3_POWER_UP)
5710                  * appropriately here, but we need to look more thoroughly into how
5711                  * panels behave in the two modes.
5712                  */
5713                 if (adjusted_mode->flags & DRM_MODE_FLAG_NHSYNC)
5714                         lvds_sync |= LVDS_HSYNC_POLARITY;
5715                 if (adjusted_mode->flags & DRM_MODE_FLAG_NVSYNC)
5716                         lvds_sync |= LVDS_VSYNC_POLARITY;
5717                 if ((temp & (LVDS_HSYNC_POLARITY | LVDS_VSYNC_POLARITY))
5718                     != lvds_sync) {
5719                         char flags[2] = "-+";
5720                         DRM_INFO("Changing LVDS panel from "
5721                                  "(%chsync, %cvsync) to (%chsync, %cvsync)\n",
5722                                  flags[!(temp & LVDS_HSYNC_POLARITY)],
5723                                  flags[!(temp & LVDS_VSYNC_POLARITY)],
5724                                  flags[!(lvds_sync & LVDS_HSYNC_POLARITY)],
5725                                  flags[!(lvds_sync & LVDS_VSYNC_POLARITY)]);
5726                         temp &= ~(LVDS_HSYNC_POLARITY | LVDS_VSYNC_POLARITY);
5727                         temp |= lvds_sync;
5728                 }
5729                 I915_WRITE(PCH_LVDS, temp);
5730         }
5731
5732         pipeconf &= ~PIPECONF_DITHER_EN;
5733         pipeconf &= ~PIPECONF_DITHER_TYPE_MASK;
5734         if ((is_lvds && dev_priv->lvds_dither) || dither) {
5735                 pipeconf |= PIPECONF_DITHER_EN;
5736                 pipeconf |= PIPECONF_DITHER_TYPE_SP;
5737         }
5738         if (is_dp || intel_encoder_is_pch_edp(&has_edp_encoder->base)) {
5739                 intel_dp_set_m_n(crtc, mode, adjusted_mode);
5740         } else {
5741                 /* For non-DP output, clear any trans DP clock recovery setting.*/
5742                 I915_WRITE(TRANSDATA_M1(pipe), 0);
5743                 I915_WRITE(TRANSDATA_N1(pipe), 0);
5744                 I915_WRITE(TRANSDPLINK_M1(pipe), 0);
5745                 I915_WRITE(TRANSDPLINK_N1(pipe), 0);
5746         }
5747
5748         if (!intel_crtc->no_pll &&
5749             (!has_edp_encoder ||
5750              intel_encoder_is_pch_edp(&has_edp_encoder->base))) {
5751                 I915_WRITE(PCH_DPLL(pipe), dpll);
5752
5753                 /* Wait for the clocks to stabilize. */
5754                 POSTING_READ(PCH_DPLL(pipe));
5755                 udelay(150);
5756
5757                 /* The pixel multiplier can only be updated once the
5758                  * DPLL is enabled and the clocks are stable.
5759                  *
5760                  * So write it again.
5761                  */
5762                 I915_WRITE(PCH_DPLL(pipe), dpll);
5763         }
5764
5765         intel_crtc->lowfreq_avail = false;
5766         if (!intel_crtc->no_pll) {
5767                 if (is_lvds && has_reduced_clock && i915_powersave) {
5768                         I915_WRITE(PCH_FP1(pipe), fp2);
5769                         intel_crtc->lowfreq_avail = true;
5770                         if (HAS_PIPE_CXSR(dev)) {
5771                                 DRM_DEBUG_KMS("enabling CxSR downclocking\n");
5772                                 pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
5773                         }
5774                 } else {
5775                         I915_WRITE(PCH_FP1(pipe), fp);
5776                         if (HAS_PIPE_CXSR(dev)) {
5777                                 DRM_DEBUG_KMS("disabling CxSR downclocking\n");
5778                                 pipeconf &= ~PIPECONF_CXSR_DOWNCLOCK;
5779                         }
5780                 }
5781         }
5782
5783         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5784                 pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
5785                 /* the chip adds 2 halflines automatically */
5786                 adjusted_mode->crtc_vdisplay -= 1;
5787                 adjusted_mode->crtc_vtotal -= 1;
5788                 adjusted_mode->crtc_vblank_start -= 1;
5789                 adjusted_mode->crtc_vblank_end -= 1;
5790                 adjusted_mode->crtc_vsync_end -= 1;
5791                 adjusted_mode->crtc_vsync_start -= 1;
5792         } else
5793                 pipeconf &= ~PIPECONF_INTERLACE_W_FIELD_INDICATION; /* progressive */
5794
5795         I915_WRITE(HTOTAL(pipe),
5796                    (adjusted_mode->crtc_hdisplay - 1) |
5797                    ((adjusted_mode->crtc_htotal - 1) << 16));
5798         I915_WRITE(HBLANK(pipe),
5799                    (adjusted_mode->crtc_hblank_start - 1) |
5800                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
5801         I915_WRITE(HSYNC(pipe),
5802                    (adjusted_mode->crtc_hsync_start - 1) |
5803                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
5804
5805         I915_WRITE(VTOTAL(pipe),
5806                    (adjusted_mode->crtc_vdisplay - 1) |
5807                    ((adjusted_mode->crtc_vtotal - 1) << 16));
5808         I915_WRITE(VBLANK(pipe),
5809                    (adjusted_mode->crtc_vblank_start - 1) |
5810                    ((adjusted_mode->crtc_vblank_end - 1) << 16));
5811         I915_WRITE(VSYNC(pipe),
5812                    (adjusted_mode->crtc_vsync_start - 1) |
5813                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
5814
5815         /* pipesrc controls the size that is scaled from, which should
5816          * always be the user's requested size.
5817          */
5818         I915_WRITE(PIPESRC(pipe),
5819                    ((mode->hdisplay - 1) << 16) | (mode->vdisplay - 1));
5820
5821         I915_WRITE(PIPE_DATA_M1(pipe), TU_SIZE(m_n.tu) | m_n.gmch_m);
5822         I915_WRITE(PIPE_DATA_N1(pipe), m_n.gmch_n);
5823         I915_WRITE(PIPE_LINK_M1(pipe), m_n.link_m);
5824         I915_WRITE(PIPE_LINK_N1(pipe), m_n.link_n);
5825
5826         if (has_edp_encoder &&
5827             !intel_encoder_is_pch_edp(&has_edp_encoder->base)) {
5828                 ironlake_set_pll_edp(crtc, adjusted_mode->clock);
5829         }
5830
5831         I915_WRITE(PIPECONF(pipe), pipeconf);
5832         POSTING_READ(PIPECONF(pipe));
5833
5834         intel_wait_for_vblank(dev, pipe);
5835
5836         if (IS_GEN5(dev)) {
5837                 /* enable address swizzle for tiling buffer */
5838                 temp = I915_READ(DISP_ARB_CTL);
5839                 I915_WRITE(DISP_ARB_CTL, temp | DISP_TILE_SURFACE_SWIZZLING);
5840         }
5841
5842         I915_WRITE(DSPCNTR(plane), dspcntr);
5843         POSTING_READ(DSPCNTR(plane));
5844
5845         ret = intel_pipe_set_base(crtc, x, y, old_fb);
5846
5847         intel_update_watermarks(dev);
5848
5849         return ret;
5850 }
5851
5852 static int intel_crtc_mode_set(struct drm_crtc *crtc,
5853                                struct drm_display_mode *mode,
5854                                struct drm_display_mode *adjusted_mode,
5855                                int x, int y,
5856                                struct drm_framebuffer *old_fb)
5857 {
5858         struct drm_device *dev = crtc->dev;
5859         struct drm_i915_private *dev_priv = dev->dev_private;
5860         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5861         int pipe = intel_crtc->pipe;
5862         int ret;
5863
5864         drm_vblank_pre_modeset(dev, pipe);
5865
5866         ret = dev_priv->display.crtc_mode_set(crtc, mode, adjusted_mode,
5867                                               x, y, old_fb);
5868
5869         drm_vblank_post_modeset(dev, pipe);
5870
5871         intel_crtc->dpms_mode = DRM_MODE_DPMS_ON;
5872
5873         return ret;
5874 }
5875
5876 static void g4x_write_eld(struct drm_connector *connector,
5877                           struct drm_crtc *crtc)
5878 {
5879         struct drm_i915_private *dev_priv = connector->dev->dev_private;
5880         uint8_t *eld = connector->eld;
5881         uint32_t eldv;
5882         uint32_t len;
5883         uint32_t i;
5884
5885         i = I915_READ(G4X_AUD_VID_DID);
5886
5887         if (i == INTEL_AUDIO_DEVBLC || i == INTEL_AUDIO_DEVCL)
5888                 eldv = G4X_ELDV_DEVCL_DEVBLC;
5889         else
5890                 eldv = G4X_ELDV_DEVCTG;
5891
5892         i = I915_READ(G4X_AUD_CNTL_ST);
5893         i &= ~(eldv | G4X_ELD_ADDR);
5894         len = (i >> 9) & 0x1f;          /* ELD buffer size */
5895         I915_WRITE(G4X_AUD_CNTL_ST, i);
5896
5897         if (!eld[0])
5898                 return;
5899
5900         len = min_t(uint8_t, eld[2], len);
5901         DRM_DEBUG_DRIVER("ELD size %d\n", len);
5902         for (i = 0; i < len; i++)
5903                 I915_WRITE(G4X_HDMIW_HDMIEDID, *((uint32_t *)eld + i));
5904
5905         i = I915_READ(G4X_AUD_CNTL_ST);
5906         i |= eldv;
5907         I915_WRITE(G4X_AUD_CNTL_ST, i);
5908 }
5909
5910 static void ironlake_write_eld(struct drm_connector *connector,
5911                                      struct drm_crtc *crtc)
5912 {
5913         struct drm_i915_private *dev_priv = connector->dev->dev_private;
5914         uint8_t *eld = connector->eld;
5915         uint32_t eldv;
5916         uint32_t i;
5917         int len;
5918         int hdmiw_hdmiedid;
5919         int aud_cntl_st;
5920         int aud_cntrl_st2;
5921
5922         if (HAS_PCH_IBX(connector->dev)) {
5923                 hdmiw_hdmiedid = GEN5_HDMIW_HDMIEDID_A;
5924                 aud_cntl_st = GEN5_AUD_CNTL_ST_A;
5925                 aud_cntrl_st2 = GEN5_AUD_CNTL_ST2;
5926         } else {
5927                 hdmiw_hdmiedid = GEN7_HDMIW_HDMIEDID_A;
5928                 aud_cntl_st = GEN7_AUD_CNTRL_ST_A;
5929                 aud_cntrl_st2 = GEN7_AUD_CNTRL_ST2;
5930         }
5931
5932         i = to_intel_crtc(crtc)->pipe;
5933         hdmiw_hdmiedid += i * 0x100;
5934         aud_cntl_st += i * 0x100;
5935
5936         DRM_DEBUG_DRIVER("ELD on pipe %c\n", pipe_name(i));
5937
5938         i = I915_READ(aud_cntl_st);
5939         i = (i >> 29) & 0x3;            /* DIP_Port_Select, 0x1 = PortB */
5940         if (!i) {
5941                 DRM_DEBUG_DRIVER("Audio directed to unknown port\n");
5942                 /* operate blindly on all ports */
5943                 eldv = GEN5_ELD_VALIDB;
5944                 eldv |= GEN5_ELD_VALIDB << 4;
5945                 eldv |= GEN5_ELD_VALIDB << 8;
5946         } else {
5947                 DRM_DEBUG_DRIVER("ELD on port %c\n", 'A' + i);
5948                 eldv = GEN5_ELD_VALIDB << ((i - 1) * 4);
5949         }
5950
5951         i = I915_READ(aud_cntrl_st2);
5952         i &= ~eldv;
5953         I915_WRITE(aud_cntrl_st2, i);
5954
5955         if (!eld[0])
5956                 return;
5957
5958         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT)) {
5959                 DRM_DEBUG_DRIVER("ELD: DisplayPort detected\n");
5960                 eld[5] |= (1 << 2);     /* Conn_Type, 0x1 = DisplayPort */
5961         }
5962
5963         i = I915_READ(aud_cntl_st);
5964         i &= ~GEN5_ELD_ADDRESS;
5965         I915_WRITE(aud_cntl_st, i);
5966
5967         len = min_t(uint8_t, eld[2], 21);       /* 84 bytes of hw ELD buffer */
5968         DRM_DEBUG_DRIVER("ELD size %d\n", len);
5969         for (i = 0; i < len; i++)
5970                 I915_WRITE(hdmiw_hdmiedid, *((uint32_t *)eld + i));
5971
5972         i = I915_READ(aud_cntrl_st2);
5973         i |= eldv;
5974         I915_WRITE(aud_cntrl_st2, i);
5975 }
5976
5977 void intel_write_eld(struct drm_encoder *encoder,
5978                      struct drm_display_mode *mode)
5979 {
5980         struct drm_crtc *crtc = encoder->crtc;
5981         struct drm_connector *connector;
5982         struct drm_device *dev = encoder->dev;
5983         struct drm_i915_private *dev_priv = dev->dev_private;
5984
5985         connector = drm_select_eld(encoder, mode);
5986         if (!connector)
5987                 return;
5988
5989         DRM_DEBUG_DRIVER("ELD on [CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
5990                          connector->base.id,
5991                          drm_get_connector_name(connector),
5992                          connector->encoder->base.id,
5993                          drm_get_encoder_name(connector->encoder));
5994
5995         connector->eld[6] = drm_av_sync_delay(connector, mode) / 2;
5996
5997         if (dev_priv->display.write_eld)
5998                 dev_priv->display.write_eld(connector, crtc);
5999 }
6000
6001 /** Loads the palette/gamma unit for the CRTC with the prepared values */
6002 void intel_crtc_load_lut(struct drm_crtc *crtc)
6003 {
6004         struct drm_device *dev = crtc->dev;
6005         struct drm_i915_private *dev_priv = dev->dev_private;
6006         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6007         int palreg = PALETTE(intel_crtc->pipe);
6008         int i;
6009
6010         /* The clocks have to be on to load the palette. */
6011         if (!crtc->enabled || !intel_crtc->active)
6012                 return;
6013
6014         /* use legacy palette for Ironlake */
6015         if (HAS_PCH_SPLIT(dev))
6016                 palreg = LGC_PALETTE(intel_crtc->pipe);
6017
6018         for (i = 0; i < 256; i++) {
6019                 I915_WRITE(palreg + 4 * i,
6020                            (intel_crtc->lut_r[i] << 16) |
6021                            (intel_crtc->lut_g[i] << 8) |
6022                            intel_crtc->lut_b[i]);
6023         }
6024 }
6025
6026 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
6027 {
6028         struct drm_device *dev = crtc->dev;
6029         struct drm_i915_private *dev_priv = dev->dev_private;
6030         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6031         bool visible = base != 0;
6032         u32 cntl;
6033
6034         if (intel_crtc->cursor_visible == visible)
6035                 return;
6036
6037         cntl = I915_READ(_CURACNTR);
6038         if (visible) {
6039                 /* On these chipsets we can only modify the base whilst
6040                  * the cursor is disabled.
6041                  */
6042                 I915_WRITE(_CURABASE, base);
6043
6044                 cntl &= ~(CURSOR_FORMAT_MASK);
6045                 /* XXX width must be 64, stride 256 => 0x00 << 28 */
6046                 cntl |= CURSOR_ENABLE |
6047                         CURSOR_GAMMA_ENABLE |
6048                         CURSOR_FORMAT_ARGB;
6049         } else
6050                 cntl &= ~(CURSOR_ENABLE | CURSOR_GAMMA_ENABLE);
6051         I915_WRITE(_CURACNTR, cntl);
6052
6053         intel_crtc->cursor_visible = visible;
6054 }
6055
6056 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
6057 {
6058         struct drm_device *dev = crtc->dev;
6059         struct drm_i915_private *dev_priv = dev->dev_private;
6060         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6061         int pipe = intel_crtc->pipe;
6062         bool visible = base != 0;
6063
6064         if (intel_crtc->cursor_visible != visible) {
6065                 uint32_t cntl = I915_READ(CURCNTR(pipe));
6066                 if (base) {
6067                         cntl &= ~(CURSOR_MODE | MCURSOR_PIPE_SELECT);
6068                         cntl |= CURSOR_MODE_64_ARGB_AX | MCURSOR_GAMMA_ENABLE;
6069                         cntl |= pipe << 28; /* Connect to correct pipe */
6070                 } else {
6071                         cntl &= ~(CURSOR_MODE | MCURSOR_GAMMA_ENABLE);
6072                         cntl |= CURSOR_MODE_DISABLE;
6073                 }
6074                 I915_WRITE(CURCNTR(pipe), cntl);
6075
6076                 intel_crtc->cursor_visible = visible;
6077         }
6078         /* and commit changes on next vblank */
6079         I915_WRITE(CURBASE(pipe), base);
6080 }
6081
6082 static void ivb_update_cursor(struct drm_crtc *crtc, u32 base)
6083 {
6084         struct drm_device *dev = crtc->dev;
6085         struct drm_i915_private *dev_priv = dev->dev_private;
6086         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6087         int pipe = intel_crtc->pipe;
6088         bool visible = base != 0;
6089
6090         if (intel_crtc->cursor_visible != visible) {
6091                 uint32_t cntl = I915_READ(CURCNTR_IVB(pipe));
6092                 if (base) {
6093                         cntl &= ~CURSOR_MODE;
6094                         cntl |= CURSOR_MODE_64_ARGB_AX | MCURSOR_GAMMA_ENABLE;
6095                 } else {
6096                         cntl &= ~(CURSOR_MODE | MCURSOR_GAMMA_ENABLE);
6097                         cntl |= CURSOR_MODE_DISABLE;
6098                 }
6099                 I915_WRITE(CURCNTR_IVB(pipe), cntl);
6100
6101                 intel_crtc->cursor_visible = visible;
6102         }
6103         /* and commit changes on next vblank */
6104         I915_WRITE(CURBASE_IVB(pipe), base);
6105 }
6106
6107 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
6108 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
6109                                      bool on)
6110 {
6111         struct drm_device *dev = crtc->dev;
6112         struct drm_i915_private *dev_priv = dev->dev_private;
6113         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6114         int pipe = intel_crtc->pipe;
6115         int x = intel_crtc->cursor_x;
6116         int y = intel_crtc->cursor_y;
6117         u32 base, pos;
6118         bool visible;
6119
6120         pos = 0;
6121
6122         if (on && crtc->enabled && crtc->fb) {
6123                 base = intel_crtc->cursor_addr;
6124                 if (x > (int) crtc->fb->width)
6125                         base = 0;
6126
6127                 if (y > (int) crtc->fb->height)
6128                         base = 0;
6129         } else
6130                 base = 0;
6131
6132         if (x < 0) {
6133                 if (x + intel_crtc->cursor_width < 0)
6134                         base = 0;
6135
6136                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
6137                 x = -x;
6138         }
6139         pos |= x << CURSOR_X_SHIFT;
6140
6141         if (y < 0) {
6142                 if (y + intel_crtc->cursor_height < 0)
6143                         base = 0;
6144
6145                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
6146                 y = -y;
6147         }
6148         pos |= y << CURSOR_Y_SHIFT;
6149
6150         visible = base != 0;
6151         if (!visible && !intel_crtc->cursor_visible)
6152                 return;
6153
6154         if (IS_IVYBRIDGE(dev)) {
6155                 I915_WRITE(CURPOS_IVB(pipe), pos);
6156                 ivb_update_cursor(crtc, base);
6157         } else {
6158                 I915_WRITE(CURPOS(pipe), pos);
6159                 if (IS_845G(dev) || IS_I865G(dev))
6160                         i845_update_cursor(crtc, base);
6161                 else
6162                         i9xx_update_cursor(crtc, base);
6163         }
6164
6165         if (visible)
6166                 intel_mark_busy(dev, to_intel_framebuffer(crtc->fb)->obj);
6167 }
6168
6169 static int intel_crtc_cursor_set(struct drm_crtc *crtc,
6170                                  struct drm_file *file,
6171                                  uint32_t handle,
6172                                  uint32_t width, uint32_t height)
6173 {
6174         struct drm_device *dev = crtc->dev;
6175         struct drm_i915_private *dev_priv = dev->dev_private;
6176         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6177         struct drm_i915_gem_object *obj;
6178         uint32_t addr;
6179         int ret;
6180
6181         DRM_DEBUG_KMS("\n");
6182
6183         /* if we want to turn off the cursor ignore width and height */
6184         if (!handle) {
6185                 DRM_DEBUG_KMS("cursor off\n");
6186                 addr = 0;
6187                 obj = NULL;
6188                 mutex_lock(&dev->struct_mutex);
6189                 goto finish;
6190         }
6191
6192         /* Currently we only support 64x64 cursors */
6193         if (width != 64 || height != 64) {
6194                 DRM_ERROR("we currently only support 64x64 cursors\n");
6195                 return -EINVAL;
6196         }
6197
6198         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
6199         if (&obj->base == NULL)
6200                 return -ENOENT;
6201
6202         if (obj->base.size < width * height * 4) {
6203                 DRM_ERROR("buffer is to small\n");
6204                 ret = -ENOMEM;
6205                 goto fail;
6206         }
6207
6208         /* we only need to pin inside GTT if cursor is non-phy */
6209         mutex_lock(&dev->struct_mutex);
6210         if (!dev_priv->info->cursor_needs_physical) {
6211                 if (obj->tiling_mode) {
6212                         DRM_ERROR("cursor cannot be tiled\n");
6213                         ret = -EINVAL;
6214                         goto fail_locked;
6215                 }
6216
6217                 ret = i915_gem_object_pin_to_display_plane(obj, 0, NULL);
6218                 if (ret) {
6219                         DRM_ERROR("failed to move cursor bo into the GTT\n");
6220                         goto fail_locked;
6221                 }
6222
6223                 ret = i915_gem_object_put_fence(obj);
6224                 if (ret) {
6225                         DRM_ERROR("failed to release fence for cursor");
6226                         goto fail_unpin;
6227                 }
6228
6229                 addr = obj->gtt_offset;
6230         } else {
6231                 int align = IS_I830(dev) ? 16 * 1024 : 256;
6232                 ret = i915_gem_attach_phys_object(dev, obj,
6233                                                   (intel_crtc->pipe == 0) ? I915_GEM_PHYS_CURSOR_0 : I915_GEM_PHYS_CURSOR_1,
6234                                                   align);
6235                 if (ret) {
6236                         DRM_ERROR("failed to attach phys object\n");
6237                         goto fail_locked;
6238                 }
6239                 addr = obj->phys_obj->handle->busaddr;
6240         }
6241
6242         if (IS_GEN2(dev))
6243                 I915_WRITE(CURSIZE, (height << 12) | width);
6244
6245  finish:
6246         if (intel_crtc->cursor_bo) {
6247                 if (dev_priv->info->cursor_needs_physical) {
6248                         if (intel_crtc->cursor_bo != obj)
6249                                 i915_gem_detach_phys_object(dev, intel_crtc->cursor_bo);
6250                 } else
6251                         i915_gem_object_unpin(intel_crtc->cursor_bo);
6252                 drm_gem_object_unreference(&intel_crtc->cursor_bo->base);
6253         }
6254
6255         mutex_unlock(&dev->struct_mutex);
6256
6257         intel_crtc->cursor_addr = addr;
6258         intel_crtc->cursor_bo = obj;
6259         intel_crtc->cursor_width = width;
6260         intel_crtc->cursor_height = height;
6261
6262         intel_crtc_update_cursor(crtc, true);
6263
6264         return 0;
6265 fail_unpin:
6266         i915_gem_object_unpin(obj);
6267 fail_locked:
6268         mutex_unlock(&dev->struct_mutex);
6269 fail:
6270         drm_gem_object_unreference_unlocked(&obj->base);
6271         return ret;
6272 }
6273
6274 static int intel_crtc_cursor_move(struct drm_crtc *crtc, int x, int y)
6275 {
6276         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6277
6278         intel_crtc->cursor_x = x;
6279         intel_crtc->cursor_y = y;
6280
6281         intel_crtc_update_cursor(crtc, true);
6282
6283         return 0;
6284 }
6285
6286 /** Sets the color ramps on behalf of RandR */
6287 void intel_crtc_fb_gamma_set(struct drm_crtc *crtc, u16 red, u16 green,
6288                                  u16 blue, int regno)
6289 {
6290         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6291
6292         intel_crtc->lut_r[regno] = red >> 8;
6293         intel_crtc->lut_g[regno] = green >> 8;
6294         intel_crtc->lut_b[regno] = blue >> 8;
6295 }
6296
6297 void intel_crtc_fb_gamma_get(struct drm_crtc *crtc, u16 *red, u16 *green,
6298                              u16 *blue, int regno)
6299 {
6300         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6301
6302         *red = intel_crtc->lut_r[regno] << 8;
6303         *green = intel_crtc->lut_g[regno] << 8;
6304         *blue = intel_crtc->lut_b[regno] << 8;
6305 }
6306
6307 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
6308                                  u16 *blue, uint32_t start, uint32_t size)
6309 {
6310         int end = (start + size > 256) ? 256 : start + size, i;
6311         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6312
6313         for (i = start; i < end; i++) {
6314                 intel_crtc->lut_r[i] = red[i] >> 8;
6315                 intel_crtc->lut_g[i] = green[i] >> 8;
6316                 intel_crtc->lut_b[i] = blue[i] >> 8;
6317         }
6318
6319         intel_crtc_load_lut(crtc);
6320 }
6321
6322 /**
6323  * Get a pipe with a simple mode set on it for doing load-based monitor
6324  * detection.
6325  *
6326  * It will be up to the load-detect code to adjust the pipe as appropriate for
6327  * its requirements.  The pipe will be connected to no other encoders.
6328  *
6329  * Currently this code will only succeed if there is a pipe with no encoders
6330  * configured for it.  In the future, it could choose to temporarily disable
6331  * some outputs to free up a pipe for its use.
6332  *
6333  * \return crtc, or NULL if no pipes are available.
6334  */
6335
6336 /* VESA 640x480x72Hz mode to set on the pipe */
6337 static struct drm_display_mode load_detect_mode = {
6338         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
6339                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
6340 };
6341
6342 static struct drm_framebuffer *
6343 intel_framebuffer_create(struct drm_device *dev,
6344                          struct drm_mode_fb_cmd *mode_cmd,
6345                          struct drm_i915_gem_object *obj)
6346 {
6347         struct intel_framebuffer *intel_fb;
6348         int ret;
6349
6350         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
6351         if (!intel_fb) {
6352                 drm_gem_object_unreference_unlocked(&obj->base);
6353                 return ERR_PTR(-ENOMEM);
6354         }
6355
6356         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
6357         if (ret) {
6358                 drm_gem_object_unreference_unlocked(&obj->base);
6359                 kfree(intel_fb);
6360                 return ERR_PTR(ret);
6361         }
6362
6363         return &intel_fb->base;
6364 }
6365
6366 static u32
6367 intel_framebuffer_pitch_for_width(int width, int bpp)
6368 {
6369         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
6370         return ALIGN(pitch, 64);
6371 }
6372
6373 static u32
6374 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
6375 {
6376         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
6377         return ALIGN(pitch * mode->vdisplay, PAGE_SIZE);
6378 }
6379
6380 static struct drm_framebuffer *
6381 intel_framebuffer_create_for_mode(struct drm_device *dev,
6382                                   struct drm_display_mode *mode,
6383                                   int depth, int bpp)
6384 {
6385         struct drm_i915_gem_object *obj;
6386         struct drm_mode_fb_cmd mode_cmd;
6387
6388         obj = i915_gem_alloc_object(dev,
6389                                     intel_framebuffer_size_for_mode(mode, bpp));
6390         if (obj == NULL)
6391                 return ERR_PTR(-ENOMEM);
6392
6393         mode_cmd.width = mode->hdisplay;
6394         mode_cmd.height = mode->vdisplay;
6395         mode_cmd.depth = depth;
6396         mode_cmd.bpp = bpp;
6397         mode_cmd.pitch = intel_framebuffer_pitch_for_width(mode_cmd.width, bpp);
6398
6399         return intel_framebuffer_create(dev, &mode_cmd, obj);
6400 }
6401
6402 static struct drm_framebuffer *
6403 mode_fits_in_fbdev(struct drm_device *dev,
6404                    struct drm_display_mode *mode)
6405 {
6406         struct drm_i915_private *dev_priv = dev->dev_private;
6407         struct drm_i915_gem_object *obj;
6408         struct drm_framebuffer *fb;
6409
6410         if (dev_priv->fbdev == NULL)
6411                 return NULL;
6412
6413         obj = dev_priv->fbdev->ifb.obj;
6414         if (obj == NULL)
6415                 return NULL;
6416
6417         fb = &dev_priv->fbdev->ifb.base;
6418         if (fb->pitch < intel_framebuffer_pitch_for_width(mode->hdisplay,
6419                                                           fb->bits_per_pixel))
6420                 return NULL;
6421
6422         if (obj->base.size < mode->vdisplay * fb->pitch)
6423                 return NULL;
6424
6425         return fb;
6426 }
6427
6428 bool intel_get_load_detect_pipe(struct intel_encoder *intel_encoder,
6429                                 struct drm_connector *connector,
6430                                 struct drm_display_mode *mode,
6431                                 struct intel_load_detect_pipe *old)
6432 {
6433         struct intel_crtc *intel_crtc;
6434         struct drm_crtc *possible_crtc;
6435         struct drm_encoder *encoder = &intel_encoder->base;
6436         struct drm_crtc *crtc = NULL;
6437         struct drm_device *dev = encoder->dev;
6438         struct drm_framebuffer *old_fb;
6439         int i = -1;
6440
6441         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
6442                       connector->base.id, drm_get_connector_name(connector),
6443                       encoder->base.id, drm_get_encoder_name(encoder));
6444
6445         /*
6446          * Algorithm gets a little messy:
6447          *
6448          *   - if the connector already has an assigned crtc, use it (but make
6449          *     sure it's on first)
6450          *
6451          *   - try to find the first unused crtc that can drive this connector,
6452          *     and use that if we find one
6453          */
6454
6455         /* See if we already have a CRTC for this connector */
6456         if (encoder->crtc) {
6457                 crtc = encoder->crtc;
6458
6459                 intel_crtc = to_intel_crtc(crtc);
6460                 old->dpms_mode = intel_crtc->dpms_mode;
6461                 old->load_detect_temp = false;
6462
6463                 /* Make sure the crtc and connector are running */
6464                 if (intel_crtc->dpms_mode != DRM_MODE_DPMS_ON) {
6465                         struct drm_encoder_helper_funcs *encoder_funcs;
6466                         struct drm_crtc_helper_funcs *crtc_funcs;
6467
6468                         crtc_funcs = crtc->helper_private;
6469                         crtc_funcs->dpms(crtc, DRM_MODE_DPMS_ON);
6470
6471                         encoder_funcs = encoder->helper_private;
6472                         encoder_funcs->dpms(encoder, DRM_MODE_DPMS_ON);
6473                 }
6474
6475                 return true;
6476         }
6477
6478         /* Find an unused one (if possible) */
6479         list_for_each_entry(possible_crtc, &dev->mode_config.crtc_list, head) {
6480                 i++;
6481                 if (!(encoder->possible_crtcs & (1 << i)))
6482                         continue;
6483                 if (!possible_crtc->enabled) {
6484                         crtc = possible_crtc;
6485                         break;
6486                 }
6487         }
6488
6489         /*
6490          * If we didn't find an unused CRTC, don't use any.
6491          */
6492         if (!crtc) {
6493                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
6494                 return false;
6495         }
6496
6497         encoder->crtc = crtc;
6498         connector->encoder = encoder;
6499
6500         intel_crtc = to_intel_crtc(crtc);
6501         old->dpms_mode = intel_crtc->dpms_mode;
6502         old->load_detect_temp = true;
6503         old->release_fb = NULL;
6504
6505         if (!mode)
6506                 mode = &load_detect_mode;
6507
6508         old_fb = crtc->fb;
6509
6510         /* We need a framebuffer large enough to accommodate all accesses
6511          * that the plane may generate whilst we perform load detection.
6512          * We can not rely on the fbcon either being present (we get called
6513          * during its initialisation to detect all boot displays, or it may
6514          * not even exist) or that it is large enough to satisfy the
6515          * requested mode.
6516          */
6517         crtc->fb = mode_fits_in_fbdev(dev, mode);
6518         if (crtc->fb == NULL) {
6519                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
6520                 crtc->fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
6521                 old->release_fb = crtc->fb;
6522         } else
6523                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
6524         if (IS_ERR(crtc->fb)) {
6525                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
6526                 crtc->fb = old_fb;
6527                 return false;
6528         }
6529
6530         if (!drm_crtc_helper_set_mode(crtc, mode, 0, 0, old_fb)) {
6531                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
6532                 if (old->release_fb)
6533                         old->release_fb->funcs->destroy(old->release_fb);
6534                 crtc->fb = old_fb;
6535                 return false;
6536         }
6537
6538         /* let the connector get through one full cycle before testing */
6539         intel_wait_for_vblank(dev, intel_crtc->pipe);
6540
6541         return true;
6542 }
6543
6544 void intel_release_load_detect_pipe(struct intel_encoder *intel_encoder,
6545                                     struct drm_connector *connector,
6546                                     struct intel_load_detect_pipe *old)
6547 {
6548         struct drm_encoder *encoder = &intel_encoder->base;
6549         struct drm_device *dev = encoder->dev;
6550         struct drm_crtc *crtc = encoder->crtc;
6551         struct drm_encoder_helper_funcs *encoder_funcs = encoder->helper_private;
6552         struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private;
6553
6554         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
6555                       connector->base.id, drm_get_connector_name(connector),
6556                       encoder->base.id, drm_get_encoder_name(encoder));
6557
6558         if (old->load_detect_temp) {
6559                 connector->encoder = NULL;
6560                 drm_helper_disable_unused_functions(dev);
6561
6562                 if (old->release_fb)
6563                         old->release_fb->funcs->destroy(old->release_fb);
6564
6565                 return;
6566         }
6567
6568         /* Switch crtc and encoder back off if necessary */
6569         if (old->dpms_mode != DRM_MODE_DPMS_ON) {
6570                 encoder_funcs->dpms(encoder, old->dpms_mode);
6571                 crtc_funcs->dpms(crtc, old->dpms_mode);
6572         }
6573 }
6574
6575 /* Returns the clock of the currently programmed mode of the given pipe. */
6576 static int intel_crtc_clock_get(struct drm_device *dev, struct drm_crtc *crtc)
6577 {
6578         struct drm_i915_private *dev_priv = dev->dev_private;
6579         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6580         int pipe = intel_crtc->pipe;
6581         u32 dpll = I915_READ(DPLL(pipe));
6582         u32 fp;
6583         intel_clock_t clock;
6584
6585         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
6586                 fp = I915_READ(FP0(pipe));
6587         else
6588                 fp = I915_READ(FP1(pipe));
6589
6590         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
6591         if (IS_PINEVIEW(dev)) {
6592                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
6593                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
6594         } else {
6595                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
6596                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
6597         }
6598
6599         if (!IS_GEN2(dev)) {
6600                 if (IS_PINEVIEW(dev))
6601                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
6602                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
6603                 else
6604                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
6605                                DPLL_FPA01_P1_POST_DIV_SHIFT);
6606
6607                 switch (dpll & DPLL_MODE_MASK) {
6608                 case DPLLB_MODE_DAC_SERIAL:
6609                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
6610                                 5 : 10;
6611                         break;
6612                 case DPLLB_MODE_LVDS:
6613                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
6614                                 7 : 14;
6615                         break;
6616                 default:
6617                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
6618                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
6619                         return 0;
6620                 }
6621
6622                 /* XXX: Handle the 100Mhz refclk */
6623                 intel_clock(dev, 96000, &clock);
6624         } else {
6625                 bool is_lvds = (pipe == 1) && (I915_READ(LVDS) & LVDS_PORT_EN);
6626
6627                 if (is_lvds) {
6628                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
6629                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
6630                         clock.p2 = 14;
6631
6632                         if ((dpll & PLL_REF_INPUT_MASK) ==
6633                             PLLB_REF_INPUT_SPREADSPECTRUMIN) {
6634                                 /* XXX: might not be 66MHz */
6635                                 intel_clock(dev, 66000, &clock);
6636                         } else
6637                                 intel_clock(dev, 48000, &clock);
6638                 } else {
6639                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
6640                                 clock.p1 = 2;
6641                         else {
6642                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
6643                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
6644                         }
6645                         if (dpll & PLL_P2_DIVIDE_BY_4)
6646                                 clock.p2 = 4;
6647                         else
6648                                 clock.p2 = 2;
6649
6650                         intel_clock(dev, 48000, &clock);
6651                 }
6652         }
6653
6654         /* XXX: It would be nice to validate the clocks, but we can't reuse
6655          * i830PllIsValid() because it relies on the xf86_config connector
6656          * configuration being accurate, which it isn't necessarily.
6657          */
6658
6659         return clock.dot;
6660 }
6661
6662 /** Returns the currently programmed mode of the given pipe. */
6663 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
6664                                              struct drm_crtc *crtc)
6665 {
6666         struct drm_i915_private *dev_priv = dev->dev_private;
6667         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6668         int pipe = intel_crtc->pipe;
6669         struct drm_display_mode *mode;
6670         int htot = I915_READ(HTOTAL(pipe));
6671         int hsync = I915_READ(HSYNC(pipe));
6672         int vtot = I915_READ(VTOTAL(pipe));
6673         int vsync = I915_READ(VSYNC(pipe));
6674
6675         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
6676         if (!mode)
6677                 return NULL;
6678
6679         mode->clock = intel_crtc_clock_get(dev, crtc);
6680         mode->hdisplay = (htot & 0xffff) + 1;
6681         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
6682         mode->hsync_start = (hsync & 0xffff) + 1;
6683         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
6684         mode->vdisplay = (vtot & 0xffff) + 1;
6685         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
6686         mode->vsync_start = (vsync & 0xffff) + 1;
6687         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
6688
6689         drm_mode_set_name(mode);
6690         drm_mode_set_crtcinfo(mode, 0);
6691
6692         return mode;
6693 }
6694
6695 #define GPU_IDLE_TIMEOUT 500 /* ms */
6696
6697 /* When this timer fires, we've been idle for awhile */
6698 static void intel_gpu_idle_timer(unsigned long arg)
6699 {
6700         struct drm_device *dev = (struct drm_device *)arg;
6701         drm_i915_private_t *dev_priv = dev->dev_private;
6702
6703         if (!list_empty(&dev_priv->mm.active_list)) {
6704                 /* Still processing requests, so just re-arm the timer. */
6705                 mod_timer(&dev_priv->idle_timer, jiffies +
6706                           msecs_to_jiffies(GPU_IDLE_TIMEOUT));
6707                 return;
6708         }
6709
6710         dev_priv->busy = false;
6711         queue_work(dev_priv->wq, &dev_priv->idle_work);
6712 }
6713
6714 #define CRTC_IDLE_TIMEOUT 1000 /* ms */
6715
6716 static void intel_crtc_idle_timer(unsigned long arg)
6717 {
6718         struct intel_crtc *intel_crtc = (struct intel_crtc *)arg;
6719         struct drm_crtc *crtc = &intel_crtc->base;
6720         drm_i915_private_t *dev_priv = crtc->dev->dev_private;
6721         struct intel_framebuffer *intel_fb;
6722
6723         intel_fb = to_intel_framebuffer(crtc->fb);
6724         if (intel_fb && intel_fb->obj->active) {
6725                 /* The framebuffer is still being accessed by the GPU. */
6726                 mod_timer(&intel_crtc->idle_timer, jiffies +
6727                           msecs_to_jiffies(CRTC_IDLE_TIMEOUT));
6728                 return;
6729         }
6730
6731         intel_crtc->busy = false;
6732         queue_work(dev_priv->wq, &dev_priv->idle_work);
6733 }
6734
6735 static void intel_increase_pllclock(struct drm_crtc *crtc)
6736 {
6737         struct drm_device *dev = crtc->dev;
6738         drm_i915_private_t *dev_priv = dev->dev_private;
6739         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6740         int pipe = intel_crtc->pipe;
6741         int dpll_reg = DPLL(pipe);
6742         int dpll;
6743
6744         if (HAS_PCH_SPLIT(dev))
6745                 return;
6746
6747         if (!dev_priv->lvds_downclock_avail)
6748                 return;
6749
6750         dpll = I915_READ(dpll_reg);
6751         if (!HAS_PIPE_CXSR(dev) && (dpll & DISPLAY_RATE_SELECT_FPA1)) {
6752                 DRM_DEBUG_DRIVER("upclocking LVDS\n");
6753
6754                 /* Unlock panel regs */
6755                 I915_WRITE(PP_CONTROL,
6756                            I915_READ(PP_CONTROL) | PANEL_UNLOCK_REGS);
6757
6758                 dpll &= ~DISPLAY_RATE_SELECT_FPA1;
6759                 I915_WRITE(dpll_reg, dpll);
6760                 intel_wait_for_vblank(dev, pipe);
6761
6762                 dpll = I915_READ(dpll_reg);
6763                 if (dpll & DISPLAY_RATE_SELECT_FPA1)
6764                         DRM_DEBUG_DRIVER("failed to upclock LVDS!\n");
6765
6766                 /* ...and lock them again */
6767                 I915_WRITE(PP_CONTROL, I915_READ(PP_CONTROL) & 0x3);
6768         }
6769
6770         /* Schedule downclock */
6771         mod_timer(&intel_crtc->idle_timer, jiffies +
6772                   msecs_to_jiffies(CRTC_IDLE_TIMEOUT));
6773 }
6774
6775 static void intel_decrease_pllclock(struct drm_crtc *crtc)
6776 {
6777         struct drm_device *dev = crtc->dev;
6778         drm_i915_private_t *dev_priv = dev->dev_private;
6779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6780         int pipe = intel_crtc->pipe;
6781         int dpll_reg = DPLL(pipe);
6782         int dpll = I915_READ(dpll_reg);
6783
6784         if (HAS_PCH_SPLIT(dev))
6785                 return;
6786
6787         if (!dev_priv->lvds_downclock_avail)
6788                 return;
6789
6790         /*
6791          * Since this is called by a timer, we should never get here in
6792          * the manual case.
6793          */
6794         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
6795                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
6796
6797                 /* Unlock panel regs */
6798                 I915_WRITE(PP_CONTROL, I915_READ(PP_CONTROL) |
6799                            PANEL_UNLOCK_REGS);
6800
6801                 dpll |= DISPLAY_RATE_SELECT_FPA1;
6802                 I915_WRITE(dpll_reg, dpll);
6803                 intel_wait_for_vblank(dev, pipe);
6804                 dpll = I915_READ(dpll_reg);
6805                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
6806                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
6807
6808                 /* ...and lock them again */
6809                 I915_WRITE(PP_CONTROL, I915_READ(PP_CONTROL) & 0x3);
6810         }
6811
6812 }
6813
6814 /**
6815  * intel_idle_update - adjust clocks for idleness
6816  * @work: work struct
6817  *
6818  * Either the GPU or display (or both) went idle.  Check the busy status
6819  * here and adjust the CRTC and GPU clocks as necessary.
6820  */
6821 static void intel_idle_update(struct work_struct *work)
6822 {
6823         drm_i915_private_t *dev_priv = container_of(work, drm_i915_private_t,
6824                                                     idle_work);
6825         struct drm_device *dev = dev_priv->dev;
6826         struct drm_crtc *crtc;
6827         struct intel_crtc *intel_crtc;
6828
6829         if (!i915_powersave)
6830                 return;
6831
6832         mutex_lock(&dev->struct_mutex);
6833
6834         i915_update_gfx_val(dev_priv);
6835
6836         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6837                 /* Skip inactive CRTCs */
6838                 if (!crtc->fb)
6839                         continue;
6840
6841                 intel_crtc = to_intel_crtc(crtc);
6842                 if (!intel_crtc->busy)
6843                         intel_decrease_pllclock(crtc);
6844         }
6845
6846
6847         mutex_unlock(&dev->struct_mutex);
6848 }
6849
6850 /**
6851  * intel_mark_busy - mark the GPU and possibly the display busy
6852  * @dev: drm device
6853  * @obj: object we're operating on
6854  *
6855  * Callers can use this function to indicate that the GPU is busy processing
6856  * commands.  If @obj matches one of the CRTC objects (i.e. it's a scanout
6857  * buffer), we'll also mark the display as busy, so we know to increase its
6858  * clock frequency.
6859  */
6860 void intel_mark_busy(struct drm_device *dev, struct drm_i915_gem_object *obj)
6861 {
6862         drm_i915_private_t *dev_priv = dev->dev_private;
6863         struct drm_crtc *crtc = NULL;
6864         struct intel_framebuffer *intel_fb;
6865         struct intel_crtc *intel_crtc;
6866
6867         if (!drm_core_check_feature(dev, DRIVER_MODESET))
6868                 return;
6869
6870         if (!dev_priv->busy)
6871                 dev_priv->busy = true;
6872         else
6873                 mod_timer(&dev_priv->idle_timer, jiffies +
6874                           msecs_to_jiffies(GPU_IDLE_TIMEOUT));
6875
6876         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6877                 if (!crtc->fb)
6878                         continue;
6879
6880                 intel_crtc = to_intel_crtc(crtc);
6881                 intel_fb = to_intel_framebuffer(crtc->fb);
6882                 if (intel_fb->obj == obj) {
6883                         if (!intel_crtc->busy) {
6884                                 /* Non-busy -> busy, upclock */
6885                                 intel_increase_pllclock(crtc);
6886                                 intel_crtc->busy = true;
6887                         } else {
6888                                 /* Busy -> busy, put off timer */
6889                                 mod_timer(&intel_crtc->idle_timer, jiffies +
6890                                           msecs_to_jiffies(CRTC_IDLE_TIMEOUT));
6891                         }
6892                 }
6893         }
6894 }
6895
6896 static void intel_crtc_destroy(struct drm_crtc *crtc)
6897 {
6898         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6899         struct drm_device *dev = crtc->dev;
6900         struct intel_unpin_work *work;
6901         unsigned long flags;
6902
6903         spin_lock_irqsave(&dev->event_lock, flags);
6904         work = intel_crtc->unpin_work;
6905         intel_crtc->unpin_work = NULL;
6906         spin_unlock_irqrestore(&dev->event_lock, flags);
6907
6908         if (work) {
6909                 cancel_work_sync(&work->work);
6910                 kfree(work);
6911         }
6912
6913         drm_crtc_cleanup(crtc);
6914
6915         kfree(intel_crtc);
6916 }
6917
6918 static void intel_unpin_work_fn(struct work_struct *__work)
6919 {
6920         struct intel_unpin_work *work =
6921                 container_of(__work, struct intel_unpin_work, work);
6922
6923         mutex_lock(&work->dev->struct_mutex);
6924         i915_gem_object_unpin(work->old_fb_obj);
6925         drm_gem_object_unreference(&work->pending_flip_obj->base);
6926         drm_gem_object_unreference(&work->old_fb_obj->base);
6927
6928         intel_update_fbc(work->dev);
6929         mutex_unlock(&work->dev->struct_mutex);
6930         kfree(work);
6931 }
6932
6933 static void do_intel_finish_page_flip(struct drm_device *dev,
6934                                       struct drm_crtc *crtc)
6935 {
6936         drm_i915_private_t *dev_priv = dev->dev_private;
6937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6938         struct intel_unpin_work *work;
6939         struct drm_i915_gem_object *obj;
6940         struct drm_pending_vblank_event *e;
6941         struct timeval tnow, tvbl;
6942         unsigned long flags;
6943
6944         /* Ignore early vblank irqs */
6945         if (intel_crtc == NULL)
6946                 return;
6947
6948         do_gettimeofday(&tnow);
6949
6950         spin_lock_irqsave(&dev->event_lock, flags);
6951         work = intel_crtc->unpin_work;
6952
6953         /* Ensure we don't miss a work->pending update ... */
6954         smp_rmb();
6955
6956         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
6957                 spin_unlock_irqrestore(&dev->event_lock, flags);
6958                 return;
6959         }
6960
6961         /* and that the unpin work is consistent wrt ->pending. */
6962         smp_rmb();
6963
6964         intel_crtc->unpin_work = NULL;
6965
6966         if (work->event) {
6967                 e = work->event;
6968                 e->event.sequence = drm_vblank_count_and_time(dev, intel_crtc->pipe, &tvbl);
6969
6970                 /* Called before vblank count and timestamps have
6971                  * been updated for the vblank interval of flip
6972                  * completion? Need to increment vblank count and
6973                  * add one videorefresh duration to returned timestamp
6974                  * to account for this. We assume this happened if we
6975                  * get called over 0.9 frame durations after the last
6976                  * timestamped vblank.
6977                  *
6978                  * This calculation can not be used with vrefresh rates
6979                  * below 5Hz (10Hz to be on the safe side) without
6980                  * promoting to 64 integers.
6981                  */
6982                 if (10 * (timeval_to_ns(&tnow) - timeval_to_ns(&tvbl)) >
6983                     9 * crtc->framedur_ns) {
6984                         e->event.sequence++;
6985                         tvbl = ns_to_timeval(timeval_to_ns(&tvbl) +
6986                                              crtc->framedur_ns);
6987                 }
6988
6989                 e->event.tv_sec = tvbl.tv_sec;
6990                 e->event.tv_usec = tvbl.tv_usec;
6991
6992                 list_add_tail(&e->base.link,
6993                               &e->base.file_priv->event_list);
6994                 wake_up_interruptible(&e->base.file_priv->event_wait);
6995         }
6996
6997         drm_vblank_put(dev, intel_crtc->pipe);
6998
6999         spin_unlock_irqrestore(&dev->event_lock, flags);
7000
7001         obj = work->old_fb_obj;
7002
7003         atomic_clear_mask(1 << intel_crtc->plane,
7004                           &obj->pending_flip.counter);
7005
7006         wake_up(&dev_priv->pending_flip_queue);
7007         schedule_work(&work->work);
7008
7009         trace_i915_flip_complete(intel_crtc->plane, work->pending_flip_obj);
7010 }
7011
7012 void intel_finish_page_flip(struct drm_device *dev, int pipe)
7013 {
7014         drm_i915_private_t *dev_priv = dev->dev_private;
7015         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
7016
7017         do_intel_finish_page_flip(dev, crtc);
7018 }
7019
7020 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
7021 {
7022         drm_i915_private_t *dev_priv = dev->dev_private;
7023         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
7024
7025         do_intel_finish_page_flip(dev, crtc);
7026 }
7027
7028 void intel_prepare_page_flip(struct drm_device *dev, int plane)
7029 {
7030         drm_i915_private_t *dev_priv = dev->dev_private;
7031         struct intel_crtc *intel_crtc =
7032                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
7033         unsigned long flags;
7034
7035         /* NB: An MMIO update of the plane base pointer will also
7036          * generate a page-flip completion irq, i.e. every modeset
7037          * is also accompanied by a spurious intel_prepare_page_flip().
7038          */
7039         spin_lock_irqsave(&dev->event_lock, flags);
7040         if (intel_crtc->unpin_work)
7041                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
7042         spin_unlock_irqrestore(&dev->event_lock, flags);
7043 }
7044
7045 inline static void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
7046 {
7047         /* Ensure that the work item is consistent when activating it ... */
7048         smp_wmb();
7049         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
7050         /* and that it is marked active as soon as the irq could fire. */
7051         smp_wmb();
7052 }
7053
7054 static int intel_gen2_queue_flip(struct drm_device *dev,
7055                                  struct drm_crtc *crtc,
7056                                  struct drm_framebuffer *fb,
7057                                  struct drm_i915_gem_object *obj)
7058 {
7059         struct drm_i915_private *dev_priv = dev->dev_private;
7060         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7061         unsigned long offset;
7062         u32 flip_mask;
7063         int ret;
7064
7065         ret = intel_pin_and_fence_fb_obj(dev, obj, LP_RING(dev_priv));
7066         if (ret)
7067                 goto err;
7068
7069         /* Offset into the new buffer for cases of shared fbs between CRTCs */
7070         offset = crtc->y * fb->pitch + crtc->x * fb->bits_per_pixel/8;
7071
7072         ret = BEGIN_LP_RING(6);
7073         if (ret)
7074                 goto err_unpin;
7075
7076         /* Can't queue multiple flips, so wait for the previous
7077          * one to finish before executing the next.
7078          */
7079         if (intel_crtc->plane)
7080                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
7081         else
7082                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
7083         OUT_RING(MI_WAIT_FOR_EVENT | flip_mask);
7084         OUT_RING(MI_NOOP);
7085         OUT_RING(MI_DISPLAY_FLIP |
7086                  MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
7087         OUT_RING(fb->pitch);
7088         OUT_RING(obj->gtt_offset + offset);
7089         OUT_RING(MI_NOOP);
7090
7091         intel_mark_page_flip_active(intel_crtc);
7092         ADVANCE_LP_RING();
7093         return 0;
7094
7095 err_unpin:
7096         i915_gem_object_unpin(obj);
7097 err:
7098         return ret;
7099 }
7100
7101 static int intel_gen3_queue_flip(struct drm_device *dev,
7102                                  struct drm_crtc *crtc,
7103                                  struct drm_framebuffer *fb,
7104                                  struct drm_i915_gem_object *obj)
7105 {
7106         struct drm_i915_private *dev_priv = dev->dev_private;
7107         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7108         unsigned long offset;
7109         u32 flip_mask;
7110         int ret;
7111
7112         ret = intel_pin_and_fence_fb_obj(dev, obj, LP_RING(dev_priv));
7113         if (ret)
7114                 goto err;
7115
7116         /* Offset into the new buffer for cases of shared fbs between CRTCs */
7117         offset = crtc->y * fb->pitch + crtc->x * fb->bits_per_pixel/8;
7118
7119         ret = BEGIN_LP_RING(6);
7120         if (ret)
7121                 goto err_unpin;
7122
7123         if (intel_crtc->plane)
7124                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
7125         else
7126                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
7127         OUT_RING(MI_WAIT_FOR_EVENT | flip_mask);
7128         OUT_RING(MI_NOOP);
7129         OUT_RING(MI_DISPLAY_FLIP_I915 |
7130                  MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
7131         OUT_RING(fb->pitch);
7132         OUT_RING(obj->gtt_offset + offset);
7133         OUT_RING(MI_NOOP);
7134
7135         intel_mark_page_flip_active(intel_crtc);
7136         ADVANCE_LP_RING();
7137         return 0;
7138
7139 err_unpin:
7140         i915_gem_object_unpin(obj);
7141 err:
7142         return ret;
7143 }
7144
7145 static int intel_gen4_queue_flip(struct drm_device *dev,
7146                                  struct drm_crtc *crtc,
7147                                  struct drm_framebuffer *fb,
7148                                  struct drm_i915_gem_object *obj)
7149 {
7150         struct drm_i915_private *dev_priv = dev->dev_private;
7151         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7152         uint32_t pf, pipesrc;
7153         int ret;
7154
7155         ret = intel_pin_and_fence_fb_obj(dev, obj, LP_RING(dev_priv));
7156         if (ret)
7157                 goto err;
7158
7159         ret = BEGIN_LP_RING(4);
7160         if (ret)
7161                 goto err_unpin;
7162
7163         /* i965+ uses the linear or tiled offsets from the
7164          * Display Registers (which do not change across a page-flip)
7165          * so we need only reprogram the base address.
7166          */
7167         OUT_RING(MI_DISPLAY_FLIP |
7168                  MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
7169         OUT_RING(fb->pitch);
7170         OUT_RING(obj->gtt_offset | obj->tiling_mode);
7171
7172         /* XXX Enabling the panel-fitter across page-flip is so far
7173          * untested on non-native modes, so ignore it for now.
7174          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
7175          */
7176         pf = 0;
7177         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
7178         OUT_RING(pf | pipesrc);
7179
7180         intel_mark_page_flip_active(intel_crtc);
7181
7182         intel_mark_page_flip_active(intel_crtc);
7183         ADVANCE_LP_RING();
7184         return 0;
7185
7186 err_unpin:
7187         i915_gem_object_unpin(obj);
7188 err:
7189         return ret;
7190 }
7191
7192 static int intel_gen6_queue_flip(struct drm_device *dev,
7193                                  struct drm_crtc *crtc,
7194                                  struct drm_framebuffer *fb,
7195                                  struct drm_i915_gem_object *obj)
7196 {
7197         struct drm_i915_private *dev_priv = dev->dev_private;
7198         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7199         uint32_t pf, pipesrc;
7200         int ret;
7201
7202         ret = intel_pin_and_fence_fb_obj(dev, obj, LP_RING(dev_priv));
7203         if (ret)
7204                 goto err;
7205
7206         ret = BEGIN_LP_RING(4);
7207         if (ret)
7208                 goto err_unpin;
7209
7210         OUT_RING(MI_DISPLAY_FLIP |
7211                  MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
7212         OUT_RING(fb->pitch | obj->tiling_mode);
7213         OUT_RING(obj->gtt_offset);
7214
7215         pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
7216         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
7217         OUT_RING(pf | pipesrc);
7218         ADVANCE_LP_RING();
7219         return 0;
7220
7221 err_unpin:
7222         i915_gem_object_unpin(obj);
7223 err:
7224         return ret;
7225 }
7226
7227 /*
7228  * On gen7 we currently use the blit ring because (in early silicon at least)
7229  * the render ring doesn't give us interrpts for page flip completion, which
7230  * means clients will hang after the first flip is queued.  Fortunately the
7231  * blit ring generates interrupts properly, so use it instead.
7232  */
7233 static int intel_gen7_queue_flip(struct drm_device *dev,
7234                                  struct drm_crtc *crtc,
7235                                  struct drm_framebuffer *fb,
7236                                  struct drm_i915_gem_object *obj)
7237 {
7238         struct drm_i915_private *dev_priv = dev->dev_private;
7239         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7240         struct intel_ring_buffer *ring = &dev_priv->ring[BCS];
7241         uint32_t plane_bit = 0;
7242         int ret;
7243
7244         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
7245         if (ret)
7246                 goto err;
7247
7248         switch(intel_crtc->plane) {
7249         case PLANE_A:
7250                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
7251                 break;
7252         case PLANE_B:
7253                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
7254                 break;
7255         case PLANE_C:
7256                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
7257                 break;
7258         default:
7259                 WARN_ONCE(1, "unknown plane in flip command\n");
7260                 ret = -ENODEV;
7261                 goto err_unpin;
7262         }
7263
7264         ret = intel_ring_begin(ring, 4);
7265         if (ret)
7266                 goto err_unpin;
7267
7268         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
7269         intel_ring_emit(ring, (fb->pitch | obj->tiling_mode));
7270         intel_ring_emit(ring, (obj->gtt_offset));
7271         intel_ring_emit(ring, (MI_NOOP));
7272
7273         intel_mark_page_flip_active(intel_crtc);
7274         intel_ring_advance(ring);
7275         return 0;
7276
7277 err_unpin:
7278         i915_gem_object_unpin(obj);
7279 err:
7280         return ret;
7281 }
7282
7283 static int intel_default_queue_flip(struct drm_device *dev,
7284                                     struct drm_crtc *crtc,
7285                                     struct drm_framebuffer *fb,
7286                                     struct drm_i915_gem_object *obj)
7287 {
7288         return -ENODEV;
7289 }
7290
7291 static int intel_crtc_page_flip(struct drm_crtc *crtc,
7292                                 struct drm_framebuffer *fb,
7293                                 struct drm_pending_vblank_event *event)
7294 {
7295         struct drm_device *dev = crtc->dev;
7296         struct drm_i915_private *dev_priv = dev->dev_private;
7297         struct intel_framebuffer *intel_fb;
7298         struct drm_i915_gem_object *obj;
7299         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7300         struct intel_unpin_work *work;
7301         unsigned long flags;
7302         int ret;
7303
7304         work = kzalloc(sizeof *work, GFP_KERNEL);
7305         if (work == NULL)
7306                 return -ENOMEM;
7307
7308         work->event = event;
7309         work->dev = crtc->dev;
7310         intel_fb = to_intel_framebuffer(crtc->fb);
7311         work->old_fb_obj = intel_fb->obj;
7312         INIT_WORK(&work->work, intel_unpin_work_fn);
7313
7314         ret = drm_vblank_get(dev, intel_crtc->pipe);
7315         if (ret)
7316                 goto free_work;
7317
7318         /* We borrow the event spin lock for protecting unpin_work */
7319         spin_lock_irqsave(&dev->event_lock, flags);
7320         if (intel_crtc->unpin_work) {
7321                 spin_unlock_irqrestore(&dev->event_lock, flags);
7322                 kfree(work);
7323                 drm_vblank_put(dev, intel_crtc->pipe);
7324
7325                 DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
7326                 return -EBUSY;
7327         }
7328         intel_crtc->unpin_work = work;
7329         spin_unlock_irqrestore(&dev->event_lock, flags);
7330
7331         intel_fb = to_intel_framebuffer(fb);
7332         obj = intel_fb->obj;
7333
7334         mutex_lock(&dev->struct_mutex);
7335
7336         /* Reference the objects for the scheduled work. */
7337         drm_gem_object_reference(&work->old_fb_obj->base);
7338         drm_gem_object_reference(&obj->base);
7339
7340         crtc->fb = fb;
7341
7342         work->pending_flip_obj = obj;
7343
7344         work->enable_stall_check = true;
7345
7346         /* Block clients from rendering to the new back buffer until
7347          * the flip occurs and the object is no longer visible.
7348          */
7349         atomic_add(1 << intel_crtc->plane, &work->old_fb_obj->pending_flip);
7350
7351         ret = dev_priv->display.queue_flip(dev, crtc, fb, obj);
7352         if (ret)
7353                 goto cleanup_pending;
7354
7355         intel_disable_fbc(dev);
7356         mutex_unlock(&dev->struct_mutex);
7357
7358         trace_i915_flip_request(intel_crtc->plane, obj);
7359
7360         return 0;
7361
7362 cleanup_pending:
7363         atomic_sub(1 << intel_crtc->plane, &work->old_fb_obj->pending_flip);
7364         drm_gem_object_unreference(&work->old_fb_obj->base);
7365         drm_gem_object_unreference(&obj->base);
7366         mutex_unlock(&dev->struct_mutex);
7367
7368         spin_lock_irqsave(&dev->event_lock, flags);
7369         intel_crtc->unpin_work = NULL;
7370         spin_unlock_irqrestore(&dev->event_lock, flags);
7371
7372         drm_vblank_put(dev, intel_crtc->pipe);
7373 free_work:
7374         kfree(work);
7375
7376         return ret;
7377 }
7378
7379 static void intel_sanitize_modesetting(struct drm_device *dev,
7380                                        int pipe, int plane)
7381 {
7382         struct drm_i915_private *dev_priv = dev->dev_private;
7383         u32 reg, val;
7384         int i;
7385
7386         /* Clear any frame start delays used for debugging left by the BIOS */
7387         for_each_pipe(i) {
7388                 reg = PIPECONF(i);
7389                 I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
7390         }
7391
7392         if (HAS_PCH_SPLIT(dev))
7393                 return;
7394
7395         /* Who knows what state these registers were left in by the BIOS or
7396          * grub?
7397          *
7398          * If we leave the registers in a conflicting state (e.g. with the
7399          * display plane reading from the other pipe than the one we intend
7400          * to use) then when we attempt to teardown the active mode, we will
7401          * not disable the pipes and planes in the correct order -- leaving
7402          * a plane reading from a disabled pipe and possibly leading to
7403          * undefined behaviour.
7404          */
7405
7406         reg = DSPCNTR(plane);
7407         val = I915_READ(reg);
7408
7409         if ((val & DISPLAY_PLANE_ENABLE) == 0)
7410                 return;
7411         if (!!(val & DISPPLANE_SEL_PIPE_MASK) == pipe)
7412                 return;
7413
7414         /* This display plane is active and attached to the other CPU pipe. */
7415         pipe = !pipe;
7416
7417         /* Disable the plane and wait for it to stop reading from the pipe. */
7418         intel_disable_plane(dev_priv, plane, pipe);
7419         intel_disable_pipe(dev_priv, pipe);
7420 }
7421
7422 static void intel_crtc_reset(struct drm_crtc *crtc)
7423 {
7424         struct drm_device *dev = crtc->dev;
7425         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7426
7427         /* Reset flags back to the 'unknown' status so that they
7428          * will be correctly set on the initial modeset.
7429          */
7430         intel_crtc->dpms_mode = -1;
7431
7432         /* We need to fix up any BIOS configuration that conflicts with
7433          * our expectations.
7434          */
7435         intel_sanitize_modesetting(dev, intel_crtc->pipe, intel_crtc->plane);
7436 }
7437
7438 static struct drm_crtc_helper_funcs intel_helper_funcs = {
7439         .dpms = intel_crtc_dpms,
7440         .mode_fixup = intel_crtc_mode_fixup,
7441         .mode_set = intel_crtc_mode_set,
7442         .mode_set_base = intel_pipe_set_base,
7443         .mode_set_base_atomic = intel_pipe_set_base_atomic,
7444         .load_lut = intel_crtc_load_lut,
7445         .disable = intel_crtc_disable,
7446 };
7447
7448 static const struct drm_crtc_funcs intel_crtc_funcs = {
7449         .reset = intel_crtc_reset,
7450         .cursor_set = intel_crtc_cursor_set,
7451         .cursor_move = intel_crtc_cursor_move,
7452         .gamma_set = intel_crtc_gamma_set,
7453         .set_config = drm_crtc_helper_set_config,
7454         .destroy = intel_crtc_destroy,
7455         .page_flip = intel_crtc_page_flip,
7456 };
7457
7458 static void intel_crtc_init(struct drm_device *dev, int pipe)
7459 {
7460         drm_i915_private_t *dev_priv = dev->dev_private;
7461         struct intel_crtc *intel_crtc;
7462         int i;
7463
7464         intel_crtc = kzalloc(sizeof(struct intel_crtc) + (INTELFB_CONN_LIMIT * sizeof(struct drm_connector *)), GFP_KERNEL);
7465         if (intel_crtc == NULL)
7466                 return;
7467
7468         drm_crtc_init(dev, &intel_crtc->base, &intel_crtc_funcs);
7469
7470         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
7471         for (i = 0; i < 256; i++) {
7472                 intel_crtc->lut_r[i] = i;
7473                 intel_crtc->lut_g[i] = i;
7474                 intel_crtc->lut_b[i] = i;
7475         }
7476
7477         /* Swap pipes & planes for FBC on pre-965 */
7478         intel_crtc->pipe = pipe;
7479         intel_crtc->plane = pipe;
7480         if (IS_MOBILE(dev) && IS_GEN3(dev)) {
7481                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
7482                 intel_crtc->plane = !pipe;
7483         }
7484
7485         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
7486                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
7487         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
7488         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
7489
7490         intel_crtc_reset(&intel_crtc->base);
7491         intel_crtc->active = true; /* force the pipe off on setup_init_config */
7492         intel_crtc->bpp = 24; /* default for pre-Ironlake */
7493
7494         if (HAS_PCH_SPLIT(dev)) {
7495                 if (pipe == 2 && IS_IVYBRIDGE(dev))
7496                         intel_crtc->no_pll = true;
7497                 intel_helper_funcs.prepare = ironlake_crtc_prepare;
7498                 intel_helper_funcs.commit = ironlake_crtc_commit;
7499         } else {
7500                 intel_helper_funcs.prepare = i9xx_crtc_prepare;
7501                 intel_helper_funcs.commit = i9xx_crtc_commit;
7502         }
7503
7504         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
7505
7506         intel_crtc->busy = false;
7507
7508         setup_timer(&intel_crtc->idle_timer, intel_crtc_idle_timer,
7509                     (unsigned long)intel_crtc);
7510 }
7511
7512 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
7513                                 struct drm_file *file)
7514 {
7515         drm_i915_private_t *dev_priv = dev->dev_private;
7516         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
7517         struct drm_mode_object *drmmode_obj;
7518         struct intel_crtc *crtc;
7519
7520         if (!dev_priv) {
7521                 DRM_ERROR("called with no initialization\n");
7522                 return -EINVAL;
7523         }
7524
7525         drmmode_obj = drm_mode_object_find(dev, pipe_from_crtc_id->crtc_id,
7526                         DRM_MODE_OBJECT_CRTC);
7527
7528         if (!drmmode_obj) {
7529                 DRM_ERROR("no such CRTC id\n");
7530                 return -EINVAL;
7531         }
7532
7533         crtc = to_intel_crtc(obj_to_crtc(drmmode_obj));
7534         pipe_from_crtc_id->pipe = crtc->pipe;
7535
7536         return 0;
7537 }
7538
7539 static int intel_encoder_clones(struct drm_device *dev, int type_mask)
7540 {
7541         struct intel_encoder *encoder;
7542         int index_mask = 0;
7543         int entry = 0;
7544
7545         list_for_each_entry(encoder, &dev->mode_config.encoder_list, base.head) {
7546                 if (type_mask & encoder->clone_mask)
7547                         index_mask |= (1 << entry);
7548                 entry++;
7549         }
7550
7551         return index_mask;
7552 }
7553
7554 static bool has_edp_a(struct drm_device *dev)
7555 {
7556         struct drm_i915_private *dev_priv = dev->dev_private;
7557
7558         if (!IS_MOBILE(dev))
7559                 return false;
7560
7561         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
7562                 return false;
7563
7564         if (IS_GEN5(dev) &&
7565             (I915_READ(ILK_DISPLAY_CHICKEN_FUSES) & ILK_eDP_A_DISABLE))
7566                 return false;
7567
7568         return true;
7569 }
7570
7571 static void intel_setup_outputs(struct drm_device *dev)
7572 {
7573         struct drm_i915_private *dev_priv = dev->dev_private;
7574         struct intel_encoder *encoder;
7575         bool dpd_is_edp = false;
7576         bool has_lvds = false;
7577
7578         if (IS_MOBILE(dev) && !IS_I830(dev))
7579                 has_lvds = intel_lvds_init(dev);
7580         if (!has_lvds && !HAS_PCH_SPLIT(dev)) {
7581                 /* disable the panel fitter on everything but LVDS */
7582                 I915_WRITE(PFIT_CONTROL, 0);
7583         }
7584
7585         if (HAS_PCH_SPLIT(dev)) {
7586                 dpd_is_edp = intel_dpd_is_edp(dev);
7587
7588                 if (has_edp_a(dev))
7589                         intel_dp_init(dev, DP_A);
7590
7591                 if (dpd_is_edp && (I915_READ(PCH_DP_D) & DP_DETECTED))
7592                         intel_dp_init(dev, PCH_DP_D);
7593         }
7594
7595         intel_crt_init(dev);
7596
7597         if (HAS_PCH_SPLIT(dev)) {
7598                 int found;
7599
7600                 if (I915_READ(HDMIB) & PORT_DETECTED) {
7601                         /* PCH SDVOB multiplex with HDMIB */
7602                         found = intel_sdvo_init(dev, PCH_SDVOB);
7603                         if (!found)
7604                                 intel_hdmi_init(dev, HDMIB);
7605                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
7606                                 intel_dp_init(dev, PCH_DP_B);
7607                 }
7608
7609                 if (I915_READ(HDMIC) & PORT_DETECTED)
7610                         intel_hdmi_init(dev, HDMIC);
7611
7612                 if (I915_READ(HDMID) & PORT_DETECTED)
7613                         intel_hdmi_init(dev, HDMID);
7614
7615                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
7616                         intel_dp_init(dev, PCH_DP_C);
7617
7618                 if (!dpd_is_edp && (I915_READ(PCH_DP_D) & DP_DETECTED))
7619                         intel_dp_init(dev, PCH_DP_D);
7620
7621         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
7622                 bool found = false;
7623
7624                 if (I915_READ(SDVOB) & SDVO_DETECTED) {
7625                         DRM_DEBUG_KMS("probing SDVOB\n");
7626                         found = intel_sdvo_init(dev, SDVOB);
7627                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
7628                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
7629                                 intel_hdmi_init(dev, SDVOB);
7630                         }
7631
7632                         if (!found && SUPPORTS_INTEGRATED_DP(dev)) {
7633                                 DRM_DEBUG_KMS("probing DP_B\n");
7634                                 intel_dp_init(dev, DP_B);
7635                         }
7636                 }
7637
7638                 /* Before G4X SDVOC doesn't have its own detect register */
7639
7640                 if (I915_READ(SDVOB) & SDVO_DETECTED) {
7641                         DRM_DEBUG_KMS("probing SDVOC\n");
7642                         found = intel_sdvo_init(dev, SDVOC);
7643                 }
7644
7645                 if (!found && (I915_READ(SDVOC) & SDVO_DETECTED)) {
7646
7647                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
7648                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
7649                                 intel_hdmi_init(dev, SDVOC);
7650                         }
7651                         if (SUPPORTS_INTEGRATED_DP(dev)) {
7652                                 DRM_DEBUG_KMS("probing DP_C\n");
7653                                 intel_dp_init(dev, DP_C);
7654                         }
7655                 }
7656
7657                 if (SUPPORTS_INTEGRATED_DP(dev) &&
7658                     (I915_READ(DP_D) & DP_DETECTED)) {
7659                         DRM_DEBUG_KMS("probing DP_D\n");
7660                         intel_dp_init(dev, DP_D);
7661                 }
7662         } else if (IS_GEN2(dev))
7663                 intel_dvo_init(dev);
7664
7665         if (SUPPORTS_TV(dev))
7666                 intel_tv_init(dev);
7667
7668         list_for_each_entry(encoder, &dev->mode_config.encoder_list, base.head) {
7669                 encoder->base.possible_crtcs = encoder->crtc_mask;
7670                 encoder->base.possible_clones =
7671                         intel_encoder_clones(dev, encoder->clone_mask);
7672         }
7673
7674         /* disable all the possible outputs/crtcs before entering KMS mode */
7675         drm_helper_disable_unused_functions(dev);
7676
7677         if (HAS_PCH_SPLIT(dev))
7678                 ironlake_init_pch_refclk(dev);
7679 }
7680
7681 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
7682 {
7683         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
7684
7685         drm_framebuffer_cleanup(fb);
7686         drm_gem_object_unreference_unlocked(&intel_fb->obj->base);
7687
7688         kfree(intel_fb);
7689 }
7690
7691 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
7692                                                 struct drm_file *file,
7693                                                 unsigned int *handle)
7694 {
7695         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
7696         struct drm_i915_gem_object *obj = intel_fb->obj;
7697
7698         return drm_gem_handle_create(file, &obj->base, handle);
7699 }
7700
7701 static const struct drm_framebuffer_funcs intel_fb_funcs = {
7702         .destroy = intel_user_framebuffer_destroy,
7703         .create_handle = intel_user_framebuffer_create_handle,
7704 };
7705
7706 int intel_framebuffer_init(struct drm_device *dev,
7707                            struct intel_framebuffer *intel_fb,
7708                            struct drm_mode_fb_cmd *mode_cmd,
7709                            struct drm_i915_gem_object *obj)
7710 {
7711         int ret;
7712
7713         if (obj->tiling_mode == I915_TILING_Y)
7714                 return -EINVAL;
7715
7716         if (mode_cmd->pitch & 63)
7717                 return -EINVAL;
7718
7719         switch (mode_cmd->bpp) {
7720         case 8:
7721         case 16:
7722                 /* Only pre-ILK can handle 5:5:5 */
7723                 if (mode_cmd->depth == 15 && !HAS_PCH_SPLIT(dev))
7724                         return -EINVAL;
7725                 break;
7726
7727         case 24:
7728         case 32:
7729                 break;
7730         default:
7731                 return -EINVAL;
7732         }
7733
7734         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
7735         if (ret) {
7736                 DRM_ERROR("framebuffer init failed %d\n", ret);
7737                 return ret;
7738         }
7739
7740         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
7741         intel_fb->obj = obj;
7742         return 0;
7743 }
7744
7745 static struct drm_framebuffer *
7746 intel_user_framebuffer_create(struct drm_device *dev,
7747                               struct drm_file *filp,
7748                               struct drm_mode_fb_cmd *mode_cmd)
7749 {
7750         struct drm_i915_gem_object *obj;
7751
7752         obj = to_intel_bo(drm_gem_object_lookup(dev, filp, mode_cmd->handle));
7753         if (&obj->base == NULL)
7754                 return ERR_PTR(-ENOENT);
7755
7756         return intel_framebuffer_create(dev, mode_cmd, obj);
7757 }
7758
7759 static const struct drm_mode_config_funcs intel_mode_funcs = {
7760         .fb_create = intel_user_framebuffer_create,
7761         .output_poll_changed = intel_fb_output_poll_changed,
7762 };
7763
7764 static struct drm_i915_gem_object *
7765 intel_alloc_context_page(struct drm_device *dev)
7766 {
7767         struct drm_i915_gem_object *ctx;
7768         int ret;
7769
7770         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
7771
7772         ctx = i915_gem_alloc_object(dev, 4096);
7773         if (!ctx) {
7774                 DRM_DEBUG("failed to alloc power context, RC6 disabled\n");
7775                 return NULL;
7776         }
7777
7778         ret = i915_gem_object_pin(ctx, 4096, true);
7779         if (ret) {
7780                 DRM_ERROR("failed to pin power context: %d\n", ret);
7781                 goto err_unref;
7782         }
7783
7784         ret = i915_gem_object_set_to_gtt_domain(ctx, 1);
7785         if (ret) {
7786                 DRM_ERROR("failed to set-domain on power context: %d\n", ret);
7787                 goto err_unpin;
7788         }
7789
7790         return ctx;
7791
7792 err_unpin:
7793         i915_gem_object_unpin(ctx);
7794 err_unref:
7795         drm_gem_object_unreference(&ctx->base);
7796         mutex_unlock(&dev->struct_mutex);
7797         return NULL;
7798 }
7799
7800 bool ironlake_set_drps(struct drm_device *dev, u8 val)
7801 {
7802         struct drm_i915_private *dev_priv = dev->dev_private;
7803         u16 rgvswctl;
7804
7805         rgvswctl = I915_READ16(MEMSWCTL);
7806         if (rgvswctl & MEMCTL_CMD_STS) {
7807                 DRM_DEBUG("gpu busy, RCS change rejected\n");
7808                 return false; /* still busy with another command */
7809         }
7810
7811         rgvswctl = (MEMCTL_CMD_CHFREQ << MEMCTL_CMD_SHIFT) |
7812                 (val << MEMCTL_FREQ_SHIFT) | MEMCTL_SFCAVM;
7813         I915_WRITE16(MEMSWCTL, rgvswctl);
7814         POSTING_READ16(MEMSWCTL);
7815
7816         rgvswctl |= MEMCTL_CMD_STS;
7817         I915_WRITE16(MEMSWCTL, rgvswctl);
7818
7819         return true;
7820 }
7821
7822 void ironlake_enable_drps(struct drm_device *dev)
7823 {
7824         struct drm_i915_private *dev_priv = dev->dev_private;
7825         u32 rgvmodectl = I915_READ(MEMMODECTL);
7826         u8 fmax, fmin, fstart, vstart;
7827
7828         /* Enable temp reporting */
7829         I915_WRITE16(PMMISC, I915_READ(PMMISC) | MCPPCE_EN);
7830         I915_WRITE16(TSC1, I915_READ(TSC1) | TSE);
7831
7832         /* 100ms RC evaluation intervals */
7833         I915_WRITE(RCUPEI, 100000);
7834         I915_WRITE(RCDNEI, 100000);
7835
7836         /* Set max/min thresholds to 90ms and 80ms respectively */
7837         I915_WRITE(RCBMAXAVG, 90000);
7838         I915_WRITE(RCBMINAVG, 80000);
7839
7840         I915_WRITE(MEMIHYST, 1);
7841
7842         /* Set up min, max, and cur for interrupt handling */
7843         fmax = (rgvmodectl & MEMMODE_FMAX_MASK) >> MEMMODE_FMAX_SHIFT;
7844         fmin = (rgvmodectl & MEMMODE_FMIN_MASK);
7845         fstart = (rgvmodectl & MEMMODE_FSTART_MASK) >>
7846                 MEMMODE_FSTART_SHIFT;
7847
7848         vstart = (I915_READ(PXVFREQ_BASE + (fstart * 4)) & PXVFREQ_PX_MASK) >>
7849                 PXVFREQ_PX_SHIFT;
7850
7851         dev_priv->fmax = fmax; /* IPS callback will increase this */
7852         dev_priv->fstart = fstart;
7853
7854         dev_priv->max_delay = fstart;
7855         dev_priv->min_delay = fmin;
7856         dev_priv->cur_delay = fstart;
7857
7858         DRM_DEBUG_DRIVER("fmax: %d, fmin: %d, fstart: %d\n",
7859                          fmax, fmin, fstart);
7860
7861         I915_WRITE(MEMINTREN, MEMINT_CX_SUPR_EN | MEMINT_EVAL_CHG_EN);
7862
7863         /*
7864          * Interrupts will be enabled in ironlake_irq_postinstall
7865          */
7866
7867         I915_WRITE(VIDSTART, vstart);
7868         POSTING_READ(VIDSTART);
7869
7870         rgvmodectl |= MEMMODE_SWMODE_EN;
7871         I915_WRITE(MEMMODECTL, rgvmodectl);
7872
7873         if (wait_for((I915_READ(MEMSWCTL) & MEMCTL_CMD_STS) == 0, 10))
7874                 DRM_ERROR("stuck trying to change perf mode\n");
7875         msleep(1);
7876
7877         ironlake_set_drps(dev, fstart);
7878
7879         dev_priv->last_count1 = I915_READ(0x112e4) + I915_READ(0x112e8) +
7880                 I915_READ(0x112e0);
7881         dev_priv->last_time1 = jiffies_to_msecs(jiffies);
7882         dev_priv->last_count2 = I915_READ(0x112f4);
7883         getrawmonotonic(&dev_priv->last_time2);
7884 }
7885
7886 void ironlake_disable_drps(struct drm_device *dev)
7887 {
7888         struct drm_i915_private *dev_priv = dev->dev_private;
7889         u16 rgvswctl = I915_READ16(MEMSWCTL);
7890
7891         /* Ack interrupts, disable EFC interrupt */
7892         I915_WRITE(MEMINTREN, I915_READ(MEMINTREN) & ~MEMINT_EVAL_CHG_EN);
7893         I915_WRITE(MEMINTRSTS, MEMINT_EVAL_CHG);
7894         I915_WRITE(DEIER, I915_READ(DEIER) & ~DE_PCU_EVENT);
7895         I915_WRITE(DEIIR, DE_PCU_EVENT);
7896         I915_WRITE(DEIMR, I915_READ(DEIMR) | DE_PCU_EVENT);
7897
7898         /* Go back to the starting frequency */
7899         ironlake_set_drps(dev, dev_priv->fstart);
7900         msleep(1);
7901         rgvswctl |= MEMCTL_CMD_STS;
7902         I915_WRITE(MEMSWCTL, rgvswctl);
7903         msleep(1);
7904
7905 }
7906
7907 void gen6_set_rps(struct drm_device *dev, u8 val)
7908 {
7909         struct drm_i915_private *dev_priv = dev->dev_private;
7910         u32 swreq;
7911
7912         swreq = (val & 0x3ff) << 25;
7913         I915_WRITE(GEN6_RPNSWREQ, swreq);
7914 }
7915
7916 void gen6_disable_rps(struct drm_device *dev)
7917 {
7918         struct drm_i915_private *dev_priv = dev->dev_private;
7919
7920         I915_WRITE(GEN6_RPNSWREQ, 1 << 31);
7921         I915_WRITE(GEN6_PMINTRMSK, 0xffffffff);
7922         I915_WRITE(GEN6_PMIER, 0);
7923         /* Complete PM interrupt masking here doesn't race with the rps work
7924          * item again unmasking PM interrupts because that is using a different
7925          * register (PMIMR) to mask PM interrupts. The only risk is in leaving
7926          * stale bits in PMIIR and PMIMR which gen6_enable_rps will clean up. */
7927
7928         spin_lock_irq(&dev_priv->rps_lock);
7929         dev_priv->pm_iir = 0;
7930         spin_unlock_irq(&dev_priv->rps_lock);
7931
7932         I915_WRITE(GEN6_PMIIR, I915_READ(GEN6_PMIIR));
7933 }
7934
7935 static unsigned long intel_pxfreq(u32 vidfreq)
7936 {
7937         unsigned long freq;
7938         int div = (vidfreq & 0x3f0000) >> 16;
7939         int post = (vidfreq & 0x3000) >> 12;
7940         int pre = (vidfreq & 0x7);
7941
7942         if (!pre)
7943                 return 0;
7944
7945         freq = ((div * 133333) / ((1<<post) * pre));
7946
7947         return freq;
7948 }
7949
7950 void intel_init_emon(struct drm_device *dev)
7951 {
7952         struct drm_i915_private *dev_priv = dev->dev_private;
7953         u32 lcfuse;
7954         u8 pxw[16];
7955         int i;
7956
7957         /* Disable to program */
7958         I915_WRITE(ECR, 0);
7959         POSTING_READ(ECR);
7960
7961         /* Program energy weights for various events */
7962         I915_WRITE(SDEW, 0x15040d00);
7963         I915_WRITE(CSIEW0, 0x007f0000);
7964         I915_WRITE(CSIEW1, 0x1e220004);
7965         I915_WRITE(CSIEW2, 0x04000004);
7966
7967         for (i = 0; i < 5; i++)
7968                 I915_WRITE(PEW + (i * 4), 0);
7969         for (i = 0; i < 3; i++)
7970                 I915_WRITE(DEW + (i * 4), 0);
7971
7972         /* Program P-state weights to account for frequency power adjustment */
7973         for (i = 0; i < 16; i++) {
7974                 u32 pxvidfreq = I915_READ(PXVFREQ_BASE + (i * 4));
7975                 unsigned long freq = intel_pxfreq(pxvidfreq);
7976                 unsigned long vid = (pxvidfreq & PXVFREQ_PX_MASK) >>
7977                         PXVFREQ_PX_SHIFT;
7978                 unsigned long val;
7979
7980                 val = vid * vid;
7981                 val *= (freq / 1000);
7982                 val *= 255;
7983                 val /= (127*127*900);
7984                 if (val > 0xff)
7985                         DRM_ERROR("bad pxval: %ld\n", val);
7986                 pxw[i] = val;
7987         }
7988         /* Render standby states get 0 weight */
7989         pxw[14] = 0;
7990         pxw[15] = 0;
7991
7992         for (i = 0; i < 4; i++) {
7993                 u32 val = (pxw[i*4] << 24) | (pxw[(i*4)+1] << 16) |
7994                         (pxw[(i*4)+2] << 8) | (pxw[(i*4)+3]);
7995                 I915_WRITE(PXW + (i * 4), val);
7996         }
7997
7998         /* Adjust magic regs to magic values (more experimental results) */
7999         I915_WRITE(OGW0, 0);
8000         I915_WRITE(OGW1, 0);
8001         I915_WRITE(EG0, 0x00007f00);
8002         I915_WRITE(EG1, 0x0000000e);
8003         I915_WRITE(EG2, 0x000e0000);
8004         I915_WRITE(EG3, 0x68000300);
8005         I915_WRITE(EG4, 0x42000000);
8006         I915_WRITE(EG5, 0x00140031);
8007         I915_WRITE(EG6, 0);
8008         I915_WRITE(EG7, 0);
8009
8010         for (i = 0; i < 8; i++)
8011                 I915_WRITE(PXWL + (i * 4), 0);
8012
8013         /* Enable PMON + select events */
8014         I915_WRITE(ECR, 0x80000019);
8015
8016         lcfuse = I915_READ(LCFUSE02);
8017
8018         dev_priv->corr = (lcfuse & LCFUSE_HIV_MASK);
8019 }
8020
8021 static bool intel_enable_rc6(struct drm_device *dev)
8022 {
8023         /*
8024          * Respect the kernel parameter if it is set
8025          */
8026         if (i915_enable_rc6 >= 0)
8027                 return i915_enable_rc6;
8028
8029         /*
8030          * Disable RC6 on Ironlake
8031          */
8032         if (INTEL_INFO(dev)->gen == 5)
8033                 return 0;
8034
8035         /*
8036          * Disable rc6 on Sandybridge
8037          */
8038         if (INTEL_INFO(dev)->gen == 6) {
8039                 DRM_DEBUG_DRIVER("Sandybridge: RC6 disabled\n");
8040                 return 0;
8041         }
8042         DRM_DEBUG_DRIVER("RC6 enabled\n");
8043         return 1;
8044 }
8045
8046 void gen6_enable_rps(struct drm_i915_private *dev_priv)
8047 {
8048         u32 rp_state_cap = I915_READ(GEN6_RP_STATE_CAP);
8049         u32 gt_perf_status = I915_READ(GEN6_GT_PERF_STATUS);
8050         u32 pcu_mbox, rc6_mask = 0;
8051         int cur_freq, min_freq, max_freq;
8052         int i;
8053
8054         /* Here begins a magic sequence of register writes to enable
8055          * auto-downclocking.
8056          *
8057          * Perhaps there might be some value in exposing these to
8058          * userspace...
8059          */
8060         I915_WRITE(GEN6_RC_STATE, 0);
8061         mutex_lock(&dev_priv->dev->struct_mutex);
8062         gen6_gt_force_wake_get(dev_priv);
8063
8064         /* disable the counters and set deterministic thresholds */
8065         I915_WRITE(GEN6_RC_CONTROL, 0);
8066
8067         I915_WRITE(GEN6_RC1_WAKE_RATE_LIMIT, 1000 << 16);
8068         I915_WRITE(GEN6_RC6_WAKE_RATE_LIMIT, 40 << 16 | 30);
8069         I915_WRITE(GEN6_RC6pp_WAKE_RATE_LIMIT, 30);
8070         I915_WRITE(GEN6_RC_EVALUATION_INTERVAL, 125000);
8071         I915_WRITE(GEN6_RC_IDLE_HYSTERSIS, 25);
8072
8073         for (i = 0; i < I915_NUM_RINGS; i++)
8074                 I915_WRITE(RING_MAX_IDLE(dev_priv->ring[i].mmio_base), 10);
8075
8076         I915_WRITE(GEN6_RC_SLEEP, 0);
8077         I915_WRITE(GEN6_RC1e_THRESHOLD, 1000);
8078         I915_WRITE(GEN6_RC6_THRESHOLD, 50000);
8079         I915_WRITE(GEN6_RC6p_THRESHOLD, 100000);
8080         I915_WRITE(GEN6_RC6pp_THRESHOLD, 64000); /* unused */
8081
8082         if (intel_enable_rc6(dev_priv->dev))
8083                 rc6_mask = GEN6_RC_CTL_RC6_ENABLE |
8084                         ((IS_GEN7(dev_priv->dev)) ? GEN6_RC_CTL_RC6p_ENABLE : 0);
8085
8086         I915_WRITE(GEN6_RC_CONTROL,
8087                    rc6_mask |
8088                    GEN6_RC_CTL_EI_MODE(1) |
8089                    GEN6_RC_CTL_HW_ENABLE);
8090
8091         I915_WRITE(GEN6_RPNSWREQ,
8092                    GEN6_FREQUENCY(10) |
8093                    GEN6_OFFSET(0) |
8094                    GEN6_AGGRESSIVE_TURBO);
8095         I915_WRITE(GEN6_RC_VIDEO_FREQ,
8096                    GEN6_FREQUENCY(12));
8097
8098         I915_WRITE(GEN6_RP_DOWN_TIMEOUT, 1000000);
8099         I915_WRITE(GEN6_RP_INTERRUPT_LIMITS,
8100                    18 << 24 |
8101                    6 << 16);
8102         I915_WRITE(GEN6_RP_UP_THRESHOLD, 10000);
8103         I915_WRITE(GEN6_RP_DOWN_THRESHOLD, 1000000);
8104         I915_WRITE(GEN6_RP_UP_EI, 100000);
8105         I915_WRITE(GEN6_RP_DOWN_EI, 5000000);
8106         I915_WRITE(GEN6_RP_IDLE_HYSTERSIS, 10);
8107         I915_WRITE(GEN6_RP_CONTROL,
8108                    GEN6_RP_MEDIA_TURBO |
8109                    GEN6_RP_MEDIA_HW_NORMAL_MODE |
8110                    GEN6_RP_MEDIA_IS_GFX |
8111                    GEN6_RP_ENABLE |
8112                    GEN6_RP_UP_BUSY_AVG |
8113                    GEN6_RP_DOWN_IDLE_CONT);
8114
8115         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
8116                      500))
8117                 DRM_ERROR("timeout waiting for pcode mailbox to become idle\n");
8118
8119         I915_WRITE(GEN6_PCODE_DATA, 0);
8120         I915_WRITE(GEN6_PCODE_MAILBOX,
8121                    GEN6_PCODE_READY |
8122                    GEN6_PCODE_WRITE_MIN_FREQ_TABLE);
8123         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
8124                      500))
8125                 DRM_ERROR("timeout waiting for pcode mailbox to finish\n");
8126
8127         min_freq = (rp_state_cap & 0xff0000) >> 16;
8128         max_freq = rp_state_cap & 0xff;
8129         cur_freq = (gt_perf_status & 0xff00) >> 8;
8130
8131         /* Check for overclock support */
8132         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
8133                      500))
8134                 DRM_ERROR("timeout waiting for pcode mailbox to become idle\n");
8135         I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_READ_OC_PARAMS);
8136         pcu_mbox = I915_READ(GEN6_PCODE_DATA);
8137         if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY) == 0,
8138                      500))
8139                 DRM_ERROR("timeout waiting for pcode mailbox to finish\n");
8140         if (pcu_mbox & (1<<31)) { /* OC supported */
8141                 max_freq = pcu_mbox & 0xff;
8142                 DRM_DEBUG_DRIVER("overclocking supported, adjusting frequency max to %dMHz\n", pcu_mbox * 50);
8143         }
8144
8145         /* In units of 100MHz */
8146         dev_priv->max_delay = max_freq;
8147         dev_priv->min_delay = min_freq;
8148         dev_priv->cur_delay = cur_freq;
8149
8150         /* requires MSI enabled */
8151         I915_WRITE(GEN6_PMIER,
8152                    GEN6_PM_MBOX_EVENT |
8153                    GEN6_PM_THERMAL_EVENT |
8154                    GEN6_PM_RP_DOWN_TIMEOUT |
8155                    GEN6_PM_RP_UP_THRESHOLD |
8156                    GEN6_PM_RP_DOWN_THRESHOLD |
8157                    GEN6_PM_RP_UP_EI_EXPIRED |
8158                    GEN6_PM_RP_DOWN_EI_EXPIRED);
8159         spin_lock_irq(&dev_priv->rps_lock);
8160         WARN_ON(dev_priv->pm_iir != 0);
8161         I915_WRITE(GEN6_PMIMR, 0);
8162         spin_unlock_irq(&dev_priv->rps_lock);
8163         /* enable all PM interrupts */
8164         I915_WRITE(GEN6_PMINTRMSK, 0);
8165
8166         gen6_gt_force_wake_put(dev_priv);
8167         mutex_unlock(&dev_priv->dev->struct_mutex);
8168 }
8169
8170 void gen6_update_ring_freq(struct drm_i915_private *dev_priv)
8171 {
8172         int min_freq = 15;
8173         int gpu_freq, ia_freq, max_ia_freq;
8174         int scaling_factor = 180;
8175
8176         max_ia_freq = cpufreq_quick_get_max(0);
8177         /*
8178          * Default to measured freq if none found, PCU will ensure we don't go
8179          * over
8180          */
8181         if (!max_ia_freq)
8182                 max_ia_freq = tsc_khz;
8183
8184         /* Convert from kHz to MHz */
8185         max_ia_freq /= 1000;
8186
8187         mutex_lock(&dev_priv->dev->struct_mutex);
8188
8189         /*
8190          * For each potential GPU frequency, load a ring frequency we'd like
8191          * to use for memory access.  We do this by specifying the IA frequency
8192          * the PCU should use as a reference to determine the ring frequency.
8193          */
8194         for (gpu_freq = dev_priv->max_delay; gpu_freq >= dev_priv->min_delay;
8195              gpu_freq--) {
8196                 int diff = dev_priv->max_delay - gpu_freq;
8197
8198                 /*
8199                  * For GPU frequencies less than 750MHz, just use the lowest
8200                  * ring freq.
8201                  */
8202                 if (gpu_freq < min_freq)
8203                         ia_freq = 800;
8204                 else
8205                         ia_freq = max_ia_freq - ((diff * scaling_factor) / 2);
8206                 ia_freq = DIV_ROUND_CLOSEST(ia_freq, 100);
8207
8208                 I915_WRITE(GEN6_PCODE_DATA,
8209                            (ia_freq << GEN6_PCODE_FREQ_IA_RATIO_SHIFT) |
8210                            gpu_freq);
8211                 I915_WRITE(GEN6_PCODE_MAILBOX, GEN6_PCODE_READY |
8212                            GEN6_PCODE_WRITE_MIN_FREQ_TABLE);
8213                 if (wait_for((I915_READ(GEN6_PCODE_MAILBOX) &
8214                               GEN6_PCODE_READY) == 0, 10)) {
8215                         DRM_ERROR("pcode write of freq table timed out\n");
8216                         continue;
8217                 }
8218         }
8219
8220         mutex_unlock(&dev_priv->dev->struct_mutex);
8221 }
8222
8223 static void ironlake_init_clock_gating(struct drm_device *dev)
8224 {
8225         struct drm_i915_private *dev_priv = dev->dev_private;
8226         uint32_t dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE;
8227
8228         /* Required for FBC */
8229         dspclk_gate |= DPFCUNIT_CLOCK_GATE_DISABLE |
8230                 DPFCRUNIT_CLOCK_GATE_DISABLE |
8231                 DPFDUNIT_CLOCK_GATE_DISABLE;
8232         /* Required for CxSR */
8233         dspclk_gate |= DPARBUNIT_CLOCK_GATE_DISABLE;
8234
8235         I915_WRITE(PCH_3DCGDIS0,
8236                    MARIUNIT_CLOCK_GATE_DISABLE |
8237                    SVSMUNIT_CLOCK_GATE_DISABLE);
8238         I915_WRITE(PCH_3DCGDIS1,
8239                    VFMUNIT_CLOCK_GATE_DISABLE);
8240
8241         I915_WRITE(PCH_DSPCLK_GATE_D, dspclk_gate);
8242
8243         /*
8244          * According to the spec the following bits should be set in
8245          * order to enable memory self-refresh
8246          * The bit 22/21 of 0x42004
8247          * The bit 5 of 0x42020
8248          * The bit 15 of 0x45000
8249          */
8250         I915_WRITE(ILK_DISPLAY_CHICKEN2,
8251                    (I915_READ(ILK_DISPLAY_CHICKEN2) |
8252                     ILK_DPARB_GATE | ILK_VSDPFD_FULL));
8253         I915_WRITE(ILK_DSPCLK_GATE,
8254                    (I915_READ(ILK_DSPCLK_GATE) |
8255                     ILK_DPARB_CLK_GATE));
8256         I915_WRITE(DISP_ARB_CTL,
8257                    (I915_READ(DISP_ARB_CTL) |
8258                     DISP_FBC_WM_DIS));
8259         I915_WRITE(WM3_LP_ILK, 0);
8260         I915_WRITE(WM2_LP_ILK, 0);
8261         I915_WRITE(WM1_LP_ILK, 0);
8262
8263         /*
8264          * Based on the document from hardware guys the following bits
8265          * should be set unconditionally in order to enable FBC.
8266          * The bit 22 of 0x42000
8267          * The bit 22 of 0x42004
8268          * The bit 7,8,9 of 0x42020.
8269          */
8270         if (IS_IRONLAKE_M(dev)) {
8271                 I915_WRITE(ILK_DISPLAY_CHICKEN1,
8272                            I915_READ(ILK_DISPLAY_CHICKEN1) |
8273                            ILK_FBCQ_DIS);
8274                 I915_WRITE(ILK_DISPLAY_CHICKEN2,
8275                            I915_READ(ILK_DISPLAY_CHICKEN2) |
8276                            ILK_DPARB_GATE);
8277                 I915_WRITE(ILK_DSPCLK_GATE,
8278                            I915_READ(ILK_DSPCLK_GATE) |
8279                            ILK_DPFC_DIS1 |
8280                            ILK_DPFC_DIS2 |
8281                            ILK_CLK_FBC);
8282         }
8283
8284         I915_WRITE(ILK_DISPLAY_CHICKEN2,
8285                    I915_READ(ILK_DISPLAY_CHICKEN2) |
8286                    ILK_ELPIN_409_SELECT);
8287         I915_WRITE(_3D_CHICKEN2,
8288                    _3D_CHICKEN2_WM_READ_PIPELINED << 16 |
8289                    _3D_CHICKEN2_WM_READ_PIPELINED);
8290 }
8291
8292 static void gen6_init_clock_gating(struct drm_device *dev)
8293 {
8294         struct drm_i915_private *dev_priv = dev->dev_private;
8295         int pipe;
8296         uint32_t dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE;
8297
8298         I915_WRITE(PCH_DSPCLK_GATE_D, dspclk_gate);
8299
8300         I915_WRITE(ILK_DISPLAY_CHICKEN2,
8301                    I915_READ(ILK_DISPLAY_CHICKEN2) |
8302                    ILK_ELPIN_409_SELECT);
8303
8304         I915_WRITE(WM3_LP_ILK, 0);
8305         I915_WRITE(WM2_LP_ILK, 0);
8306         I915_WRITE(WM1_LP_ILK, 0);
8307
8308         /* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
8309          * gating disable must be set.  Failure to set it results in
8310          * flickering pixels due to Z write ordering failures after
8311          * some amount of runtime in the Mesa "fire" demo, and Unigine
8312          * Sanctuary and Tropics, and apparently anything else with
8313          * alpha test or pixel discard.
8314          *
8315          * According to the spec, bit 11 (RCCUNIT) must also be set,
8316          * but we didn't debug actual testcases to find it out.
8317          */
8318         I915_WRITE(GEN6_UCGCTL2,
8319                    GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
8320                    GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
8321
8322         /*
8323          * According to the spec the following bits should be
8324          * set in order to enable memory self-refresh and fbc:
8325          * The bit21 and bit22 of 0x42000
8326          * The bit21 and bit22 of 0x42004
8327          * The bit5 and bit7 of 0x42020
8328          * The bit14 of 0x70180
8329          * The bit14 of 0x71180
8330          */
8331         I915_WRITE(ILK_DISPLAY_CHICKEN1,
8332                    I915_READ(ILK_DISPLAY_CHICKEN1) |
8333                    ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
8334         I915_WRITE(ILK_DISPLAY_CHICKEN2,
8335                    I915_READ(ILK_DISPLAY_CHICKEN2) |
8336                    ILK_DPARB_GATE | ILK_VSDPFD_FULL);
8337         I915_WRITE(ILK_DSPCLK_GATE,
8338                    I915_READ(ILK_DSPCLK_GATE) |
8339                    ILK_DPARB_CLK_GATE  |
8340                    ILK_DPFD_CLK_GATE);
8341
8342         for_each_pipe(pipe) {
8343                 I915_WRITE(DSPCNTR(pipe),
8344                            I915_READ(DSPCNTR(pipe)) |
8345                            DISPPLANE_TRICKLE_FEED_DISABLE);
8346                 intel_flush_display_plane(dev_priv, pipe);
8347         }
8348
8349         /* The default value should be 0x200 according to docs, but the two
8350          * platforms I checked have a 0 for this. (Maybe BIOS overrides?) */
8351         I915_WRITE(GEN6_GT_MODE, 0xffff << 16);
8352         I915_WRITE(GEN6_GT_MODE, GEN6_GT_MODE_HI << 16 | GEN6_GT_MODE_HI);
8353 }
8354
8355 static void gen7_setup_fixed_func_scheduler(struct drm_i915_private *dev_priv)
8356 {
8357         uint32_t reg = I915_READ(GEN7_FF_THREAD_MODE);
8358
8359         reg &= ~GEN7_FF_SCHED_MASK;
8360         reg |= GEN7_FF_TS_SCHED_HW;
8361         reg |= GEN7_FF_VS_SCHED_HW;
8362         reg |= GEN7_FF_DS_SCHED_HW;
8363
8364         I915_WRITE(GEN7_FF_THREAD_MODE, reg);
8365 }
8366
8367 static void ivybridge_init_clock_gating(struct drm_device *dev)
8368 {
8369         struct drm_i915_private *dev_priv = dev->dev_private;
8370         int pipe;
8371         uint32_t dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE;
8372
8373         I915_WRITE(PCH_DSPCLK_GATE_D, dspclk_gate);
8374
8375         I915_WRITE(WM3_LP_ILK, 0);
8376         I915_WRITE(WM2_LP_ILK, 0);
8377         I915_WRITE(WM1_LP_ILK, 0);
8378
8379         /* According to the spec, bit 13 (RCZUNIT) must be set on IVB.
8380          * This implements the WaDisableRCZUnitClockGating workaround.
8381          */
8382         I915_WRITE(GEN6_UCGCTL2, GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
8383
8384         I915_WRITE(ILK_DSPCLK_GATE, IVB_VRHUNIT_CLK_GATE);
8385
8386         /* Apply the WaDisableRHWOOptimizationForRenderHang workaround. */
8387         I915_WRITE(GEN7_COMMON_SLICE_CHICKEN1,
8388                    GEN7_CSC1_RHWO_OPT_DISABLE_IN_RCC);
8389
8390         /* WaApplyL3ControlAndL3ChickenMode requires those two on Ivy Bridge */
8391         I915_WRITE(GEN7_L3CNTLREG1,
8392                         GEN7_WA_FOR_GEN7_L3_CONTROL);
8393         I915_WRITE(GEN7_L3_CHICKEN_MODE_REGISTER,
8394                         GEN7_WA_L3_CHICKEN_MODE);
8395
8396         /* This is required by WaCatErrorRejectionIssue */
8397         I915_WRITE(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
8398                         I915_READ(GEN7_SQ_CHICKEN_MBCUNIT_CONFIG) |
8399                         GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
8400
8401         for_each_pipe(pipe) {
8402                 I915_WRITE(DSPCNTR(pipe),
8403                            I915_READ(DSPCNTR(pipe)) |
8404                            DISPPLANE_TRICKLE_FEED_DISABLE);
8405                 intel_flush_display_plane(dev_priv, pipe);
8406         }
8407
8408         gen7_setup_fixed_func_scheduler(dev_priv);
8409 }
8410
8411 static void g4x_init_clock_gating(struct drm_device *dev)
8412 {
8413         struct drm_i915_private *dev_priv = dev->dev_private;
8414         uint32_t dspclk_gate;
8415
8416         I915_WRITE(RENCLK_GATE_D1, 0);
8417         I915_WRITE(RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
8418                    GS_UNIT_CLOCK_GATE_DISABLE |
8419                    CL_UNIT_CLOCK_GATE_DISABLE);
8420         I915_WRITE(RAMCLK_GATE_D, 0);
8421         dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
8422                 OVRUNIT_CLOCK_GATE_DISABLE |
8423                 OVCUNIT_CLOCK_GATE_DISABLE;
8424         if (IS_GM45(dev))
8425                 dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
8426         I915_WRITE(DSPCLK_GATE_D, dspclk_gate);
8427 }
8428
8429 static void crestline_init_clock_gating(struct drm_device *dev)
8430 {
8431         struct drm_i915_private *dev_priv = dev->dev_private;
8432
8433         I915_WRITE(RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
8434         I915_WRITE(RENCLK_GATE_D2, 0);
8435         I915_WRITE(DSPCLK_GATE_D, 0);
8436         I915_WRITE(RAMCLK_GATE_D, 0);
8437         I915_WRITE16(DEUC, 0);
8438 }
8439
8440 static void broadwater_init_clock_gating(struct drm_device *dev)
8441 {
8442         struct drm_i915_private *dev_priv = dev->dev_private;
8443
8444         I915_WRITE(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
8445                    I965_RCC_CLOCK_GATE_DISABLE |
8446                    I965_RCPB_CLOCK_GATE_DISABLE |
8447                    I965_ISC_CLOCK_GATE_DISABLE |
8448                    I965_FBC_CLOCK_GATE_DISABLE);
8449         I915_WRITE(RENCLK_GATE_D2, 0);
8450 }
8451
8452 static void gen3_init_clock_gating(struct drm_device *dev)
8453 {
8454         struct drm_i915_private *dev_priv = dev->dev_private;
8455         u32 dstate = I915_READ(D_STATE);
8456
8457         dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
8458                 DSTATE_DOT_CLOCK_GATING;
8459         I915_WRITE(D_STATE, dstate);
8460 }
8461
8462 static void i85x_init_clock_gating(struct drm_device *dev)
8463 {
8464         struct drm_i915_private *dev_priv = dev->dev_private;
8465
8466         I915_WRITE(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
8467 }
8468
8469 static void i830_init_clock_gating(struct drm_device *dev)
8470 {
8471         struct drm_i915_private *dev_priv = dev->dev_private;
8472
8473         I915_WRITE(DSPCLK_GATE_D, OVRUNIT_CLOCK_GATE_DISABLE);
8474 }
8475
8476 static void ibx_init_clock_gating(struct drm_device *dev)
8477 {
8478         struct drm_i915_private *dev_priv = dev->dev_private;
8479
8480         /*
8481          * On Ibex Peak and Cougar Point, we need to disable clock
8482          * gating for the panel power sequencer or it will fail to
8483          * start up when no ports are active.
8484          */
8485         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
8486 }
8487
8488 static void cpt_init_clock_gating(struct drm_device *dev)
8489 {
8490         struct drm_i915_private *dev_priv = dev->dev_private;
8491         int pipe;
8492
8493         /*
8494          * On Ibex Peak and Cougar Point, we need to disable clock
8495          * gating for the panel power sequencer or it will fail to
8496          * start up when no ports are active.
8497          */
8498         I915_WRITE(SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
8499         I915_WRITE(SOUTH_CHICKEN2, I915_READ(SOUTH_CHICKEN2) |
8500                    DPLS_EDP_PPS_FIX_DIS);
8501         /* Without this, mode sets may fail silently on FDI */
8502         for_each_pipe(pipe)
8503                 I915_WRITE(TRANS_CHICKEN2(pipe), TRANS_AUTOTRAIN_GEN_STALL_DIS);
8504 }
8505
8506 static void ironlake_teardown_rc6(struct drm_device *dev)
8507 {
8508         struct drm_i915_private *dev_priv = dev->dev_private;
8509
8510         if (dev_priv->renderctx) {
8511                 i915_gem_object_unpin(dev_priv->renderctx);
8512                 drm_gem_object_unreference(&dev_priv->renderctx->base);
8513                 dev_priv->renderctx = NULL;
8514         }
8515
8516         if (dev_priv->pwrctx) {
8517                 i915_gem_object_unpin(dev_priv->pwrctx);
8518                 drm_gem_object_unreference(&dev_priv->pwrctx->base);
8519                 dev_priv->pwrctx = NULL;
8520         }
8521 }
8522
8523 static void ironlake_disable_rc6(struct drm_device *dev)
8524 {
8525         struct drm_i915_private *dev_priv = dev->dev_private;
8526
8527         if (I915_READ(PWRCTXA)) {
8528                 /* Wake the GPU, prevent RC6, then restore RSTDBYCTL */
8529                 I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) | RCX_SW_EXIT);
8530                 wait_for(((I915_READ(RSTDBYCTL) & RSX_STATUS_MASK) == RSX_STATUS_ON),
8531                          50);
8532
8533                 I915_WRITE(PWRCTXA, 0);
8534                 POSTING_READ(PWRCTXA);
8535
8536                 I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) & ~RCX_SW_EXIT);
8537                 POSTING_READ(RSTDBYCTL);
8538         }
8539
8540         ironlake_teardown_rc6(dev);
8541 }
8542
8543 static int ironlake_setup_rc6(struct drm_device *dev)
8544 {
8545         struct drm_i915_private *dev_priv = dev->dev_private;
8546
8547         if (dev_priv->renderctx == NULL)
8548                 dev_priv->renderctx = intel_alloc_context_page(dev);
8549         if (!dev_priv->renderctx)
8550                 return -ENOMEM;
8551
8552         if (dev_priv->pwrctx == NULL)
8553                 dev_priv->pwrctx = intel_alloc_context_page(dev);
8554         if (!dev_priv->pwrctx) {
8555                 ironlake_teardown_rc6(dev);
8556                 return -ENOMEM;
8557         }
8558
8559         return 0;
8560 }
8561
8562 void ironlake_enable_rc6(struct drm_device *dev)
8563 {
8564         struct drm_i915_private *dev_priv = dev->dev_private;
8565         int ret;
8566
8567         /* rc6 disabled by default due to repeated reports of hanging during
8568          * boot and resume.
8569          */
8570         if (!intel_enable_rc6(dev))
8571                 return;
8572
8573         mutex_lock(&dev->struct_mutex);
8574         ret = ironlake_setup_rc6(dev);
8575         if (ret) {
8576                 mutex_unlock(&dev->struct_mutex);
8577                 return;
8578         }
8579
8580         /*
8581          * GPU can automatically power down the render unit if given a page
8582          * to save state.
8583          */
8584         ret = BEGIN_LP_RING(6);
8585         if (ret) {
8586                 ironlake_teardown_rc6(dev);
8587                 mutex_unlock(&dev->struct_mutex);
8588                 return;
8589         }
8590
8591         OUT_RING(MI_SUSPEND_FLUSH | MI_SUSPEND_FLUSH_EN);
8592         OUT_RING(MI_SET_CONTEXT);
8593         OUT_RING(dev_priv->renderctx->gtt_offset |
8594                  MI_MM_SPACE_GTT |
8595                  MI_SAVE_EXT_STATE_EN |
8596                  MI_RESTORE_EXT_STATE_EN |
8597                  MI_RESTORE_INHIBIT);
8598         OUT_RING(MI_SUSPEND_FLUSH);
8599         OUT_RING(MI_NOOP);
8600         OUT_RING(MI_FLUSH);
8601         ADVANCE_LP_RING();
8602
8603         /*
8604          * Wait for the command parser to advance past MI_SET_CONTEXT. The HW
8605          * does an implicit flush, combined with MI_FLUSH above, it should be
8606          * safe to assume that renderctx is valid
8607          */
8608         ret = intel_wait_ring_idle(LP_RING(dev_priv));
8609         if (ret) {
8610                 DRM_ERROR("failed to enable ironlake power power savings\n");
8611                 ironlake_teardown_rc6(dev);
8612                 mutex_unlock(&dev->struct_mutex);
8613                 return;
8614         }
8615
8616         I915_WRITE(PWRCTXA, dev_priv->pwrctx->gtt_offset | PWRCTX_EN);
8617         I915_WRITE(RSTDBYCTL, I915_READ(RSTDBYCTL) & ~RCX_SW_EXIT);
8618         mutex_unlock(&dev->struct_mutex);
8619 }
8620
8621 void intel_init_clock_gating(struct drm_device *dev)
8622 {
8623         struct drm_i915_private *dev_priv = dev->dev_private;
8624
8625         dev_priv->display.init_clock_gating(dev);
8626
8627         if (dev_priv->display.init_pch_clock_gating)
8628                 dev_priv->display.init_pch_clock_gating(dev);
8629 }
8630
8631 /* Set up chip specific display functions */
8632 static void intel_init_display(struct drm_device *dev)
8633 {
8634         struct drm_i915_private *dev_priv = dev->dev_private;
8635
8636         /* We always want a DPMS function */
8637         if (HAS_PCH_SPLIT(dev)) {
8638                 dev_priv->display.dpms = ironlake_crtc_dpms;
8639                 dev_priv->display.crtc_mode_set = ironlake_crtc_mode_set;
8640                 dev_priv->display.update_plane = ironlake_update_plane;
8641         } else {
8642                 dev_priv->display.dpms = i9xx_crtc_dpms;
8643                 dev_priv->display.crtc_mode_set = i9xx_crtc_mode_set;
8644                 dev_priv->display.update_plane = i9xx_update_plane;
8645         }
8646
8647         if (I915_HAS_FBC(dev)) {
8648                 if (HAS_PCH_SPLIT(dev)) {
8649                         dev_priv->display.fbc_enabled = ironlake_fbc_enabled;
8650                         dev_priv->display.enable_fbc = ironlake_enable_fbc;
8651                         dev_priv->display.disable_fbc = ironlake_disable_fbc;
8652                 } else if (IS_GM45(dev)) {
8653                         dev_priv->display.fbc_enabled = g4x_fbc_enabled;
8654                         dev_priv->display.enable_fbc = g4x_enable_fbc;
8655                         dev_priv->display.disable_fbc = g4x_disable_fbc;
8656                 } else if (IS_CRESTLINE(dev)) {
8657                         dev_priv->display.fbc_enabled = i8xx_fbc_enabled;
8658                         dev_priv->display.enable_fbc = i8xx_enable_fbc;
8659                         dev_priv->display.disable_fbc = i8xx_disable_fbc;
8660                 }
8661                 /* 855GM needs testing */
8662         }
8663
8664         /* Returns the core display clock speed */
8665         if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
8666                 dev_priv->display.get_display_clock_speed =
8667                         i945_get_display_clock_speed;
8668         else if (IS_I915G(dev))
8669                 dev_priv->display.get_display_clock_speed =
8670                         i915_get_display_clock_speed;
8671         else if (IS_I945GM(dev) || IS_845G(dev) || IS_PINEVIEW_M(dev))
8672                 dev_priv->display.get_display_clock_speed =
8673                         i9xx_misc_get_display_clock_speed;
8674         else if (IS_I915GM(dev))
8675                 dev_priv->display.get_display_clock_speed =
8676                         i915gm_get_display_clock_speed;
8677         else if (IS_I865G(dev))
8678                 dev_priv->display.get_display_clock_speed =
8679                         i865_get_display_clock_speed;
8680         else if (IS_I85X(dev))
8681                 dev_priv->display.get_display_clock_speed =
8682                         i855_get_display_clock_speed;
8683         else /* 852, 830 */
8684                 dev_priv->display.get_display_clock_speed =
8685                         i830_get_display_clock_speed;
8686
8687         /* For FIFO watermark updates */
8688         if (HAS_PCH_SPLIT(dev)) {
8689                 dev_priv->display.force_wake_get = __gen6_gt_force_wake_get;
8690                 dev_priv->display.force_wake_put = __gen6_gt_force_wake_put;
8691
8692                 /* IVB configs may use multi-threaded forcewake */
8693                 if (IS_IVYBRIDGE(dev)) {
8694                         u32     ecobus;
8695
8696                         mutex_lock(&dev->struct_mutex);
8697                         __gen6_gt_force_wake_mt_get(dev_priv);
8698                         ecobus = I915_READ(ECOBUS);
8699                         __gen6_gt_force_wake_mt_put(dev_priv);
8700                         mutex_unlock(&dev->struct_mutex);
8701
8702                         if (ecobus & FORCEWAKE_MT_ENABLE) {
8703                                 DRM_DEBUG_KMS("Using MT version of forcewake\n");
8704                                 dev_priv->display.force_wake_get =
8705                                         __gen6_gt_force_wake_mt_get;
8706                                 dev_priv->display.force_wake_put =
8707                                         __gen6_gt_force_wake_mt_put;
8708                         }
8709                 }
8710
8711                 if (HAS_PCH_IBX(dev))
8712                         dev_priv->display.init_pch_clock_gating = ibx_init_clock_gating;
8713                 else if (HAS_PCH_CPT(dev))
8714                         dev_priv->display.init_pch_clock_gating = cpt_init_clock_gating;
8715
8716                 if (IS_GEN5(dev)) {
8717                         if (I915_READ(MLTR_ILK) & ILK_SRLT_MASK)
8718                                 dev_priv->display.update_wm = ironlake_update_wm;
8719                         else {
8720                                 DRM_DEBUG_KMS("Failed to get proper latency. "
8721                                               "Disable CxSR\n");
8722                                 dev_priv->display.update_wm = NULL;
8723                         }
8724                         dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
8725                         dev_priv->display.init_clock_gating = ironlake_init_clock_gating;
8726                         dev_priv->display.write_eld = ironlake_write_eld;
8727                 } else if (IS_GEN6(dev)) {
8728                         if (SNB_READ_WM0_LATENCY()) {
8729                                 dev_priv->display.update_wm = sandybridge_update_wm;
8730                         } else {
8731                                 DRM_DEBUG_KMS("Failed to read display plane latency. "
8732                                               "Disable CxSR\n");
8733                                 dev_priv->display.update_wm = NULL;
8734                         }
8735                         dev_priv->display.fdi_link_train = gen6_fdi_link_train;
8736                         dev_priv->display.init_clock_gating = gen6_init_clock_gating;
8737                         dev_priv->display.write_eld = ironlake_write_eld;
8738                 } else if (IS_IVYBRIDGE(dev)) {
8739                         /* FIXME: detect B0+ stepping and use auto training */
8740                         dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
8741                         if (SNB_READ_WM0_LATENCY()) {
8742                                 dev_priv->display.update_wm = sandybridge_update_wm;
8743                         } else {
8744                                 DRM_DEBUG_KMS("Failed to read display plane latency. "
8745                                               "Disable CxSR\n");
8746                                 dev_priv->display.update_wm = NULL;
8747                         }
8748                         dev_priv->display.init_clock_gating = ivybridge_init_clock_gating;
8749                         dev_priv->display.write_eld = ironlake_write_eld;
8750                 } else
8751                         dev_priv->display.update_wm = NULL;
8752         } else if (IS_PINEVIEW(dev)) {
8753                 if (!intel_get_cxsr_latency(IS_PINEVIEW_G(dev),
8754                                             dev_priv->is_ddr3,
8755                                             dev_priv->fsb_freq,
8756                                             dev_priv->mem_freq)) {
8757                         DRM_INFO("failed to find known CxSR latency "
8758                                  "(found ddr%s fsb freq %d, mem freq %d), "
8759                                  "disabling CxSR\n",
8760                                  (dev_priv->is_ddr3 == 1) ? "3" : "2",
8761                                  dev_priv->fsb_freq, dev_priv->mem_freq);
8762                         /* Disable CxSR and never update its watermark again */
8763                         pineview_disable_cxsr(dev);
8764                         dev_priv->display.update_wm = NULL;
8765                 } else
8766                         dev_priv->display.update_wm = pineview_update_wm;
8767                 dev_priv->display.init_clock_gating = gen3_init_clock_gating;
8768         } else if (IS_G4X(dev)) {
8769                 dev_priv->display.write_eld = g4x_write_eld;
8770                 dev_priv->display.update_wm = g4x_update_wm;
8771                 dev_priv->display.init_clock_gating = g4x_init_clock_gating;
8772         } else if (IS_GEN4(dev)) {
8773                 dev_priv->display.update_wm = i965_update_wm;
8774                 if (IS_CRESTLINE(dev))
8775                         dev_priv->display.init_clock_gating = crestline_init_clock_gating;
8776                 else if (IS_BROADWATER(dev))
8777                         dev_priv->display.init_clock_gating = broadwater_init_clock_gating;
8778         } else if (IS_GEN3(dev)) {
8779                 dev_priv->display.update_wm = i9xx_update_wm;
8780                 dev_priv->display.get_fifo_size = i9xx_get_fifo_size;
8781                 dev_priv->display.init_clock_gating = gen3_init_clock_gating;
8782         } else if (IS_I865G(dev)) {
8783                 dev_priv->display.update_wm = i830_update_wm;
8784                 dev_priv->display.init_clock_gating = i85x_init_clock_gating;
8785                 dev_priv->display.get_fifo_size = i830_get_fifo_size;
8786         } else if (IS_I85X(dev)) {
8787                 dev_priv->display.update_wm = i9xx_update_wm;
8788                 dev_priv->display.get_fifo_size = i85x_get_fifo_size;
8789                 dev_priv->display.init_clock_gating = i85x_init_clock_gating;
8790         } else {
8791                 dev_priv->display.update_wm = i830_update_wm;
8792                 dev_priv->display.init_clock_gating = i830_init_clock_gating;
8793                 if (IS_845G(dev))
8794                         dev_priv->display.get_fifo_size = i845_get_fifo_size;
8795                 else
8796                         dev_priv->display.get_fifo_size = i830_get_fifo_size;
8797         }
8798
8799         /* Default just returns -ENODEV to indicate unsupported */
8800         dev_priv->display.queue_flip = intel_default_queue_flip;
8801
8802         switch (INTEL_INFO(dev)->gen) {
8803         case 2:
8804                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
8805                 break;
8806
8807         case 3:
8808                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
8809                 break;
8810
8811         case 4:
8812         case 5:
8813                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
8814                 break;
8815
8816         case 6:
8817                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
8818                 break;
8819         case 7:
8820                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
8821                 break;
8822         }
8823 }
8824
8825 /*
8826  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
8827  * resume, or other times.  This quirk makes sure that's the case for
8828  * affected systems.
8829  */
8830 static void quirk_pipea_force(struct drm_device *dev)
8831 {
8832         struct drm_i915_private *dev_priv = dev->dev_private;
8833
8834         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
8835         DRM_DEBUG_DRIVER("applying pipe a force quirk\n");
8836 }
8837
8838 /*
8839  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
8840  */
8841 static void quirk_ssc_force_disable(struct drm_device *dev)
8842 {
8843         struct drm_i915_private *dev_priv = dev->dev_private;
8844         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
8845 }
8846
8847 struct intel_quirk {
8848         int device;
8849         int subsystem_vendor;
8850         int subsystem_device;
8851         void (*hook)(struct drm_device *dev);
8852 };
8853
8854 struct intel_quirk intel_quirks[] = {
8855         /* HP Compaq 2730p needs pipe A force quirk (LP: #291555) */
8856         { 0x2a42, 0x103c, 0x30eb, quirk_pipea_force },
8857         /* HP Mini needs pipe A force quirk (LP: #322104) */
8858         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
8859
8860         /* Thinkpad R31 needs pipe A force quirk */
8861         { 0x3577, 0x1014, 0x0505, quirk_pipea_force },
8862         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
8863         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
8864
8865         /* ThinkPad X30 needs pipe A force quirk (LP: #304614) */
8866         { 0x3577,  0x1014, 0x0513, quirk_pipea_force },
8867         /* ThinkPad X40 needs pipe A force quirk */
8868
8869         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
8870         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
8871
8872         /* 855 & before need to leave pipe A & dpll A up */
8873         { 0x3582, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
8874         { 0x2562, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
8875
8876         /* Lenovo U160 cannot use SSC on LVDS */
8877         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
8878
8879         /* Sony Vaio Y cannot use SSC on LVDS */
8880         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
8881 };
8882
8883 static void intel_init_quirks(struct drm_device *dev)
8884 {
8885         struct pci_dev *d = dev->pdev;
8886         int i;
8887
8888         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
8889                 struct intel_quirk *q = &intel_quirks[i];
8890
8891                 if (d->device == q->device &&
8892                     (d->subsystem_vendor == q->subsystem_vendor ||
8893                      q->subsystem_vendor == PCI_ANY_ID) &&
8894                     (d->subsystem_device == q->subsystem_device ||
8895                      q->subsystem_device == PCI_ANY_ID))
8896                         q->hook(dev);
8897         }
8898 }
8899
8900 /* Disable the VGA plane that we never use */
8901 static void i915_disable_vga(struct drm_device *dev)
8902 {
8903         struct drm_i915_private *dev_priv = dev->dev_private;
8904         u8 sr1;
8905         u32 vga_reg;
8906
8907         if (HAS_PCH_SPLIT(dev))
8908                 vga_reg = CPU_VGACNTRL;
8909         else
8910                 vga_reg = VGACNTRL;
8911
8912         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
8913         outb(1, VGA_SR_INDEX);
8914         sr1 = inb(VGA_SR_DATA);
8915         outb(sr1 | 1<<5, VGA_SR_DATA);
8916         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
8917         udelay(300);
8918
8919         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
8920         POSTING_READ(vga_reg);
8921 }
8922
8923 void intel_modeset_init(struct drm_device *dev)
8924 {
8925         struct drm_i915_private *dev_priv = dev->dev_private;
8926         int i;
8927
8928         drm_mode_config_init(dev);
8929
8930         dev->mode_config.min_width = 0;
8931         dev->mode_config.min_height = 0;
8932
8933         dev->mode_config.funcs = (void *)&intel_mode_funcs;
8934
8935         intel_init_quirks(dev);
8936
8937         intel_init_display(dev);
8938
8939         if (IS_GEN2(dev)) {
8940                 dev->mode_config.max_width = 2048;
8941                 dev->mode_config.max_height = 2048;
8942         } else if (IS_GEN3(dev)) {
8943                 dev->mode_config.max_width = 4096;
8944                 dev->mode_config.max_height = 4096;
8945         } else {
8946                 dev->mode_config.max_width = 8192;
8947                 dev->mode_config.max_height = 8192;
8948         }
8949         dev->mode_config.fb_base = dev->agp->base;
8950
8951         DRM_DEBUG_KMS("%d display pipe%s available.\n",
8952                       dev_priv->num_pipe, dev_priv->num_pipe > 1 ? "s" : "");
8953
8954         for (i = 0; i < dev_priv->num_pipe; i++) {
8955                 intel_crtc_init(dev, i);
8956         }
8957
8958         /* Just disable it once at startup */
8959         i915_disable_vga(dev);
8960         intel_setup_outputs(dev);
8961
8962         intel_init_clock_gating(dev);
8963
8964         if (IS_IRONLAKE_M(dev)) {
8965                 ironlake_enable_drps(dev);
8966                 intel_init_emon(dev);
8967         }
8968
8969         if (IS_GEN6(dev) || IS_GEN7(dev)) {
8970                 gen6_enable_rps(dev_priv);
8971                 gen6_update_ring_freq(dev_priv);
8972         }
8973
8974         INIT_WORK(&dev_priv->idle_work, intel_idle_update);
8975         setup_timer(&dev_priv->idle_timer, intel_gpu_idle_timer,
8976                     (unsigned long)dev);
8977 }
8978
8979 void intel_modeset_gem_init(struct drm_device *dev)
8980 {
8981         if (IS_IRONLAKE_M(dev))
8982                 ironlake_enable_rc6(dev);
8983
8984         intel_setup_overlay(dev);
8985 }
8986
8987 void intel_modeset_cleanup(struct drm_device *dev)
8988 {
8989         struct drm_i915_private *dev_priv = dev->dev_private;
8990         struct drm_crtc *crtc;
8991         struct intel_crtc *intel_crtc;
8992
8993         drm_kms_helper_poll_fini(dev);
8994         mutex_lock(&dev->struct_mutex);
8995
8996         intel_unregister_dsm_handler();
8997
8998
8999         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
9000                 /* Skip inactive CRTCs */
9001                 if (!crtc->fb)
9002                         continue;
9003
9004                 intel_crtc = to_intel_crtc(crtc);
9005                 intel_increase_pllclock(crtc);
9006         }
9007
9008         intel_disable_fbc(dev);
9009
9010         if (IS_IRONLAKE_M(dev))
9011                 ironlake_disable_drps(dev);
9012         if (IS_GEN6(dev) || IS_GEN7(dev))
9013                 gen6_disable_rps(dev);
9014
9015         if (IS_IRONLAKE_M(dev))
9016                 ironlake_disable_rc6(dev);
9017
9018         mutex_unlock(&dev->struct_mutex);
9019
9020         /* Disable the irq before mode object teardown, for the irq might
9021          * enqueue unpin/hotplug work. */
9022         drm_irq_uninstall(dev);
9023         cancel_work_sync(&dev_priv->hotplug_work);
9024         cancel_work_sync(&dev_priv->rps_work);
9025
9026         /* flush any delayed tasks or pending work */
9027         flush_scheduled_work();
9028
9029         /* Shut off idle work before the crtcs get freed. */
9030         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
9031                 intel_crtc = to_intel_crtc(crtc);
9032                 del_timer_sync(&intel_crtc->idle_timer);
9033         }
9034         del_timer_sync(&dev_priv->idle_timer);
9035         cancel_work_sync(&dev_priv->idle_work);
9036
9037         drm_mode_config_cleanup(dev);
9038 }
9039
9040 /*
9041  * Return which encoder is currently attached for connector.
9042  */
9043 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
9044 {
9045         return &intel_attached_encoder(connector)->base;
9046 }
9047
9048 void intel_connector_attach_encoder(struct intel_connector *connector,
9049                                     struct intel_encoder *encoder)
9050 {
9051         connector->encoder = encoder;
9052         drm_mode_connector_attach_encoder(&connector->base,
9053                                           &encoder->base);
9054 }
9055
9056 /*
9057  * set vga decode state - true == enable VGA decode
9058  */
9059 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
9060 {
9061         struct drm_i915_private *dev_priv = dev->dev_private;
9062         u16 gmch_ctrl;
9063
9064         pci_read_config_word(dev_priv->bridge_dev, INTEL_GMCH_CTRL, &gmch_ctrl);
9065         if (state)
9066                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
9067         else
9068                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
9069         pci_write_config_word(dev_priv->bridge_dev, INTEL_GMCH_CTRL, gmch_ctrl);
9070         return 0;
9071 }
9072
9073 #ifdef CONFIG_DEBUG_FS
9074 #include <linux/seq_file.h>
9075
9076 struct intel_display_error_state {
9077         struct intel_cursor_error_state {
9078                 u32 control;
9079                 u32 position;
9080                 u32 base;
9081                 u32 size;
9082         } cursor[2];
9083
9084         struct intel_pipe_error_state {
9085                 u32 conf;
9086                 u32 source;
9087
9088                 u32 htotal;
9089                 u32 hblank;
9090                 u32 hsync;
9091                 u32 vtotal;
9092                 u32 vblank;
9093                 u32 vsync;
9094         } pipe[2];
9095
9096         struct intel_plane_error_state {
9097                 u32 control;
9098                 u32 stride;
9099                 u32 size;
9100                 u32 pos;
9101                 u32 addr;
9102                 u32 surface;
9103                 u32 tile_offset;
9104         } plane[2];
9105 };
9106
9107 struct intel_display_error_state *
9108 intel_display_capture_error_state(struct drm_device *dev)
9109 {
9110         drm_i915_private_t *dev_priv = dev->dev_private;
9111         struct intel_display_error_state *error;
9112         int i;
9113
9114         error = kmalloc(sizeof(*error), GFP_ATOMIC);
9115         if (error == NULL)
9116                 return NULL;
9117
9118         for (i = 0; i < 2; i++) {
9119                 error->cursor[i].control = I915_READ(CURCNTR(i));
9120                 error->cursor[i].position = I915_READ(CURPOS(i));
9121                 error->cursor[i].base = I915_READ(CURBASE(i));
9122
9123                 error->plane[i].control = I915_READ(DSPCNTR(i));
9124                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
9125                 error->plane[i].size = I915_READ(DSPSIZE(i));
9126                 error->plane[i].pos = I915_READ(DSPPOS(i));
9127                 error->plane[i].addr = I915_READ(DSPADDR(i));
9128                 if (INTEL_INFO(dev)->gen >= 4) {
9129                         error->plane[i].surface = I915_READ(DSPSURF(i));
9130                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
9131                 }
9132
9133                 error->pipe[i].conf = I915_READ(PIPECONF(i));
9134                 error->pipe[i].source = I915_READ(PIPESRC(i));
9135                 error->pipe[i].htotal = I915_READ(HTOTAL(i));
9136                 error->pipe[i].hblank = I915_READ(HBLANK(i));
9137                 error->pipe[i].hsync = I915_READ(HSYNC(i));
9138                 error->pipe[i].vtotal = I915_READ(VTOTAL(i));
9139                 error->pipe[i].vblank = I915_READ(VBLANK(i));
9140                 error->pipe[i].vsync = I915_READ(VSYNC(i));
9141         }
9142
9143         return error;
9144 }
9145
9146 void
9147 intel_display_print_error_state(struct seq_file *m,
9148                                 struct drm_device *dev,
9149                                 struct intel_display_error_state *error)
9150 {
9151         int i;
9152
9153         for (i = 0; i < 2; i++) {
9154                 seq_printf(m, "Pipe [%d]:\n", i);
9155                 seq_printf(m, "  CONF: %08x\n", error->pipe[i].conf);
9156                 seq_printf(m, "  SRC: %08x\n", error->pipe[i].source);
9157                 seq_printf(m, "  HTOTAL: %08x\n", error->pipe[i].htotal);
9158                 seq_printf(m, "  HBLANK: %08x\n", error->pipe[i].hblank);
9159                 seq_printf(m, "  HSYNC: %08x\n", error->pipe[i].hsync);
9160                 seq_printf(m, "  VTOTAL: %08x\n", error->pipe[i].vtotal);
9161                 seq_printf(m, "  VBLANK: %08x\n", error->pipe[i].vblank);
9162                 seq_printf(m, "  VSYNC: %08x\n", error->pipe[i].vsync);
9163
9164                 seq_printf(m, "Plane [%d]:\n", i);
9165                 seq_printf(m, "  CNTR: %08x\n", error->plane[i].control);
9166                 seq_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
9167                 seq_printf(m, "  SIZE: %08x\n", error->plane[i].size);
9168                 seq_printf(m, "  POS: %08x\n", error->plane[i].pos);
9169                 seq_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
9170                 if (INTEL_INFO(dev)->gen >= 4) {
9171                         seq_printf(m, "  SURF: %08x\n", error->plane[i].surface);
9172                         seq_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
9173                 }
9174
9175                 seq_printf(m, "Cursor [%d]:\n", i);
9176                 seq_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
9177                 seq_printf(m, "  POS: %08x\n", error->cursor[i].position);
9178                 seq_printf(m, "  BASE: %08x\n", error->cursor[i].base);
9179         }
9180 }
9181 #endif