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