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