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