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