drm/i915: Shovel hw setup code out of hsw_crtc_mode_set
[firefly-linux-kernel-4.4.55.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 <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_dp_helper.h>
41 #include <drm/drm_crtc_helper.h>
42 #include <linux/dma_remapping.h>
43
44 #define DIV_ROUND_CLOSEST_ULL(ll, d)    \
45         ({ unsigned long long _tmp = (ll)+(d)/2; do_div(_tmp, d); _tmp; })
46
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 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
51                                 struct intel_crtc_config *pipe_config);
52 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
53                                    struct intel_crtc_config *pipe_config);
54
55 static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
56                           int x, int y, struct drm_framebuffer *old_fb);
57 static int intel_framebuffer_init(struct drm_device *dev,
58                                   struct intel_framebuffer *ifb,
59                                   struct drm_mode_fb_cmd2 *mode_cmd,
60                                   struct drm_i915_gem_object *obj);
61 static void intel_dp_set_m_n(struct intel_crtc *crtc);
62 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
63 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
64 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
65                                          struct intel_link_m_n *m_n);
66 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
67 static void haswell_set_pipeconf(struct drm_crtc *crtc);
68 static void intel_set_pipe_csc(struct drm_crtc *crtc);
69
70 typedef struct {
71         int     min, max;
72 } intel_range_t;
73
74 typedef struct {
75         int     dot_limit;
76         int     p2_slow, p2_fast;
77 } intel_p2_t;
78
79 typedef struct intel_limit intel_limit_t;
80 struct intel_limit {
81         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
82         intel_p2_t          p2;
83 };
84
85 int
86 intel_pch_rawclk(struct drm_device *dev)
87 {
88         struct drm_i915_private *dev_priv = dev->dev_private;
89
90         WARN_ON(!HAS_PCH_SPLIT(dev));
91
92         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
93 }
94
95 static inline u32 /* units of 100MHz */
96 intel_fdi_link_freq(struct drm_device *dev)
97 {
98         if (IS_GEN5(dev)) {
99                 struct drm_i915_private *dev_priv = dev->dev_private;
100                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
101         } else
102                 return 27;
103 }
104
105 static const intel_limit_t intel_limits_i8xx_dac = {
106         .dot = { .min = 25000, .max = 350000 },
107         .vco = { .min = 908000, .max = 1512000 },
108         .n = { .min = 2, .max = 16 },
109         .m = { .min = 96, .max = 140 },
110         .m1 = { .min = 18, .max = 26 },
111         .m2 = { .min = 6, .max = 16 },
112         .p = { .min = 4, .max = 128 },
113         .p1 = { .min = 2, .max = 33 },
114         .p2 = { .dot_limit = 165000,
115                 .p2_slow = 4, .p2_fast = 2 },
116 };
117
118 static const intel_limit_t intel_limits_i8xx_dvo = {
119         .dot = { .min = 25000, .max = 350000 },
120         .vco = { .min = 908000, .max = 1512000 },
121         .n = { .min = 2, .max = 16 },
122         .m = { .min = 96, .max = 140 },
123         .m1 = { .min = 18, .max = 26 },
124         .m2 = { .min = 6, .max = 16 },
125         .p = { .min = 4, .max = 128 },
126         .p1 = { .min = 2, .max = 33 },
127         .p2 = { .dot_limit = 165000,
128                 .p2_slow = 4, .p2_fast = 4 },
129 };
130
131 static const intel_limit_t intel_limits_i8xx_lvds = {
132         .dot = { .min = 25000, .max = 350000 },
133         .vco = { .min = 908000, .max = 1512000 },
134         .n = { .min = 2, .max = 16 },
135         .m = { .min = 96, .max = 140 },
136         .m1 = { .min = 18, .max = 26 },
137         .m2 = { .min = 6, .max = 16 },
138         .p = { .min = 4, .max = 128 },
139         .p1 = { .min = 1, .max = 6 },
140         .p2 = { .dot_limit = 165000,
141                 .p2_slow = 14, .p2_fast = 7 },
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 = 8, .max = 18 },
150         .m2 = { .min = 3, .max = 7 },
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 };
156
157 static const intel_limit_t intel_limits_i9xx_lvds = {
158         .dot = { .min = 20000, .max = 400000 },
159         .vco = { .min = 1400000, .max = 2800000 },
160         .n = { .min = 1, .max = 6 },
161         .m = { .min = 70, .max = 120 },
162         .m1 = { .min = 8, .max = 18 },
163         .m2 = { .min = 3, .max = 7 },
164         .p = { .min = 7, .max = 98 },
165         .p1 = { .min = 1, .max = 8 },
166         .p2 = { .dot_limit = 112000,
167                 .p2_slow = 14, .p2_fast = 7 },
168 };
169
170
171 static const intel_limit_t intel_limits_g4x_sdvo = {
172         .dot = { .min = 25000, .max = 270000 },
173         .vco = { .min = 1750000, .max = 3500000},
174         .n = { .min = 1, .max = 4 },
175         .m = { .min = 104, .max = 138 },
176         .m1 = { .min = 17, .max = 23 },
177         .m2 = { .min = 5, .max = 11 },
178         .p = { .min = 10, .max = 30 },
179         .p1 = { .min = 1, .max = 3},
180         .p2 = { .dot_limit = 270000,
181                 .p2_slow = 10,
182                 .p2_fast = 10
183         },
184 };
185
186 static const intel_limit_t intel_limits_g4x_hdmi = {
187         .dot = { .min = 22000, .max = 400000 },
188         .vco = { .min = 1750000, .max = 3500000},
189         .n = { .min = 1, .max = 4 },
190         .m = { .min = 104, .max = 138 },
191         .m1 = { .min = 16, .max = 23 },
192         .m2 = { .min = 5, .max = 11 },
193         .p = { .min = 5, .max = 80 },
194         .p1 = { .min = 1, .max = 8},
195         .p2 = { .dot_limit = 165000,
196                 .p2_slow = 10, .p2_fast = 5 },
197 };
198
199 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
200         .dot = { .min = 20000, .max = 115000 },
201         .vco = { .min = 1750000, .max = 3500000 },
202         .n = { .min = 1, .max = 3 },
203         .m = { .min = 104, .max = 138 },
204         .m1 = { .min = 17, .max = 23 },
205         .m2 = { .min = 5, .max = 11 },
206         .p = { .min = 28, .max = 112 },
207         .p1 = { .min = 2, .max = 8 },
208         .p2 = { .dot_limit = 0,
209                 .p2_slow = 14, .p2_fast = 14
210         },
211 };
212
213 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
214         .dot = { .min = 80000, .max = 224000 },
215         .vco = { .min = 1750000, .max = 3500000 },
216         .n = { .min = 1, .max = 3 },
217         .m = { .min = 104, .max = 138 },
218         .m1 = { .min = 17, .max = 23 },
219         .m2 = { .min = 5, .max = 11 },
220         .p = { .min = 14, .max = 42 },
221         .p1 = { .min = 2, .max = 6 },
222         .p2 = { .dot_limit = 0,
223                 .p2_slow = 7, .p2_fast = 7
224         },
225 };
226
227 static const intel_limit_t intel_limits_pineview_sdvo = {
228         .dot = { .min = 20000, .max = 400000},
229         .vco = { .min = 1700000, .max = 3500000 },
230         /* Pineview's Ncounter is a ring counter */
231         .n = { .min = 3, .max = 6 },
232         .m = { .min = 2, .max = 256 },
233         /* Pineview only has one combined m divider, which we treat as m2. */
234         .m1 = { .min = 0, .max = 0 },
235         .m2 = { .min = 0, .max = 254 },
236         .p = { .min = 5, .max = 80 },
237         .p1 = { .min = 1, .max = 8 },
238         .p2 = { .dot_limit = 200000,
239                 .p2_slow = 10, .p2_fast = 5 },
240 };
241
242 static const intel_limit_t intel_limits_pineview_lvds = {
243         .dot = { .min = 20000, .max = 400000 },
244         .vco = { .min = 1700000, .max = 3500000 },
245         .n = { .min = 3, .max = 6 },
246         .m = { .min = 2, .max = 256 },
247         .m1 = { .min = 0, .max = 0 },
248         .m2 = { .min = 0, .max = 254 },
249         .p = { .min = 7, .max = 112 },
250         .p1 = { .min = 1, .max = 8 },
251         .p2 = { .dot_limit = 112000,
252                 .p2_slow = 14, .p2_fast = 14 },
253 };
254
255 /* Ironlake / Sandybridge
256  *
257  * We calculate clock using (register_value + 2) for N/M1/M2, so here
258  * the range value for them is (actual_value - 2).
259  */
260 static const intel_limit_t intel_limits_ironlake_dac = {
261         .dot = { .min = 25000, .max = 350000 },
262         .vco = { .min = 1760000, .max = 3510000 },
263         .n = { .min = 1, .max = 5 },
264         .m = { .min = 79, .max = 127 },
265         .m1 = { .min = 12, .max = 22 },
266         .m2 = { .min = 5, .max = 9 },
267         .p = { .min = 5, .max = 80 },
268         .p1 = { .min = 1, .max = 8 },
269         .p2 = { .dot_limit = 225000,
270                 .p2_slow = 10, .p2_fast = 5 },
271 };
272
273 static const intel_limit_t intel_limits_ironlake_single_lvds = {
274         .dot = { .min = 25000, .max = 350000 },
275         .vco = { .min = 1760000, .max = 3510000 },
276         .n = { .min = 1, .max = 3 },
277         .m = { .min = 79, .max = 118 },
278         .m1 = { .min = 12, .max = 22 },
279         .m2 = { .min = 5, .max = 9 },
280         .p = { .min = 28, .max = 112 },
281         .p1 = { .min = 2, .max = 8 },
282         .p2 = { .dot_limit = 225000,
283                 .p2_slow = 14, .p2_fast = 14 },
284 };
285
286 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
287         .dot = { .min = 25000, .max = 350000 },
288         .vco = { .min = 1760000, .max = 3510000 },
289         .n = { .min = 1, .max = 3 },
290         .m = { .min = 79, .max = 127 },
291         .m1 = { .min = 12, .max = 22 },
292         .m2 = { .min = 5, .max = 9 },
293         .p = { .min = 14, .max = 56 },
294         .p1 = { .min = 2, .max = 8 },
295         .p2 = { .dot_limit = 225000,
296                 .p2_slow = 7, .p2_fast = 7 },
297 };
298
299 /* LVDS 100mhz refclk limits. */
300 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
301         .dot = { .min = 25000, .max = 350000 },
302         .vco = { .min = 1760000, .max = 3510000 },
303         .n = { .min = 1, .max = 2 },
304         .m = { .min = 79, .max = 126 },
305         .m1 = { .min = 12, .max = 22 },
306         .m2 = { .min = 5, .max = 9 },
307         .p = { .min = 28, .max = 112 },
308         .p1 = { .min = 2, .max = 8 },
309         .p2 = { .dot_limit = 225000,
310                 .p2_slow = 14, .p2_fast = 14 },
311 };
312
313 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
314         .dot = { .min = 25000, .max = 350000 },
315         .vco = { .min = 1760000, .max = 3510000 },
316         .n = { .min = 1, .max = 3 },
317         .m = { .min = 79, .max = 126 },
318         .m1 = { .min = 12, .max = 22 },
319         .m2 = { .min = 5, .max = 9 },
320         .p = { .min = 14, .max = 42 },
321         .p1 = { .min = 2, .max = 6 },
322         .p2 = { .dot_limit = 225000,
323                 .p2_slow = 7, .p2_fast = 7 },
324 };
325
326 static const intel_limit_t intel_limits_vlv = {
327          /*
328           * These are the data rate limits (measured in fast clocks)
329           * since those are the strictest limits we have. The fast
330           * clock and actual rate limits are more relaxed, so checking
331           * them would make no difference.
332           */
333         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
334         .vco = { .min = 4000000, .max = 6000000 },
335         .n = { .min = 1, .max = 7 },
336         .m1 = { .min = 2, .max = 3 },
337         .m2 = { .min = 11, .max = 156 },
338         .p1 = { .min = 2, .max = 3 },
339         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
340 };
341
342 static const intel_limit_t intel_limits_chv = {
343         /*
344          * These are the data rate limits (measured in fast clocks)
345          * since those are the strictest limits we have.  The fast
346          * clock and actual rate limits are more relaxed, so checking
347          * them would make no difference.
348          */
349         .dot = { .min = 25000 * 5, .max = 540000 * 5},
350         .vco = { .min = 4860000, .max = 6700000 },
351         .n = { .min = 1, .max = 1 },
352         .m1 = { .min = 2, .max = 2 },
353         .m2 = { .min = 24 << 22, .max = 175 << 22 },
354         .p1 = { .min = 2, .max = 4 },
355         .p2 = { .p2_slow = 1, .p2_fast = 14 },
356 };
357
358 static void vlv_clock(int refclk, intel_clock_t *clock)
359 {
360         clock->m = clock->m1 * clock->m2;
361         clock->p = clock->p1 * clock->p2;
362         if (WARN_ON(clock->n == 0 || clock->p == 0))
363                 return;
364         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
365         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
366 }
367
368 /**
369  * Returns whether any output on the specified pipe is of the specified type
370  */
371 static bool intel_pipe_has_type(struct drm_crtc *crtc, int type)
372 {
373         struct drm_device *dev = crtc->dev;
374         struct intel_encoder *encoder;
375
376         for_each_encoder_on_crtc(dev, crtc, encoder)
377                 if (encoder->type == type)
378                         return true;
379
380         return false;
381 }
382
383 static const intel_limit_t *intel_ironlake_limit(struct drm_crtc *crtc,
384                                                 int refclk)
385 {
386         struct drm_device *dev = crtc->dev;
387         const intel_limit_t *limit;
388
389         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
390                 if (intel_is_dual_link_lvds(dev)) {
391                         if (refclk == 100000)
392                                 limit = &intel_limits_ironlake_dual_lvds_100m;
393                         else
394                                 limit = &intel_limits_ironlake_dual_lvds;
395                 } else {
396                         if (refclk == 100000)
397                                 limit = &intel_limits_ironlake_single_lvds_100m;
398                         else
399                                 limit = &intel_limits_ironlake_single_lvds;
400                 }
401         } else
402                 limit = &intel_limits_ironlake_dac;
403
404         return limit;
405 }
406
407 static const intel_limit_t *intel_g4x_limit(struct drm_crtc *crtc)
408 {
409         struct drm_device *dev = crtc->dev;
410         const intel_limit_t *limit;
411
412         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
413                 if (intel_is_dual_link_lvds(dev))
414                         limit = &intel_limits_g4x_dual_channel_lvds;
415                 else
416                         limit = &intel_limits_g4x_single_channel_lvds;
417         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI) ||
418                    intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG)) {
419                 limit = &intel_limits_g4x_hdmi;
420         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_SDVO)) {
421                 limit = &intel_limits_g4x_sdvo;
422         } else /* The option is for other outputs */
423                 limit = &intel_limits_i9xx_sdvo;
424
425         return limit;
426 }
427
428 static const intel_limit_t *intel_limit(struct drm_crtc *crtc, int refclk)
429 {
430         struct drm_device *dev = crtc->dev;
431         const intel_limit_t *limit;
432
433         if (HAS_PCH_SPLIT(dev))
434                 limit = intel_ironlake_limit(crtc, refclk);
435         else if (IS_G4X(dev)) {
436                 limit = intel_g4x_limit(crtc);
437         } else if (IS_PINEVIEW(dev)) {
438                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
439                         limit = &intel_limits_pineview_lvds;
440                 else
441                         limit = &intel_limits_pineview_sdvo;
442         } else if (IS_CHERRYVIEW(dev)) {
443                 limit = &intel_limits_chv;
444         } else if (IS_VALLEYVIEW(dev)) {
445                 limit = &intel_limits_vlv;
446         } else if (!IS_GEN2(dev)) {
447                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
448                         limit = &intel_limits_i9xx_lvds;
449                 else
450                         limit = &intel_limits_i9xx_sdvo;
451         } else {
452                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
453                         limit = &intel_limits_i8xx_lvds;
454                 else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO))
455                         limit = &intel_limits_i8xx_dvo;
456                 else
457                         limit = &intel_limits_i8xx_dac;
458         }
459         return limit;
460 }
461
462 /* m1 is reserved as 0 in Pineview, n is a ring counter */
463 static void pineview_clock(int refclk, intel_clock_t *clock)
464 {
465         clock->m = clock->m2 + 2;
466         clock->p = clock->p1 * clock->p2;
467         if (WARN_ON(clock->n == 0 || clock->p == 0))
468                 return;
469         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
470         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
471 }
472
473 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
474 {
475         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
476 }
477
478 static void i9xx_clock(int refclk, intel_clock_t *clock)
479 {
480         clock->m = i9xx_dpll_compute_m(clock);
481         clock->p = clock->p1 * clock->p2;
482         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
483                 return;
484         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
485         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
486 }
487
488 static void chv_clock(int refclk, intel_clock_t *clock)
489 {
490         clock->m = clock->m1 * clock->m2;
491         clock->p = clock->p1 * clock->p2;
492         if (WARN_ON(clock->n == 0 || clock->p == 0))
493                 return;
494         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
495                         clock->n << 22);
496         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
497 }
498
499 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
500 /**
501  * Returns whether the given set of divisors are valid for a given refclk with
502  * the given connectors.
503  */
504
505 static bool intel_PLL_is_valid(struct drm_device *dev,
506                                const intel_limit_t *limit,
507                                const intel_clock_t *clock)
508 {
509         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
510                 INTELPllInvalid("n out of range\n");
511         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
512                 INTELPllInvalid("p1 out of range\n");
513         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
514                 INTELPllInvalid("m2 out of range\n");
515         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
516                 INTELPllInvalid("m1 out of range\n");
517
518         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
519                 if (clock->m1 <= clock->m2)
520                         INTELPllInvalid("m1 <= m2\n");
521
522         if (!IS_VALLEYVIEW(dev)) {
523                 if (clock->p < limit->p.min || limit->p.max < clock->p)
524                         INTELPllInvalid("p out of range\n");
525                 if (clock->m < limit->m.min || limit->m.max < clock->m)
526                         INTELPllInvalid("m out of range\n");
527         }
528
529         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
530                 INTELPllInvalid("vco out of range\n");
531         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
532          * connector, etc., rather than just a single range.
533          */
534         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
535                 INTELPllInvalid("dot out of range\n");
536
537         return true;
538 }
539
540 static bool
541 i9xx_find_best_dpll(const intel_limit_t *limit, struct drm_crtc *crtc,
542                     int target, int refclk, intel_clock_t *match_clock,
543                     intel_clock_t *best_clock)
544 {
545         struct drm_device *dev = crtc->dev;
546         intel_clock_t clock;
547         int err = target;
548
549         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
550                 /*
551                  * For LVDS just rely on its current settings for dual-channel.
552                  * We haven't figured out how to reliably set up different
553                  * single/dual channel state, if we even can.
554                  */
555                 if (intel_is_dual_link_lvds(dev))
556                         clock.p2 = limit->p2.p2_fast;
557                 else
558                         clock.p2 = limit->p2.p2_slow;
559         } else {
560                 if (target < limit->p2.dot_limit)
561                         clock.p2 = limit->p2.p2_slow;
562                 else
563                         clock.p2 = limit->p2.p2_fast;
564         }
565
566         memset(best_clock, 0, sizeof(*best_clock));
567
568         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
569              clock.m1++) {
570                 for (clock.m2 = limit->m2.min;
571                      clock.m2 <= limit->m2.max; clock.m2++) {
572                         if (clock.m2 >= clock.m1)
573                                 break;
574                         for (clock.n = limit->n.min;
575                              clock.n <= limit->n.max; clock.n++) {
576                                 for (clock.p1 = limit->p1.min;
577                                         clock.p1 <= limit->p1.max; clock.p1++) {
578                                         int this_err;
579
580                                         i9xx_clock(refclk, &clock);
581                                         if (!intel_PLL_is_valid(dev, limit,
582                                                                 &clock))
583                                                 continue;
584                                         if (match_clock &&
585                                             clock.p != match_clock->p)
586                                                 continue;
587
588                                         this_err = abs(clock.dot - target);
589                                         if (this_err < err) {
590                                                 *best_clock = clock;
591                                                 err = this_err;
592                                         }
593                                 }
594                         }
595                 }
596         }
597
598         return (err != target);
599 }
600
601 static bool
602 pnv_find_best_dpll(const intel_limit_t *limit, struct drm_crtc *crtc,
603                    int target, int refclk, intel_clock_t *match_clock,
604                    intel_clock_t *best_clock)
605 {
606         struct drm_device *dev = crtc->dev;
607         intel_clock_t clock;
608         int err = target;
609
610         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
611                 /*
612                  * For LVDS just rely on its current settings for dual-channel.
613                  * We haven't figured out how to reliably set up different
614                  * single/dual channel state, if we even can.
615                  */
616                 if (intel_is_dual_link_lvds(dev))
617                         clock.p2 = limit->p2.p2_fast;
618                 else
619                         clock.p2 = limit->p2.p2_slow;
620         } else {
621                 if (target < limit->p2.dot_limit)
622                         clock.p2 = limit->p2.p2_slow;
623                 else
624                         clock.p2 = limit->p2.p2_fast;
625         }
626
627         memset(best_clock, 0, sizeof(*best_clock));
628
629         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
630              clock.m1++) {
631                 for (clock.m2 = limit->m2.min;
632                      clock.m2 <= limit->m2.max; clock.m2++) {
633                         for (clock.n = limit->n.min;
634                              clock.n <= limit->n.max; clock.n++) {
635                                 for (clock.p1 = limit->p1.min;
636                                         clock.p1 <= limit->p1.max; clock.p1++) {
637                                         int this_err;
638
639                                         pineview_clock(refclk, &clock);
640                                         if (!intel_PLL_is_valid(dev, limit,
641                                                                 &clock))
642                                                 continue;
643                                         if (match_clock &&
644                                             clock.p != match_clock->p)
645                                                 continue;
646
647                                         this_err = abs(clock.dot - target);
648                                         if (this_err < err) {
649                                                 *best_clock = clock;
650                                                 err = this_err;
651                                         }
652                                 }
653                         }
654                 }
655         }
656
657         return (err != target);
658 }
659
660 static bool
661 g4x_find_best_dpll(const intel_limit_t *limit, struct drm_crtc *crtc,
662                    int target, int refclk, intel_clock_t *match_clock,
663                    intel_clock_t *best_clock)
664 {
665         struct drm_device *dev = crtc->dev;
666         intel_clock_t clock;
667         int max_n;
668         bool found;
669         /* approximately equals target * 0.00585 */
670         int err_most = (target >> 8) + (target >> 9);
671         found = false;
672
673         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
674                 if (intel_is_dual_link_lvds(dev))
675                         clock.p2 = limit->p2.p2_fast;
676                 else
677                         clock.p2 = limit->p2.p2_slow;
678         } else {
679                 if (target < limit->p2.dot_limit)
680                         clock.p2 = limit->p2.p2_slow;
681                 else
682                         clock.p2 = limit->p2.p2_fast;
683         }
684
685         memset(best_clock, 0, sizeof(*best_clock));
686         max_n = limit->n.max;
687         /* based on hardware requirement, prefer smaller n to precision */
688         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
689                 /* based on hardware requirement, prefere larger m1,m2 */
690                 for (clock.m1 = limit->m1.max;
691                      clock.m1 >= limit->m1.min; clock.m1--) {
692                         for (clock.m2 = limit->m2.max;
693                              clock.m2 >= limit->m2.min; clock.m2--) {
694                                 for (clock.p1 = limit->p1.max;
695                                      clock.p1 >= limit->p1.min; clock.p1--) {
696                                         int this_err;
697
698                                         i9xx_clock(refclk, &clock);
699                                         if (!intel_PLL_is_valid(dev, limit,
700                                                                 &clock))
701                                                 continue;
702
703                                         this_err = abs(clock.dot - target);
704                                         if (this_err < err_most) {
705                                                 *best_clock = clock;
706                                                 err_most = this_err;
707                                                 max_n = clock.n;
708                                                 found = true;
709                                         }
710                                 }
711                         }
712                 }
713         }
714         return found;
715 }
716
717 static bool
718 vlv_find_best_dpll(const intel_limit_t *limit, struct drm_crtc *crtc,
719                    int target, int refclk, intel_clock_t *match_clock,
720                    intel_clock_t *best_clock)
721 {
722         struct drm_device *dev = crtc->dev;
723         intel_clock_t clock;
724         unsigned int bestppm = 1000000;
725         /* min update 19.2 MHz */
726         int max_n = min(limit->n.max, refclk / 19200);
727         bool found = false;
728
729         target *= 5; /* fast clock */
730
731         memset(best_clock, 0, sizeof(*best_clock));
732
733         /* based on hardware requirement, prefer smaller n to precision */
734         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
735                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
736                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
737                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
738                                 clock.p = clock.p1 * clock.p2;
739                                 /* based on hardware requirement, prefer bigger m1,m2 values */
740                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
741                                         unsigned int ppm, diff;
742
743                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
744                                                                      refclk * clock.m1);
745
746                                         vlv_clock(refclk, &clock);
747
748                                         if (!intel_PLL_is_valid(dev, limit,
749                                                                 &clock))
750                                                 continue;
751
752                                         diff = abs(clock.dot - target);
753                                         ppm = div_u64(1000000ULL * diff, target);
754
755                                         if (ppm < 100 && clock.p > best_clock->p) {
756                                                 bestppm = 0;
757                                                 *best_clock = clock;
758                                                 found = true;
759                                         }
760
761                                         if (bestppm >= 10 && ppm < bestppm - 10) {
762                                                 bestppm = ppm;
763                                                 *best_clock = clock;
764                                                 found = true;
765                                         }
766                                 }
767                         }
768                 }
769         }
770
771         return found;
772 }
773
774 static bool
775 chv_find_best_dpll(const intel_limit_t *limit, struct drm_crtc *crtc,
776                    int target, int refclk, intel_clock_t *match_clock,
777                    intel_clock_t *best_clock)
778 {
779         struct drm_device *dev = crtc->dev;
780         intel_clock_t clock;
781         uint64_t m2;
782         int found = false;
783
784         memset(best_clock, 0, sizeof(*best_clock));
785
786         /*
787          * Based on hardware doc, the n always set to 1, and m1 always
788          * set to 2.  If requires to support 200Mhz refclk, we need to
789          * revisit this because n may not 1 anymore.
790          */
791         clock.n = 1, clock.m1 = 2;
792         target *= 5;    /* fast clock */
793
794         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
795                 for (clock.p2 = limit->p2.p2_fast;
796                                 clock.p2 >= limit->p2.p2_slow;
797                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
798
799                         clock.p = clock.p1 * clock.p2;
800
801                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
802                                         clock.n) << 22, refclk * clock.m1);
803
804                         if (m2 > INT_MAX/clock.m1)
805                                 continue;
806
807                         clock.m2 = m2;
808
809                         chv_clock(refclk, &clock);
810
811                         if (!intel_PLL_is_valid(dev, limit, &clock))
812                                 continue;
813
814                         /* based on hardware requirement, prefer bigger p
815                          */
816                         if (clock.p > best_clock->p) {
817                                 *best_clock = clock;
818                                 found = true;
819                         }
820                 }
821         }
822
823         return found;
824 }
825
826 bool intel_crtc_active(struct drm_crtc *crtc)
827 {
828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
829
830         /* Be paranoid as we can arrive here with only partial
831          * state retrieved from the hardware during setup.
832          *
833          * We can ditch the adjusted_mode.crtc_clock check as soon
834          * as Haswell has gained clock readout/fastboot support.
835          *
836          * We can ditch the crtc->primary->fb check as soon as we can
837          * properly reconstruct framebuffers.
838          */
839         return intel_crtc->active && crtc->primary->fb &&
840                 intel_crtc->config.adjusted_mode.crtc_clock;
841 }
842
843 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
844                                              enum pipe pipe)
845 {
846         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
847         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
848
849         return intel_crtc->config.cpu_transcoder;
850 }
851
852 static void g4x_wait_for_vblank(struct drm_device *dev, int pipe)
853 {
854         struct drm_i915_private *dev_priv = dev->dev_private;
855         u32 frame, frame_reg = PIPE_FRMCOUNT_GM45(pipe);
856
857         frame = I915_READ(frame_reg);
858
859         if (wait_for(I915_READ_NOTRACE(frame_reg) != frame, 50))
860                 WARN(1, "vblank wait timed out\n");
861 }
862
863 /**
864  * intel_wait_for_vblank - wait for vblank on a given pipe
865  * @dev: drm device
866  * @pipe: pipe to wait for
867  *
868  * Wait for vblank to occur on a given pipe.  Needed for various bits of
869  * mode setting code.
870  */
871 void intel_wait_for_vblank(struct drm_device *dev, int pipe)
872 {
873         struct drm_i915_private *dev_priv = dev->dev_private;
874         int pipestat_reg = PIPESTAT(pipe);
875
876         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5) {
877                 g4x_wait_for_vblank(dev, pipe);
878                 return;
879         }
880
881         /* Clear existing vblank status. Note this will clear any other
882          * sticky status fields as well.
883          *
884          * This races with i915_driver_irq_handler() with the result
885          * that either function could miss a vblank event.  Here it is not
886          * fatal, as we will either wait upon the next vblank interrupt or
887          * timeout.  Generally speaking intel_wait_for_vblank() is only
888          * called during modeset at which time the GPU should be idle and
889          * should *not* be performing page flips and thus not waiting on
890          * vblanks...
891          * Currently, the result of us stealing a vblank from the irq
892          * handler is that a single frame will be skipped during swapbuffers.
893          */
894         I915_WRITE(pipestat_reg,
895                    I915_READ(pipestat_reg) | PIPE_VBLANK_INTERRUPT_STATUS);
896
897         /* Wait for vblank interrupt bit to set */
898         if (wait_for(I915_READ(pipestat_reg) &
899                      PIPE_VBLANK_INTERRUPT_STATUS,
900                      50))
901                 DRM_DEBUG_KMS("vblank wait timed out\n");
902 }
903
904 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
905 {
906         struct drm_i915_private *dev_priv = dev->dev_private;
907         u32 reg = PIPEDSL(pipe);
908         u32 line1, line2;
909         u32 line_mask;
910
911         if (IS_GEN2(dev))
912                 line_mask = DSL_LINEMASK_GEN2;
913         else
914                 line_mask = DSL_LINEMASK_GEN3;
915
916         line1 = I915_READ(reg) & line_mask;
917         mdelay(5);
918         line2 = I915_READ(reg) & line_mask;
919
920         return line1 == line2;
921 }
922
923 /*
924  * intel_wait_for_pipe_off - wait for pipe to turn off
925  * @dev: drm device
926  * @pipe: pipe to wait for
927  *
928  * After disabling a pipe, we can't wait for vblank in the usual way,
929  * spinning on the vblank interrupt status bit, since we won't actually
930  * see an interrupt when the pipe is disabled.
931  *
932  * On Gen4 and above:
933  *   wait for the pipe register state bit to turn off
934  *
935  * Otherwise:
936  *   wait for the display line value to settle (it usually
937  *   ends up stopping at the start of the next frame).
938  *
939  */
940 void intel_wait_for_pipe_off(struct drm_device *dev, int pipe)
941 {
942         struct drm_i915_private *dev_priv = dev->dev_private;
943         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
944                                                                       pipe);
945
946         if (INTEL_INFO(dev)->gen >= 4) {
947                 int reg = PIPECONF(cpu_transcoder);
948
949                 /* Wait for the Pipe State to go off */
950                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
951                              100))
952                         WARN(1, "pipe_off wait timed out\n");
953         } else {
954                 /* Wait for the display line to settle */
955                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
956                         WARN(1, "pipe_off wait timed out\n");
957         }
958 }
959
960 /*
961  * ibx_digital_port_connected - is the specified port connected?
962  * @dev_priv: i915 private structure
963  * @port: the port to test
964  *
965  * Returns true if @port is connected, false otherwise.
966  */
967 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
968                                 struct intel_digital_port *port)
969 {
970         u32 bit;
971
972         if (HAS_PCH_IBX(dev_priv->dev)) {
973                 switch (port->port) {
974                 case PORT_B:
975                         bit = SDE_PORTB_HOTPLUG;
976                         break;
977                 case PORT_C:
978                         bit = SDE_PORTC_HOTPLUG;
979                         break;
980                 case PORT_D:
981                         bit = SDE_PORTD_HOTPLUG;
982                         break;
983                 default:
984                         return true;
985                 }
986         } else {
987                 switch (port->port) {
988                 case PORT_B:
989                         bit = SDE_PORTB_HOTPLUG_CPT;
990                         break;
991                 case PORT_C:
992                         bit = SDE_PORTC_HOTPLUG_CPT;
993                         break;
994                 case PORT_D:
995                         bit = SDE_PORTD_HOTPLUG_CPT;
996                         break;
997                 default:
998                         return true;
999                 }
1000         }
1001
1002         return I915_READ(SDEISR) & bit;
1003 }
1004
1005 static const char *state_string(bool enabled)
1006 {
1007         return enabled ? "on" : "off";
1008 }
1009
1010 /* Only for pre-ILK configs */
1011 void assert_pll(struct drm_i915_private *dev_priv,
1012                 enum pipe pipe, bool state)
1013 {
1014         int reg;
1015         u32 val;
1016         bool cur_state;
1017
1018         reg = DPLL(pipe);
1019         val = I915_READ(reg);
1020         cur_state = !!(val & DPLL_VCO_ENABLE);
1021         WARN(cur_state != state,
1022              "PLL state assertion failure (expected %s, current %s)\n",
1023              state_string(state), state_string(cur_state));
1024 }
1025
1026 /* XXX: the dsi pll is shared between MIPI DSI ports */
1027 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1028 {
1029         u32 val;
1030         bool cur_state;
1031
1032         mutex_lock(&dev_priv->dpio_lock);
1033         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1034         mutex_unlock(&dev_priv->dpio_lock);
1035
1036         cur_state = val & DSI_PLL_VCO_EN;
1037         WARN(cur_state != state,
1038              "DSI PLL state assertion failure (expected %s, current %s)\n",
1039              state_string(state), state_string(cur_state));
1040 }
1041 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1042 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1043
1044 struct intel_shared_dpll *
1045 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1046 {
1047         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1048
1049         if (crtc->config.shared_dpll < 0)
1050                 return NULL;
1051
1052         return &dev_priv->shared_dplls[crtc->config.shared_dpll];
1053 }
1054
1055 /* For ILK+ */
1056 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1057                         struct intel_shared_dpll *pll,
1058                         bool state)
1059 {
1060         bool cur_state;
1061         struct intel_dpll_hw_state hw_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 DPLL %s with no DPLL\n", state_string(state)))
1070                 return;
1071
1072         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1073         WARN(cur_state != state,
1074              "%s assertion failure (expected %s, current %s)\n",
1075              pll->name, state_string(state), state_string(cur_state));
1076 }
1077
1078 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1079                           enum pipe pipe, bool state)
1080 {
1081         int reg;
1082         u32 val;
1083         bool cur_state;
1084         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1085                                                                       pipe);
1086
1087         if (HAS_DDI(dev_priv->dev)) {
1088                 /* DDI does not have a specific FDI_TX register */
1089                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1090                 val = I915_READ(reg);
1091                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1092         } else {
1093                 reg = FDI_TX_CTL(pipe);
1094                 val = I915_READ(reg);
1095                 cur_state = !!(val & FDI_TX_ENABLE);
1096         }
1097         WARN(cur_state != state,
1098              "FDI TX state assertion failure (expected %s, current %s)\n",
1099              state_string(state), state_string(cur_state));
1100 }
1101 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1102 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1103
1104 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1105                           enum pipe pipe, bool state)
1106 {
1107         int reg;
1108         u32 val;
1109         bool cur_state;
1110
1111         reg = FDI_RX_CTL(pipe);
1112         val = I915_READ(reg);
1113         cur_state = !!(val & FDI_RX_ENABLE);
1114         WARN(cur_state != state,
1115              "FDI RX state assertion failure (expected %s, current %s)\n",
1116              state_string(state), state_string(cur_state));
1117 }
1118 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1119 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1120
1121 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1122                                       enum pipe pipe)
1123 {
1124         int reg;
1125         u32 val;
1126
1127         /* ILK FDI PLL is always enabled */
1128         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1129                 return;
1130
1131         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1132         if (HAS_DDI(dev_priv->dev))
1133                 return;
1134
1135         reg = FDI_TX_CTL(pipe);
1136         val = I915_READ(reg);
1137         WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1138 }
1139
1140 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1141                        enum pipe pipe, bool state)
1142 {
1143         int reg;
1144         u32 val;
1145         bool cur_state;
1146
1147         reg = FDI_RX_CTL(pipe);
1148         val = I915_READ(reg);
1149         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1150         WARN(cur_state != state,
1151              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1152              state_string(state), state_string(cur_state));
1153 }
1154
1155 static void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1156                                   enum pipe pipe)
1157 {
1158         int pp_reg, lvds_reg;
1159         u32 val;
1160         enum pipe panel_pipe = PIPE_A;
1161         bool locked = true;
1162
1163         if (HAS_PCH_SPLIT(dev_priv->dev)) {
1164                 pp_reg = PCH_PP_CONTROL;
1165                 lvds_reg = PCH_LVDS;
1166         } else {
1167                 pp_reg = PP_CONTROL;
1168                 lvds_reg = LVDS;
1169         }
1170
1171         val = I915_READ(pp_reg);
1172         if (!(val & PANEL_POWER_ON) ||
1173             ((val & PANEL_UNLOCK_REGS) == PANEL_UNLOCK_REGS))
1174                 locked = false;
1175
1176         if (I915_READ(lvds_reg) & LVDS_PIPEB_SELECT)
1177                 panel_pipe = PIPE_B;
1178
1179         WARN(panel_pipe == pipe && locked,
1180              "panel assertion failure, pipe %c regs locked\n",
1181              pipe_name(pipe));
1182 }
1183
1184 static void assert_cursor(struct drm_i915_private *dev_priv,
1185                           enum pipe pipe, bool state)
1186 {
1187         struct drm_device *dev = dev_priv->dev;
1188         bool cur_state;
1189
1190         if (IS_845G(dev) || IS_I865G(dev))
1191                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1192         else if (INTEL_INFO(dev)->gen <= 6 || IS_VALLEYVIEW(dev))
1193                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1194         else
1195                 cur_state = I915_READ(CURCNTR_IVB(pipe)) & CURSOR_MODE;
1196
1197         WARN(cur_state != state,
1198              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1199              pipe_name(pipe), state_string(state), state_string(cur_state));
1200 }
1201 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1202 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1203
1204 void assert_pipe(struct drm_i915_private *dev_priv,
1205                  enum pipe pipe, bool state)
1206 {
1207         int reg;
1208         u32 val;
1209         bool cur_state;
1210         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1211                                                                       pipe);
1212
1213         /* if we need the pipe A quirk it must be always on */
1214         if (pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE)
1215                 state = true;
1216
1217         if (!intel_display_power_enabled(dev_priv,
1218                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1219                 cur_state = false;
1220         } else {
1221                 reg = PIPECONF(cpu_transcoder);
1222                 val = I915_READ(reg);
1223                 cur_state = !!(val & PIPECONF_ENABLE);
1224         }
1225
1226         WARN(cur_state != state,
1227              "pipe %c assertion failure (expected %s, current %s)\n",
1228              pipe_name(pipe), state_string(state), state_string(cur_state));
1229 }
1230
1231 static void assert_plane(struct drm_i915_private *dev_priv,
1232                          enum plane plane, bool state)
1233 {
1234         int reg;
1235         u32 val;
1236         bool cur_state;
1237
1238         reg = DSPCNTR(plane);
1239         val = I915_READ(reg);
1240         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1241         WARN(cur_state != state,
1242              "plane %c assertion failure (expected %s, current %s)\n",
1243              plane_name(plane), state_string(state), state_string(cur_state));
1244 }
1245
1246 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1247 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1248
1249 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1250                                    enum pipe pipe)
1251 {
1252         struct drm_device *dev = dev_priv->dev;
1253         int reg, i;
1254         u32 val;
1255         int cur_pipe;
1256
1257         /* Primary planes are fixed to pipes on gen4+ */
1258         if (INTEL_INFO(dev)->gen >= 4) {
1259                 reg = DSPCNTR(pipe);
1260                 val = I915_READ(reg);
1261                 WARN(val & DISPLAY_PLANE_ENABLE,
1262                      "plane %c assertion failure, should be disabled but not\n",
1263                      plane_name(pipe));
1264                 return;
1265         }
1266
1267         /* Need to check both planes against the pipe */
1268         for_each_pipe(i) {
1269                 reg = DSPCNTR(i);
1270                 val = I915_READ(reg);
1271                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1272                         DISPPLANE_SEL_PIPE_SHIFT;
1273                 WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1274                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1275                      plane_name(i), pipe_name(pipe));
1276         }
1277 }
1278
1279 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1280                                     enum pipe pipe)
1281 {
1282         struct drm_device *dev = dev_priv->dev;
1283         int reg, sprite;
1284         u32 val;
1285
1286         if (IS_VALLEYVIEW(dev)) {
1287                 for_each_sprite(pipe, sprite) {
1288                         reg = SPCNTR(pipe, sprite);
1289                         val = I915_READ(reg);
1290                         WARN(val & SP_ENABLE,
1291                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1292                              sprite_name(pipe, sprite), pipe_name(pipe));
1293                 }
1294         } else if (INTEL_INFO(dev)->gen >= 7) {
1295                 reg = SPRCTL(pipe);
1296                 val = I915_READ(reg);
1297                 WARN(val & SPRITE_ENABLE,
1298                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1299                      plane_name(pipe), pipe_name(pipe));
1300         } else if (INTEL_INFO(dev)->gen >= 5) {
1301                 reg = DVSCNTR(pipe);
1302                 val = I915_READ(reg);
1303                 WARN(val & DVS_ENABLE,
1304                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1305                      plane_name(pipe), pipe_name(pipe));
1306         }
1307 }
1308
1309 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1310 {
1311         u32 val;
1312         bool enabled;
1313
1314         WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1315
1316         val = I915_READ(PCH_DREF_CONTROL);
1317         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1318                             DREF_SUPERSPREAD_SOURCE_MASK));
1319         WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1320 }
1321
1322 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1323                                            enum pipe pipe)
1324 {
1325         int reg;
1326         u32 val;
1327         bool enabled;
1328
1329         reg = PCH_TRANSCONF(pipe);
1330         val = I915_READ(reg);
1331         enabled = !!(val & TRANS_ENABLE);
1332         WARN(enabled,
1333              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1334              pipe_name(pipe));
1335 }
1336
1337 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1338                             enum pipe pipe, u32 port_sel, u32 val)
1339 {
1340         if ((val & DP_PORT_EN) == 0)
1341                 return false;
1342
1343         if (HAS_PCH_CPT(dev_priv->dev)) {
1344                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1345                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1346                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1347                         return false;
1348         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1349                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1350                         return false;
1351         } else {
1352                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1353                         return false;
1354         }
1355         return true;
1356 }
1357
1358 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1359                               enum pipe pipe, u32 val)
1360 {
1361         if ((val & SDVO_ENABLE) == 0)
1362                 return false;
1363
1364         if (HAS_PCH_CPT(dev_priv->dev)) {
1365                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1366                         return false;
1367         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1368                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1369                         return false;
1370         } else {
1371                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1372                         return false;
1373         }
1374         return true;
1375 }
1376
1377 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1378                               enum pipe pipe, u32 val)
1379 {
1380         if ((val & LVDS_PORT_EN) == 0)
1381                 return false;
1382
1383         if (HAS_PCH_CPT(dev_priv->dev)) {
1384                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1385                         return false;
1386         } else {
1387                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1388                         return false;
1389         }
1390         return true;
1391 }
1392
1393 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1394                               enum pipe pipe, u32 val)
1395 {
1396         if ((val & ADPA_DAC_ENABLE) == 0)
1397                 return false;
1398         if (HAS_PCH_CPT(dev_priv->dev)) {
1399                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1400                         return false;
1401         } else {
1402                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1403                         return false;
1404         }
1405         return true;
1406 }
1407
1408 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1409                                    enum pipe pipe, int reg, u32 port_sel)
1410 {
1411         u32 val = I915_READ(reg);
1412         WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1413              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1414              reg, pipe_name(pipe));
1415
1416         WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1417              && (val & DP_PIPEB_SELECT),
1418              "IBX PCH dp port still using transcoder B\n");
1419 }
1420
1421 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1422                                      enum pipe pipe, int reg)
1423 {
1424         u32 val = I915_READ(reg);
1425         WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1426              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1427              reg, pipe_name(pipe));
1428
1429         WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1430              && (val & SDVO_PIPE_B_SELECT),
1431              "IBX PCH hdmi port still using transcoder B\n");
1432 }
1433
1434 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1435                                       enum pipe pipe)
1436 {
1437         int reg;
1438         u32 val;
1439
1440         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1441         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1442         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1443
1444         reg = PCH_ADPA;
1445         val = I915_READ(reg);
1446         WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1447              "PCH VGA enabled on transcoder %c, should be disabled\n",
1448              pipe_name(pipe));
1449
1450         reg = PCH_LVDS;
1451         val = I915_READ(reg);
1452         WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1453              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1454              pipe_name(pipe));
1455
1456         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1457         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1458         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1459 }
1460
1461 static void intel_init_dpio(struct drm_device *dev)
1462 {
1463         struct drm_i915_private *dev_priv = dev->dev_private;
1464
1465         if (!IS_VALLEYVIEW(dev))
1466                 return;
1467
1468         /*
1469          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1470          * CHV x1 PHY (DP/HDMI D)
1471          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1472          */
1473         if (IS_CHERRYVIEW(dev)) {
1474                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1475                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1476         } else {
1477                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1478         }
1479 }
1480
1481 static void intel_reset_dpio(struct drm_device *dev)
1482 {
1483         struct drm_i915_private *dev_priv = dev->dev_private;
1484
1485         if (!IS_VALLEYVIEW(dev))
1486                 return;
1487
1488         /*
1489          * Enable the CRI clock source so we can get at the display and the
1490          * reference clock for VGA hotplug / manual detection.
1491          */
1492         I915_WRITE(DPLL(PIPE_B), I915_READ(DPLL(PIPE_B)) |
1493                    DPLL_REFA_CLK_ENABLE_VLV |
1494                    DPLL_INTEGRATED_CRI_CLK_VLV);
1495
1496         if (IS_CHERRYVIEW(dev)) {
1497                 enum dpio_phy phy;
1498                 u32 val;
1499
1500                 for (phy = DPIO_PHY0; phy < I915_NUM_PHYS_VLV; phy++) {
1501                         /* Poll for phypwrgood signal */
1502                         if (wait_for(I915_READ(DISPLAY_PHY_STATUS) &
1503                                                 PHY_POWERGOOD(phy), 1))
1504                                 DRM_ERROR("Display PHY %d is not power up\n", phy);
1505
1506                         /*
1507                          * Deassert common lane reset for PHY.
1508                          *
1509                          * This should only be done on init and resume from S3
1510                          * with both PLLs disabled, or we risk losing DPIO and
1511                          * PLL synchronization.
1512                          */
1513                         val = I915_READ(DISPLAY_PHY_CONTROL);
1514                         I915_WRITE(DISPLAY_PHY_CONTROL,
1515                                 PHY_COM_LANE_RESET_DEASSERT(phy, val));
1516                 }
1517
1518         } else {
1519                 /*
1520                  * From VLV2A0_DP_eDP_DPIO_driver_vbios_notes_10.docx -
1521                  *  6.  De-assert cmn_reset/side_reset. Same as VLV X0.
1522                  *   a. GUnit 0x2110 bit[0] set to 1 (def 0)
1523                  *   b. The other bits such as sfr settings / modesel may all
1524                  *      be set to 0.
1525                  *
1526                  * This should only be done on init and resume from S3 with
1527                  * both PLLs disabled, or we risk losing DPIO and PLL
1528                  * synchronization.
1529                  */
1530                 I915_WRITE(DPIO_CTL, I915_READ(DPIO_CTL) | DPIO_CMNRST);
1531         }
1532 }
1533
1534 static void vlv_enable_pll(struct intel_crtc *crtc)
1535 {
1536         struct drm_device *dev = crtc->base.dev;
1537         struct drm_i915_private *dev_priv = dev->dev_private;
1538         int reg = DPLL(crtc->pipe);
1539         u32 dpll = crtc->config.dpll_hw_state.dpll;
1540
1541         assert_pipe_disabled(dev_priv, crtc->pipe);
1542
1543         /* No really, not for ILK+ */
1544         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1545
1546         /* PLL is protected by panel, make sure we can write it */
1547         if (IS_MOBILE(dev_priv->dev) && !IS_I830(dev_priv->dev))
1548                 assert_panel_unlocked(dev_priv, crtc->pipe);
1549
1550         I915_WRITE(reg, dpll);
1551         POSTING_READ(reg);
1552         udelay(150);
1553
1554         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1555                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1556
1557         I915_WRITE(DPLL_MD(crtc->pipe), crtc->config.dpll_hw_state.dpll_md);
1558         POSTING_READ(DPLL_MD(crtc->pipe));
1559
1560         /* We do this three times for luck */
1561         I915_WRITE(reg, dpll);
1562         POSTING_READ(reg);
1563         udelay(150); /* wait for warmup */
1564         I915_WRITE(reg, dpll);
1565         POSTING_READ(reg);
1566         udelay(150); /* wait for warmup */
1567         I915_WRITE(reg, dpll);
1568         POSTING_READ(reg);
1569         udelay(150); /* wait for warmup */
1570 }
1571
1572 static void chv_enable_pll(struct intel_crtc *crtc)
1573 {
1574         struct drm_device *dev = crtc->base.dev;
1575         struct drm_i915_private *dev_priv = dev->dev_private;
1576         int pipe = crtc->pipe;
1577         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1578         int dpll = DPLL(crtc->pipe);
1579         u32 tmp;
1580
1581         assert_pipe_disabled(dev_priv, crtc->pipe);
1582
1583         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1584
1585         mutex_lock(&dev_priv->dpio_lock);
1586
1587         /* Enable back the 10bit clock to display controller */
1588         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1589         tmp |= DPIO_DCLKP_EN;
1590         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1591
1592         /*
1593          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1594          */
1595         udelay(1);
1596
1597         /* Enable PLL */
1598         tmp = I915_READ(dpll);
1599         tmp |= DPLL_VCO_ENABLE;
1600         I915_WRITE(dpll, tmp);
1601
1602         /* Check PLL is locked */
1603         if (wait_for(((I915_READ(dpll) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1604                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1605
1606         /* Deassert soft data lane reset*/
1607         tmp = vlv_dpio_read(dev_priv, pipe, VLV_PCS_DW0(port));
1608         tmp |= (DPIO_PCS_TX_LANE2_RESET | DPIO_PCS_TX_LANE1_RESET);
1609         vlv_dpio_write(dev_priv, pipe, VLV_PCS_DW0(port), tmp);
1610
1611
1612         mutex_unlock(&dev_priv->dpio_lock);
1613 }
1614
1615 static void i9xx_enable_pll(struct intel_crtc *crtc)
1616 {
1617         struct drm_device *dev = crtc->base.dev;
1618         struct drm_i915_private *dev_priv = dev->dev_private;
1619         int reg = DPLL(crtc->pipe);
1620         u32 dpll = crtc->config.dpll_hw_state.dpll;
1621
1622         assert_pipe_disabled(dev_priv, crtc->pipe);
1623
1624         /* No really, not for ILK+ */
1625         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1626
1627         /* PLL is protected by panel, make sure we can write it */
1628         if (IS_MOBILE(dev) && !IS_I830(dev))
1629                 assert_panel_unlocked(dev_priv, crtc->pipe);
1630
1631         I915_WRITE(reg, dpll);
1632
1633         /* Wait for the clocks to stabilize. */
1634         POSTING_READ(reg);
1635         udelay(150);
1636
1637         if (INTEL_INFO(dev)->gen >= 4) {
1638                 I915_WRITE(DPLL_MD(crtc->pipe),
1639                            crtc->config.dpll_hw_state.dpll_md);
1640         } else {
1641                 /* The pixel multiplier can only be updated once the
1642                  * DPLL is enabled and the clocks are stable.
1643                  *
1644                  * So write it again.
1645                  */
1646                 I915_WRITE(reg, dpll);
1647         }
1648
1649         /* We do this three times for luck */
1650         I915_WRITE(reg, dpll);
1651         POSTING_READ(reg);
1652         udelay(150); /* wait for warmup */
1653         I915_WRITE(reg, dpll);
1654         POSTING_READ(reg);
1655         udelay(150); /* wait for warmup */
1656         I915_WRITE(reg, dpll);
1657         POSTING_READ(reg);
1658         udelay(150); /* wait for warmup */
1659 }
1660
1661 /**
1662  * i9xx_disable_pll - disable a PLL
1663  * @dev_priv: i915 private structure
1664  * @pipe: pipe PLL to disable
1665  *
1666  * Disable the PLL for @pipe, making sure the pipe is off first.
1667  *
1668  * Note!  This is for pre-ILK only.
1669  */
1670 static void i9xx_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1671 {
1672         /* Don't disable pipe A or pipe A PLLs if needed */
1673         if (pipe == PIPE_A && (dev_priv->quirks & QUIRK_PIPEA_FORCE))
1674                 return;
1675
1676         /* Make sure the pipe isn't still relying on us */
1677         assert_pipe_disabled(dev_priv, pipe);
1678
1679         I915_WRITE(DPLL(pipe), 0);
1680         POSTING_READ(DPLL(pipe));
1681 }
1682
1683 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1684 {
1685         u32 val = 0;
1686
1687         /* Make sure the pipe isn't still relying on us */
1688         assert_pipe_disabled(dev_priv, pipe);
1689
1690         /*
1691          * Leave integrated clock source and reference clock enabled for pipe B.
1692          * The latter is needed for VGA hotplug / manual detection.
1693          */
1694         if (pipe == PIPE_B)
1695                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1696         I915_WRITE(DPLL(pipe), val);
1697         POSTING_READ(DPLL(pipe));
1698
1699 }
1700
1701 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1702 {
1703         int dpll = DPLL(pipe);
1704         u32 val;
1705
1706         /* Set PLL en = 0 */
1707         val = I915_READ(dpll);
1708         val &= ~DPLL_VCO_ENABLE;
1709         I915_WRITE(dpll, val);
1710
1711 }
1712
1713 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1714                 struct intel_digital_port *dport)
1715 {
1716         u32 port_mask;
1717         int dpll_reg;
1718
1719         switch (dport->port) {
1720         case PORT_B:
1721                 port_mask = DPLL_PORTB_READY_MASK;
1722                 dpll_reg = DPLL(0);
1723                 break;
1724         case PORT_C:
1725                 port_mask = DPLL_PORTC_READY_MASK;
1726                 dpll_reg = DPLL(0);
1727                 break;
1728         case PORT_D:
1729                 port_mask = DPLL_PORTD_READY_MASK;
1730                 dpll_reg = DPIO_PHY_STATUS;
1731                 break;
1732         default:
1733                 BUG();
1734         }
1735
1736         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1737                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1738                      port_name(dport->port), I915_READ(dpll_reg));
1739 }
1740
1741 /**
1742  * ironlake_enable_shared_dpll - enable PCH PLL
1743  * @dev_priv: i915 private structure
1744  * @pipe: pipe PLL to enable
1745  *
1746  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1747  * drives the transcoder clock.
1748  */
1749 static void ironlake_enable_shared_dpll(struct intel_crtc *crtc)
1750 {
1751         struct drm_device *dev = crtc->base.dev;
1752         struct drm_i915_private *dev_priv = dev->dev_private;
1753         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1754
1755         /* PCH PLLs only available on ILK, SNB and IVB */
1756         BUG_ON(INTEL_INFO(dev)->gen < 5);
1757         if (WARN_ON(pll == NULL))
1758                 return;
1759
1760         if (WARN_ON(pll->refcount == 0))
1761                 return;
1762
1763         DRM_DEBUG_KMS("enable %s (active %d, on? %d)for crtc %d\n",
1764                       pll->name, pll->active, pll->on,
1765                       crtc->base.base.id);
1766
1767         if (pll->active++) {
1768                 WARN_ON(!pll->on);
1769                 assert_shared_dpll_enabled(dev_priv, pll);
1770                 return;
1771         }
1772         WARN_ON(pll->on);
1773
1774         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1775         pll->enable(dev_priv, pll);
1776         pll->on = true;
1777 }
1778
1779 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1780 {
1781         struct drm_device *dev = crtc->base.dev;
1782         struct drm_i915_private *dev_priv = dev->dev_private;
1783         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1784
1785         /* PCH only available on ILK+ */
1786         BUG_ON(INTEL_INFO(dev)->gen < 5);
1787         if (WARN_ON(pll == NULL))
1788                return;
1789
1790         if (WARN_ON(pll->refcount == 0))
1791                 return;
1792
1793         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1794                       pll->name, pll->active, pll->on,
1795                       crtc->base.base.id);
1796
1797         if (WARN_ON(pll->active == 0)) {
1798                 assert_shared_dpll_disabled(dev_priv, pll);
1799                 return;
1800         }
1801
1802         assert_shared_dpll_enabled(dev_priv, pll);
1803         WARN_ON(!pll->on);
1804         if (--pll->active)
1805                 return;
1806
1807         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1808         pll->disable(dev_priv, pll);
1809         pll->on = false;
1810 }
1811
1812 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1813                                            enum pipe pipe)
1814 {
1815         struct drm_device *dev = dev_priv->dev;
1816         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1817         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1818         uint32_t reg, val, pipeconf_val;
1819
1820         /* PCH only available on ILK+ */
1821         BUG_ON(INTEL_INFO(dev)->gen < 5);
1822
1823         /* Make sure PCH DPLL is enabled */
1824         assert_shared_dpll_enabled(dev_priv,
1825                                    intel_crtc_to_shared_dpll(intel_crtc));
1826
1827         /* FDI must be feeding us bits for PCH ports */
1828         assert_fdi_tx_enabled(dev_priv, pipe);
1829         assert_fdi_rx_enabled(dev_priv, pipe);
1830
1831         if (HAS_PCH_CPT(dev)) {
1832                 /* Workaround: Set the timing override bit before enabling the
1833                  * pch transcoder. */
1834                 reg = TRANS_CHICKEN2(pipe);
1835                 val = I915_READ(reg);
1836                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1837                 I915_WRITE(reg, val);
1838         }
1839
1840         reg = PCH_TRANSCONF(pipe);
1841         val = I915_READ(reg);
1842         pipeconf_val = I915_READ(PIPECONF(pipe));
1843
1844         if (HAS_PCH_IBX(dev_priv->dev)) {
1845                 /*
1846                  * make the BPC in transcoder be consistent with
1847                  * that in pipeconf reg.
1848                  */
1849                 val &= ~PIPECONF_BPC_MASK;
1850                 val |= pipeconf_val & PIPECONF_BPC_MASK;
1851         }
1852
1853         val &= ~TRANS_INTERLACE_MASK;
1854         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1855                 if (HAS_PCH_IBX(dev_priv->dev) &&
1856                     intel_pipe_has_type(crtc, INTEL_OUTPUT_SDVO))
1857                         val |= TRANS_LEGACY_INTERLACED_ILK;
1858                 else
1859                         val |= TRANS_INTERLACED;
1860         else
1861                 val |= TRANS_PROGRESSIVE;
1862
1863         I915_WRITE(reg, val | TRANS_ENABLE);
1864         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1865                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1866 }
1867
1868 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1869                                       enum transcoder cpu_transcoder)
1870 {
1871         u32 val, pipeconf_val;
1872
1873         /* PCH only available on ILK+ */
1874         BUG_ON(INTEL_INFO(dev_priv->dev)->gen < 5);
1875
1876         /* FDI must be feeding us bits for PCH ports */
1877         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1878         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1879
1880         /* Workaround: set timing override bit. */
1881         val = I915_READ(_TRANSA_CHICKEN2);
1882         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1883         I915_WRITE(_TRANSA_CHICKEN2, val);
1884
1885         val = TRANS_ENABLE;
1886         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1887
1888         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1889             PIPECONF_INTERLACED_ILK)
1890                 val |= TRANS_INTERLACED;
1891         else
1892                 val |= TRANS_PROGRESSIVE;
1893
1894         I915_WRITE(LPT_TRANSCONF, val);
1895         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1896                 DRM_ERROR("Failed to enable PCH transcoder\n");
1897 }
1898
1899 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1900                                             enum pipe pipe)
1901 {
1902         struct drm_device *dev = dev_priv->dev;
1903         uint32_t reg, val;
1904
1905         /* FDI relies on the transcoder */
1906         assert_fdi_tx_disabled(dev_priv, pipe);
1907         assert_fdi_rx_disabled(dev_priv, pipe);
1908
1909         /* Ports must be off as well */
1910         assert_pch_ports_disabled(dev_priv, pipe);
1911
1912         reg = PCH_TRANSCONF(pipe);
1913         val = I915_READ(reg);
1914         val &= ~TRANS_ENABLE;
1915         I915_WRITE(reg, val);
1916         /* wait for PCH transcoder off, transcoder state */
1917         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1918                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1919
1920         if (!HAS_PCH_IBX(dev)) {
1921                 /* Workaround: Clear the timing override chicken bit again. */
1922                 reg = TRANS_CHICKEN2(pipe);
1923                 val = I915_READ(reg);
1924                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1925                 I915_WRITE(reg, val);
1926         }
1927 }
1928
1929 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1930 {
1931         u32 val;
1932
1933         val = I915_READ(LPT_TRANSCONF);
1934         val &= ~TRANS_ENABLE;
1935         I915_WRITE(LPT_TRANSCONF, val);
1936         /* wait for PCH transcoder off, transcoder state */
1937         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1938                 DRM_ERROR("Failed to disable PCH transcoder\n");
1939
1940         /* Workaround: clear timing override bit. */
1941         val = I915_READ(_TRANSA_CHICKEN2);
1942         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1943         I915_WRITE(_TRANSA_CHICKEN2, val);
1944 }
1945
1946 /**
1947  * intel_enable_pipe - enable a pipe, asserting requirements
1948  * @crtc: crtc responsible for the pipe
1949  *
1950  * Enable @crtc's pipe, making sure that various hardware specific requirements
1951  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1952  */
1953 static void intel_enable_pipe(struct intel_crtc *crtc)
1954 {
1955         struct drm_device *dev = crtc->base.dev;
1956         struct drm_i915_private *dev_priv = dev->dev_private;
1957         enum pipe pipe = crtc->pipe;
1958         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1959                                                                       pipe);
1960         enum pipe pch_transcoder;
1961         int reg;
1962         u32 val;
1963
1964         assert_planes_disabled(dev_priv, pipe);
1965         assert_cursor_disabled(dev_priv, pipe);
1966         assert_sprites_disabled(dev_priv, pipe);
1967
1968         if (HAS_PCH_LPT(dev_priv->dev))
1969                 pch_transcoder = TRANSCODER_A;
1970         else
1971                 pch_transcoder = pipe;
1972
1973         /*
1974          * A pipe without a PLL won't actually be able to drive bits from
1975          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1976          * need the check.
1977          */
1978         if (!HAS_PCH_SPLIT(dev_priv->dev))
1979                 if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_DSI))
1980                         assert_dsi_pll_enabled(dev_priv);
1981                 else
1982                         assert_pll_enabled(dev_priv, pipe);
1983         else {
1984                 if (crtc->config.has_pch_encoder) {
1985                         /* if driving the PCH, we need FDI enabled */
1986                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1987                         assert_fdi_tx_pll_enabled(dev_priv,
1988                                                   (enum pipe) cpu_transcoder);
1989                 }
1990                 /* FIXME: assert CPU port conditions for SNB+ */
1991         }
1992
1993         reg = PIPECONF(cpu_transcoder);
1994         val = I915_READ(reg);
1995         if (val & PIPECONF_ENABLE) {
1996                 WARN_ON(!(pipe == PIPE_A &&
1997                           dev_priv->quirks & QUIRK_PIPEA_FORCE));
1998                 return;
1999         }
2000
2001         I915_WRITE(reg, val | PIPECONF_ENABLE);
2002         POSTING_READ(reg);
2003 }
2004
2005 /**
2006  * intel_disable_pipe - disable a pipe, asserting requirements
2007  * @dev_priv: i915 private structure
2008  * @pipe: pipe to disable
2009  *
2010  * Disable @pipe, making sure that various hardware specific requirements
2011  * are met, if applicable, e.g. plane disabled, panel fitter off, etc.
2012  *
2013  * @pipe should be %PIPE_A or %PIPE_B.
2014  *
2015  * Will wait until the pipe has shut down before returning.
2016  */
2017 static void intel_disable_pipe(struct drm_i915_private *dev_priv,
2018                                enum pipe pipe)
2019 {
2020         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2021                                                                       pipe);
2022         int reg;
2023         u32 val;
2024
2025         /*
2026          * Make sure planes won't keep trying to pump pixels to us,
2027          * or we might hang the display.
2028          */
2029         assert_planes_disabled(dev_priv, pipe);
2030         assert_cursor_disabled(dev_priv, pipe);
2031         assert_sprites_disabled(dev_priv, pipe);
2032
2033         /* Don't disable pipe A or pipe A PLLs if needed */
2034         if (pipe == PIPE_A && (dev_priv->quirks & QUIRK_PIPEA_FORCE))
2035                 return;
2036
2037         reg = PIPECONF(cpu_transcoder);
2038         val = I915_READ(reg);
2039         if ((val & PIPECONF_ENABLE) == 0)
2040                 return;
2041
2042         I915_WRITE(reg, val & ~PIPECONF_ENABLE);
2043         intel_wait_for_pipe_off(dev_priv->dev, pipe);
2044 }
2045
2046 /*
2047  * Plane regs are double buffered, going from enabled->disabled needs a
2048  * trigger in order to latch.  The display address reg provides this.
2049  */
2050 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2051                                enum plane plane)
2052 {
2053         struct drm_device *dev = dev_priv->dev;
2054         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2055
2056         I915_WRITE(reg, I915_READ(reg));
2057         POSTING_READ(reg);
2058 }
2059
2060 /**
2061  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2062  * @dev_priv: i915 private structure
2063  * @plane: plane to enable
2064  * @pipe: pipe being fed
2065  *
2066  * Enable @plane on @pipe, making sure that @pipe is running first.
2067  */
2068 static void intel_enable_primary_hw_plane(struct drm_i915_private *dev_priv,
2069                                           enum plane plane, enum pipe pipe)
2070 {
2071         struct intel_crtc *intel_crtc =
2072                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
2073         int reg;
2074         u32 val;
2075
2076         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2077         assert_pipe_enabled(dev_priv, pipe);
2078
2079         if (intel_crtc->primary_enabled)
2080                 return;
2081
2082         intel_crtc->primary_enabled = true;
2083
2084         reg = DSPCNTR(plane);
2085         val = I915_READ(reg);
2086         WARN_ON(val & DISPLAY_PLANE_ENABLE);
2087
2088         I915_WRITE(reg, val | DISPLAY_PLANE_ENABLE);
2089         intel_flush_primary_plane(dev_priv, plane);
2090         intel_wait_for_vblank(dev_priv->dev, pipe);
2091 }
2092
2093 /**
2094  * intel_disable_primary_hw_plane - disable the primary hardware plane
2095  * @dev_priv: i915 private structure
2096  * @plane: plane to disable
2097  * @pipe: pipe consuming the data
2098  *
2099  * Disable @plane; should be an independent operation.
2100  */
2101 static void intel_disable_primary_hw_plane(struct drm_i915_private *dev_priv,
2102                                            enum plane plane, enum pipe pipe)
2103 {
2104         struct intel_crtc *intel_crtc =
2105                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
2106         int reg;
2107         u32 val;
2108
2109         if (!intel_crtc->primary_enabled)
2110                 return;
2111
2112         intel_crtc->primary_enabled = false;
2113
2114         reg = DSPCNTR(plane);
2115         val = I915_READ(reg);
2116         WARN_ON((val & DISPLAY_PLANE_ENABLE) == 0);
2117
2118         I915_WRITE(reg, val & ~DISPLAY_PLANE_ENABLE);
2119         intel_flush_primary_plane(dev_priv, plane);
2120         intel_wait_for_vblank(dev_priv->dev, pipe);
2121 }
2122
2123 static bool need_vtd_wa(struct drm_device *dev)
2124 {
2125 #ifdef CONFIG_INTEL_IOMMU
2126         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2127                 return true;
2128 #endif
2129         return false;
2130 }
2131
2132 static int intel_align_height(struct drm_device *dev, int height, bool tiled)
2133 {
2134         int tile_height;
2135
2136         tile_height = tiled ? (IS_GEN2(dev) ? 16 : 8) : 1;
2137         return ALIGN(height, tile_height);
2138 }
2139
2140 int
2141 intel_pin_and_fence_fb_obj(struct drm_device *dev,
2142                            struct drm_i915_gem_object *obj,
2143                            struct intel_ring_buffer *pipelined)
2144 {
2145         struct drm_i915_private *dev_priv = dev->dev_private;
2146         u32 alignment;
2147         int ret;
2148
2149         switch (obj->tiling_mode) {
2150         case I915_TILING_NONE:
2151                 if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2152                         alignment = 128 * 1024;
2153                 else if (INTEL_INFO(dev)->gen >= 4)
2154                         alignment = 4 * 1024;
2155                 else
2156                         alignment = 64 * 1024;
2157                 break;
2158         case I915_TILING_X:
2159                 /* pin() will align the object as required by fence */
2160                 alignment = 0;
2161                 break;
2162         case I915_TILING_Y:
2163                 WARN(1, "Y tiled bo slipped through, driver bug!\n");
2164                 return -EINVAL;
2165         default:
2166                 BUG();
2167         }
2168
2169         /* Note that the w/a also requires 64 PTE of padding following the
2170          * bo. We currently fill all unused PTE with the shadow page and so
2171          * we should always have valid PTE following the scanout preventing
2172          * the VT-d warning.
2173          */
2174         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2175                 alignment = 256 * 1024;
2176
2177         dev_priv->mm.interruptible = false;
2178         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined);
2179         if (ret)
2180                 goto err_interruptible;
2181
2182         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2183          * fence, whereas 965+ only requires a fence if using
2184          * framebuffer compression.  For simplicity, we always install
2185          * a fence as the cost is not that onerous.
2186          */
2187         ret = i915_gem_object_get_fence(obj);
2188         if (ret)
2189                 goto err_unpin;
2190
2191         i915_gem_object_pin_fence(obj);
2192
2193         dev_priv->mm.interruptible = true;
2194         return 0;
2195
2196 err_unpin:
2197         i915_gem_object_unpin_from_display_plane(obj);
2198 err_interruptible:
2199         dev_priv->mm.interruptible = true;
2200         return ret;
2201 }
2202
2203 void intel_unpin_fb_obj(struct drm_i915_gem_object *obj)
2204 {
2205         i915_gem_object_unpin_fence(obj);
2206         i915_gem_object_unpin_from_display_plane(obj);
2207 }
2208
2209 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2210  * is assumed to be a power-of-two. */
2211 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2212                                              unsigned int tiling_mode,
2213                                              unsigned int cpp,
2214                                              unsigned int pitch)
2215 {
2216         if (tiling_mode != I915_TILING_NONE) {
2217                 unsigned int tile_rows, tiles;
2218
2219                 tile_rows = *y / 8;
2220                 *y %= 8;
2221
2222                 tiles = *x / (512/cpp);
2223                 *x %= 512/cpp;
2224
2225                 return tile_rows * pitch * 8 + tiles * 4096;
2226         } else {
2227                 unsigned int offset;
2228
2229                 offset = *y * pitch + *x * cpp;
2230                 *y = 0;
2231                 *x = (offset & 4095) / cpp;
2232                 return offset & -4096;
2233         }
2234 }
2235
2236 int intel_format_to_fourcc(int format)
2237 {
2238         switch (format) {
2239         case DISPPLANE_8BPP:
2240                 return DRM_FORMAT_C8;
2241         case DISPPLANE_BGRX555:
2242                 return DRM_FORMAT_XRGB1555;
2243         case DISPPLANE_BGRX565:
2244                 return DRM_FORMAT_RGB565;
2245         default:
2246         case DISPPLANE_BGRX888:
2247                 return DRM_FORMAT_XRGB8888;
2248         case DISPPLANE_RGBX888:
2249                 return DRM_FORMAT_XBGR8888;
2250         case DISPPLANE_BGRX101010:
2251                 return DRM_FORMAT_XRGB2101010;
2252         case DISPPLANE_RGBX101010:
2253                 return DRM_FORMAT_XBGR2101010;
2254         }
2255 }
2256
2257 static bool intel_alloc_plane_obj(struct intel_crtc *crtc,
2258                                   struct intel_plane_config *plane_config)
2259 {
2260         struct drm_device *dev = crtc->base.dev;
2261         struct drm_i915_gem_object *obj = NULL;
2262         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2263         u32 base = plane_config->base;
2264
2265         if (plane_config->size == 0)
2266                 return false;
2267
2268         obj = i915_gem_object_create_stolen_for_preallocated(dev, base, base,
2269                                                              plane_config->size);
2270         if (!obj)
2271                 return false;
2272
2273         if (plane_config->tiled) {
2274                 obj->tiling_mode = I915_TILING_X;
2275                 obj->stride = crtc->base.primary->fb->pitches[0];
2276         }
2277
2278         mode_cmd.pixel_format = crtc->base.primary->fb->pixel_format;
2279         mode_cmd.width = crtc->base.primary->fb->width;
2280         mode_cmd.height = crtc->base.primary->fb->height;
2281         mode_cmd.pitches[0] = crtc->base.primary->fb->pitches[0];
2282
2283         mutex_lock(&dev->struct_mutex);
2284
2285         if (intel_framebuffer_init(dev, to_intel_framebuffer(crtc->base.primary->fb),
2286                                    &mode_cmd, obj)) {
2287                 DRM_DEBUG_KMS("intel fb init failed\n");
2288                 goto out_unref_obj;
2289         }
2290
2291         mutex_unlock(&dev->struct_mutex);
2292
2293         DRM_DEBUG_KMS("plane fb obj %p\n", obj);
2294         return true;
2295
2296 out_unref_obj:
2297         drm_gem_object_unreference(&obj->base);
2298         mutex_unlock(&dev->struct_mutex);
2299         return false;
2300 }
2301
2302 static void intel_find_plane_obj(struct intel_crtc *intel_crtc,
2303                                  struct intel_plane_config *plane_config)
2304 {
2305         struct drm_device *dev = intel_crtc->base.dev;
2306         struct drm_crtc *c;
2307         struct intel_crtc *i;
2308         struct intel_framebuffer *fb;
2309
2310         if (!intel_crtc->base.primary->fb)
2311                 return;
2312
2313         if (intel_alloc_plane_obj(intel_crtc, plane_config))
2314                 return;
2315
2316         kfree(intel_crtc->base.primary->fb);
2317         intel_crtc->base.primary->fb = NULL;
2318
2319         /*
2320          * Failed to alloc the obj, check to see if we should share
2321          * an fb with another CRTC instead
2322          */
2323         for_each_crtc(dev, c) {
2324                 i = to_intel_crtc(c);
2325
2326                 if (c == &intel_crtc->base)
2327                         continue;
2328
2329                 if (!i->active || !c->primary->fb)
2330                         continue;
2331
2332                 fb = to_intel_framebuffer(c->primary->fb);
2333                 if (i915_gem_obj_ggtt_offset(fb->obj) == plane_config->base) {
2334                         drm_framebuffer_reference(c->primary->fb);
2335                         intel_crtc->base.primary->fb = c->primary->fb;
2336                         break;
2337                 }
2338         }
2339 }
2340
2341 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2342                                       struct drm_framebuffer *fb,
2343                                       int x, int y)
2344 {
2345         struct drm_device *dev = crtc->dev;
2346         struct drm_i915_private *dev_priv = dev->dev_private;
2347         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2348         struct intel_framebuffer *intel_fb;
2349         struct drm_i915_gem_object *obj;
2350         int plane = intel_crtc->plane;
2351         unsigned long linear_offset;
2352         u32 dspcntr;
2353         u32 reg;
2354
2355         intel_fb = to_intel_framebuffer(fb);
2356         obj = intel_fb->obj;
2357
2358         reg = DSPCNTR(plane);
2359         dspcntr = I915_READ(reg);
2360         /* Mask out pixel format bits in case we change it */
2361         dspcntr &= ~DISPPLANE_PIXFORMAT_MASK;
2362         switch (fb->pixel_format) {
2363         case DRM_FORMAT_C8:
2364                 dspcntr |= DISPPLANE_8BPP;
2365                 break;
2366         case DRM_FORMAT_XRGB1555:
2367         case DRM_FORMAT_ARGB1555:
2368                 dspcntr |= DISPPLANE_BGRX555;
2369                 break;
2370         case DRM_FORMAT_RGB565:
2371                 dspcntr |= DISPPLANE_BGRX565;
2372                 break;
2373         case DRM_FORMAT_XRGB8888:
2374         case DRM_FORMAT_ARGB8888:
2375                 dspcntr |= DISPPLANE_BGRX888;
2376                 break;
2377         case DRM_FORMAT_XBGR8888:
2378         case DRM_FORMAT_ABGR8888:
2379                 dspcntr |= DISPPLANE_RGBX888;
2380                 break;
2381         case DRM_FORMAT_XRGB2101010:
2382         case DRM_FORMAT_ARGB2101010:
2383                 dspcntr |= DISPPLANE_BGRX101010;
2384                 break;
2385         case DRM_FORMAT_XBGR2101010:
2386         case DRM_FORMAT_ABGR2101010:
2387                 dspcntr |= DISPPLANE_RGBX101010;
2388                 break;
2389         default:
2390                 BUG();
2391         }
2392
2393         if (INTEL_INFO(dev)->gen >= 4) {
2394                 if (obj->tiling_mode != I915_TILING_NONE)
2395                         dspcntr |= DISPPLANE_TILED;
2396                 else
2397                         dspcntr &= ~DISPPLANE_TILED;
2398         }
2399
2400         if (IS_G4X(dev))
2401                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2402
2403         I915_WRITE(reg, dspcntr);
2404
2405         linear_offset = y * fb->pitches[0] + x * (fb->bits_per_pixel / 8);
2406
2407         if (INTEL_INFO(dev)->gen >= 4) {
2408                 intel_crtc->dspaddr_offset =
2409                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2410                                                        fb->bits_per_pixel / 8,
2411                                                        fb->pitches[0]);
2412                 linear_offset -= intel_crtc->dspaddr_offset;
2413         } else {
2414                 intel_crtc->dspaddr_offset = linear_offset;
2415         }
2416
2417         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2418                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2419                       fb->pitches[0]);
2420         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2421         if (INTEL_INFO(dev)->gen >= 4) {
2422                 I915_WRITE(DSPSURF(plane),
2423                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2424                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2425                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2426         } else
2427                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2428         POSTING_READ(reg);
2429 }
2430
2431 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2432                                           struct drm_framebuffer *fb,
2433                                           int x, int y)
2434 {
2435         struct drm_device *dev = crtc->dev;
2436         struct drm_i915_private *dev_priv = dev->dev_private;
2437         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2438         struct intel_framebuffer *intel_fb;
2439         struct drm_i915_gem_object *obj;
2440         int plane = intel_crtc->plane;
2441         unsigned long linear_offset;
2442         u32 dspcntr;
2443         u32 reg;
2444
2445         intel_fb = to_intel_framebuffer(fb);
2446         obj = intel_fb->obj;
2447
2448         reg = DSPCNTR(plane);
2449         dspcntr = I915_READ(reg);
2450         /* Mask out pixel format bits in case we change it */
2451         dspcntr &= ~DISPPLANE_PIXFORMAT_MASK;
2452         switch (fb->pixel_format) {
2453         case DRM_FORMAT_C8:
2454                 dspcntr |= DISPPLANE_8BPP;
2455                 break;
2456         case DRM_FORMAT_RGB565:
2457                 dspcntr |= DISPPLANE_BGRX565;
2458                 break;
2459         case DRM_FORMAT_XRGB8888:
2460         case DRM_FORMAT_ARGB8888:
2461                 dspcntr |= DISPPLANE_BGRX888;
2462                 break;
2463         case DRM_FORMAT_XBGR8888:
2464         case DRM_FORMAT_ABGR8888:
2465                 dspcntr |= DISPPLANE_RGBX888;
2466                 break;
2467         case DRM_FORMAT_XRGB2101010:
2468         case DRM_FORMAT_ARGB2101010:
2469                 dspcntr |= DISPPLANE_BGRX101010;
2470                 break;
2471         case DRM_FORMAT_XBGR2101010:
2472         case DRM_FORMAT_ABGR2101010:
2473                 dspcntr |= DISPPLANE_RGBX101010;
2474                 break;
2475         default:
2476                 BUG();
2477         }
2478
2479         if (obj->tiling_mode != I915_TILING_NONE)
2480                 dspcntr |= DISPPLANE_TILED;
2481         else
2482                 dspcntr &= ~DISPPLANE_TILED;
2483
2484         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2485                 dspcntr &= ~DISPPLANE_TRICKLE_FEED_DISABLE;
2486         else
2487                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2488
2489         I915_WRITE(reg, dspcntr);
2490
2491         linear_offset = y * fb->pitches[0] + x * (fb->bits_per_pixel / 8);
2492         intel_crtc->dspaddr_offset =
2493                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2494                                                fb->bits_per_pixel / 8,
2495                                                fb->pitches[0]);
2496         linear_offset -= intel_crtc->dspaddr_offset;
2497
2498         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2499                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2500                       fb->pitches[0]);
2501         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2502         I915_WRITE(DSPSURF(plane),
2503                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2504         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2505                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2506         } else {
2507                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2508                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2509         }
2510         POSTING_READ(reg);
2511 }
2512
2513 /* Assume fb object is pinned & idle & fenced and just update base pointers */
2514 static int
2515 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2516                            int x, int y, enum mode_set_atomic state)
2517 {
2518         struct drm_device *dev = crtc->dev;
2519         struct drm_i915_private *dev_priv = dev->dev_private;
2520
2521         if (dev_priv->display.disable_fbc)
2522                 dev_priv->display.disable_fbc(dev);
2523         intel_increase_pllclock(crtc);
2524
2525         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2526
2527         return 0;
2528 }
2529
2530 void intel_display_handle_reset(struct drm_device *dev)
2531 {
2532         struct drm_i915_private *dev_priv = dev->dev_private;
2533         struct drm_crtc *crtc;
2534
2535         /*
2536          * Flips in the rings have been nuked by the reset,
2537          * so complete all pending flips so that user space
2538          * will get its events and not get stuck.
2539          *
2540          * Also update the base address of all primary
2541          * planes to the the last fb to make sure we're
2542          * showing the correct fb after a reset.
2543          *
2544          * Need to make two loops over the crtcs so that we
2545          * don't try to grab a crtc mutex before the
2546          * pending_flip_queue really got woken up.
2547          */
2548
2549         for_each_crtc(dev, crtc) {
2550                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2551                 enum plane plane = intel_crtc->plane;
2552
2553                 intel_prepare_page_flip(dev, plane);
2554                 intel_finish_page_flip_plane(dev, plane);
2555         }
2556
2557         for_each_crtc(dev, crtc) {
2558                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2559
2560                 mutex_lock(&crtc->mutex);
2561                 /*
2562                  * FIXME: Once we have proper support for primary planes (and
2563                  * disabling them without disabling the entire crtc) allow again
2564                  * a NULL crtc->primary->fb.
2565                  */
2566                 if (intel_crtc->active && crtc->primary->fb)
2567                         dev_priv->display.update_primary_plane(crtc,
2568                                                                crtc->primary->fb,
2569                                                                crtc->x,
2570                                                                crtc->y);
2571                 mutex_unlock(&crtc->mutex);
2572         }
2573 }
2574
2575 static int
2576 intel_finish_fb(struct drm_framebuffer *old_fb)
2577 {
2578         struct drm_i915_gem_object *obj = to_intel_framebuffer(old_fb)->obj;
2579         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2580         bool was_interruptible = dev_priv->mm.interruptible;
2581         int ret;
2582
2583         /* Big Hammer, we also need to ensure that any pending
2584          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
2585          * current scanout is retired before unpinning the old
2586          * framebuffer.
2587          *
2588          * This should only fail upon a hung GPU, in which case we
2589          * can safely continue.
2590          */
2591         dev_priv->mm.interruptible = false;
2592         ret = i915_gem_object_finish_gpu(obj);
2593         dev_priv->mm.interruptible = was_interruptible;
2594
2595         return ret;
2596 }
2597
2598 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
2599 {
2600         struct drm_device *dev = crtc->dev;
2601         struct drm_i915_private *dev_priv = dev->dev_private;
2602         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2603         unsigned long flags;
2604         bool pending;
2605
2606         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
2607             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
2608                 return false;
2609
2610         spin_lock_irqsave(&dev->event_lock, flags);
2611         pending = to_intel_crtc(crtc)->unpin_work != NULL;
2612         spin_unlock_irqrestore(&dev->event_lock, flags);
2613
2614         return pending;
2615 }
2616
2617 static int
2618 intel_pipe_set_base(struct drm_crtc *crtc, int x, int y,
2619                     struct drm_framebuffer *fb)
2620 {
2621         struct drm_device *dev = crtc->dev;
2622         struct drm_i915_private *dev_priv = dev->dev_private;
2623         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2624         struct drm_framebuffer *old_fb;
2625         int ret;
2626
2627         if (intel_crtc_has_pending_flip(crtc)) {
2628                 DRM_ERROR("pipe is still busy with an old pageflip\n");
2629                 return -EBUSY;
2630         }
2631
2632         /* no fb bound */
2633         if (!fb) {
2634                 DRM_ERROR("No FB bound\n");
2635                 return 0;
2636         }
2637
2638         if (intel_crtc->plane > INTEL_INFO(dev)->num_pipes) {
2639                 DRM_ERROR("no plane for crtc: plane %c, num_pipes %d\n",
2640                           plane_name(intel_crtc->plane),
2641                           INTEL_INFO(dev)->num_pipes);
2642                 return -EINVAL;
2643         }
2644
2645         mutex_lock(&dev->struct_mutex);
2646         ret = intel_pin_and_fence_fb_obj(dev,
2647                                          to_intel_framebuffer(fb)->obj,
2648                                          NULL);
2649         mutex_unlock(&dev->struct_mutex);
2650         if (ret != 0) {
2651                 DRM_ERROR("pin & fence failed\n");
2652                 return ret;
2653         }
2654
2655         /*
2656          * Update pipe size and adjust fitter if needed: the reason for this is
2657          * that in compute_mode_changes we check the native mode (not the pfit
2658          * mode) to see if we can flip rather than do a full mode set. In the
2659          * fastboot case, we'll flip, but if we don't update the pipesrc and
2660          * pfit state, we'll end up with a big fb scanned out into the wrong
2661          * sized surface.
2662          *
2663          * To fix this properly, we need to hoist the checks up into
2664          * compute_mode_changes (or above), check the actual pfit state and
2665          * whether the platform allows pfit disable with pipe active, and only
2666          * then update the pipesrc and pfit state, even on the flip path.
2667          */
2668         if (i915.fastboot) {
2669                 const struct drm_display_mode *adjusted_mode =
2670                         &intel_crtc->config.adjusted_mode;
2671
2672                 I915_WRITE(PIPESRC(intel_crtc->pipe),
2673                            ((adjusted_mode->crtc_hdisplay - 1) << 16) |
2674                            (adjusted_mode->crtc_vdisplay - 1));
2675                 if (!intel_crtc->config.pch_pfit.enabled &&
2676                     (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
2677                      intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
2678                         I915_WRITE(PF_CTL(intel_crtc->pipe), 0);
2679                         I915_WRITE(PF_WIN_POS(intel_crtc->pipe), 0);
2680                         I915_WRITE(PF_WIN_SZ(intel_crtc->pipe), 0);
2681                 }
2682                 intel_crtc->config.pipe_src_w = adjusted_mode->crtc_hdisplay;
2683                 intel_crtc->config.pipe_src_h = adjusted_mode->crtc_vdisplay;
2684         }
2685
2686         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2687
2688         old_fb = crtc->primary->fb;
2689         crtc->primary->fb = fb;
2690         crtc->x = x;
2691         crtc->y = y;
2692
2693         if (old_fb) {
2694                 if (intel_crtc->active && old_fb != fb)
2695                         intel_wait_for_vblank(dev, intel_crtc->pipe);
2696                 mutex_lock(&dev->struct_mutex);
2697                 intel_unpin_fb_obj(to_intel_framebuffer(old_fb)->obj);
2698                 mutex_unlock(&dev->struct_mutex);
2699         }
2700
2701         mutex_lock(&dev->struct_mutex);
2702         intel_update_fbc(dev);
2703         intel_edp_psr_update(dev);
2704         mutex_unlock(&dev->struct_mutex);
2705
2706         return 0;
2707 }
2708
2709 static void intel_fdi_normal_train(struct drm_crtc *crtc)
2710 {
2711         struct drm_device *dev = crtc->dev;
2712         struct drm_i915_private *dev_priv = dev->dev_private;
2713         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2714         int pipe = intel_crtc->pipe;
2715         u32 reg, temp;
2716
2717         /* enable normal train */
2718         reg = FDI_TX_CTL(pipe);
2719         temp = I915_READ(reg);
2720         if (IS_IVYBRIDGE(dev)) {
2721                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
2722                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
2723         } else {
2724                 temp &= ~FDI_LINK_TRAIN_NONE;
2725                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
2726         }
2727         I915_WRITE(reg, temp);
2728
2729         reg = FDI_RX_CTL(pipe);
2730         temp = I915_READ(reg);
2731         if (HAS_PCH_CPT(dev)) {
2732                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2733                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
2734         } else {
2735                 temp &= ~FDI_LINK_TRAIN_NONE;
2736                 temp |= FDI_LINK_TRAIN_NONE;
2737         }
2738         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
2739
2740         /* wait one idle pattern time */
2741         POSTING_READ(reg);
2742         udelay(1000);
2743
2744         /* IVB wants error correction enabled */
2745         if (IS_IVYBRIDGE(dev))
2746                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
2747                            FDI_FE_ERRC_ENABLE);
2748 }
2749
2750 static bool pipe_has_enabled_pch(struct intel_crtc *crtc)
2751 {
2752         return crtc->base.enabled && crtc->active &&
2753                 crtc->config.has_pch_encoder;
2754 }
2755
2756 static void ivb_modeset_global_resources(struct drm_device *dev)
2757 {
2758         struct drm_i915_private *dev_priv = dev->dev_private;
2759         struct intel_crtc *pipe_B_crtc =
2760                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
2761         struct intel_crtc *pipe_C_crtc =
2762                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_C]);
2763         uint32_t temp;
2764
2765         /*
2766          * When everything is off disable fdi C so that we could enable fdi B
2767          * with all lanes. Note that we don't care about enabled pipes without
2768          * an enabled pch encoder.
2769          */
2770         if (!pipe_has_enabled_pch(pipe_B_crtc) &&
2771             !pipe_has_enabled_pch(pipe_C_crtc)) {
2772                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
2773                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
2774
2775                 temp = I915_READ(SOUTH_CHICKEN1);
2776                 temp &= ~FDI_BC_BIFURCATION_SELECT;
2777                 DRM_DEBUG_KMS("disabling fdi C rx\n");
2778                 I915_WRITE(SOUTH_CHICKEN1, temp);
2779         }
2780 }
2781
2782 /* The FDI link training functions for ILK/Ibexpeak. */
2783 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
2784 {
2785         struct drm_device *dev = crtc->dev;
2786         struct drm_i915_private *dev_priv = dev->dev_private;
2787         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2788         int pipe = intel_crtc->pipe;
2789         u32 reg, temp, tries;
2790
2791         /* FDI needs bits from pipe first */
2792         assert_pipe_enabled(dev_priv, pipe);
2793
2794         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
2795            for train result */
2796         reg = FDI_RX_IMR(pipe);
2797         temp = I915_READ(reg);
2798         temp &= ~FDI_RX_SYMBOL_LOCK;
2799         temp &= ~FDI_RX_BIT_LOCK;
2800         I915_WRITE(reg, temp);
2801         I915_READ(reg);
2802         udelay(150);
2803
2804         /* enable CPU FDI TX and PCH FDI RX */
2805         reg = FDI_TX_CTL(pipe);
2806         temp = I915_READ(reg);
2807         temp &= ~FDI_DP_PORT_WIDTH_MASK;
2808         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
2809         temp &= ~FDI_LINK_TRAIN_NONE;
2810         temp |= FDI_LINK_TRAIN_PATTERN_1;
2811         I915_WRITE(reg, temp | FDI_TX_ENABLE);
2812
2813         reg = FDI_RX_CTL(pipe);
2814         temp = I915_READ(reg);
2815         temp &= ~FDI_LINK_TRAIN_NONE;
2816         temp |= FDI_LINK_TRAIN_PATTERN_1;
2817         I915_WRITE(reg, temp | FDI_RX_ENABLE);
2818
2819         POSTING_READ(reg);
2820         udelay(150);
2821
2822         /* Ironlake workaround, enable clock pointer after FDI enable*/
2823         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
2824         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
2825                    FDI_RX_PHASE_SYNC_POINTER_EN);
2826
2827         reg = FDI_RX_IIR(pipe);
2828         for (tries = 0; tries < 5; tries++) {
2829                 temp = I915_READ(reg);
2830                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2831
2832                 if ((temp & FDI_RX_BIT_LOCK)) {
2833                         DRM_DEBUG_KMS("FDI train 1 done.\n");
2834                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
2835                         break;
2836                 }
2837         }
2838         if (tries == 5)
2839                 DRM_ERROR("FDI train 1 fail!\n");
2840
2841         /* Train 2 */
2842         reg = FDI_TX_CTL(pipe);
2843         temp = I915_READ(reg);
2844         temp &= ~FDI_LINK_TRAIN_NONE;
2845         temp |= FDI_LINK_TRAIN_PATTERN_2;
2846         I915_WRITE(reg, temp);
2847
2848         reg = FDI_RX_CTL(pipe);
2849         temp = I915_READ(reg);
2850         temp &= ~FDI_LINK_TRAIN_NONE;
2851         temp |= FDI_LINK_TRAIN_PATTERN_2;
2852         I915_WRITE(reg, temp);
2853
2854         POSTING_READ(reg);
2855         udelay(150);
2856
2857         reg = FDI_RX_IIR(pipe);
2858         for (tries = 0; tries < 5; tries++) {
2859                 temp = I915_READ(reg);
2860                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2861
2862                 if (temp & FDI_RX_SYMBOL_LOCK) {
2863                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
2864                         DRM_DEBUG_KMS("FDI train 2 done.\n");
2865                         break;
2866                 }
2867         }
2868         if (tries == 5)
2869                 DRM_ERROR("FDI train 2 fail!\n");
2870
2871         DRM_DEBUG_KMS("FDI train done\n");
2872
2873 }
2874
2875 static const int snb_b_fdi_train_param[] = {
2876         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
2877         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
2878         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
2879         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
2880 };
2881
2882 /* The FDI link training functions for SNB/Cougarpoint. */
2883 static void gen6_fdi_link_train(struct drm_crtc *crtc)
2884 {
2885         struct drm_device *dev = crtc->dev;
2886         struct drm_i915_private *dev_priv = dev->dev_private;
2887         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2888         int pipe = intel_crtc->pipe;
2889         u32 reg, temp, i, retry;
2890
2891         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
2892            for train result */
2893         reg = FDI_RX_IMR(pipe);
2894         temp = I915_READ(reg);
2895         temp &= ~FDI_RX_SYMBOL_LOCK;
2896         temp &= ~FDI_RX_BIT_LOCK;
2897         I915_WRITE(reg, temp);
2898
2899         POSTING_READ(reg);
2900         udelay(150);
2901
2902         /* enable CPU FDI TX and PCH FDI RX */
2903         reg = FDI_TX_CTL(pipe);
2904         temp = I915_READ(reg);
2905         temp &= ~FDI_DP_PORT_WIDTH_MASK;
2906         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
2907         temp &= ~FDI_LINK_TRAIN_NONE;
2908         temp |= FDI_LINK_TRAIN_PATTERN_1;
2909         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2910         /* SNB-B */
2911         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2912         I915_WRITE(reg, temp | FDI_TX_ENABLE);
2913
2914         I915_WRITE(FDI_RX_MISC(pipe),
2915                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
2916
2917         reg = FDI_RX_CTL(pipe);
2918         temp = I915_READ(reg);
2919         if (HAS_PCH_CPT(dev)) {
2920                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2921                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
2922         } else {
2923                 temp &= ~FDI_LINK_TRAIN_NONE;
2924                 temp |= FDI_LINK_TRAIN_PATTERN_1;
2925         }
2926         I915_WRITE(reg, temp | FDI_RX_ENABLE);
2927
2928         POSTING_READ(reg);
2929         udelay(150);
2930
2931         for (i = 0; i < 4; i++) {
2932                 reg = FDI_TX_CTL(pipe);
2933                 temp = I915_READ(reg);
2934                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2935                 temp |= snb_b_fdi_train_param[i];
2936                 I915_WRITE(reg, temp);
2937
2938                 POSTING_READ(reg);
2939                 udelay(500);
2940
2941                 for (retry = 0; retry < 5; retry++) {
2942                         reg = FDI_RX_IIR(pipe);
2943                         temp = I915_READ(reg);
2944                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2945                         if (temp & FDI_RX_BIT_LOCK) {
2946                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
2947                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
2948                                 break;
2949                         }
2950                         udelay(50);
2951                 }
2952                 if (retry < 5)
2953                         break;
2954         }
2955         if (i == 4)
2956                 DRM_ERROR("FDI train 1 fail!\n");
2957
2958         /* Train 2 */
2959         reg = FDI_TX_CTL(pipe);
2960         temp = I915_READ(reg);
2961         temp &= ~FDI_LINK_TRAIN_NONE;
2962         temp |= FDI_LINK_TRAIN_PATTERN_2;
2963         if (IS_GEN6(dev)) {
2964                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2965                 /* SNB-B */
2966                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
2967         }
2968         I915_WRITE(reg, temp);
2969
2970         reg = FDI_RX_CTL(pipe);
2971         temp = I915_READ(reg);
2972         if (HAS_PCH_CPT(dev)) {
2973                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2974                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
2975         } else {
2976                 temp &= ~FDI_LINK_TRAIN_NONE;
2977                 temp |= FDI_LINK_TRAIN_PATTERN_2;
2978         }
2979         I915_WRITE(reg, temp);
2980
2981         POSTING_READ(reg);
2982         udelay(150);
2983
2984         for (i = 0; i < 4; i++) {
2985                 reg = FDI_TX_CTL(pipe);
2986                 temp = I915_READ(reg);
2987                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
2988                 temp |= snb_b_fdi_train_param[i];
2989                 I915_WRITE(reg, temp);
2990
2991                 POSTING_READ(reg);
2992                 udelay(500);
2993
2994                 for (retry = 0; retry < 5; retry++) {
2995                         reg = FDI_RX_IIR(pipe);
2996                         temp = I915_READ(reg);
2997                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
2998                         if (temp & FDI_RX_SYMBOL_LOCK) {
2999                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3000                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3001                                 break;
3002                         }
3003                         udelay(50);
3004                 }
3005                 if (retry < 5)
3006                         break;
3007         }
3008         if (i == 4)
3009                 DRM_ERROR("FDI train 2 fail!\n");
3010
3011         DRM_DEBUG_KMS("FDI train done.\n");
3012 }
3013
3014 /* Manual link training for Ivy Bridge A0 parts */
3015 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3016 {
3017         struct drm_device *dev = crtc->dev;
3018         struct drm_i915_private *dev_priv = dev->dev_private;
3019         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3020         int pipe = intel_crtc->pipe;
3021         u32 reg, temp, i, j;
3022
3023         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3024            for train result */
3025         reg = FDI_RX_IMR(pipe);
3026         temp = I915_READ(reg);
3027         temp &= ~FDI_RX_SYMBOL_LOCK;
3028         temp &= ~FDI_RX_BIT_LOCK;
3029         I915_WRITE(reg, temp);
3030
3031         POSTING_READ(reg);
3032         udelay(150);
3033
3034         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3035                       I915_READ(FDI_RX_IIR(pipe)));
3036
3037         /* Try each vswing and preemphasis setting twice before moving on */
3038         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3039                 /* disable first in case we need to retry */
3040                 reg = FDI_TX_CTL(pipe);
3041                 temp = I915_READ(reg);
3042                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3043                 temp &= ~FDI_TX_ENABLE;
3044                 I915_WRITE(reg, temp);
3045
3046                 reg = FDI_RX_CTL(pipe);
3047                 temp = I915_READ(reg);
3048                 temp &= ~FDI_LINK_TRAIN_AUTO;
3049                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3050                 temp &= ~FDI_RX_ENABLE;
3051                 I915_WRITE(reg, temp);
3052
3053                 /* enable CPU FDI TX and PCH FDI RX */
3054                 reg = FDI_TX_CTL(pipe);
3055                 temp = I915_READ(reg);
3056                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3057                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3058                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3059                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3060                 temp |= snb_b_fdi_train_param[j/2];
3061                 temp |= FDI_COMPOSITE_SYNC;
3062                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3063
3064                 I915_WRITE(FDI_RX_MISC(pipe),
3065                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3066
3067                 reg = FDI_RX_CTL(pipe);
3068                 temp = I915_READ(reg);
3069                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3070                 temp |= FDI_COMPOSITE_SYNC;
3071                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3072
3073                 POSTING_READ(reg);
3074                 udelay(1); /* should be 0.5us */
3075
3076                 for (i = 0; i < 4; i++) {
3077                         reg = FDI_RX_IIR(pipe);
3078                         temp = I915_READ(reg);
3079                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3080
3081                         if (temp & FDI_RX_BIT_LOCK ||
3082                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3083                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3084                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3085                                               i);
3086                                 break;
3087                         }
3088                         udelay(1); /* should be 0.5us */
3089                 }
3090                 if (i == 4) {
3091                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3092                         continue;
3093                 }
3094
3095                 /* Train 2 */
3096                 reg = FDI_TX_CTL(pipe);
3097                 temp = I915_READ(reg);
3098                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3099                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3100                 I915_WRITE(reg, temp);
3101
3102                 reg = FDI_RX_CTL(pipe);
3103                 temp = I915_READ(reg);
3104                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3105                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3106                 I915_WRITE(reg, temp);
3107
3108                 POSTING_READ(reg);
3109                 udelay(2); /* should be 1.5us */
3110
3111                 for (i = 0; i < 4; i++) {
3112                         reg = FDI_RX_IIR(pipe);
3113                         temp = I915_READ(reg);
3114                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3115
3116                         if (temp & FDI_RX_SYMBOL_LOCK ||
3117                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3118                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3119                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3120                                               i);
3121                                 goto train_done;
3122                         }
3123                         udelay(2); /* should be 1.5us */
3124                 }
3125                 if (i == 4)
3126                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3127         }
3128
3129 train_done:
3130         DRM_DEBUG_KMS("FDI train done.\n");
3131 }
3132
3133 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3134 {
3135         struct drm_device *dev = intel_crtc->base.dev;
3136         struct drm_i915_private *dev_priv = dev->dev_private;
3137         int pipe = intel_crtc->pipe;
3138         u32 reg, temp;
3139
3140
3141         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3142         reg = FDI_RX_CTL(pipe);
3143         temp = I915_READ(reg);
3144         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3145         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3146         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3147         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3148
3149         POSTING_READ(reg);
3150         udelay(200);
3151
3152         /* Switch from Rawclk to PCDclk */
3153         temp = I915_READ(reg);
3154         I915_WRITE(reg, temp | FDI_PCDCLK);
3155
3156         POSTING_READ(reg);
3157         udelay(200);
3158
3159         /* Enable CPU FDI TX PLL, always on for Ironlake */
3160         reg = FDI_TX_CTL(pipe);
3161         temp = I915_READ(reg);
3162         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3163                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3164
3165                 POSTING_READ(reg);
3166                 udelay(100);
3167         }
3168 }
3169
3170 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3171 {
3172         struct drm_device *dev = intel_crtc->base.dev;
3173         struct drm_i915_private *dev_priv = dev->dev_private;
3174         int pipe = intel_crtc->pipe;
3175         u32 reg, temp;
3176
3177         /* Switch from PCDclk to Rawclk */
3178         reg = FDI_RX_CTL(pipe);
3179         temp = I915_READ(reg);
3180         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3181
3182         /* Disable CPU FDI TX PLL */
3183         reg = FDI_TX_CTL(pipe);
3184         temp = I915_READ(reg);
3185         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3186
3187         POSTING_READ(reg);
3188         udelay(100);
3189
3190         reg = FDI_RX_CTL(pipe);
3191         temp = I915_READ(reg);
3192         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3193
3194         /* Wait for the clocks to turn off. */
3195         POSTING_READ(reg);
3196         udelay(100);
3197 }
3198
3199 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3200 {
3201         struct drm_device *dev = crtc->dev;
3202         struct drm_i915_private *dev_priv = dev->dev_private;
3203         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3204         int pipe = intel_crtc->pipe;
3205         u32 reg, temp;
3206
3207         /* disable CPU FDI tx and PCH FDI rx */
3208         reg = FDI_TX_CTL(pipe);
3209         temp = I915_READ(reg);
3210         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3211         POSTING_READ(reg);
3212
3213         reg = FDI_RX_CTL(pipe);
3214         temp = I915_READ(reg);
3215         temp &= ~(0x7 << 16);
3216         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3217         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3218
3219         POSTING_READ(reg);
3220         udelay(100);
3221
3222         /* Ironlake workaround, disable clock pointer after downing FDI */
3223         if (HAS_PCH_IBX(dev))
3224                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3225
3226         /* still set train pattern 1 */
3227         reg = FDI_TX_CTL(pipe);
3228         temp = I915_READ(reg);
3229         temp &= ~FDI_LINK_TRAIN_NONE;
3230         temp |= FDI_LINK_TRAIN_PATTERN_1;
3231         I915_WRITE(reg, temp);
3232
3233         reg = FDI_RX_CTL(pipe);
3234         temp = I915_READ(reg);
3235         if (HAS_PCH_CPT(dev)) {
3236                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3237                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3238         } else {
3239                 temp &= ~FDI_LINK_TRAIN_NONE;
3240                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3241         }
3242         /* BPC in FDI rx is consistent with that in PIPECONF */
3243         temp &= ~(0x07 << 16);
3244         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3245         I915_WRITE(reg, temp);
3246
3247         POSTING_READ(reg);
3248         udelay(100);
3249 }
3250
3251 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3252 {
3253         struct intel_crtc *crtc;
3254
3255         /* Note that we don't need to be called with mode_config.lock here
3256          * as our list of CRTC objects is static for the lifetime of the
3257          * device and so cannot disappear as we iterate. Similarly, we can
3258          * happily treat the predicates as racy, atomic checks as userspace
3259          * cannot claim and pin a new fb without at least acquring the
3260          * struct_mutex and so serialising with us.
3261          */
3262         for_each_intel_crtc(dev, crtc) {
3263                 if (atomic_read(&crtc->unpin_work_count) == 0)
3264                         continue;
3265
3266                 if (crtc->unpin_work)
3267                         intel_wait_for_vblank(dev, crtc->pipe);
3268
3269                 return true;
3270         }
3271
3272         return false;
3273 }
3274
3275 static void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3276 {
3277         struct drm_device *dev = crtc->dev;
3278         struct drm_i915_private *dev_priv = dev->dev_private;
3279
3280         if (crtc->primary->fb == NULL)
3281                 return;
3282
3283         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3284
3285         WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3286                                    !intel_crtc_has_pending_flip(crtc),
3287                                    60*HZ) == 0);
3288
3289         mutex_lock(&dev->struct_mutex);
3290         intel_finish_fb(crtc->primary->fb);
3291         mutex_unlock(&dev->struct_mutex);
3292 }
3293
3294 /* Program iCLKIP clock to the desired frequency */
3295 static void lpt_program_iclkip(struct drm_crtc *crtc)
3296 {
3297         struct drm_device *dev = crtc->dev;
3298         struct drm_i915_private *dev_priv = dev->dev_private;
3299         int clock = to_intel_crtc(crtc)->config.adjusted_mode.crtc_clock;
3300         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3301         u32 temp;
3302
3303         mutex_lock(&dev_priv->dpio_lock);
3304
3305         /* It is necessary to ungate the pixclk gate prior to programming
3306          * the divisors, and gate it back when it is done.
3307          */
3308         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3309
3310         /* Disable SSCCTL */
3311         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3312                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3313                                 SBI_SSCCTL_DISABLE,
3314                         SBI_ICLK);
3315
3316         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3317         if (clock == 20000) {
3318                 auxdiv = 1;
3319                 divsel = 0x41;
3320                 phaseinc = 0x20;
3321         } else {
3322                 /* The iCLK virtual clock root frequency is in MHz,
3323                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3324                  * divisors, it is necessary to divide one by another, so we
3325                  * convert the virtual clock precision to KHz here for higher
3326                  * precision.
3327                  */
3328                 u32 iclk_virtual_root_freq = 172800 * 1000;
3329                 u32 iclk_pi_range = 64;
3330                 u32 desired_divisor, msb_divisor_value, pi_value;
3331
3332                 desired_divisor = (iclk_virtual_root_freq / clock);
3333                 msb_divisor_value = desired_divisor / iclk_pi_range;
3334                 pi_value = desired_divisor % iclk_pi_range;
3335
3336                 auxdiv = 0;
3337                 divsel = msb_divisor_value - 2;
3338                 phaseinc = pi_value;
3339         }
3340
3341         /* This should not happen with any sane values */
3342         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3343                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3344         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3345                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3346
3347         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3348                         clock,
3349                         auxdiv,
3350                         divsel,
3351                         phasedir,
3352                         phaseinc);
3353
3354         /* Program SSCDIVINTPHASE6 */
3355         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3356         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3357         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3358         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3359         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3360         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3361         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3362         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3363
3364         /* Program SSCAUXDIV */
3365         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3366         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3367         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3368         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3369
3370         /* Enable modulator and associated divider */
3371         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3372         temp &= ~SBI_SSCCTL_DISABLE;
3373         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3374
3375         /* Wait for initialization time */
3376         udelay(24);
3377
3378         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3379
3380         mutex_unlock(&dev_priv->dpio_lock);
3381 }
3382
3383 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3384                                                 enum pipe pch_transcoder)
3385 {
3386         struct drm_device *dev = crtc->base.dev;
3387         struct drm_i915_private *dev_priv = dev->dev_private;
3388         enum transcoder cpu_transcoder = crtc->config.cpu_transcoder;
3389
3390         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3391                    I915_READ(HTOTAL(cpu_transcoder)));
3392         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3393                    I915_READ(HBLANK(cpu_transcoder)));
3394         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3395                    I915_READ(HSYNC(cpu_transcoder)));
3396
3397         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3398                    I915_READ(VTOTAL(cpu_transcoder)));
3399         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3400                    I915_READ(VBLANK(cpu_transcoder)));
3401         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3402                    I915_READ(VSYNC(cpu_transcoder)));
3403         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3404                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3405 }
3406
3407 static void cpt_enable_fdi_bc_bifurcation(struct drm_device *dev)
3408 {
3409         struct drm_i915_private *dev_priv = dev->dev_private;
3410         uint32_t temp;
3411
3412         temp = I915_READ(SOUTH_CHICKEN1);
3413         if (temp & FDI_BC_BIFURCATION_SELECT)
3414                 return;
3415
3416         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3417         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3418
3419         temp |= FDI_BC_BIFURCATION_SELECT;
3420         DRM_DEBUG_KMS("enabling fdi C rx\n");
3421         I915_WRITE(SOUTH_CHICKEN1, temp);
3422         POSTING_READ(SOUTH_CHICKEN1);
3423 }
3424
3425 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3426 {
3427         struct drm_device *dev = intel_crtc->base.dev;
3428         struct drm_i915_private *dev_priv = dev->dev_private;
3429
3430         switch (intel_crtc->pipe) {
3431         case PIPE_A:
3432                 break;
3433         case PIPE_B:
3434                 if (intel_crtc->config.fdi_lanes > 2)
3435                         WARN_ON(I915_READ(SOUTH_CHICKEN1) & FDI_BC_BIFURCATION_SELECT);
3436                 else
3437                         cpt_enable_fdi_bc_bifurcation(dev);
3438
3439                 break;
3440         case PIPE_C:
3441                 cpt_enable_fdi_bc_bifurcation(dev);
3442
3443                 break;
3444         default:
3445                 BUG();
3446         }
3447 }
3448
3449 /*
3450  * Enable PCH resources required for PCH ports:
3451  *   - PCH PLLs
3452  *   - FDI training & RX/TX
3453  *   - update transcoder timings
3454  *   - DP transcoding bits
3455  *   - transcoder
3456  */
3457 static void ironlake_pch_enable(struct drm_crtc *crtc)
3458 {
3459         struct drm_device *dev = crtc->dev;
3460         struct drm_i915_private *dev_priv = dev->dev_private;
3461         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3462         int pipe = intel_crtc->pipe;
3463         u32 reg, temp;
3464
3465         assert_pch_transcoder_disabled(dev_priv, pipe);
3466
3467         if (IS_IVYBRIDGE(dev))
3468                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
3469
3470         /* Write the TU size bits before fdi link training, so that error
3471          * detection works. */
3472         I915_WRITE(FDI_RX_TUSIZE1(pipe),
3473                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
3474
3475         /* For PCH output, training FDI link */
3476         dev_priv->display.fdi_link_train(crtc);
3477
3478         /* We need to program the right clock selection before writing the pixel
3479          * mutliplier into the DPLL. */
3480         if (HAS_PCH_CPT(dev)) {
3481                 u32 sel;
3482
3483                 temp = I915_READ(PCH_DPLL_SEL);
3484                 temp |= TRANS_DPLL_ENABLE(pipe);
3485                 sel = TRANS_DPLLB_SEL(pipe);
3486                 if (intel_crtc->config.shared_dpll == DPLL_ID_PCH_PLL_B)
3487                         temp |= sel;
3488                 else
3489                         temp &= ~sel;
3490                 I915_WRITE(PCH_DPLL_SEL, temp);
3491         }
3492
3493         /* XXX: pch pll's can be enabled any time before we enable the PCH
3494          * transcoder, and we actually should do this to not upset any PCH
3495          * transcoder that already use the clock when we share it.
3496          *
3497          * Note that enable_shared_dpll tries to do the right thing, but
3498          * get_shared_dpll unconditionally resets the pll - we need that to have
3499          * the right LVDS enable sequence. */
3500         ironlake_enable_shared_dpll(intel_crtc);
3501
3502         /* set transcoder timing, panel must allow it */
3503         assert_panel_unlocked(dev_priv, pipe);
3504         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
3505
3506         intel_fdi_normal_train(crtc);
3507
3508         /* For PCH DP, enable TRANS_DP_CTL */
3509         if (HAS_PCH_CPT(dev) &&
3510             (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
3511              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3512                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
3513                 reg = TRANS_DP_CTL(pipe);
3514                 temp = I915_READ(reg);
3515                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
3516                           TRANS_DP_SYNC_MASK |
3517                           TRANS_DP_BPC_MASK);
3518                 temp |= (TRANS_DP_OUTPUT_ENABLE |
3519                          TRANS_DP_ENH_FRAMING);
3520                 temp |= bpc << 9; /* same format but at 11:9 */
3521
3522                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
3523                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
3524                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
3525                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
3526
3527                 switch (intel_trans_dp_port_sel(crtc)) {
3528                 case PCH_DP_B:
3529                         temp |= TRANS_DP_PORT_SEL_B;
3530                         break;
3531                 case PCH_DP_C:
3532                         temp |= TRANS_DP_PORT_SEL_C;
3533                         break;
3534                 case PCH_DP_D:
3535                         temp |= TRANS_DP_PORT_SEL_D;
3536                         break;
3537                 default:
3538                         BUG();
3539                 }
3540
3541                 I915_WRITE(reg, temp);
3542         }
3543
3544         ironlake_enable_pch_transcoder(dev_priv, pipe);
3545 }
3546
3547 static void lpt_pch_enable(struct drm_crtc *crtc)
3548 {
3549         struct drm_device *dev = crtc->dev;
3550         struct drm_i915_private *dev_priv = dev->dev_private;
3551         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3552         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
3553
3554         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
3555
3556         lpt_program_iclkip(crtc);
3557
3558         /* Set transcoder timing. */
3559         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
3560
3561         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
3562 }
3563
3564 static void intel_put_shared_dpll(struct intel_crtc *crtc)
3565 {
3566         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3567
3568         if (pll == NULL)
3569                 return;
3570
3571         if (pll->refcount == 0) {
3572                 WARN(1, "bad %s refcount\n", pll->name);
3573                 return;
3574         }
3575
3576         if (--pll->refcount == 0) {
3577                 WARN_ON(pll->on);
3578                 WARN_ON(pll->active);
3579         }
3580
3581         crtc->config.shared_dpll = DPLL_ID_PRIVATE;
3582 }
3583
3584 static struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc)
3585 {
3586         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
3587         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3588         enum intel_dpll_id i;
3589
3590         if (pll) {
3591                 DRM_DEBUG_KMS("CRTC:%d dropping existing %s\n",
3592                               crtc->base.base.id, pll->name);
3593                 intel_put_shared_dpll(crtc);
3594         }
3595
3596         if (HAS_PCH_IBX(dev_priv->dev)) {
3597                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
3598                 i = (enum intel_dpll_id) crtc->pipe;
3599                 pll = &dev_priv->shared_dplls[i];
3600
3601                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
3602                               crtc->base.base.id, pll->name);
3603
3604                 goto found;
3605         }
3606
3607         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3608                 pll = &dev_priv->shared_dplls[i];
3609
3610                 /* Only want to check enabled timings first */
3611                 if (pll->refcount == 0)
3612                         continue;
3613
3614                 if (memcmp(&crtc->config.dpll_hw_state, &pll->hw_state,
3615                            sizeof(pll->hw_state)) == 0) {
3616                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (refcount %d, ative %d)\n",
3617                                       crtc->base.base.id,
3618                                       pll->name, pll->refcount, pll->active);
3619
3620                         goto found;
3621                 }
3622         }
3623
3624         /* Ok no matching timings, maybe there's a free one? */
3625         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3626                 pll = &dev_priv->shared_dplls[i];
3627                 if (pll->refcount == 0) {
3628                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
3629                                       crtc->base.base.id, pll->name);
3630                         goto found;
3631                 }
3632         }
3633
3634         return NULL;
3635
3636 found:
3637         crtc->config.shared_dpll = i;
3638         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
3639                          pipe_name(crtc->pipe));
3640
3641         if (pll->active == 0) {
3642                 memcpy(&pll->hw_state, &crtc->config.dpll_hw_state,
3643                        sizeof(pll->hw_state));
3644
3645                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
3646                 WARN_ON(pll->on);
3647                 assert_shared_dpll_disabled(dev_priv, pll);
3648
3649                 pll->mode_set(dev_priv, pll);
3650         }
3651         pll->refcount++;
3652
3653         return pll;
3654 }
3655
3656 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
3657 {
3658         struct drm_i915_private *dev_priv = dev->dev_private;
3659         int dslreg = PIPEDSL(pipe);
3660         u32 temp;
3661
3662         temp = I915_READ(dslreg);
3663         udelay(500);
3664         if (wait_for(I915_READ(dslreg) != temp, 5)) {
3665                 if (wait_for(I915_READ(dslreg) != temp, 5))
3666                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
3667         }
3668 }
3669
3670 static void ironlake_pfit_enable(struct intel_crtc *crtc)
3671 {
3672         struct drm_device *dev = crtc->base.dev;
3673         struct drm_i915_private *dev_priv = dev->dev_private;
3674         int pipe = crtc->pipe;
3675
3676         if (crtc->config.pch_pfit.enabled) {
3677                 /* Force use of hard-coded filter coefficients
3678                  * as some pre-programmed values are broken,
3679                  * e.g. x201.
3680                  */
3681                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
3682                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
3683                                                  PF_PIPE_SEL_IVB(pipe));
3684                 else
3685                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
3686                 I915_WRITE(PF_WIN_POS(pipe), crtc->config.pch_pfit.pos);
3687                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config.pch_pfit.size);
3688         }
3689 }
3690
3691 static void intel_enable_planes(struct drm_crtc *crtc)
3692 {
3693         struct drm_device *dev = crtc->dev;
3694         enum pipe pipe = to_intel_crtc(crtc)->pipe;
3695         struct drm_plane *plane;
3696         struct intel_plane *intel_plane;
3697
3698         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
3699                 intel_plane = to_intel_plane(plane);
3700                 if (intel_plane->pipe == pipe)
3701                         intel_plane_restore(&intel_plane->base);
3702         }
3703 }
3704
3705 static void intel_disable_planes(struct drm_crtc *crtc)
3706 {
3707         struct drm_device *dev = crtc->dev;
3708         enum pipe pipe = to_intel_crtc(crtc)->pipe;
3709         struct drm_plane *plane;
3710         struct intel_plane *intel_plane;
3711
3712         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
3713                 intel_plane = to_intel_plane(plane);
3714                 if (intel_plane->pipe == pipe)
3715                         intel_plane_disable(&intel_plane->base);
3716         }
3717 }
3718
3719 void hsw_enable_ips(struct intel_crtc *crtc)
3720 {
3721         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
3722
3723         if (!crtc->config.ips_enabled)
3724                 return;
3725
3726         /* We can only enable IPS after we enable a plane and wait for a vblank.
3727          * We guarantee that the plane is enabled by calling intel_enable_ips
3728          * only after intel_enable_plane. And intel_enable_plane already waits
3729          * for a vblank, so all we need to do here is to enable the IPS bit. */
3730         assert_plane_enabled(dev_priv, crtc->plane);
3731         if (IS_BROADWELL(crtc->base.dev)) {
3732                 mutex_lock(&dev_priv->rps.hw_lock);
3733                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
3734                 mutex_unlock(&dev_priv->rps.hw_lock);
3735                 /* Quoting Art Runyan: "its not safe to expect any particular
3736                  * value in IPS_CTL bit 31 after enabling IPS through the
3737                  * mailbox." Moreover, the mailbox may return a bogus state,
3738                  * so we need to just enable it and continue on.
3739                  */
3740         } else {
3741                 I915_WRITE(IPS_CTL, IPS_ENABLE);
3742                 /* The bit only becomes 1 in the next vblank, so this wait here
3743                  * is essentially intel_wait_for_vblank. If we don't have this
3744                  * and don't wait for vblanks until the end of crtc_enable, then
3745                  * the HW state readout code will complain that the expected
3746                  * IPS_CTL value is not the one we read. */
3747                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
3748                         DRM_ERROR("Timed out waiting for IPS enable\n");
3749         }
3750 }
3751
3752 void hsw_disable_ips(struct intel_crtc *crtc)
3753 {
3754         struct drm_device *dev = crtc->base.dev;
3755         struct drm_i915_private *dev_priv = dev->dev_private;
3756
3757         if (!crtc->config.ips_enabled)
3758                 return;
3759
3760         assert_plane_enabled(dev_priv, crtc->plane);
3761         if (IS_BROADWELL(dev)) {
3762                 mutex_lock(&dev_priv->rps.hw_lock);
3763                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
3764                 mutex_unlock(&dev_priv->rps.hw_lock);
3765                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
3766                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
3767                         DRM_ERROR("Timed out waiting for IPS disable\n");
3768         } else {
3769                 I915_WRITE(IPS_CTL, 0);
3770                 POSTING_READ(IPS_CTL);
3771         }
3772
3773         /* We need to wait for a vblank before we can disable the plane. */
3774         intel_wait_for_vblank(dev, crtc->pipe);
3775 }
3776
3777 /** Loads the palette/gamma unit for the CRTC with the prepared values */
3778 static void intel_crtc_load_lut(struct drm_crtc *crtc)
3779 {
3780         struct drm_device *dev = crtc->dev;
3781         struct drm_i915_private *dev_priv = dev->dev_private;
3782         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3783         enum pipe pipe = intel_crtc->pipe;
3784         int palreg = PALETTE(pipe);
3785         int i;
3786         bool reenable_ips = false;
3787
3788         /* The clocks have to be on to load the palette. */
3789         if (!crtc->enabled || !intel_crtc->active)
3790                 return;
3791
3792         if (!HAS_PCH_SPLIT(dev_priv->dev)) {
3793                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
3794                         assert_dsi_pll_enabled(dev_priv);
3795                 else
3796                         assert_pll_enabled(dev_priv, pipe);
3797         }
3798
3799         /* use legacy palette for Ironlake */
3800         if (HAS_PCH_SPLIT(dev))
3801                 palreg = LGC_PALETTE(pipe);
3802
3803         /* Workaround : Do not read or write the pipe palette/gamma data while
3804          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
3805          */
3806         if (IS_HASWELL(dev) && intel_crtc->config.ips_enabled &&
3807             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
3808              GAMMA_MODE_MODE_SPLIT)) {
3809                 hsw_disable_ips(intel_crtc);
3810                 reenable_ips = true;
3811         }
3812
3813         for (i = 0; i < 256; i++) {
3814                 I915_WRITE(palreg + 4 * i,
3815                            (intel_crtc->lut_r[i] << 16) |
3816                            (intel_crtc->lut_g[i] << 8) |
3817                            intel_crtc->lut_b[i]);
3818         }
3819
3820         if (reenable_ips)
3821                 hsw_enable_ips(intel_crtc);
3822 }
3823
3824 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
3825 {
3826         if (!enable && intel_crtc->overlay) {
3827                 struct drm_device *dev = intel_crtc->base.dev;
3828                 struct drm_i915_private *dev_priv = dev->dev_private;
3829
3830                 mutex_lock(&dev->struct_mutex);
3831                 dev_priv->mm.interruptible = false;
3832                 (void) intel_overlay_switch_off(intel_crtc->overlay);
3833                 dev_priv->mm.interruptible = true;
3834                 mutex_unlock(&dev->struct_mutex);
3835         }
3836
3837         /* Let userspace switch the overlay on again. In most cases userspace
3838          * has to recompute where to put it anyway.
3839          */
3840 }
3841
3842 /**
3843  * i9xx_fixup_plane - ugly workaround for G45 to fire up the hardware
3844  * cursor plane briefly if not already running after enabling the display
3845  * plane.
3846  * This workaround avoids occasional blank screens when self refresh is
3847  * enabled.
3848  */
3849 static void
3850 g4x_fixup_plane(struct drm_i915_private *dev_priv, enum pipe pipe)
3851 {
3852         u32 cntl = I915_READ(CURCNTR(pipe));
3853
3854         if ((cntl & CURSOR_MODE) == 0) {
3855                 u32 fw_bcl_self = I915_READ(FW_BLC_SELF);
3856
3857                 I915_WRITE(FW_BLC_SELF, fw_bcl_self & ~FW_BLC_SELF_EN);
3858                 I915_WRITE(CURCNTR(pipe), CURSOR_MODE_64_ARGB_AX);
3859                 intel_wait_for_vblank(dev_priv->dev, pipe);
3860                 I915_WRITE(CURCNTR(pipe), cntl);
3861                 I915_WRITE(CURBASE(pipe), I915_READ(CURBASE(pipe)));
3862                 I915_WRITE(FW_BLC_SELF, fw_bcl_self);
3863         }
3864 }
3865
3866 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
3867 {
3868         struct drm_device *dev = crtc->dev;
3869         struct drm_i915_private *dev_priv = dev->dev_private;
3870         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3871         int pipe = intel_crtc->pipe;
3872         int plane = intel_crtc->plane;
3873
3874         intel_enable_primary_hw_plane(dev_priv, plane, pipe);
3875         intel_enable_planes(crtc);
3876         /* The fixup needs to happen before cursor is enabled */
3877         if (IS_G4X(dev))
3878                 g4x_fixup_plane(dev_priv, pipe);
3879         intel_crtc_update_cursor(crtc, true);
3880         intel_crtc_dpms_overlay(intel_crtc, true);
3881
3882         hsw_enable_ips(intel_crtc);
3883
3884         mutex_lock(&dev->struct_mutex);
3885         intel_update_fbc(dev);
3886         intel_edp_psr_update(dev);
3887         mutex_unlock(&dev->struct_mutex);
3888 }
3889
3890 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
3891 {
3892         struct drm_device *dev = crtc->dev;
3893         struct drm_i915_private *dev_priv = dev->dev_private;
3894         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3895         int pipe = intel_crtc->pipe;
3896         int plane = intel_crtc->plane;
3897
3898         intel_crtc_wait_for_pending_flips(crtc);
3899         drm_vblank_off(dev, pipe);
3900
3901         if (dev_priv->fbc.plane == plane)
3902                 intel_disable_fbc(dev);
3903
3904         hsw_disable_ips(intel_crtc);
3905
3906         intel_crtc_dpms_overlay(intel_crtc, false);
3907         intel_crtc_update_cursor(crtc, false);
3908         intel_disable_planes(crtc);
3909         intel_disable_primary_hw_plane(dev_priv, plane, pipe);
3910 }
3911
3912 static void ironlake_crtc_enable(struct drm_crtc *crtc)
3913 {
3914         struct drm_device *dev = crtc->dev;
3915         struct drm_i915_private *dev_priv = dev->dev_private;
3916         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3917         struct intel_encoder *encoder;
3918         int pipe = intel_crtc->pipe;
3919         enum plane plane = intel_crtc->plane;
3920
3921         WARN_ON(!crtc->enabled);
3922
3923         if (intel_crtc->active)
3924                 return;
3925
3926         if (intel_crtc->config.has_dp_encoder)
3927                 intel_dp_set_m_n(intel_crtc);
3928
3929         intel_set_pipe_timings(intel_crtc);
3930
3931         if (intel_crtc->config.has_pch_encoder) {
3932                 intel_cpu_transcoder_set_m_n(intel_crtc,
3933                                              &intel_crtc->config.fdi_m_n);
3934         }
3935
3936         ironlake_set_pipeconf(crtc);
3937
3938         /* Set up the display plane register */
3939         I915_WRITE(DSPCNTR(plane), DISPPLANE_GAMMA_ENABLE);
3940         POSTING_READ(DSPCNTR(plane));
3941
3942         dev_priv->display.update_primary_plane(crtc, crtc->primary->fb,
3943                                                crtc->x, crtc->y);
3944
3945         intel_crtc->active = true;
3946
3947         intel_set_cpu_fifo_underrun_reporting(dev, pipe, true);
3948         intel_set_pch_fifo_underrun_reporting(dev, pipe, true);
3949
3950         for_each_encoder_on_crtc(dev, crtc, encoder)
3951                 if (encoder->pre_enable)
3952                         encoder->pre_enable(encoder);
3953
3954         if (intel_crtc->config.has_pch_encoder) {
3955                 /* Note: FDI PLL enabling _must_ be done before we enable the
3956                  * cpu pipes, hence this is separate from all the other fdi/pch
3957                  * enabling. */
3958                 ironlake_fdi_pll_enable(intel_crtc);
3959         } else {
3960                 assert_fdi_tx_disabled(dev_priv, pipe);
3961                 assert_fdi_rx_disabled(dev_priv, pipe);
3962         }
3963
3964         ironlake_pfit_enable(intel_crtc);
3965
3966         /*
3967          * On ILK+ LUT must be loaded before the pipe is running but with
3968          * clocks enabled
3969          */
3970         intel_crtc_load_lut(crtc);
3971
3972         intel_update_watermarks(crtc);
3973         intel_enable_pipe(intel_crtc);
3974
3975         if (intel_crtc->config.has_pch_encoder)
3976                 ironlake_pch_enable(crtc);
3977
3978         for_each_encoder_on_crtc(dev, crtc, encoder)
3979                 encoder->enable(encoder);
3980
3981         if (HAS_PCH_CPT(dev))
3982                 cpt_verify_modeset(dev, intel_crtc->pipe);
3983
3984         intel_crtc_enable_planes(crtc);
3985
3986         /*
3987          * There seems to be a race in PCH platform hw (at least on some
3988          * outputs) where an enabled pipe still completes any pageflip right
3989          * away (as if the pipe is off) instead of waiting for vblank. As soon
3990          * as the first vblank happend, everything works as expected. Hence just
3991          * wait for one vblank before returning to avoid strange things
3992          * happening.
3993          */
3994         intel_wait_for_vblank(dev, intel_crtc->pipe);
3995 }
3996
3997 /* IPS only exists on ULT machines and is tied to pipe A. */
3998 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
3999 {
4000         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4001 }
4002
4003 /*
4004  * This implements the workaround described in the "notes" section of the mode
4005  * set sequence documentation. When going from no pipes or single pipe to
4006  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4007  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4008  */
4009 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4010 {
4011         struct drm_device *dev = crtc->base.dev;
4012         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4013
4014         /* We want to get the other_active_crtc only if there's only 1 other
4015          * active crtc. */
4016         for_each_intel_crtc(dev, crtc_it) {
4017                 if (!crtc_it->active || crtc_it == crtc)
4018                         continue;
4019
4020                 if (other_active_crtc)
4021                         return;
4022
4023                 other_active_crtc = crtc_it;
4024         }
4025         if (!other_active_crtc)
4026                 return;
4027
4028         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4029         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4030 }
4031
4032 static void haswell_crtc_enable(struct drm_crtc *crtc)
4033 {
4034         struct drm_device *dev = crtc->dev;
4035         struct drm_i915_private *dev_priv = dev->dev_private;
4036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4037         struct intel_encoder *encoder;
4038         int pipe = intel_crtc->pipe;
4039         enum plane plane = intel_crtc->plane;
4040
4041         WARN_ON(!crtc->enabled);
4042
4043         if (intel_crtc->active)
4044                 return;
4045
4046         if (intel_crtc->config.has_dp_encoder)
4047                 intel_dp_set_m_n(intel_crtc);
4048
4049         intel_set_pipe_timings(intel_crtc);
4050
4051         if (intel_crtc->config.has_pch_encoder) {
4052                 intel_cpu_transcoder_set_m_n(intel_crtc,
4053                                              &intel_crtc->config.fdi_m_n);
4054         }
4055
4056         haswell_set_pipeconf(crtc);
4057
4058         intel_set_pipe_csc(crtc);
4059
4060         /* Set up the display plane register */
4061         I915_WRITE(DSPCNTR(plane), DISPPLANE_GAMMA_ENABLE | DISPPLANE_PIPE_CSC_ENABLE);
4062         POSTING_READ(DSPCNTR(plane));
4063
4064         dev_priv->display.update_primary_plane(crtc, crtc->primary->fb,
4065                                                crtc->x, crtc->y);
4066
4067         intel_crtc->active = true;
4068
4069         intel_set_cpu_fifo_underrun_reporting(dev, pipe, true);
4070         if (intel_crtc->config.has_pch_encoder)
4071                 intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_A, true);
4072
4073         if (intel_crtc->config.has_pch_encoder)
4074                 dev_priv->display.fdi_link_train(crtc);
4075
4076         for_each_encoder_on_crtc(dev, crtc, encoder)
4077                 if (encoder->pre_enable)
4078                         encoder->pre_enable(encoder);
4079
4080         intel_ddi_enable_pipe_clock(intel_crtc);
4081
4082         ironlake_pfit_enable(intel_crtc);
4083
4084         /*
4085          * On ILK+ LUT must be loaded before the pipe is running but with
4086          * clocks enabled
4087          */
4088         intel_crtc_load_lut(crtc);
4089
4090         intel_ddi_set_pipe_settings(crtc);
4091         intel_ddi_enable_transcoder_func(crtc);
4092
4093         intel_update_watermarks(crtc);
4094         intel_enable_pipe(intel_crtc);
4095
4096         if (intel_crtc->config.has_pch_encoder)
4097                 lpt_pch_enable(crtc);
4098
4099         for_each_encoder_on_crtc(dev, crtc, encoder) {
4100                 encoder->enable(encoder);
4101                 intel_opregion_notify_encoder(encoder, true);
4102         }
4103
4104         /* If we change the relative order between pipe/planes enabling, we need
4105          * to change the workaround. */
4106         haswell_mode_set_planes_workaround(intel_crtc);
4107         intel_crtc_enable_planes(crtc);
4108 }
4109
4110 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4111 {
4112         struct drm_device *dev = crtc->base.dev;
4113         struct drm_i915_private *dev_priv = dev->dev_private;
4114         int pipe = crtc->pipe;
4115
4116         /* To avoid upsetting the power well on haswell only disable the pfit if
4117          * it's in use. The hw state code will make sure we get this right. */
4118         if (crtc->config.pch_pfit.enabled) {
4119                 I915_WRITE(PF_CTL(pipe), 0);
4120                 I915_WRITE(PF_WIN_POS(pipe), 0);
4121                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4122         }
4123 }
4124
4125 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4126 {
4127         struct drm_device *dev = crtc->dev;
4128         struct drm_i915_private *dev_priv = dev->dev_private;
4129         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4130         struct intel_encoder *encoder;
4131         int pipe = intel_crtc->pipe;
4132         u32 reg, temp;
4133
4134         if (!intel_crtc->active)
4135                 return;
4136
4137         intel_crtc_disable_planes(crtc);
4138
4139         for_each_encoder_on_crtc(dev, crtc, encoder)
4140                 encoder->disable(encoder);
4141
4142         if (intel_crtc->config.has_pch_encoder)
4143                 intel_set_pch_fifo_underrun_reporting(dev, pipe, false);
4144
4145         intel_disable_pipe(dev_priv, pipe);
4146
4147         ironlake_pfit_disable(intel_crtc);
4148
4149         for_each_encoder_on_crtc(dev, crtc, encoder)
4150                 if (encoder->post_disable)
4151                         encoder->post_disable(encoder);
4152
4153         if (intel_crtc->config.has_pch_encoder) {
4154                 ironlake_fdi_disable(crtc);
4155
4156                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4157                 intel_set_pch_fifo_underrun_reporting(dev, pipe, true);
4158
4159                 if (HAS_PCH_CPT(dev)) {
4160                         /* disable TRANS_DP_CTL */
4161                         reg = TRANS_DP_CTL(pipe);
4162                         temp = I915_READ(reg);
4163                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4164                                   TRANS_DP_PORT_SEL_MASK);
4165                         temp |= TRANS_DP_PORT_SEL_NONE;
4166                         I915_WRITE(reg, temp);
4167
4168                         /* disable DPLL_SEL */
4169                         temp = I915_READ(PCH_DPLL_SEL);
4170                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4171                         I915_WRITE(PCH_DPLL_SEL, temp);
4172                 }
4173
4174                 /* disable PCH DPLL */
4175                 intel_disable_shared_dpll(intel_crtc);
4176
4177                 ironlake_fdi_pll_disable(intel_crtc);
4178         }
4179
4180         intel_crtc->active = false;
4181         intel_update_watermarks(crtc);
4182
4183         mutex_lock(&dev->struct_mutex);
4184         intel_update_fbc(dev);
4185         intel_edp_psr_update(dev);
4186         mutex_unlock(&dev->struct_mutex);
4187 }
4188
4189 static void haswell_crtc_disable(struct drm_crtc *crtc)
4190 {
4191         struct drm_device *dev = crtc->dev;
4192         struct drm_i915_private *dev_priv = dev->dev_private;
4193         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4194         struct intel_encoder *encoder;
4195         int pipe = intel_crtc->pipe;
4196         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
4197
4198         if (!intel_crtc->active)
4199                 return;
4200
4201         intel_crtc_disable_planes(crtc);
4202
4203         for_each_encoder_on_crtc(dev, crtc, encoder) {
4204                 intel_opregion_notify_encoder(encoder, false);
4205                 encoder->disable(encoder);
4206         }
4207
4208         if (intel_crtc->config.has_pch_encoder)
4209                 intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_A, false);
4210         intel_disable_pipe(dev_priv, pipe);
4211
4212         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4213
4214         ironlake_pfit_disable(intel_crtc);
4215
4216         intel_ddi_disable_pipe_clock(intel_crtc);
4217
4218         for_each_encoder_on_crtc(dev, crtc, encoder)
4219                 if (encoder->post_disable)
4220                         encoder->post_disable(encoder);
4221
4222         if (intel_crtc->config.has_pch_encoder) {
4223                 lpt_disable_pch_transcoder(dev_priv);
4224                 intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_A, true);
4225                 intel_ddi_fdi_disable(crtc);
4226         }
4227
4228         intel_crtc->active = false;
4229         intel_update_watermarks(crtc);
4230
4231         mutex_lock(&dev->struct_mutex);
4232         intel_update_fbc(dev);
4233         intel_edp_psr_update(dev);
4234         mutex_unlock(&dev->struct_mutex);
4235 }
4236
4237 static void ironlake_crtc_off(struct drm_crtc *crtc)
4238 {
4239         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4240         intel_put_shared_dpll(intel_crtc);
4241 }
4242
4243 static void haswell_crtc_off(struct drm_crtc *crtc)
4244 {
4245         intel_ddi_put_crtc_pll(crtc);
4246 }
4247
4248 static void i9xx_pfit_enable(struct intel_crtc *crtc)
4249 {
4250         struct drm_device *dev = crtc->base.dev;
4251         struct drm_i915_private *dev_priv = dev->dev_private;
4252         struct intel_crtc_config *pipe_config = &crtc->config;
4253
4254         if (!crtc->config.gmch_pfit.control)
4255                 return;
4256
4257         /*
4258          * The panel fitter should only be adjusted whilst the pipe is disabled,
4259          * according to register description and PRM.
4260          */
4261         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
4262         assert_pipe_disabled(dev_priv, crtc->pipe);
4263
4264         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
4265         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
4266
4267         /* Border color in case we don't scale up to the full screen. Black by
4268          * default, change to something else for debugging. */
4269         I915_WRITE(BCLRPAT(crtc->pipe), 0);
4270 }
4271
4272 #define for_each_power_domain(domain, mask)                             \
4273         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
4274                 if ((1 << (domain)) & (mask))
4275
4276 enum intel_display_power_domain
4277 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
4278 {
4279         struct drm_device *dev = intel_encoder->base.dev;
4280         struct intel_digital_port *intel_dig_port;
4281
4282         switch (intel_encoder->type) {
4283         case INTEL_OUTPUT_UNKNOWN:
4284                 /* Only DDI platforms should ever use this output type */
4285                 WARN_ON_ONCE(!HAS_DDI(dev));
4286         case INTEL_OUTPUT_DISPLAYPORT:
4287         case INTEL_OUTPUT_HDMI:
4288         case INTEL_OUTPUT_EDP:
4289                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
4290                 switch (intel_dig_port->port) {
4291                 case PORT_A:
4292                         return POWER_DOMAIN_PORT_DDI_A_4_LANES;
4293                 case PORT_B:
4294                         return POWER_DOMAIN_PORT_DDI_B_4_LANES;
4295                 case PORT_C:
4296                         return POWER_DOMAIN_PORT_DDI_C_4_LANES;
4297                 case PORT_D:
4298                         return POWER_DOMAIN_PORT_DDI_D_4_LANES;
4299                 default:
4300                         WARN_ON_ONCE(1);
4301                         return POWER_DOMAIN_PORT_OTHER;
4302                 }
4303         case INTEL_OUTPUT_ANALOG:
4304                 return POWER_DOMAIN_PORT_CRT;
4305         case INTEL_OUTPUT_DSI:
4306                 return POWER_DOMAIN_PORT_DSI;
4307         default:
4308                 return POWER_DOMAIN_PORT_OTHER;
4309         }
4310 }
4311
4312 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
4313 {
4314         struct drm_device *dev = crtc->dev;
4315         struct intel_encoder *intel_encoder;
4316         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4317         enum pipe pipe = intel_crtc->pipe;
4318         bool pfit_enabled = intel_crtc->config.pch_pfit.enabled;
4319         unsigned long mask;
4320         enum transcoder transcoder;
4321
4322         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
4323
4324         mask = BIT(POWER_DOMAIN_PIPE(pipe));
4325         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
4326         if (pfit_enabled)
4327                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
4328
4329         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4330                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
4331
4332         return mask;
4333 }
4334
4335 void intel_display_set_init_power(struct drm_i915_private *dev_priv,
4336                                   bool enable)
4337 {
4338         if (dev_priv->power_domains.init_power_on == enable)
4339                 return;
4340
4341         if (enable)
4342                 intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
4343         else
4344                 intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
4345
4346         dev_priv->power_domains.init_power_on = enable;
4347 }
4348
4349 static void modeset_update_crtc_power_domains(struct drm_device *dev)
4350 {
4351         struct drm_i915_private *dev_priv = dev->dev_private;
4352         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
4353         struct intel_crtc *crtc;
4354
4355         /*
4356          * First get all needed power domains, then put all unneeded, to avoid
4357          * any unnecessary toggling of the power wells.
4358          */
4359         for_each_intel_crtc(dev, crtc) {
4360                 enum intel_display_power_domain domain;
4361
4362                 if (!crtc->base.enabled)
4363                         continue;
4364
4365                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
4366
4367                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
4368                         intel_display_power_get(dev_priv, domain);
4369         }
4370
4371         for_each_intel_crtc(dev, crtc) {
4372                 enum intel_display_power_domain domain;
4373
4374                 for_each_power_domain(domain, crtc->enabled_power_domains)
4375                         intel_display_power_put(dev_priv, domain);
4376
4377                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
4378         }
4379
4380         intel_display_set_init_power(dev_priv, false);
4381 }
4382
4383 int valleyview_get_vco(struct drm_i915_private *dev_priv)
4384 {
4385         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
4386
4387         /* Obtain SKU information */
4388         mutex_lock(&dev_priv->dpio_lock);
4389         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
4390                 CCK_FUSE_HPLL_FREQ_MASK;
4391         mutex_unlock(&dev_priv->dpio_lock);
4392
4393         return vco_freq[hpll_freq];
4394 }
4395
4396 /* Adjust CDclk dividers to allow high res or save power if possible */
4397 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
4398 {
4399         struct drm_i915_private *dev_priv = dev->dev_private;
4400         u32 val, cmd;
4401
4402         WARN_ON(valleyview_cur_cdclk(dev_priv) != dev_priv->vlv_cdclk_freq);
4403         dev_priv->vlv_cdclk_freq = cdclk;
4404
4405         if (cdclk >= 320) /* jump to highest voltage for 400MHz too */
4406                 cmd = 2;
4407         else if (cdclk == 266)
4408                 cmd = 1;
4409         else
4410                 cmd = 0;
4411
4412         mutex_lock(&dev_priv->rps.hw_lock);
4413         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4414         val &= ~DSPFREQGUAR_MASK;
4415         val |= (cmd << DSPFREQGUAR_SHIFT);
4416         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4417         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4418                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
4419                      50)) {
4420                 DRM_ERROR("timed out waiting for CDclk change\n");
4421         }
4422         mutex_unlock(&dev_priv->rps.hw_lock);
4423
4424         if (cdclk == 400) {
4425                 u32 divider, vco;
4426
4427                 vco = valleyview_get_vco(dev_priv);
4428                 divider = ((vco << 1) / cdclk) - 1;
4429
4430                 mutex_lock(&dev_priv->dpio_lock);
4431                 /* adjust cdclk divider */
4432                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
4433                 val &= ~0xf;
4434                 val |= divider;
4435                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
4436                 mutex_unlock(&dev_priv->dpio_lock);
4437         }
4438
4439         mutex_lock(&dev_priv->dpio_lock);
4440         /* adjust self-refresh exit latency value */
4441         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
4442         val &= ~0x7f;
4443
4444         /*
4445          * For high bandwidth configs, we set a higher latency in the bunit
4446          * so that the core display fetch happens in time to avoid underruns.
4447          */
4448         if (cdclk == 400)
4449                 val |= 4500 / 250; /* 4.5 usec */
4450         else
4451                 val |= 3000 / 250; /* 3.0 usec */
4452         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
4453         mutex_unlock(&dev_priv->dpio_lock);
4454
4455         /* Since we changed the CDclk, we need to update the GMBUSFREQ too */
4456         intel_i2c_reset(dev);
4457 }
4458
4459 int valleyview_cur_cdclk(struct drm_i915_private *dev_priv)
4460 {
4461         int cur_cdclk, vco;
4462         int divider;
4463
4464         vco = valleyview_get_vco(dev_priv);
4465
4466         mutex_lock(&dev_priv->dpio_lock);
4467         divider = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
4468         mutex_unlock(&dev_priv->dpio_lock);
4469
4470         divider &= 0xf;
4471
4472         cur_cdclk = (vco << 1) / (divider + 1);
4473
4474         return cur_cdclk;
4475 }
4476
4477 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
4478                                  int max_pixclk)
4479 {
4480         /*
4481          * Really only a few cases to deal with, as only 4 CDclks are supported:
4482          *   200MHz
4483          *   267MHz
4484          *   320MHz
4485          *   400MHz
4486          * So we check to see whether we're above 90% of the lower bin and
4487          * adjust if needed.
4488          */
4489         if (max_pixclk > 288000) {
4490                 return 400;
4491         } else if (max_pixclk > 240000) {
4492                 return 320;
4493         } else
4494                 return 266;
4495         /* Looks like the 200MHz CDclk freq doesn't work on some configs */
4496 }
4497
4498 /* compute the max pixel clock for new configuration */
4499 static int intel_mode_max_pixclk(struct drm_i915_private *dev_priv)
4500 {
4501         struct drm_device *dev = dev_priv->dev;
4502         struct intel_crtc *intel_crtc;
4503         int max_pixclk = 0;
4504
4505         for_each_intel_crtc(dev, intel_crtc) {
4506                 if (intel_crtc->new_enabled)
4507                         max_pixclk = max(max_pixclk,
4508                                          intel_crtc->new_config->adjusted_mode.crtc_clock);
4509         }
4510
4511         return max_pixclk;
4512 }
4513
4514 static void valleyview_modeset_global_pipes(struct drm_device *dev,
4515                                             unsigned *prepare_pipes)
4516 {
4517         struct drm_i915_private *dev_priv = dev->dev_private;
4518         struct intel_crtc *intel_crtc;
4519         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4520
4521         if (valleyview_calc_cdclk(dev_priv, max_pixclk) ==
4522             dev_priv->vlv_cdclk_freq)
4523                 return;
4524
4525         /* disable/enable all currently active pipes while we change cdclk */
4526         for_each_intel_crtc(dev, intel_crtc)
4527                 if (intel_crtc->base.enabled)
4528                         *prepare_pipes |= (1 << intel_crtc->pipe);
4529 }
4530
4531 static void valleyview_modeset_global_resources(struct drm_device *dev)
4532 {
4533         struct drm_i915_private *dev_priv = dev->dev_private;
4534         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4535         int req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
4536
4537         if (req_cdclk != dev_priv->vlv_cdclk_freq)
4538                 valleyview_set_cdclk(dev, req_cdclk);
4539         modeset_update_crtc_power_domains(dev);
4540 }
4541
4542 static void valleyview_crtc_enable(struct drm_crtc *crtc)
4543 {
4544         struct drm_device *dev = crtc->dev;
4545         struct drm_i915_private *dev_priv = dev->dev_private;
4546         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4547         struct intel_encoder *encoder;
4548         int pipe = intel_crtc->pipe;
4549         int plane = intel_crtc->plane;
4550         bool is_dsi;
4551         u32 dspcntr;
4552
4553         WARN_ON(!crtc->enabled);
4554
4555         if (intel_crtc->active)
4556                 return;
4557
4558         /* Set up the display plane register */
4559         dspcntr = DISPPLANE_GAMMA_ENABLE;
4560
4561         if (intel_crtc->config.has_dp_encoder)
4562                 intel_dp_set_m_n(intel_crtc);
4563
4564         intel_set_pipe_timings(intel_crtc);
4565
4566         /* pipesrc and dspsize control the size that is scaled from,
4567          * which should always be the user's requested size.
4568          */
4569         I915_WRITE(DSPSIZE(plane),
4570                    ((intel_crtc->config.pipe_src_h - 1) << 16) |
4571                    (intel_crtc->config.pipe_src_w - 1));
4572         I915_WRITE(DSPPOS(plane), 0);
4573
4574         i9xx_set_pipeconf(intel_crtc);
4575
4576         I915_WRITE(DSPCNTR(plane), dspcntr);
4577         POSTING_READ(DSPCNTR(plane));
4578
4579         dev_priv->display.update_primary_plane(crtc, crtc->primary->fb,
4580                                                crtc->x, crtc->y);
4581
4582         intel_crtc->active = true;
4583
4584         for_each_encoder_on_crtc(dev, crtc, encoder)
4585                 if (encoder->pre_pll_enable)
4586                         encoder->pre_pll_enable(encoder);
4587
4588         is_dsi = intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI);
4589
4590         if (!is_dsi) {
4591                 if (IS_CHERRYVIEW(dev))
4592                         chv_enable_pll(intel_crtc);
4593                 else
4594                         vlv_enable_pll(intel_crtc);
4595         }
4596
4597         for_each_encoder_on_crtc(dev, crtc, encoder)
4598                 if (encoder->pre_enable)
4599                         encoder->pre_enable(encoder);
4600
4601         i9xx_pfit_enable(intel_crtc);
4602
4603         intel_crtc_load_lut(crtc);
4604
4605         intel_update_watermarks(crtc);
4606         intel_enable_pipe(intel_crtc);
4607         intel_set_cpu_fifo_underrun_reporting(dev, pipe, true);
4608
4609         for_each_encoder_on_crtc(dev, crtc, encoder)
4610                 encoder->enable(encoder);
4611
4612         intel_crtc_enable_planes(crtc);
4613 }
4614
4615 static void i9xx_crtc_enable(struct drm_crtc *crtc)
4616 {
4617         struct drm_device *dev = crtc->dev;
4618         struct drm_i915_private *dev_priv = dev->dev_private;
4619         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4620         struct intel_encoder *encoder;
4621         int pipe = intel_crtc->pipe;
4622         int plane = intel_crtc->plane;
4623         u32 dspcntr;
4624
4625         WARN_ON(!crtc->enabled);
4626
4627         if (intel_crtc->active)
4628                 return;
4629
4630         /* Set up the display plane register */
4631         dspcntr = DISPPLANE_GAMMA_ENABLE;
4632
4633         if (pipe == 0)
4634                 dspcntr &= ~DISPPLANE_SEL_PIPE_MASK;
4635         else
4636                 dspcntr |= DISPPLANE_SEL_PIPE_B;
4637
4638         if (intel_crtc->config.has_dp_encoder)
4639                 intel_dp_set_m_n(intel_crtc);
4640
4641         intel_set_pipe_timings(intel_crtc);
4642
4643         /* pipesrc and dspsize control the size that is scaled from,
4644          * which should always be the user's requested size.
4645          */
4646         I915_WRITE(DSPSIZE(plane),
4647                    ((intel_crtc->config.pipe_src_h - 1) << 16) |
4648                    (intel_crtc->config.pipe_src_w - 1));
4649         I915_WRITE(DSPPOS(plane), 0);
4650
4651         i9xx_set_pipeconf(intel_crtc);
4652
4653         I915_WRITE(DSPCNTR(plane), dspcntr);
4654         POSTING_READ(DSPCNTR(plane));
4655
4656         dev_priv->display.update_primary_plane(crtc, crtc->primary->fb,
4657                                                crtc->x, crtc->y);
4658
4659         intel_crtc->active = true;
4660
4661         for_each_encoder_on_crtc(dev, crtc, encoder)
4662                 if (encoder->pre_enable)
4663                         encoder->pre_enable(encoder);
4664
4665         i9xx_enable_pll(intel_crtc);
4666
4667         i9xx_pfit_enable(intel_crtc);
4668
4669         intel_crtc_load_lut(crtc);
4670
4671         intel_update_watermarks(crtc);
4672         intel_enable_pipe(intel_crtc);
4673         intel_set_cpu_fifo_underrun_reporting(dev, pipe, true);
4674
4675         for_each_encoder_on_crtc(dev, crtc, encoder)
4676                 encoder->enable(encoder);
4677
4678         intel_crtc_enable_planes(crtc);
4679 }
4680
4681 static void i9xx_pfit_disable(struct intel_crtc *crtc)
4682 {
4683         struct drm_device *dev = crtc->base.dev;
4684         struct drm_i915_private *dev_priv = dev->dev_private;
4685
4686         if (!crtc->config.gmch_pfit.control)
4687                 return;
4688
4689         assert_pipe_disabled(dev_priv, crtc->pipe);
4690
4691         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
4692                          I915_READ(PFIT_CONTROL));
4693         I915_WRITE(PFIT_CONTROL, 0);
4694 }
4695
4696 static void i9xx_crtc_disable(struct drm_crtc *crtc)
4697 {
4698         struct drm_device *dev = crtc->dev;
4699         struct drm_i915_private *dev_priv = dev->dev_private;
4700         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4701         struct intel_encoder *encoder;
4702         int pipe = intel_crtc->pipe;
4703
4704         if (!intel_crtc->active)
4705                 return;
4706
4707         intel_crtc_disable_planes(crtc);
4708
4709         for_each_encoder_on_crtc(dev, crtc, encoder)
4710                 encoder->disable(encoder);
4711
4712         intel_set_cpu_fifo_underrun_reporting(dev, pipe, false);
4713         intel_disable_pipe(dev_priv, pipe);
4714
4715         i9xx_pfit_disable(intel_crtc);
4716
4717         for_each_encoder_on_crtc(dev, crtc, encoder)
4718                 if (encoder->post_disable)
4719                         encoder->post_disable(encoder);
4720
4721         if (!intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI)) {
4722                 if (IS_CHERRYVIEW(dev))
4723                         chv_disable_pll(dev_priv, pipe);
4724                 else if (IS_VALLEYVIEW(dev))
4725                         vlv_disable_pll(dev_priv, pipe);
4726                 else
4727                         i9xx_disable_pll(dev_priv, pipe);
4728         }
4729
4730         intel_crtc->active = false;
4731         intel_update_watermarks(crtc);
4732
4733         mutex_lock(&dev->struct_mutex);
4734         intel_update_fbc(dev);
4735         intel_edp_psr_update(dev);
4736         mutex_unlock(&dev->struct_mutex);
4737 }
4738
4739 static void i9xx_crtc_off(struct drm_crtc *crtc)
4740 {
4741 }
4742
4743 static void intel_crtc_update_sarea(struct drm_crtc *crtc,
4744                                     bool enabled)
4745 {
4746         struct drm_device *dev = crtc->dev;
4747         struct drm_i915_master_private *master_priv;
4748         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4749         int pipe = intel_crtc->pipe;
4750
4751         if (!dev->primary->master)
4752                 return;
4753
4754         master_priv = dev->primary->master->driver_priv;
4755         if (!master_priv->sarea_priv)
4756                 return;
4757
4758         switch (pipe) {
4759         case 0:
4760                 master_priv->sarea_priv->pipeA_w = enabled ? crtc->mode.hdisplay : 0;
4761                 master_priv->sarea_priv->pipeA_h = enabled ? crtc->mode.vdisplay : 0;
4762                 break;
4763         case 1:
4764                 master_priv->sarea_priv->pipeB_w = enabled ? crtc->mode.hdisplay : 0;
4765                 master_priv->sarea_priv->pipeB_h = enabled ? crtc->mode.vdisplay : 0;
4766                 break;
4767         default:
4768                 DRM_ERROR("Can't update pipe %c in SAREA\n", pipe_name(pipe));
4769                 break;
4770         }
4771 }
4772
4773 /**
4774  * Sets the power management mode of the pipe and plane.
4775  */
4776 void intel_crtc_update_dpms(struct drm_crtc *crtc)
4777 {
4778         struct drm_device *dev = crtc->dev;
4779         struct drm_i915_private *dev_priv = dev->dev_private;
4780         struct intel_encoder *intel_encoder;
4781         bool enable = false;
4782
4783         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4784                 enable |= intel_encoder->connectors_active;
4785
4786         if (enable)
4787                 dev_priv->display.crtc_enable(crtc);
4788         else
4789                 dev_priv->display.crtc_disable(crtc);
4790
4791         intel_crtc_update_sarea(crtc, enable);
4792 }
4793
4794 static void intel_crtc_disable(struct drm_crtc *crtc)
4795 {
4796         struct drm_device *dev = crtc->dev;
4797         struct drm_connector *connector;
4798         struct drm_i915_private *dev_priv = dev->dev_private;
4799
4800         /* crtc should still be enabled when we disable it. */
4801         WARN_ON(!crtc->enabled);
4802
4803         dev_priv->display.crtc_disable(crtc);
4804         intel_crtc_update_sarea(crtc, false);
4805         dev_priv->display.off(crtc);
4806
4807         assert_plane_disabled(dev->dev_private, to_intel_crtc(crtc)->plane);
4808         assert_cursor_disabled(dev_priv, to_intel_crtc(crtc)->pipe);
4809         assert_pipe_disabled(dev->dev_private, to_intel_crtc(crtc)->pipe);
4810
4811         if (crtc->primary->fb) {
4812                 mutex_lock(&dev->struct_mutex);
4813                 intel_unpin_fb_obj(to_intel_framebuffer(crtc->primary->fb)->obj);
4814                 mutex_unlock(&dev->struct_mutex);
4815                 crtc->primary->fb = NULL;
4816         }
4817
4818         /* Update computed state. */
4819         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
4820                 if (!connector->encoder || !connector->encoder->crtc)
4821                         continue;
4822
4823                 if (connector->encoder->crtc != crtc)
4824                         continue;
4825
4826                 connector->dpms = DRM_MODE_DPMS_OFF;
4827                 to_intel_encoder(connector->encoder)->connectors_active = false;
4828         }
4829 }
4830
4831 void intel_encoder_destroy(struct drm_encoder *encoder)
4832 {
4833         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
4834
4835         drm_encoder_cleanup(encoder);
4836         kfree(intel_encoder);
4837 }
4838
4839 /* Simple dpms helper for encoders with just one connector, no cloning and only
4840  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
4841  * state of the entire output pipe. */
4842 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
4843 {
4844         if (mode == DRM_MODE_DPMS_ON) {
4845                 encoder->connectors_active = true;
4846
4847                 intel_crtc_update_dpms(encoder->base.crtc);
4848         } else {
4849                 encoder->connectors_active = false;
4850
4851                 intel_crtc_update_dpms(encoder->base.crtc);
4852         }
4853 }
4854
4855 /* Cross check the actual hw state with our own modeset state tracking (and it's
4856  * internal consistency). */
4857 static void intel_connector_check_state(struct intel_connector *connector)
4858 {
4859         if (connector->get_hw_state(connector)) {
4860                 struct intel_encoder *encoder = connector->encoder;
4861                 struct drm_crtc *crtc;
4862                 bool encoder_enabled;
4863                 enum pipe pipe;
4864
4865                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
4866                               connector->base.base.id,
4867                               drm_get_connector_name(&connector->base));
4868
4869                 WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
4870                      "wrong connector dpms state\n");
4871                 WARN(connector->base.encoder != &encoder->base,
4872                      "active connector not linked to encoder\n");
4873                 WARN(!encoder->connectors_active,
4874                      "encoder->connectors_active not set\n");
4875
4876                 encoder_enabled = encoder->get_hw_state(encoder, &pipe);
4877                 WARN(!encoder_enabled, "encoder not enabled\n");
4878                 if (WARN_ON(!encoder->base.crtc))
4879                         return;
4880
4881                 crtc = encoder->base.crtc;
4882
4883                 WARN(!crtc->enabled, "crtc not enabled\n");
4884                 WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
4885                 WARN(pipe != to_intel_crtc(crtc)->pipe,
4886                      "encoder active on the wrong pipe\n");
4887         }
4888 }
4889
4890 /* Even simpler default implementation, if there's really no special case to
4891  * consider. */
4892 void intel_connector_dpms(struct drm_connector *connector, int mode)
4893 {
4894         /* All the simple cases only support two dpms states. */
4895         if (mode != DRM_MODE_DPMS_ON)
4896                 mode = DRM_MODE_DPMS_OFF;
4897
4898         if (mode == connector->dpms)
4899                 return;
4900
4901         connector->dpms = mode;
4902
4903         /* Only need to change hw state when actually enabled */
4904         if (connector->encoder)
4905                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
4906
4907         intel_modeset_check_state(connector->dev);
4908 }
4909
4910 /* Simple connector->get_hw_state implementation for encoders that support only
4911  * one connector and no cloning and hence the encoder state determines the state
4912  * of the connector. */
4913 bool intel_connector_get_hw_state(struct intel_connector *connector)
4914 {
4915         enum pipe pipe = 0;
4916         struct intel_encoder *encoder = connector->encoder;
4917
4918         return encoder->get_hw_state(encoder, &pipe);
4919 }
4920
4921 static bool ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
4922                                      struct intel_crtc_config *pipe_config)
4923 {
4924         struct drm_i915_private *dev_priv = dev->dev_private;
4925         struct intel_crtc *pipe_B_crtc =
4926                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
4927
4928         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
4929                       pipe_name(pipe), pipe_config->fdi_lanes);
4930         if (pipe_config->fdi_lanes > 4) {
4931                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
4932                               pipe_name(pipe), pipe_config->fdi_lanes);
4933                 return false;
4934         }
4935
4936         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
4937                 if (pipe_config->fdi_lanes > 2) {
4938                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
4939                                       pipe_config->fdi_lanes);
4940                         return false;
4941                 } else {
4942                         return true;
4943                 }
4944         }
4945
4946         if (INTEL_INFO(dev)->num_pipes == 2)
4947                 return true;
4948
4949         /* Ivybridge 3 pipe is really complicated */
4950         switch (pipe) {
4951         case PIPE_A:
4952                 return true;
4953         case PIPE_B:
4954                 if (dev_priv->pipe_to_crtc_mapping[PIPE_C]->enabled &&
4955                     pipe_config->fdi_lanes > 2) {
4956                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
4957                                       pipe_name(pipe), pipe_config->fdi_lanes);
4958                         return false;
4959                 }
4960                 return true;
4961         case PIPE_C:
4962                 if (!pipe_has_enabled_pch(pipe_B_crtc) ||
4963                     pipe_B_crtc->config.fdi_lanes <= 2) {
4964                         if (pipe_config->fdi_lanes > 2) {
4965                                 DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
4966                                               pipe_name(pipe), pipe_config->fdi_lanes);
4967                                 return false;
4968                         }
4969                 } else {
4970                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
4971                         return false;
4972                 }
4973                 return true;
4974         default:
4975                 BUG();
4976         }
4977 }
4978
4979 #define RETRY 1
4980 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
4981                                        struct intel_crtc_config *pipe_config)
4982 {
4983         struct drm_device *dev = intel_crtc->base.dev;
4984         struct drm_display_mode *adjusted_mode = &pipe_config->adjusted_mode;
4985         int lane, link_bw, fdi_dotclock;
4986         bool setup_ok, needs_recompute = false;
4987
4988 retry:
4989         /* FDI is a binary signal running at ~2.7GHz, encoding
4990          * each output octet as 10 bits. The actual frequency
4991          * is stored as a divider into a 100MHz clock, and the
4992          * mode pixel clock is stored in units of 1KHz.
4993          * Hence the bw of each lane in terms of the mode signal
4994          * is:
4995          */
4996         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
4997
4998         fdi_dotclock = adjusted_mode->crtc_clock;
4999
5000         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
5001                                            pipe_config->pipe_bpp);
5002
5003         pipe_config->fdi_lanes = lane;
5004
5005         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
5006                                link_bw, &pipe_config->fdi_m_n);
5007
5008         setup_ok = ironlake_check_fdi_lanes(intel_crtc->base.dev,
5009                                             intel_crtc->pipe, pipe_config);
5010         if (!setup_ok && pipe_config->pipe_bpp > 6*3) {
5011                 pipe_config->pipe_bpp -= 2*3;
5012                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
5013                               pipe_config->pipe_bpp);
5014                 needs_recompute = true;
5015                 pipe_config->bw_constrained = true;
5016
5017                 goto retry;
5018         }
5019
5020         if (needs_recompute)
5021                 return RETRY;
5022
5023         return setup_ok ? 0 : -EINVAL;
5024 }
5025
5026 static void hsw_compute_ips_config(struct intel_crtc *crtc,
5027                                    struct intel_crtc_config *pipe_config)
5028 {
5029         pipe_config->ips_enabled = i915.enable_ips &&
5030                                    hsw_crtc_supports_ips(crtc) &&
5031                                    pipe_config->pipe_bpp <= 24;
5032 }
5033
5034 static int intel_crtc_compute_config(struct intel_crtc *crtc,
5035                                      struct intel_crtc_config *pipe_config)
5036 {
5037         struct drm_device *dev = crtc->base.dev;
5038         struct drm_display_mode *adjusted_mode = &pipe_config->adjusted_mode;
5039
5040         /* FIXME should check pixel clock limits on all platforms */
5041         if (INTEL_INFO(dev)->gen < 4) {
5042                 struct drm_i915_private *dev_priv = dev->dev_private;
5043                 int clock_limit =
5044                         dev_priv->display.get_display_clock_speed(dev);
5045
5046                 /*
5047                  * Enable pixel doubling when the dot clock
5048                  * is > 90% of the (display) core speed.
5049                  *
5050                  * GDG double wide on either pipe,
5051                  * otherwise pipe A only.
5052                  */
5053                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
5054                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
5055                         clock_limit *= 2;
5056                         pipe_config->double_wide = true;
5057                 }
5058
5059                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
5060                         return -EINVAL;
5061         }
5062
5063         /*
5064          * Pipe horizontal size must be even in:
5065          * - DVO ganged mode
5066          * - LVDS dual channel mode
5067          * - Double wide pipe
5068          */
5069         if ((intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS) &&
5070              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
5071                 pipe_config->pipe_src_w &= ~1;
5072
5073         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
5074          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
5075          */
5076         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
5077                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
5078                 return -EINVAL;
5079
5080         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)) && pipe_config->pipe_bpp > 10*3) {
5081                 pipe_config->pipe_bpp = 10*3; /* 12bpc is gen5+ */
5082         } else if (INTEL_INFO(dev)->gen <= 4 && pipe_config->pipe_bpp > 8*3) {
5083                 /* only a 8bpc pipe, with 6bpc dither through the panel fitter
5084                  * for lvds. */
5085                 pipe_config->pipe_bpp = 8*3;
5086         }
5087
5088         if (HAS_IPS(dev))
5089                 hsw_compute_ips_config(crtc, pipe_config);
5090
5091         /* XXX: PCH clock sharing is done in ->mode_set, so make sure the old
5092          * clock survives for now. */
5093         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
5094                 pipe_config->shared_dpll = crtc->config.shared_dpll;
5095
5096         if (pipe_config->has_pch_encoder)
5097                 return ironlake_fdi_compute_config(crtc, pipe_config);
5098
5099         return 0;
5100 }
5101
5102 static int valleyview_get_display_clock_speed(struct drm_device *dev)
5103 {
5104         return 400000; /* FIXME */
5105 }
5106
5107 static int i945_get_display_clock_speed(struct drm_device *dev)
5108 {
5109         return 400000;
5110 }
5111
5112 static int i915_get_display_clock_speed(struct drm_device *dev)
5113 {
5114         return 333000;
5115 }
5116
5117 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
5118 {
5119         return 200000;
5120 }
5121
5122 static int pnv_get_display_clock_speed(struct drm_device *dev)
5123 {
5124         u16 gcfgc = 0;
5125
5126         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5127
5128         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5129         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
5130                 return 267000;
5131         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
5132                 return 333000;
5133         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
5134                 return 444000;
5135         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
5136                 return 200000;
5137         default:
5138                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
5139         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
5140                 return 133000;
5141         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
5142                 return 167000;
5143         }
5144 }
5145
5146 static int i915gm_get_display_clock_speed(struct drm_device *dev)
5147 {
5148         u16 gcfgc = 0;
5149
5150         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5151
5152         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
5153                 return 133000;
5154         else {
5155                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5156                 case GC_DISPLAY_CLOCK_333_MHZ:
5157                         return 333000;
5158                 default:
5159                 case GC_DISPLAY_CLOCK_190_200_MHZ:
5160                         return 190000;
5161                 }
5162         }
5163 }
5164
5165 static int i865_get_display_clock_speed(struct drm_device *dev)
5166 {
5167         return 266000;
5168 }
5169
5170 static int i855_get_display_clock_speed(struct drm_device *dev)
5171 {
5172         u16 hpllcc = 0;
5173         /* Assume that the hardware is in the high speed state.  This
5174          * should be the default.
5175          */
5176         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
5177         case GC_CLOCK_133_200:
5178         case GC_CLOCK_100_200:
5179                 return 200000;
5180         case GC_CLOCK_166_250:
5181                 return 250000;
5182         case GC_CLOCK_100_133:
5183                 return 133000;
5184         }
5185
5186         /* Shouldn't happen */
5187         return 0;
5188 }
5189
5190 static int i830_get_display_clock_speed(struct drm_device *dev)
5191 {
5192         return 133000;
5193 }
5194
5195 static void
5196 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
5197 {
5198         while (*num > DATA_LINK_M_N_MASK ||
5199                *den > DATA_LINK_M_N_MASK) {
5200                 *num >>= 1;
5201                 *den >>= 1;
5202         }
5203 }
5204
5205 static void compute_m_n(unsigned int m, unsigned int n,
5206                         uint32_t *ret_m, uint32_t *ret_n)
5207 {
5208         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
5209         *ret_m = div_u64((uint64_t) m * *ret_n, n);
5210         intel_reduce_m_n_ratio(ret_m, ret_n);
5211 }
5212
5213 void
5214 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
5215                        int pixel_clock, int link_clock,
5216                        struct intel_link_m_n *m_n)
5217 {
5218         m_n->tu = 64;
5219
5220         compute_m_n(bits_per_pixel * pixel_clock,
5221                     link_clock * nlanes * 8,
5222                     &m_n->gmch_m, &m_n->gmch_n);
5223
5224         compute_m_n(pixel_clock, link_clock,
5225                     &m_n->link_m, &m_n->link_n);
5226 }
5227
5228 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
5229 {
5230         if (i915.panel_use_ssc >= 0)
5231                 return i915.panel_use_ssc != 0;
5232         return dev_priv->vbt.lvds_use_ssc
5233                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
5234 }
5235
5236 static int i9xx_get_refclk(struct drm_crtc *crtc, int num_connectors)
5237 {
5238         struct drm_device *dev = crtc->dev;
5239         struct drm_i915_private *dev_priv = dev->dev_private;
5240         int refclk;
5241
5242         if (IS_VALLEYVIEW(dev)) {
5243                 refclk = 100000;
5244         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
5245             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
5246                 refclk = dev_priv->vbt.lvds_ssc_freq;
5247                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
5248         } else if (!IS_GEN2(dev)) {
5249                 refclk = 96000;
5250         } else {
5251                 refclk = 48000;
5252         }
5253
5254         return refclk;
5255 }
5256
5257 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
5258 {
5259         return (1 << dpll->n) << 16 | dpll->m2;
5260 }
5261
5262 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
5263 {
5264         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
5265 }
5266
5267 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
5268                                      intel_clock_t *reduced_clock)
5269 {
5270         struct drm_device *dev = crtc->base.dev;
5271         struct drm_i915_private *dev_priv = dev->dev_private;
5272         int pipe = crtc->pipe;
5273         u32 fp, fp2 = 0;
5274
5275         if (IS_PINEVIEW(dev)) {
5276                 fp = pnv_dpll_compute_fp(&crtc->config.dpll);
5277                 if (reduced_clock)
5278                         fp2 = pnv_dpll_compute_fp(reduced_clock);
5279         } else {
5280                 fp = i9xx_dpll_compute_fp(&crtc->config.dpll);
5281                 if (reduced_clock)
5282                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
5283         }
5284
5285         I915_WRITE(FP0(pipe), fp);
5286         crtc->config.dpll_hw_state.fp0 = fp;
5287
5288         crtc->lowfreq_avail = false;
5289         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS) &&
5290             reduced_clock && i915.powersave) {
5291                 I915_WRITE(FP1(pipe), fp2);
5292                 crtc->config.dpll_hw_state.fp1 = fp2;
5293                 crtc->lowfreq_avail = true;
5294         } else {
5295                 I915_WRITE(FP1(pipe), fp);
5296                 crtc->config.dpll_hw_state.fp1 = fp;
5297         }
5298 }
5299
5300 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
5301                 pipe)
5302 {
5303         u32 reg_val;
5304
5305         /*
5306          * PLLB opamp always calibrates to max value of 0x3f, force enable it
5307          * and set it to a reasonable value instead.
5308          */
5309         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5310         reg_val &= 0xffffff00;
5311         reg_val |= 0x00000030;
5312         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5313
5314         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5315         reg_val &= 0x8cffffff;
5316         reg_val = 0x8c000000;
5317         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5318
5319         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5320         reg_val &= 0xffffff00;
5321         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5322
5323         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5324         reg_val &= 0x00ffffff;
5325         reg_val |= 0xb0000000;
5326         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5327 }
5328
5329 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
5330                                          struct intel_link_m_n *m_n)
5331 {
5332         struct drm_device *dev = crtc->base.dev;
5333         struct drm_i915_private *dev_priv = dev->dev_private;
5334         int pipe = crtc->pipe;
5335
5336         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5337         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
5338         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
5339         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
5340 }
5341
5342 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
5343                                          struct intel_link_m_n *m_n)
5344 {
5345         struct drm_device *dev = crtc->base.dev;
5346         struct drm_i915_private *dev_priv = dev->dev_private;
5347         int pipe = crtc->pipe;
5348         enum transcoder transcoder = crtc->config.cpu_transcoder;
5349
5350         if (INTEL_INFO(dev)->gen >= 5) {
5351                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
5352                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
5353                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
5354                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
5355         } else {
5356                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5357                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
5358                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
5359                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
5360         }
5361 }
5362
5363 static void intel_dp_set_m_n(struct intel_crtc *crtc)
5364 {
5365         if (crtc->config.has_pch_encoder)
5366                 intel_pch_transcoder_set_m_n(crtc, &crtc->config.dp_m_n);
5367         else
5368                 intel_cpu_transcoder_set_m_n(crtc, &crtc->config.dp_m_n);
5369 }
5370
5371 static void vlv_update_pll(struct intel_crtc *crtc)
5372 {
5373         struct drm_device *dev = crtc->base.dev;
5374         struct drm_i915_private *dev_priv = dev->dev_private;
5375         int pipe = crtc->pipe;
5376         u32 dpll, mdiv;
5377         u32 bestn, bestm1, bestm2, bestp1, bestp2;
5378         u32 coreclk, reg_val, dpll_md;
5379
5380         mutex_lock(&dev_priv->dpio_lock);
5381
5382         bestn = crtc->config.dpll.n;
5383         bestm1 = crtc->config.dpll.m1;
5384         bestm2 = crtc->config.dpll.m2;
5385         bestp1 = crtc->config.dpll.p1;
5386         bestp2 = crtc->config.dpll.p2;
5387
5388         /* See eDP HDMI DPIO driver vbios notes doc */
5389
5390         /* PLL B needs special handling */
5391         if (pipe)
5392                 vlv_pllb_recal_opamp(dev_priv, pipe);
5393
5394         /* Set up Tx target for periodic Rcomp update */
5395         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
5396
5397         /* Disable target IRef on PLL */
5398         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
5399         reg_val &= 0x00ffffff;
5400         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
5401
5402         /* Disable fast lock */
5403         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
5404
5405         /* Set idtafcrecal before PLL is enabled */
5406         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
5407         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
5408         mdiv |= ((bestn << DPIO_N_SHIFT));
5409         mdiv |= (1 << DPIO_K_SHIFT);
5410
5411         /*
5412          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
5413          * but we don't support that).
5414          * Note: don't use the DAC post divider as it seems unstable.
5415          */
5416         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
5417         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5418
5419         mdiv |= DPIO_ENABLE_CALIBRATION;
5420         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5421
5422         /* Set HBR and RBR LPF coefficients */
5423         if (crtc->config.port_clock == 162000 ||
5424             intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_ANALOG) ||
5425             intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_HDMI))
5426                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5427                                  0x009f0003);
5428         else
5429                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5430                                  0x00d0000f);
5431
5432         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_EDP) ||
5433             intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_DISPLAYPORT)) {
5434                 /* Use SSC source */
5435                 if (!pipe)
5436                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5437                                          0x0df40000);
5438                 else
5439                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5440                                          0x0df70000);
5441         } else { /* HDMI or VGA */
5442                 /* Use bend source */
5443                 if (!pipe)
5444                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5445                                          0x0df70000);
5446                 else
5447                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5448                                          0x0df40000);
5449         }
5450
5451         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
5452         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
5453         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_DISPLAYPORT) ||
5454             intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_EDP))
5455                 coreclk |= 0x01000000;
5456         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
5457
5458         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
5459
5460         /*
5461          * Enable DPIO clock input. We should never disable the reference
5462          * clock for pipe B, since VGA hotplug / manual detection depends
5463          * on it.
5464          */
5465         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
5466                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
5467         /* We should never disable this, set it here for state tracking */
5468         if (pipe == PIPE_B)
5469                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
5470         dpll |= DPLL_VCO_ENABLE;
5471         crtc->config.dpll_hw_state.dpll = dpll;
5472
5473         dpll_md = (crtc->config.pixel_multiplier - 1)
5474                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5475         crtc->config.dpll_hw_state.dpll_md = dpll_md;
5476
5477         mutex_unlock(&dev_priv->dpio_lock);
5478 }
5479
5480 static void chv_update_pll(struct intel_crtc *crtc)
5481 {
5482         struct drm_device *dev = crtc->base.dev;
5483         struct drm_i915_private *dev_priv = dev->dev_private;
5484         int pipe = crtc->pipe;
5485         int dpll_reg = DPLL(crtc->pipe);
5486         enum dpio_channel port = vlv_pipe_to_channel(pipe);
5487         u32 val, loopfilter, intcoeff;
5488         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
5489         int refclk;
5490
5491         mutex_lock(&dev_priv->dpio_lock);
5492
5493         bestn = crtc->config.dpll.n;
5494         bestm2_frac = crtc->config.dpll.m2 & 0x3fffff;
5495         bestm1 = crtc->config.dpll.m1;
5496         bestm2 = crtc->config.dpll.m2 >> 22;
5497         bestp1 = crtc->config.dpll.p1;
5498         bestp2 = crtc->config.dpll.p2;
5499
5500         /*
5501          * Enable Refclk and SSC
5502          */
5503         val = I915_READ(dpll_reg);
5504         val |= (DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV);
5505         I915_WRITE(dpll_reg, val);
5506
5507         /* Propagate soft reset to data lane reset */
5508         val = vlv_dpio_read(dev_priv, pipe, VLV_PCS_DW0(port));
5509         val &= ~(DPIO_PCS_TX_LANE2_RESET | DPIO_PCS_TX_LANE1_RESET);
5510         vlv_dpio_write(dev_priv, pipe, VLV_PCS_DW0(port), val);
5511
5512         /* Disable 10bit clock to display controller */
5513         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
5514         val &= ~DPIO_DCLKP_EN;
5515         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
5516
5517         /* p1 and p2 divider */
5518         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
5519                         5 << DPIO_CHV_S1_DIV_SHIFT |
5520                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
5521                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
5522                         1 << DPIO_CHV_K_DIV_SHIFT);
5523
5524         /* Feedback post-divider - m2 */
5525         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
5526
5527         /* Feedback refclk divider - n and m1 */
5528         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
5529                         DPIO_CHV_M1_DIV_BY_2 |
5530                         1 << DPIO_CHV_N_DIV_SHIFT);
5531
5532         /* M2 fraction division */
5533         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
5534
5535         /* M2 fraction division enable */
5536         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port),
5537                        DPIO_CHV_FRAC_DIV_EN |
5538                        (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT));
5539
5540         /* Loop filter */
5541         refclk = i9xx_get_refclk(&crtc->base, 0);
5542         loopfilter = 5 << DPIO_CHV_PROP_COEFF_SHIFT |
5543                 2 << DPIO_CHV_GAIN_CTRL_SHIFT;
5544         if (refclk == 100000)
5545                 intcoeff = 11;
5546         else if (refclk == 38400)
5547                 intcoeff = 10;
5548         else
5549                 intcoeff = 9;
5550         loopfilter |= intcoeff << DPIO_CHV_INT_COEFF_SHIFT;
5551         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
5552
5553         /* AFC Recal */
5554         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
5555                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
5556                         DPIO_AFC_RECAL);
5557
5558         mutex_unlock(&dev_priv->dpio_lock);
5559 }
5560
5561 static void i9xx_update_pll(struct intel_crtc *crtc,
5562                             intel_clock_t *reduced_clock,
5563                             int num_connectors)
5564 {
5565         struct drm_device *dev = crtc->base.dev;
5566         struct drm_i915_private *dev_priv = dev->dev_private;
5567         u32 dpll;
5568         bool is_sdvo;
5569         struct dpll *clock = &crtc->config.dpll;
5570
5571         i9xx_update_pll_dividers(crtc, reduced_clock);
5572
5573         is_sdvo = intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_SDVO) ||
5574                 intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_HDMI);
5575
5576         dpll = DPLL_VGA_MODE_DIS;
5577
5578         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS))
5579                 dpll |= DPLLB_MODE_LVDS;
5580         else
5581                 dpll |= DPLLB_MODE_DAC_SERIAL;
5582
5583         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
5584                 dpll |= (crtc->config.pixel_multiplier - 1)
5585                         << SDVO_MULTIPLIER_SHIFT_HIRES;
5586         }
5587
5588         if (is_sdvo)
5589                 dpll |= DPLL_SDVO_HIGH_SPEED;
5590
5591         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_DISPLAYPORT))
5592                 dpll |= DPLL_SDVO_HIGH_SPEED;
5593
5594         /* compute bitmask from p1 value */
5595         if (IS_PINEVIEW(dev))
5596                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
5597         else {
5598                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5599                 if (IS_G4X(dev) && reduced_clock)
5600                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
5601         }
5602         switch (clock->p2) {
5603         case 5:
5604                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
5605                 break;
5606         case 7:
5607                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
5608                 break;
5609         case 10:
5610                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
5611                 break;
5612         case 14:
5613                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
5614                 break;
5615         }
5616         if (INTEL_INFO(dev)->gen >= 4)
5617                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
5618
5619         if (crtc->config.sdvo_tv_clock)
5620                 dpll |= PLL_REF_INPUT_TVCLKINBC;
5621         else if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS) &&
5622                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
5623                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
5624         else
5625                 dpll |= PLL_REF_INPUT_DREFCLK;
5626
5627         dpll |= DPLL_VCO_ENABLE;
5628         crtc->config.dpll_hw_state.dpll = dpll;
5629
5630         if (INTEL_INFO(dev)->gen >= 4) {
5631                 u32 dpll_md = (crtc->config.pixel_multiplier - 1)
5632                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5633                 crtc->config.dpll_hw_state.dpll_md = dpll_md;
5634         }
5635 }
5636
5637 static void i8xx_update_pll(struct intel_crtc *crtc,
5638                             intel_clock_t *reduced_clock,
5639                             int num_connectors)
5640 {
5641         struct drm_device *dev = crtc->base.dev;
5642         struct drm_i915_private *dev_priv = dev->dev_private;
5643         u32 dpll;
5644         struct dpll *clock = &crtc->config.dpll;
5645
5646         i9xx_update_pll_dividers(crtc, reduced_clock);
5647
5648         dpll = DPLL_VGA_MODE_DIS;
5649
5650         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS)) {
5651                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5652         } else {
5653                 if (clock->p1 == 2)
5654                         dpll |= PLL_P1_DIVIDE_BY_TWO;
5655                 else
5656                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
5657                 if (clock->p2 == 4)
5658                         dpll |= PLL_P2_DIVIDE_BY_4;
5659         }
5660
5661         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_DVO))
5662                 dpll |= DPLL_DVO_2X_MODE;
5663
5664         if (intel_pipe_has_type(&crtc->base, INTEL_OUTPUT_LVDS) &&
5665                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
5666                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
5667         else
5668                 dpll |= PLL_REF_INPUT_DREFCLK;
5669
5670         dpll |= DPLL_VCO_ENABLE;
5671         crtc->config.dpll_hw_state.dpll = dpll;
5672 }
5673
5674 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
5675 {
5676         struct drm_device *dev = intel_crtc->base.dev;
5677         struct drm_i915_private *dev_priv = dev->dev_private;
5678         enum pipe pipe = intel_crtc->pipe;
5679         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
5680         struct drm_display_mode *adjusted_mode =
5681                 &intel_crtc->config.adjusted_mode;
5682         uint32_t crtc_vtotal, crtc_vblank_end;
5683         int vsyncshift = 0;
5684
5685         /* We need to be careful not to changed the adjusted mode, for otherwise
5686          * the hw state checker will get angry at the mismatch. */
5687         crtc_vtotal = adjusted_mode->crtc_vtotal;
5688         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
5689
5690         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5691                 /* the chip adds 2 halflines automatically */
5692                 crtc_vtotal -= 1;
5693                 crtc_vblank_end -= 1;
5694
5695                 if (intel_pipe_has_type(&intel_crtc->base, INTEL_OUTPUT_SDVO))
5696                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
5697                 else
5698                         vsyncshift = adjusted_mode->crtc_hsync_start -
5699                                 adjusted_mode->crtc_htotal / 2;
5700                 if (vsyncshift < 0)
5701                         vsyncshift += adjusted_mode->crtc_htotal;
5702         }
5703
5704         if (INTEL_INFO(dev)->gen > 3)
5705                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
5706
5707         I915_WRITE(HTOTAL(cpu_transcoder),
5708                    (adjusted_mode->crtc_hdisplay - 1) |
5709                    ((adjusted_mode->crtc_htotal - 1) << 16));
5710         I915_WRITE(HBLANK(cpu_transcoder),
5711                    (adjusted_mode->crtc_hblank_start - 1) |
5712                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
5713         I915_WRITE(HSYNC(cpu_transcoder),
5714                    (adjusted_mode->crtc_hsync_start - 1) |
5715                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
5716
5717         I915_WRITE(VTOTAL(cpu_transcoder),
5718                    (adjusted_mode->crtc_vdisplay - 1) |
5719                    ((crtc_vtotal - 1) << 16));
5720         I915_WRITE(VBLANK(cpu_transcoder),
5721                    (adjusted_mode->crtc_vblank_start - 1) |
5722                    ((crtc_vblank_end - 1) << 16));
5723         I915_WRITE(VSYNC(cpu_transcoder),
5724                    (adjusted_mode->crtc_vsync_start - 1) |
5725                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
5726
5727         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
5728          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
5729          * documented on the DDI_FUNC_CTL register description, EDP Input Select
5730          * bits. */
5731         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
5732             (pipe == PIPE_B || pipe == PIPE_C))
5733                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
5734
5735         /* pipesrc controls the size that is scaled from, which should
5736          * always be the user's requested size.
5737          */
5738         I915_WRITE(PIPESRC(pipe),
5739                    ((intel_crtc->config.pipe_src_w - 1) << 16) |
5740                    (intel_crtc->config.pipe_src_h - 1));
5741 }
5742
5743 static void intel_get_pipe_timings(struct intel_crtc *crtc,
5744                                    struct intel_crtc_config *pipe_config)
5745 {
5746         struct drm_device *dev = crtc->base.dev;
5747         struct drm_i915_private *dev_priv = dev->dev_private;
5748         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5749         uint32_t tmp;
5750
5751         tmp = I915_READ(HTOTAL(cpu_transcoder));
5752         pipe_config->adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
5753         pipe_config->adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
5754         tmp = I915_READ(HBLANK(cpu_transcoder));
5755         pipe_config->adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
5756         pipe_config->adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
5757         tmp = I915_READ(HSYNC(cpu_transcoder));
5758         pipe_config->adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
5759         pipe_config->adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
5760
5761         tmp = I915_READ(VTOTAL(cpu_transcoder));
5762         pipe_config->adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
5763         pipe_config->adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
5764         tmp = I915_READ(VBLANK(cpu_transcoder));
5765         pipe_config->adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
5766         pipe_config->adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
5767         tmp = I915_READ(VSYNC(cpu_transcoder));
5768         pipe_config->adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
5769         pipe_config->adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
5770
5771         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
5772                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
5773                 pipe_config->adjusted_mode.crtc_vtotal += 1;
5774                 pipe_config->adjusted_mode.crtc_vblank_end += 1;
5775         }
5776
5777         tmp = I915_READ(PIPESRC(crtc->pipe));
5778         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
5779         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
5780
5781         pipe_config->requested_mode.vdisplay = pipe_config->pipe_src_h;
5782         pipe_config->requested_mode.hdisplay = pipe_config->pipe_src_w;
5783 }
5784
5785 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
5786                                  struct intel_crtc_config *pipe_config)
5787 {
5788         mode->hdisplay = pipe_config->adjusted_mode.crtc_hdisplay;
5789         mode->htotal = pipe_config->adjusted_mode.crtc_htotal;
5790         mode->hsync_start = pipe_config->adjusted_mode.crtc_hsync_start;
5791         mode->hsync_end = pipe_config->adjusted_mode.crtc_hsync_end;
5792
5793         mode->vdisplay = pipe_config->adjusted_mode.crtc_vdisplay;
5794         mode->vtotal = pipe_config->adjusted_mode.crtc_vtotal;
5795         mode->vsync_start = pipe_config->adjusted_mode.crtc_vsync_start;
5796         mode->vsync_end = pipe_config->adjusted_mode.crtc_vsync_end;
5797
5798         mode->flags = pipe_config->adjusted_mode.flags;
5799
5800         mode->clock = pipe_config->adjusted_mode.crtc_clock;
5801         mode->flags |= pipe_config->adjusted_mode.flags;
5802 }
5803
5804 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
5805 {
5806         struct drm_device *dev = intel_crtc->base.dev;
5807         struct drm_i915_private *dev_priv = dev->dev_private;
5808         uint32_t pipeconf;
5809
5810         pipeconf = 0;
5811
5812         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
5813             I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE)
5814                 pipeconf |= PIPECONF_ENABLE;
5815
5816         if (intel_crtc->config.double_wide)
5817                 pipeconf |= PIPECONF_DOUBLE_WIDE;
5818
5819         /* only g4x and later have fancy bpc/dither controls */
5820         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
5821                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
5822                 if (intel_crtc->config.dither && intel_crtc->config.pipe_bpp != 30)
5823                         pipeconf |= PIPECONF_DITHER_EN |
5824                                     PIPECONF_DITHER_TYPE_SP;
5825
5826                 switch (intel_crtc->config.pipe_bpp) {
5827                 case 18:
5828                         pipeconf |= PIPECONF_6BPC;
5829                         break;
5830                 case 24:
5831                         pipeconf |= PIPECONF_8BPC;
5832                         break;
5833                 case 30:
5834                         pipeconf |= PIPECONF_10BPC;
5835                         break;
5836                 default:
5837                         /* Case prevented by intel_choose_pipe_bpp_dither. */
5838                         BUG();
5839                 }
5840         }
5841
5842         if (HAS_PIPE_CXSR(dev)) {
5843                 if (intel_crtc->lowfreq_avail) {
5844                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
5845                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
5846                 } else {
5847                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
5848                 }
5849         }
5850
5851         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
5852                 if (INTEL_INFO(dev)->gen < 4 ||
5853                     intel_pipe_has_type(&intel_crtc->base, INTEL_OUTPUT_SDVO))
5854                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
5855                 else
5856                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
5857         } else
5858                 pipeconf |= PIPECONF_PROGRESSIVE;
5859
5860         if (IS_VALLEYVIEW(dev) && intel_crtc->config.limited_color_range)
5861                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
5862
5863         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
5864         POSTING_READ(PIPECONF(intel_crtc->pipe));
5865 }
5866
5867 static int i9xx_crtc_mode_set(struct drm_crtc *crtc,
5868                               int x, int y,
5869                               struct drm_framebuffer *fb)
5870 {
5871         struct drm_device *dev = crtc->dev;
5872         struct drm_i915_private *dev_priv = dev->dev_private;
5873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5874         int refclk, num_connectors = 0;
5875         intel_clock_t clock, reduced_clock;
5876         bool ok, has_reduced_clock = false;
5877         bool is_lvds = false, is_dsi = false;
5878         struct intel_encoder *encoder;
5879         const intel_limit_t *limit;
5880
5881         for_each_encoder_on_crtc(dev, crtc, encoder) {
5882                 switch (encoder->type) {
5883                 case INTEL_OUTPUT_LVDS:
5884                         is_lvds = true;
5885                         break;
5886                 case INTEL_OUTPUT_DSI:
5887                         is_dsi = true;
5888                         break;
5889                 }
5890
5891                 num_connectors++;
5892         }
5893
5894         if (is_dsi)
5895                 return 0;
5896
5897         if (!intel_crtc->config.clock_set) {
5898                 refclk = i9xx_get_refclk(crtc, num_connectors);
5899
5900                 /*
5901                  * Returns a set of divisors for the desired target clock with
5902                  * the given refclk, or FALSE.  The returned values represent
5903                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
5904                  * 2) / p1 / p2.
5905                  */
5906                 limit = intel_limit(crtc, refclk);
5907                 ok = dev_priv->display.find_dpll(limit, crtc,
5908                                                  intel_crtc->config.port_clock,
5909                                                  refclk, NULL, &clock);
5910                 if (!ok) {
5911                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
5912                         return -EINVAL;
5913                 }
5914
5915                 if (is_lvds && dev_priv->lvds_downclock_avail) {
5916                         /*
5917                          * Ensure we match the reduced clock's P to the target
5918                          * clock.  If the clocks don't match, we can't switch
5919                          * the display clock by using the FP0/FP1. In such case
5920                          * we will disable the LVDS downclock feature.
5921                          */
5922                         has_reduced_clock =
5923                                 dev_priv->display.find_dpll(limit, crtc,
5924                                                             dev_priv->lvds_downclock,
5925                                                             refclk, &clock,
5926                                                             &reduced_clock);
5927                 }
5928                 /* Compat-code for transition, will disappear. */
5929                 intel_crtc->config.dpll.n = clock.n;
5930                 intel_crtc->config.dpll.m1 = clock.m1;
5931                 intel_crtc->config.dpll.m2 = clock.m2;
5932                 intel_crtc->config.dpll.p1 = clock.p1;
5933                 intel_crtc->config.dpll.p2 = clock.p2;
5934         }
5935
5936         if (IS_GEN2(dev)) {
5937                 i8xx_update_pll(intel_crtc,
5938                                 has_reduced_clock ? &reduced_clock : NULL,
5939                                 num_connectors);
5940         } else if (IS_CHERRYVIEW(dev)) {
5941                 chv_update_pll(intel_crtc);
5942         } else if (IS_VALLEYVIEW(dev)) {
5943                 vlv_update_pll(intel_crtc);
5944         } else {
5945                 i9xx_update_pll(intel_crtc,
5946                                 has_reduced_clock ? &reduced_clock : NULL,
5947                                 num_connectors);
5948         }
5949
5950         return 0;
5951 }
5952
5953 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
5954                                  struct intel_crtc_config *pipe_config)
5955 {
5956         struct drm_device *dev = crtc->base.dev;
5957         struct drm_i915_private *dev_priv = dev->dev_private;
5958         uint32_t tmp;
5959
5960         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
5961                 return;
5962
5963         tmp = I915_READ(PFIT_CONTROL);
5964         if (!(tmp & PFIT_ENABLE))
5965                 return;
5966
5967         /* Check whether the pfit is attached to our pipe. */
5968         if (INTEL_INFO(dev)->gen < 4) {
5969                 if (crtc->pipe != PIPE_B)
5970                         return;
5971         } else {
5972                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
5973                         return;
5974         }
5975
5976         pipe_config->gmch_pfit.control = tmp;
5977         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
5978         if (INTEL_INFO(dev)->gen < 5)
5979                 pipe_config->gmch_pfit.lvds_border_bits =
5980                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
5981 }
5982
5983 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
5984                                struct intel_crtc_config *pipe_config)
5985 {
5986         struct drm_device *dev = crtc->base.dev;
5987         struct drm_i915_private *dev_priv = dev->dev_private;
5988         int pipe = pipe_config->cpu_transcoder;
5989         intel_clock_t clock;
5990         u32 mdiv;
5991         int refclk = 100000;
5992
5993         mutex_lock(&dev_priv->dpio_lock);
5994         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
5995         mutex_unlock(&dev_priv->dpio_lock);
5996
5997         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
5998         clock.m2 = mdiv & DPIO_M2DIV_MASK;
5999         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
6000         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
6001         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
6002
6003         vlv_clock(refclk, &clock);
6004
6005         /* clock.dot is the fast clock */
6006         pipe_config->port_clock = clock.dot / 5;
6007 }
6008
6009 static void i9xx_get_plane_config(struct intel_crtc *crtc,
6010                                   struct intel_plane_config *plane_config)
6011 {
6012         struct drm_device *dev = crtc->base.dev;
6013         struct drm_i915_private *dev_priv = dev->dev_private;
6014         u32 val, base, offset;
6015         int pipe = crtc->pipe, plane = crtc->plane;
6016         int fourcc, pixel_format;
6017         int aligned_height;
6018
6019         crtc->base.primary->fb = kzalloc(sizeof(struct intel_framebuffer), GFP_KERNEL);
6020         if (!crtc->base.primary->fb) {
6021                 DRM_DEBUG_KMS("failed to alloc fb\n");
6022                 return;
6023         }
6024
6025         val = I915_READ(DSPCNTR(plane));
6026
6027         if (INTEL_INFO(dev)->gen >= 4)
6028                 if (val & DISPPLANE_TILED)
6029                         plane_config->tiled = true;
6030
6031         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
6032         fourcc = intel_format_to_fourcc(pixel_format);
6033         crtc->base.primary->fb->pixel_format = fourcc;
6034         crtc->base.primary->fb->bits_per_pixel =
6035                 drm_format_plane_cpp(fourcc, 0) * 8;
6036
6037         if (INTEL_INFO(dev)->gen >= 4) {
6038                 if (plane_config->tiled)
6039                         offset = I915_READ(DSPTILEOFF(plane));
6040                 else
6041                         offset = I915_READ(DSPLINOFF(plane));
6042                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
6043         } else {
6044                 base = I915_READ(DSPADDR(plane));
6045         }
6046         plane_config->base = base;
6047
6048         val = I915_READ(PIPESRC(pipe));
6049         crtc->base.primary->fb->width = ((val >> 16) & 0xfff) + 1;
6050         crtc->base.primary->fb->height = ((val >> 0) & 0xfff) + 1;
6051
6052         val = I915_READ(DSPSTRIDE(pipe));
6053         crtc->base.primary->fb->pitches[0] = val & 0xffffff80;
6054
6055         aligned_height = intel_align_height(dev, crtc->base.primary->fb->height,
6056                                             plane_config->tiled);
6057
6058         plane_config->size = ALIGN(crtc->base.primary->fb->pitches[0] *
6059                                    aligned_height, PAGE_SIZE);
6060
6061         DRM_DEBUG_KMS("pipe/plane %d/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
6062                       pipe, plane, crtc->base.primary->fb->width,
6063                       crtc->base.primary->fb->height,
6064                       crtc->base.primary->fb->bits_per_pixel, base,
6065                       crtc->base.primary->fb->pitches[0],
6066                       plane_config->size);
6067
6068 }
6069
6070 static void chv_crtc_clock_get(struct intel_crtc *crtc,
6071                                struct intel_crtc_config *pipe_config)
6072 {
6073         struct drm_device *dev = crtc->base.dev;
6074         struct drm_i915_private *dev_priv = dev->dev_private;
6075         int pipe = pipe_config->cpu_transcoder;
6076         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6077         intel_clock_t clock;
6078         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
6079         int refclk = 100000;
6080
6081         mutex_lock(&dev_priv->dpio_lock);
6082         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
6083         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
6084         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
6085         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
6086         mutex_unlock(&dev_priv->dpio_lock);
6087
6088         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
6089         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
6090         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
6091         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
6092         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
6093
6094         chv_clock(refclk, &clock);
6095
6096         /* clock.dot is the fast clock */
6097         pipe_config->port_clock = clock.dot / 5;
6098 }
6099
6100 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
6101                                  struct intel_crtc_config *pipe_config)
6102 {
6103         struct drm_device *dev = crtc->base.dev;
6104         struct drm_i915_private *dev_priv = dev->dev_private;
6105         uint32_t tmp;
6106
6107         if (!intel_display_power_enabled(dev_priv,
6108                                          POWER_DOMAIN_PIPE(crtc->pipe)))
6109                 return false;
6110
6111         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
6112         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
6113
6114         tmp = I915_READ(PIPECONF(crtc->pipe));
6115         if (!(tmp & PIPECONF_ENABLE))
6116                 return false;
6117
6118         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6119                 switch (tmp & PIPECONF_BPC_MASK) {
6120                 case PIPECONF_6BPC:
6121                         pipe_config->pipe_bpp = 18;
6122                         break;
6123                 case PIPECONF_8BPC:
6124                         pipe_config->pipe_bpp = 24;
6125                         break;
6126                 case PIPECONF_10BPC:
6127                         pipe_config->pipe_bpp = 30;
6128                         break;
6129                 default:
6130                         break;
6131                 }
6132         }
6133
6134         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
6135                 pipe_config->limited_color_range = true;
6136
6137         if (INTEL_INFO(dev)->gen < 4)
6138                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
6139
6140         intel_get_pipe_timings(crtc, pipe_config);
6141
6142         i9xx_get_pfit_config(crtc, pipe_config);
6143
6144         if (INTEL_INFO(dev)->gen >= 4) {
6145                 tmp = I915_READ(DPLL_MD(crtc->pipe));
6146                 pipe_config->pixel_multiplier =
6147                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
6148                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
6149                 pipe_config->dpll_hw_state.dpll_md = tmp;
6150         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6151                 tmp = I915_READ(DPLL(crtc->pipe));
6152                 pipe_config->pixel_multiplier =
6153                         ((tmp & SDVO_MULTIPLIER_MASK)
6154                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
6155         } else {
6156                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
6157                  * port and will be fixed up in the encoder->get_config
6158                  * function. */
6159                 pipe_config->pixel_multiplier = 1;
6160         }
6161         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
6162         if (!IS_VALLEYVIEW(dev)) {
6163                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
6164                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
6165         } else {
6166                 /* Mask out read-only status bits. */
6167                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
6168                                                      DPLL_PORTC_READY_MASK |
6169                                                      DPLL_PORTB_READY_MASK);
6170         }
6171
6172         if (IS_CHERRYVIEW(dev))
6173                 chv_crtc_clock_get(crtc, pipe_config);
6174         else if (IS_VALLEYVIEW(dev))
6175                 vlv_crtc_clock_get(crtc, pipe_config);
6176         else
6177                 i9xx_crtc_clock_get(crtc, pipe_config);
6178
6179         return true;
6180 }
6181
6182 static void ironlake_init_pch_refclk(struct drm_device *dev)
6183 {
6184         struct drm_i915_private *dev_priv = dev->dev_private;
6185         struct drm_mode_config *mode_config = &dev->mode_config;
6186         struct intel_encoder *encoder;
6187         u32 val, final;
6188         bool has_lvds = false;
6189         bool has_cpu_edp = false;
6190         bool has_panel = false;
6191         bool has_ck505 = false;
6192         bool can_ssc = false;
6193
6194         /* We need to take the global config into account */
6195         list_for_each_entry(encoder, &mode_config->encoder_list,
6196                             base.head) {
6197                 switch (encoder->type) {
6198                 case INTEL_OUTPUT_LVDS:
6199                         has_panel = true;
6200                         has_lvds = true;
6201                         break;
6202                 case INTEL_OUTPUT_EDP:
6203                         has_panel = true;
6204                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
6205                                 has_cpu_edp = true;
6206                         break;
6207                 }
6208         }
6209
6210         if (HAS_PCH_IBX(dev)) {
6211                 has_ck505 = dev_priv->vbt.display_clock_mode;
6212                 can_ssc = has_ck505;
6213         } else {
6214                 has_ck505 = false;
6215                 can_ssc = true;
6216         }
6217
6218         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
6219                       has_panel, has_lvds, has_ck505);
6220
6221         /* Ironlake: try to setup display ref clock before DPLL
6222          * enabling. This is only under driver's control after
6223          * PCH B stepping, previous chipset stepping should be
6224          * ignoring this setting.
6225          */
6226         val = I915_READ(PCH_DREF_CONTROL);
6227
6228         /* As we must carefully and slowly disable/enable each source in turn,
6229          * compute the final state we want first and check if we need to
6230          * make any changes at all.
6231          */
6232         final = val;
6233         final &= ~DREF_NONSPREAD_SOURCE_MASK;
6234         if (has_ck505)
6235                 final |= DREF_NONSPREAD_CK505_ENABLE;
6236         else
6237                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
6238
6239         final &= ~DREF_SSC_SOURCE_MASK;
6240         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6241         final &= ~DREF_SSC1_ENABLE;
6242
6243         if (has_panel) {
6244                 final |= DREF_SSC_SOURCE_ENABLE;
6245
6246                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
6247                         final |= DREF_SSC1_ENABLE;
6248
6249                 if (has_cpu_edp) {
6250                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
6251                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6252                         else
6253                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6254                 } else
6255                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6256         } else {
6257                 final |= DREF_SSC_SOURCE_DISABLE;
6258                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6259         }
6260
6261         if (final == val)
6262                 return;
6263
6264         /* Always enable nonspread source */
6265         val &= ~DREF_NONSPREAD_SOURCE_MASK;
6266
6267         if (has_ck505)
6268                 val |= DREF_NONSPREAD_CK505_ENABLE;
6269         else
6270                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
6271
6272         if (has_panel) {
6273                 val &= ~DREF_SSC_SOURCE_MASK;
6274                 val |= DREF_SSC_SOURCE_ENABLE;
6275
6276                 /* SSC must be turned on before enabling the CPU output  */
6277                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6278                         DRM_DEBUG_KMS("Using SSC on panel\n");
6279                         val |= DREF_SSC1_ENABLE;
6280                 } else
6281                         val &= ~DREF_SSC1_ENABLE;
6282
6283                 /* Get SSC going before enabling the outputs */
6284                 I915_WRITE(PCH_DREF_CONTROL, val);
6285                 POSTING_READ(PCH_DREF_CONTROL);
6286                 udelay(200);
6287
6288                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6289
6290                 /* Enable CPU source on CPU attached eDP */
6291                 if (has_cpu_edp) {
6292                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6293                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
6294                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6295                         } else
6296                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6297                 } else
6298                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6299
6300                 I915_WRITE(PCH_DREF_CONTROL, val);
6301                 POSTING_READ(PCH_DREF_CONTROL);
6302                 udelay(200);
6303         } else {
6304                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
6305
6306                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6307
6308                 /* Turn off CPU output */
6309                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6310
6311                 I915_WRITE(PCH_DREF_CONTROL, val);
6312                 POSTING_READ(PCH_DREF_CONTROL);
6313                 udelay(200);
6314
6315                 /* Turn off the SSC source */
6316                 val &= ~DREF_SSC_SOURCE_MASK;
6317                 val |= DREF_SSC_SOURCE_DISABLE;
6318
6319                 /* Turn off SSC1 */
6320                 val &= ~DREF_SSC1_ENABLE;
6321
6322                 I915_WRITE(PCH_DREF_CONTROL, val);
6323                 POSTING_READ(PCH_DREF_CONTROL);
6324                 udelay(200);
6325         }
6326
6327         BUG_ON(val != final);
6328 }
6329
6330 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
6331 {
6332         uint32_t tmp;
6333
6334         tmp = I915_READ(SOUTH_CHICKEN2);
6335         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
6336         I915_WRITE(SOUTH_CHICKEN2, tmp);
6337
6338         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
6339                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
6340                 DRM_ERROR("FDI mPHY reset assert timeout\n");
6341
6342         tmp = I915_READ(SOUTH_CHICKEN2);
6343         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
6344         I915_WRITE(SOUTH_CHICKEN2, tmp);
6345
6346         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
6347                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
6348                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
6349 }
6350
6351 /* WaMPhyProgramming:hsw */
6352 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
6353 {
6354         uint32_t tmp;
6355
6356         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
6357         tmp &= ~(0xFF << 24);
6358         tmp |= (0x12 << 24);
6359         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
6360
6361         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
6362         tmp |= (1 << 11);
6363         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
6364
6365         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
6366         tmp |= (1 << 11);
6367         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
6368
6369         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
6370         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6371         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
6372
6373         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
6374         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6375         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
6376
6377         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
6378         tmp &= ~(7 << 13);
6379         tmp |= (5 << 13);
6380         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
6381
6382         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
6383         tmp &= ~(7 << 13);
6384         tmp |= (5 << 13);
6385         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
6386
6387         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
6388         tmp &= ~0xFF;
6389         tmp |= 0x1C;
6390         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
6391
6392         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
6393         tmp &= ~0xFF;
6394         tmp |= 0x1C;
6395         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
6396
6397         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
6398         tmp &= ~(0xFF << 16);
6399         tmp |= (0x1C << 16);
6400         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
6401
6402         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
6403         tmp &= ~(0xFF << 16);
6404         tmp |= (0x1C << 16);
6405         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
6406
6407         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
6408         tmp |= (1 << 27);
6409         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
6410
6411         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
6412         tmp |= (1 << 27);
6413         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
6414
6415         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
6416         tmp &= ~(0xF << 28);
6417         tmp |= (4 << 28);
6418         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
6419
6420         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
6421         tmp &= ~(0xF << 28);
6422         tmp |= (4 << 28);
6423         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
6424 }
6425
6426 /* Implements 3 different sequences from BSpec chapter "Display iCLK
6427  * Programming" based on the parameters passed:
6428  * - Sequence to enable CLKOUT_DP
6429  * - Sequence to enable CLKOUT_DP without spread
6430  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
6431  */
6432 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
6433                                  bool with_fdi)
6434 {
6435         struct drm_i915_private *dev_priv = dev->dev_private;
6436         uint32_t reg, tmp;
6437
6438         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
6439                 with_spread = true;
6440         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
6441                  with_fdi, "LP PCH doesn't have FDI\n"))
6442                 with_fdi = false;
6443
6444         mutex_lock(&dev_priv->dpio_lock);
6445
6446         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6447         tmp &= ~SBI_SSCCTL_DISABLE;
6448         tmp |= SBI_SSCCTL_PATHALT;
6449         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6450
6451         udelay(24);
6452
6453         if (with_spread) {
6454                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6455                 tmp &= ~SBI_SSCCTL_PATHALT;
6456                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6457
6458                 if (with_fdi) {
6459                         lpt_reset_fdi_mphy(dev_priv);
6460                         lpt_program_fdi_mphy(dev_priv);
6461                 }
6462         }
6463
6464         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
6465                SBI_GEN0 : SBI_DBUFF0;
6466         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
6467         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
6468         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
6469
6470         mutex_unlock(&dev_priv->dpio_lock);
6471 }
6472
6473 /* Sequence to disable CLKOUT_DP */
6474 static void lpt_disable_clkout_dp(struct drm_device *dev)
6475 {
6476         struct drm_i915_private *dev_priv = dev->dev_private;
6477         uint32_t reg, tmp;
6478
6479         mutex_lock(&dev_priv->dpio_lock);
6480
6481         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
6482                SBI_GEN0 : SBI_DBUFF0;
6483         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
6484         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
6485         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
6486
6487         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6488         if (!(tmp & SBI_SSCCTL_DISABLE)) {
6489                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
6490                         tmp |= SBI_SSCCTL_PATHALT;
6491                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6492                         udelay(32);
6493                 }
6494                 tmp |= SBI_SSCCTL_DISABLE;
6495                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6496         }
6497
6498         mutex_unlock(&dev_priv->dpio_lock);
6499 }
6500
6501 static void lpt_init_pch_refclk(struct drm_device *dev)
6502 {
6503         struct drm_mode_config *mode_config = &dev->mode_config;
6504         struct intel_encoder *encoder;
6505         bool has_vga = false;
6506
6507         list_for_each_entry(encoder, &mode_config->encoder_list, base.head) {
6508                 switch (encoder->type) {
6509                 case INTEL_OUTPUT_ANALOG:
6510                         has_vga = true;
6511                         break;
6512                 }
6513         }
6514
6515         if (has_vga)
6516                 lpt_enable_clkout_dp(dev, true, true);
6517         else
6518                 lpt_disable_clkout_dp(dev);
6519 }
6520
6521 /*
6522  * Initialize reference clocks when the driver loads
6523  */
6524 void intel_init_pch_refclk(struct drm_device *dev)
6525 {
6526         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
6527                 ironlake_init_pch_refclk(dev);
6528         else if (HAS_PCH_LPT(dev))
6529                 lpt_init_pch_refclk(dev);
6530 }
6531
6532 static int ironlake_get_refclk(struct drm_crtc *crtc)
6533 {
6534         struct drm_device *dev = crtc->dev;
6535         struct drm_i915_private *dev_priv = dev->dev_private;
6536         struct intel_encoder *encoder;
6537         int num_connectors = 0;
6538         bool is_lvds = false;
6539
6540         for_each_encoder_on_crtc(dev, crtc, encoder) {
6541                 switch (encoder->type) {
6542                 case INTEL_OUTPUT_LVDS:
6543                         is_lvds = true;
6544                         break;
6545                 }
6546                 num_connectors++;
6547         }
6548
6549         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
6550                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
6551                               dev_priv->vbt.lvds_ssc_freq);
6552                 return dev_priv->vbt.lvds_ssc_freq;
6553         }
6554
6555         return 120000;
6556 }
6557
6558 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
6559 {
6560         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
6561         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6562         int pipe = intel_crtc->pipe;
6563         uint32_t val;
6564
6565         val = 0;
6566
6567         switch (intel_crtc->config.pipe_bpp) {
6568         case 18:
6569                 val |= PIPECONF_6BPC;
6570                 break;
6571         case 24:
6572                 val |= PIPECONF_8BPC;
6573                 break;
6574         case 30:
6575                 val |= PIPECONF_10BPC;
6576                 break;
6577         case 36:
6578                 val |= PIPECONF_12BPC;
6579                 break;
6580         default:
6581                 /* Case prevented by intel_choose_pipe_bpp_dither. */
6582                 BUG();
6583         }
6584
6585         if (intel_crtc->config.dither)
6586                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
6587
6588         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
6589                 val |= PIPECONF_INTERLACED_ILK;
6590         else
6591                 val |= PIPECONF_PROGRESSIVE;
6592
6593         if (intel_crtc->config.limited_color_range)
6594                 val |= PIPECONF_COLOR_RANGE_SELECT;
6595
6596         I915_WRITE(PIPECONF(pipe), val);
6597         POSTING_READ(PIPECONF(pipe));
6598 }
6599
6600 /*
6601  * Set up the pipe CSC unit.
6602  *
6603  * Currently only full range RGB to limited range RGB conversion
6604  * is supported, but eventually this should handle various
6605  * RGB<->YCbCr scenarios as well.
6606  */
6607 static void intel_set_pipe_csc(struct drm_crtc *crtc)
6608 {
6609         struct drm_device *dev = crtc->dev;
6610         struct drm_i915_private *dev_priv = dev->dev_private;
6611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6612         int pipe = intel_crtc->pipe;
6613         uint16_t coeff = 0x7800; /* 1.0 */
6614
6615         /*
6616          * TODO: Check what kind of values actually come out of the pipe
6617          * with these coeff/postoff values and adjust to get the best
6618          * accuracy. Perhaps we even need to take the bpc value into
6619          * consideration.
6620          */
6621
6622         if (intel_crtc->config.limited_color_range)
6623                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
6624
6625         /*
6626          * GY/GU and RY/RU should be the other way around according
6627          * to BSpec, but reality doesn't agree. Just set them up in
6628          * a way that results in the correct picture.
6629          */
6630         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
6631         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
6632
6633         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
6634         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
6635
6636         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
6637         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
6638
6639         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
6640         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
6641         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
6642
6643         if (INTEL_INFO(dev)->gen > 6) {
6644                 uint16_t postoff = 0;
6645
6646                 if (intel_crtc->config.limited_color_range)
6647                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
6648
6649                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
6650                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
6651                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
6652
6653                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
6654         } else {
6655                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
6656
6657                 if (intel_crtc->config.limited_color_range)
6658                         mode |= CSC_BLACK_SCREEN_OFFSET;
6659
6660                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
6661         }
6662 }
6663
6664 static void haswell_set_pipeconf(struct drm_crtc *crtc)
6665 {
6666         struct drm_device *dev = crtc->dev;
6667         struct drm_i915_private *dev_priv = dev->dev_private;
6668         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6669         enum pipe pipe = intel_crtc->pipe;
6670         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
6671         uint32_t val;
6672
6673         val = 0;
6674
6675         if (IS_HASWELL(dev) && intel_crtc->config.dither)
6676                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
6677
6678         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
6679                 val |= PIPECONF_INTERLACED_ILK;
6680         else
6681                 val |= PIPECONF_PROGRESSIVE;
6682
6683         I915_WRITE(PIPECONF(cpu_transcoder), val);
6684         POSTING_READ(PIPECONF(cpu_transcoder));
6685
6686         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
6687         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
6688
6689         if (IS_BROADWELL(dev)) {
6690                 val = 0;
6691
6692                 switch (intel_crtc->config.pipe_bpp) {
6693                 case 18:
6694                         val |= PIPEMISC_DITHER_6_BPC;
6695                         break;
6696                 case 24:
6697                         val |= PIPEMISC_DITHER_8_BPC;
6698                         break;
6699                 case 30:
6700                         val |= PIPEMISC_DITHER_10_BPC;
6701                         break;
6702                 case 36:
6703                         val |= PIPEMISC_DITHER_12_BPC;
6704                         break;
6705                 default:
6706                         /* Case prevented by pipe_config_set_bpp. */
6707                         BUG();
6708                 }
6709
6710                 if (intel_crtc->config.dither)
6711                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
6712
6713                 I915_WRITE(PIPEMISC(pipe), val);
6714         }
6715 }
6716
6717 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
6718                                     intel_clock_t *clock,
6719                                     bool *has_reduced_clock,
6720                                     intel_clock_t *reduced_clock)
6721 {
6722         struct drm_device *dev = crtc->dev;
6723         struct drm_i915_private *dev_priv = dev->dev_private;
6724         struct intel_encoder *intel_encoder;
6725         int refclk;
6726         const intel_limit_t *limit;
6727         bool ret, is_lvds = false;
6728
6729         for_each_encoder_on_crtc(dev, crtc, intel_encoder) {
6730                 switch (intel_encoder->type) {
6731                 case INTEL_OUTPUT_LVDS:
6732                         is_lvds = true;
6733                         break;
6734                 }
6735         }
6736
6737         refclk = ironlake_get_refclk(crtc);
6738
6739         /*
6740          * Returns a set of divisors for the desired target clock with the given
6741          * refclk, or FALSE.  The returned values represent the clock equation:
6742          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
6743          */
6744         limit = intel_limit(crtc, refclk);
6745         ret = dev_priv->display.find_dpll(limit, crtc,
6746                                           to_intel_crtc(crtc)->config.port_clock,
6747                                           refclk, NULL, clock);
6748         if (!ret)
6749                 return false;
6750
6751         if (is_lvds && dev_priv->lvds_downclock_avail) {
6752                 /*
6753                  * Ensure we match the reduced clock's P to the target clock.
6754                  * If the clocks don't match, we can't switch the display clock
6755                  * by using the FP0/FP1. In such case we will disable the LVDS
6756                  * downclock feature.
6757                 */
6758                 *has_reduced_clock =
6759                         dev_priv->display.find_dpll(limit, crtc,
6760                                                     dev_priv->lvds_downclock,
6761                                                     refclk, clock,
6762                                                     reduced_clock);
6763         }
6764
6765         return true;
6766 }
6767
6768 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
6769 {
6770         /*
6771          * Account for spread spectrum to avoid
6772          * oversubscribing the link. Max center spread
6773          * is 2.5%; use 5% for safety's sake.
6774          */
6775         u32 bps = target_clock * bpp * 21 / 20;
6776         return DIV_ROUND_UP(bps, link_bw * 8);
6777 }
6778
6779 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
6780 {
6781         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
6782 }
6783
6784 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
6785                                       u32 *fp,
6786                                       intel_clock_t *reduced_clock, u32 *fp2)
6787 {
6788         struct drm_crtc *crtc = &intel_crtc->base;
6789         struct drm_device *dev = crtc->dev;
6790         struct drm_i915_private *dev_priv = dev->dev_private;
6791         struct intel_encoder *intel_encoder;
6792         uint32_t dpll;
6793         int factor, num_connectors = 0;
6794         bool is_lvds = false, is_sdvo = false;
6795
6796         for_each_encoder_on_crtc(dev, crtc, intel_encoder) {
6797                 switch (intel_encoder->type) {
6798                 case INTEL_OUTPUT_LVDS:
6799                         is_lvds = true;
6800                         break;
6801                 case INTEL_OUTPUT_SDVO:
6802                 case INTEL_OUTPUT_HDMI:
6803                         is_sdvo = true;
6804                         break;
6805                 }
6806
6807                 num_connectors++;
6808         }
6809
6810         /* Enable autotuning of the PLL clock (if permissible) */
6811         factor = 21;
6812         if (is_lvds) {
6813                 if ((intel_panel_use_ssc(dev_priv) &&
6814                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
6815                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
6816                         factor = 25;
6817         } else if (intel_crtc->config.sdvo_tv_clock)
6818                 factor = 20;
6819
6820         if (ironlake_needs_fb_cb_tune(&intel_crtc->config.dpll, factor))
6821                 *fp |= FP_CB_TUNE;
6822
6823         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
6824                 *fp2 |= FP_CB_TUNE;
6825
6826         dpll = 0;
6827
6828         if (is_lvds)
6829                 dpll |= DPLLB_MODE_LVDS;
6830         else
6831                 dpll |= DPLLB_MODE_DAC_SERIAL;
6832
6833         dpll |= (intel_crtc->config.pixel_multiplier - 1)
6834                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
6835
6836         if (is_sdvo)
6837                 dpll |= DPLL_SDVO_HIGH_SPEED;
6838         if (intel_crtc->config.has_dp_encoder)
6839                 dpll |= DPLL_SDVO_HIGH_SPEED;
6840
6841         /* compute bitmask from p1 value */
6842         dpll |= (1 << (intel_crtc->config.dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6843         /* also FPA1 */
6844         dpll |= (1 << (intel_crtc->config.dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6845
6846         switch (intel_crtc->config.dpll.p2) {
6847         case 5:
6848                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6849                 break;
6850         case 7:
6851                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6852                 break;
6853         case 10:
6854                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6855                 break;
6856         case 14:
6857                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6858                 break;
6859         }
6860
6861         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6862                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6863         else
6864                 dpll |= PLL_REF_INPUT_DREFCLK;
6865
6866         return dpll | DPLL_VCO_ENABLE;
6867 }
6868
6869 static int ironlake_crtc_mode_set(struct drm_crtc *crtc,
6870                                   int x, int y,
6871                                   struct drm_framebuffer *fb)
6872 {
6873         struct drm_device *dev = crtc->dev;
6874         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6875         int num_connectors = 0;
6876         intel_clock_t clock, reduced_clock;
6877         u32 dpll = 0, fp = 0, fp2 = 0;
6878         bool ok, has_reduced_clock = false;
6879         bool is_lvds = false;
6880         struct intel_encoder *encoder;
6881         struct intel_shared_dpll *pll;
6882
6883         for_each_encoder_on_crtc(dev, crtc, encoder) {
6884                 switch (encoder->type) {
6885                 case INTEL_OUTPUT_LVDS:
6886                         is_lvds = true;
6887                         break;
6888                 }
6889
6890                 num_connectors++;
6891         }
6892
6893         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
6894              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
6895
6896         ok = ironlake_compute_clocks(crtc, &clock,
6897                                      &has_reduced_clock, &reduced_clock);
6898         if (!ok && !intel_crtc->config.clock_set) {
6899                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
6900                 return -EINVAL;
6901         }
6902         /* Compat-code for transition, will disappear. */
6903         if (!intel_crtc->config.clock_set) {
6904                 intel_crtc->config.dpll.n = clock.n;
6905                 intel_crtc->config.dpll.m1 = clock.m1;
6906                 intel_crtc->config.dpll.m2 = clock.m2;
6907                 intel_crtc->config.dpll.p1 = clock.p1;
6908                 intel_crtc->config.dpll.p2 = clock.p2;
6909         }
6910
6911         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
6912         if (intel_crtc->config.has_pch_encoder) {
6913                 fp = i9xx_dpll_compute_fp(&intel_crtc->config.dpll);
6914                 if (has_reduced_clock)
6915                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
6916
6917                 dpll = ironlake_compute_dpll(intel_crtc,
6918                                              &fp, &reduced_clock,
6919                                              has_reduced_clock ? &fp2 : NULL);
6920
6921                 intel_crtc->config.dpll_hw_state.dpll = dpll;
6922                 intel_crtc->config.dpll_hw_state.fp0 = fp;
6923                 if (has_reduced_clock)
6924                         intel_crtc->config.dpll_hw_state.fp1 = fp2;
6925                 else
6926                         intel_crtc->config.dpll_hw_state.fp1 = fp;
6927
6928                 pll = intel_get_shared_dpll(intel_crtc);
6929                 if (pll == NULL) {
6930                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
6931                                          pipe_name(intel_crtc->pipe));
6932                         return -EINVAL;
6933                 }
6934         } else
6935                 intel_put_shared_dpll(intel_crtc);
6936
6937         if (is_lvds && has_reduced_clock && i915.powersave)
6938                 intel_crtc->lowfreq_avail = true;
6939         else
6940                 intel_crtc->lowfreq_avail = false;
6941
6942         return 0;
6943 }
6944
6945 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
6946                                          struct intel_link_m_n *m_n)
6947 {
6948         struct drm_device *dev = crtc->base.dev;
6949         struct drm_i915_private *dev_priv = dev->dev_private;
6950         enum pipe pipe = crtc->pipe;
6951
6952         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
6953         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
6954         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
6955                 & ~TU_SIZE_MASK;
6956         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
6957         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
6958                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
6959 }
6960
6961 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
6962                                          enum transcoder transcoder,
6963                                          struct intel_link_m_n *m_n)
6964 {
6965         struct drm_device *dev = crtc->base.dev;
6966         struct drm_i915_private *dev_priv = dev->dev_private;
6967         enum pipe pipe = crtc->pipe;
6968
6969         if (INTEL_INFO(dev)->gen >= 5) {
6970                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
6971                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
6972                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
6973                         & ~TU_SIZE_MASK;
6974                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
6975                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
6976                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
6977         } else {
6978                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
6979                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
6980                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
6981                         & ~TU_SIZE_MASK;
6982                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
6983                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
6984                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
6985         }
6986 }
6987
6988 void intel_dp_get_m_n(struct intel_crtc *crtc,
6989                       struct intel_crtc_config *pipe_config)
6990 {
6991         if (crtc->config.has_pch_encoder)
6992                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
6993         else
6994                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
6995                                              &pipe_config->dp_m_n);
6996 }
6997
6998 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
6999                                         struct intel_crtc_config *pipe_config)
7000 {
7001         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7002                                      &pipe_config->fdi_m_n);
7003 }
7004
7005 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
7006                                      struct intel_crtc_config *pipe_config)
7007 {
7008         struct drm_device *dev = crtc->base.dev;
7009         struct drm_i915_private *dev_priv = dev->dev_private;
7010         uint32_t tmp;
7011
7012         tmp = I915_READ(PF_CTL(crtc->pipe));
7013
7014         if (tmp & PF_ENABLE) {
7015                 pipe_config->pch_pfit.enabled = true;
7016                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
7017                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
7018
7019                 /* We currently do not free assignements of panel fitters on
7020                  * ivb/hsw (since we don't use the higher upscaling modes which
7021                  * differentiates them) so just WARN about this case for now. */
7022                 if (IS_GEN7(dev)) {
7023                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
7024                                 PF_PIPE_SEL_IVB(crtc->pipe));
7025                 }
7026         }
7027 }
7028
7029 static void ironlake_get_plane_config(struct intel_crtc *crtc,
7030                                       struct intel_plane_config *plane_config)
7031 {
7032         struct drm_device *dev = crtc->base.dev;
7033         struct drm_i915_private *dev_priv = dev->dev_private;
7034         u32 val, base, offset;
7035         int pipe = crtc->pipe, plane = crtc->plane;
7036         int fourcc, pixel_format;
7037         int aligned_height;
7038
7039         crtc->base.primary->fb = kzalloc(sizeof(struct intel_framebuffer), GFP_KERNEL);
7040         if (!crtc->base.primary->fb) {
7041                 DRM_DEBUG_KMS("failed to alloc fb\n");
7042                 return;
7043         }
7044
7045         val = I915_READ(DSPCNTR(plane));
7046
7047         if (INTEL_INFO(dev)->gen >= 4)
7048                 if (val & DISPPLANE_TILED)
7049                         plane_config->tiled = true;
7050
7051         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7052         fourcc = intel_format_to_fourcc(pixel_format);
7053         crtc->base.primary->fb->pixel_format = fourcc;
7054         crtc->base.primary->fb->bits_per_pixel =
7055                 drm_format_plane_cpp(fourcc, 0) * 8;
7056
7057         base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7058         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7059                 offset = I915_READ(DSPOFFSET(plane));
7060         } else {
7061                 if (plane_config->tiled)
7062                         offset = I915_READ(DSPTILEOFF(plane));
7063                 else
7064                         offset = I915_READ(DSPLINOFF(plane));
7065         }
7066         plane_config->base = base;
7067
7068         val = I915_READ(PIPESRC(pipe));
7069         crtc->base.primary->fb->width = ((val >> 16) & 0xfff) + 1;
7070         crtc->base.primary->fb->height = ((val >> 0) & 0xfff) + 1;
7071
7072         val = I915_READ(DSPSTRIDE(pipe));
7073         crtc->base.primary->fb->pitches[0] = val & 0xffffff80;
7074
7075         aligned_height = intel_align_height(dev, crtc->base.primary->fb->height,
7076                                             plane_config->tiled);
7077
7078         plane_config->size = ALIGN(crtc->base.primary->fb->pitches[0] *
7079                                    aligned_height, PAGE_SIZE);
7080
7081         DRM_DEBUG_KMS("pipe/plane %d/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7082                       pipe, plane, crtc->base.primary->fb->width,
7083                       crtc->base.primary->fb->height,
7084                       crtc->base.primary->fb->bits_per_pixel, base,
7085                       crtc->base.primary->fb->pitches[0],
7086                       plane_config->size);
7087 }
7088
7089 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
7090                                      struct intel_crtc_config *pipe_config)
7091 {
7092         struct drm_device *dev = crtc->base.dev;
7093         struct drm_i915_private *dev_priv = dev->dev_private;
7094         uint32_t tmp;
7095
7096         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7097         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7098
7099         tmp = I915_READ(PIPECONF(crtc->pipe));
7100         if (!(tmp & PIPECONF_ENABLE))
7101                 return false;
7102
7103         switch (tmp & PIPECONF_BPC_MASK) {
7104         case PIPECONF_6BPC:
7105                 pipe_config->pipe_bpp = 18;
7106                 break;
7107         case PIPECONF_8BPC:
7108                 pipe_config->pipe_bpp = 24;
7109                 break;
7110         case PIPECONF_10BPC:
7111                 pipe_config->pipe_bpp = 30;
7112                 break;
7113         case PIPECONF_12BPC:
7114                 pipe_config->pipe_bpp = 36;
7115                 break;
7116         default:
7117                 break;
7118         }
7119
7120         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
7121                 pipe_config->limited_color_range = true;
7122
7123         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
7124                 struct intel_shared_dpll *pll;
7125
7126                 pipe_config->has_pch_encoder = true;
7127
7128                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
7129                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7130                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7131
7132                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7133
7134                 if (HAS_PCH_IBX(dev_priv->dev)) {
7135                         pipe_config->shared_dpll =
7136                                 (enum intel_dpll_id) crtc->pipe;
7137                 } else {
7138                         tmp = I915_READ(PCH_DPLL_SEL);
7139                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
7140                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
7141                         else
7142                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
7143                 }
7144
7145                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
7146
7147                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
7148                                            &pipe_config->dpll_hw_state));
7149
7150                 tmp = pipe_config->dpll_hw_state.dpll;
7151                 pipe_config->pixel_multiplier =
7152                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
7153                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
7154
7155                 ironlake_pch_clock_get(crtc, pipe_config);
7156         } else {
7157                 pipe_config->pixel_multiplier = 1;
7158         }
7159
7160         intel_get_pipe_timings(crtc, pipe_config);
7161
7162         ironlake_get_pfit_config(crtc, pipe_config);
7163
7164         return true;
7165 }
7166
7167 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
7168 {
7169         struct drm_device *dev = dev_priv->dev;
7170         struct intel_ddi_plls *plls = &dev_priv->ddi_plls;
7171         struct intel_crtc *crtc;
7172
7173         for_each_intel_crtc(dev, crtc)
7174                 WARN(crtc->active, "CRTC for pipe %c enabled\n",
7175                      pipe_name(crtc->pipe));
7176
7177         WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
7178         WARN(plls->spll_refcount, "SPLL enabled\n");
7179         WARN(plls->wrpll1_refcount, "WRPLL1 enabled\n");
7180         WARN(plls->wrpll2_refcount, "WRPLL2 enabled\n");
7181         WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
7182         WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
7183              "CPU PWM1 enabled\n");
7184         WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
7185              "CPU PWM2 enabled\n");
7186         WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
7187              "PCH PWM1 enabled\n");
7188         WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
7189              "Utility pin enabled\n");
7190         WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
7191
7192         /*
7193          * In theory we can still leave IRQs enabled, as long as only the HPD
7194          * interrupts remain enabled. We used to check for that, but since it's
7195          * gen-specific and since we only disable LCPLL after we fully disable
7196          * the interrupts, the check below should be enough.
7197          */
7198         WARN(!dev_priv->pm.irqs_disabled, "IRQs enabled\n");
7199 }
7200
7201 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
7202 {
7203         struct drm_device *dev = dev_priv->dev;
7204
7205         if (IS_HASWELL(dev)) {
7206                 mutex_lock(&dev_priv->rps.hw_lock);
7207                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
7208                                             val))
7209                         DRM_ERROR("Failed to disable D_COMP\n");
7210                 mutex_unlock(&dev_priv->rps.hw_lock);
7211         } else {
7212                 I915_WRITE(D_COMP, val);
7213         }
7214         POSTING_READ(D_COMP);
7215 }
7216
7217 /*
7218  * This function implements pieces of two sequences from BSpec:
7219  * - Sequence for display software to disable LCPLL
7220  * - Sequence for display software to allow package C8+
7221  * The steps implemented here are just the steps that actually touch the LCPLL
7222  * register. Callers should take care of disabling all the display engine
7223  * functions, doing the mode unset, fixing interrupts, etc.
7224  */
7225 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
7226                               bool switch_to_fclk, bool allow_power_down)
7227 {
7228         uint32_t val;
7229
7230         assert_can_disable_lcpll(dev_priv);
7231
7232         val = I915_READ(LCPLL_CTL);
7233
7234         if (switch_to_fclk) {
7235                 val |= LCPLL_CD_SOURCE_FCLK;
7236                 I915_WRITE(LCPLL_CTL, val);
7237
7238                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
7239                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
7240                         DRM_ERROR("Switching to FCLK failed\n");
7241
7242                 val = I915_READ(LCPLL_CTL);
7243         }
7244
7245         val |= LCPLL_PLL_DISABLE;
7246         I915_WRITE(LCPLL_CTL, val);
7247         POSTING_READ(LCPLL_CTL);
7248
7249         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
7250                 DRM_ERROR("LCPLL still locked\n");
7251
7252         val = I915_READ(D_COMP);
7253         val |= D_COMP_COMP_DISABLE;
7254         hsw_write_dcomp(dev_priv, val);
7255         ndelay(100);
7256
7257         if (wait_for((I915_READ(D_COMP) & D_COMP_RCOMP_IN_PROGRESS) == 0, 1))
7258                 DRM_ERROR("D_COMP RCOMP still in progress\n");
7259
7260         if (allow_power_down) {
7261                 val = I915_READ(LCPLL_CTL);
7262                 val |= LCPLL_POWER_DOWN_ALLOW;
7263                 I915_WRITE(LCPLL_CTL, val);
7264                 POSTING_READ(LCPLL_CTL);
7265         }
7266 }
7267
7268 /*
7269  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
7270  * source.
7271  */
7272 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
7273 {
7274         uint32_t val;
7275         unsigned long irqflags;
7276
7277         val = I915_READ(LCPLL_CTL);
7278
7279         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
7280                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
7281                 return;
7282
7283         /*
7284          * Make sure we're not on PC8 state before disabling PC8, otherwise
7285          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
7286          *
7287          * The other problem is that hsw_restore_lcpll() is called as part of
7288          * the runtime PM resume sequence, so we can't just call
7289          * gen6_gt_force_wake_get() because that function calls
7290          * intel_runtime_pm_get(), and we can't change the runtime PM refcount
7291          * while we are on the resume sequence. So to solve this problem we have
7292          * to call special forcewake code that doesn't touch runtime PM and
7293          * doesn't enable the forcewake delayed work.
7294          */
7295         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
7296         if (dev_priv->uncore.forcewake_count++ == 0)
7297                 dev_priv->uncore.funcs.force_wake_get(dev_priv, FORCEWAKE_ALL);
7298         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
7299
7300         if (val & LCPLL_POWER_DOWN_ALLOW) {
7301                 val &= ~LCPLL_POWER_DOWN_ALLOW;
7302                 I915_WRITE(LCPLL_CTL, val);
7303                 POSTING_READ(LCPLL_CTL);
7304         }
7305
7306         val = I915_READ(D_COMP);
7307         val |= D_COMP_COMP_FORCE;
7308         val &= ~D_COMP_COMP_DISABLE;
7309         hsw_write_dcomp(dev_priv, val);
7310
7311         val = I915_READ(LCPLL_CTL);
7312         val &= ~LCPLL_PLL_DISABLE;
7313         I915_WRITE(LCPLL_CTL, val);
7314
7315         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
7316                 DRM_ERROR("LCPLL not locked yet\n");
7317
7318         if (val & LCPLL_CD_SOURCE_FCLK) {
7319                 val = I915_READ(LCPLL_CTL);
7320                 val &= ~LCPLL_CD_SOURCE_FCLK;
7321                 I915_WRITE(LCPLL_CTL, val);
7322
7323                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
7324                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
7325                         DRM_ERROR("Switching back to LCPLL failed\n");
7326         }
7327
7328         /* See the big comment above. */
7329         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
7330         if (--dev_priv->uncore.forcewake_count == 0)
7331                 dev_priv->uncore.funcs.force_wake_put(dev_priv, FORCEWAKE_ALL);
7332         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
7333 }
7334
7335 /*
7336  * Package states C8 and deeper are really deep PC states that can only be
7337  * reached when all the devices on the system allow it, so even if the graphics
7338  * device allows PC8+, it doesn't mean the system will actually get to these
7339  * states. Our driver only allows PC8+ when going into runtime PM.
7340  *
7341  * The requirements for PC8+ are that all the outputs are disabled, the power
7342  * well is disabled and most interrupts are disabled, and these are also
7343  * requirements for runtime PM. When these conditions are met, we manually do
7344  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
7345  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
7346  * hang the machine.
7347  *
7348  * When we really reach PC8 or deeper states (not just when we allow it) we lose
7349  * the state of some registers, so when we come back from PC8+ we need to
7350  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
7351  * need to take care of the registers kept by RC6. Notice that this happens even
7352  * if we don't put the device in PCI D3 state (which is what currently happens
7353  * because of the runtime PM support).
7354  *
7355  * For more, read "Display Sequences for Package C8" on the hardware
7356  * documentation.
7357  */
7358 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
7359 {
7360         struct drm_device *dev = dev_priv->dev;
7361         uint32_t val;
7362
7363         DRM_DEBUG_KMS("Enabling package C8+\n");
7364
7365         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
7366                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
7367                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
7368                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
7369         }
7370
7371         lpt_disable_clkout_dp(dev);
7372         hsw_disable_lcpll(dev_priv, true, true);
7373 }
7374
7375 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
7376 {
7377         struct drm_device *dev = dev_priv->dev;
7378         uint32_t val;
7379
7380         DRM_DEBUG_KMS("Disabling package C8+\n");
7381
7382         hsw_restore_lcpll(dev_priv);
7383         lpt_init_pch_refclk(dev);
7384
7385         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
7386                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
7387                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
7388                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
7389         }
7390
7391         intel_prepare_ddi(dev);
7392 }
7393
7394 static void snb_modeset_global_resources(struct drm_device *dev)
7395 {
7396         modeset_update_crtc_power_domains(dev);
7397 }
7398
7399 static void haswell_modeset_global_resources(struct drm_device *dev)
7400 {
7401         modeset_update_crtc_power_domains(dev);
7402 }
7403
7404 static int haswell_crtc_mode_set(struct drm_crtc *crtc,
7405                                  int x, int y,
7406                                  struct drm_framebuffer *fb)
7407 {
7408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7409
7410         if (!intel_ddi_pll_select(intel_crtc))
7411                 return -EINVAL;
7412         intel_ddi_pll_enable(intel_crtc);
7413
7414         intel_crtc->lowfreq_avail = false;
7415
7416         return 0;
7417 }
7418
7419 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
7420                                     struct intel_crtc_config *pipe_config)
7421 {
7422         struct drm_device *dev = crtc->base.dev;
7423         struct drm_i915_private *dev_priv = dev->dev_private;
7424         enum intel_display_power_domain pfit_domain;
7425         uint32_t tmp;
7426
7427         if (!intel_display_power_enabled(dev_priv,
7428                                          POWER_DOMAIN_PIPE(crtc->pipe)))
7429                 return false;
7430
7431         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7432         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7433
7434         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
7435         if (tmp & TRANS_DDI_FUNC_ENABLE) {
7436                 enum pipe trans_edp_pipe;
7437                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
7438                 default:
7439                         WARN(1, "unknown pipe linked to edp transcoder\n");
7440                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
7441                 case TRANS_DDI_EDP_INPUT_A_ON:
7442                         trans_edp_pipe = PIPE_A;
7443                         break;
7444                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
7445                         trans_edp_pipe = PIPE_B;
7446                         break;
7447                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
7448                         trans_edp_pipe = PIPE_C;
7449                         break;
7450                 }
7451
7452                 if (trans_edp_pipe == crtc->pipe)
7453                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
7454         }
7455
7456         if (!intel_display_power_enabled(dev_priv,
7457                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
7458                 return false;
7459
7460         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
7461         if (!(tmp & PIPECONF_ENABLE))
7462                 return false;
7463
7464         /*
7465          * Haswell has only FDI/PCH transcoder A. It is which is connected to
7466          * DDI E. So just check whether this pipe is wired to DDI E and whether
7467          * the PCH transcoder is on.
7468          */
7469         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
7470         if ((tmp & TRANS_DDI_PORT_MASK) == TRANS_DDI_SELECT_PORT(PORT_E) &&
7471             I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
7472                 pipe_config->has_pch_encoder = true;
7473
7474                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
7475                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7476                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7477
7478                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7479         }
7480
7481         intel_get_pipe_timings(crtc, pipe_config);
7482
7483         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
7484         if (intel_display_power_enabled(dev_priv, pfit_domain))
7485                 ironlake_get_pfit_config(crtc, pipe_config);
7486
7487         if (IS_HASWELL(dev))
7488                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
7489                         (I915_READ(IPS_CTL) & IPS_ENABLE);
7490
7491         pipe_config->pixel_multiplier = 1;
7492
7493         return true;
7494 }
7495
7496 static struct {
7497         int clock;
7498         u32 config;
7499 } hdmi_audio_clock[] = {
7500         { DIV_ROUND_UP(25200 * 1000, 1001), AUD_CONFIG_PIXEL_CLOCK_HDMI_25175 },
7501         { 25200, AUD_CONFIG_PIXEL_CLOCK_HDMI_25200 }, /* default per bspec */
7502         { 27000, AUD_CONFIG_PIXEL_CLOCK_HDMI_27000 },
7503         { 27000 * 1001 / 1000, AUD_CONFIG_PIXEL_CLOCK_HDMI_27027 },
7504         { 54000, AUD_CONFIG_PIXEL_CLOCK_HDMI_54000 },
7505         { 54000 * 1001 / 1000, AUD_CONFIG_PIXEL_CLOCK_HDMI_54054 },
7506         { DIV_ROUND_UP(74250 * 1000, 1001), AUD_CONFIG_PIXEL_CLOCK_HDMI_74176 },
7507         { 74250, AUD_CONFIG_PIXEL_CLOCK_HDMI_74250 },
7508         { DIV_ROUND_UP(148500 * 1000, 1001), AUD_CONFIG_PIXEL_CLOCK_HDMI_148352 },
7509         { 148500, AUD_CONFIG_PIXEL_CLOCK_HDMI_148500 },
7510 };
7511
7512 /* get AUD_CONFIG_PIXEL_CLOCK_HDMI_* value for mode */
7513 static u32 audio_config_hdmi_pixel_clock(struct drm_display_mode *mode)
7514 {
7515         int i;
7516
7517         for (i = 0; i < ARRAY_SIZE(hdmi_audio_clock); i++) {
7518                 if (mode->clock == hdmi_audio_clock[i].clock)
7519                         break;
7520         }
7521
7522         if (i == ARRAY_SIZE(hdmi_audio_clock)) {
7523                 DRM_DEBUG_KMS("HDMI audio pixel clock setting for %d not found, falling back to defaults\n", mode->clock);
7524                 i = 1;
7525         }
7526
7527         DRM_DEBUG_KMS("Configuring HDMI audio for pixel clock %d (0x%08x)\n",
7528                       hdmi_audio_clock[i].clock,
7529                       hdmi_audio_clock[i].config);
7530
7531         return hdmi_audio_clock[i].config;
7532 }
7533
7534 static bool intel_eld_uptodate(struct drm_connector *connector,
7535                                int reg_eldv, uint32_t bits_eldv,
7536                                int reg_elda, uint32_t bits_elda,
7537                                int reg_edid)
7538 {
7539         struct drm_i915_private *dev_priv = connector->dev->dev_private;
7540         uint8_t *eld = connector->eld;
7541         uint32_t i;
7542
7543         i = I915_READ(reg_eldv);
7544         i &= bits_eldv;
7545
7546         if (!eld[0])
7547                 return !i;
7548
7549         if (!i)
7550                 return false;
7551
7552         i = I915_READ(reg_elda);
7553         i &= ~bits_elda;
7554         I915_WRITE(reg_elda, i);
7555
7556         for (i = 0; i < eld[2]; i++)
7557                 if (I915_READ(reg_edid) != *((uint32_t *)eld + i))
7558                         return false;
7559
7560         return true;
7561 }
7562
7563 static void g4x_write_eld(struct drm_connector *connector,
7564                           struct drm_crtc *crtc,
7565                           struct drm_display_mode *mode)
7566 {
7567         struct drm_i915_private *dev_priv = connector->dev->dev_private;
7568         uint8_t *eld = connector->eld;
7569         uint32_t eldv;
7570         uint32_t len;
7571         uint32_t i;
7572
7573         i = I915_READ(G4X_AUD_VID_DID);
7574
7575         if (i == INTEL_AUDIO_DEVBLC || i == INTEL_AUDIO_DEVCL)
7576                 eldv = G4X_ELDV_DEVCL_DEVBLC;
7577         else
7578                 eldv = G4X_ELDV_DEVCTG;
7579
7580         if (intel_eld_uptodate(connector,
7581                                G4X_AUD_CNTL_ST, eldv,
7582                                G4X_AUD_CNTL_ST, G4X_ELD_ADDR,
7583                                G4X_HDMIW_HDMIEDID))
7584                 return;
7585
7586         i = I915_READ(G4X_AUD_CNTL_ST);
7587         i &= ~(eldv | G4X_ELD_ADDR);
7588         len = (i >> 9) & 0x1f;          /* ELD buffer size */
7589         I915_WRITE(G4X_AUD_CNTL_ST, i);
7590
7591         if (!eld[0])
7592                 return;
7593
7594         len = min_t(uint8_t, eld[2], len);
7595         DRM_DEBUG_DRIVER("ELD size %d\n", len);
7596         for (i = 0; i < len; i++)
7597                 I915_WRITE(G4X_HDMIW_HDMIEDID, *((uint32_t *)eld + i));
7598
7599         i = I915_READ(G4X_AUD_CNTL_ST);
7600         i |= eldv;
7601         I915_WRITE(G4X_AUD_CNTL_ST, i);
7602 }
7603
7604 static void haswell_write_eld(struct drm_connector *connector,
7605                               struct drm_crtc *crtc,
7606                               struct drm_display_mode *mode)
7607 {
7608         struct drm_i915_private *dev_priv = connector->dev->dev_private;
7609         uint8_t *eld = connector->eld;
7610         uint32_t eldv;
7611         uint32_t i;
7612         int len;
7613         int pipe = to_intel_crtc(crtc)->pipe;
7614         int tmp;
7615
7616         int hdmiw_hdmiedid = HSW_AUD_EDID_DATA(pipe);
7617         int aud_cntl_st = HSW_AUD_DIP_ELD_CTRL(pipe);
7618         int aud_config = HSW_AUD_CFG(pipe);
7619         int aud_cntrl_st2 = HSW_AUD_PIN_ELD_CP_VLD;
7620
7621         /* Audio output enable */
7622         DRM_DEBUG_DRIVER("HDMI audio: enable codec\n");
7623         tmp = I915_READ(aud_cntrl_st2);
7624         tmp |= (AUDIO_OUTPUT_ENABLE_A << (pipe * 4));
7625         I915_WRITE(aud_cntrl_st2, tmp);
7626         POSTING_READ(aud_cntrl_st2);
7627
7628         assert_pipe_disabled(dev_priv, to_intel_crtc(crtc)->pipe);
7629
7630         /* Set ELD valid state */
7631         tmp = I915_READ(aud_cntrl_st2);
7632         DRM_DEBUG_DRIVER("HDMI audio: pin eld vld status=0x%08x\n", tmp);
7633         tmp |= (AUDIO_ELD_VALID_A << (pipe * 4));
7634         I915_WRITE(aud_cntrl_st2, tmp);
7635         tmp = I915_READ(aud_cntrl_st2);
7636         DRM_DEBUG_DRIVER("HDMI audio: eld vld status=0x%08x\n", tmp);
7637
7638         /* Enable HDMI mode */
7639         tmp = I915_READ(aud_config);
7640         DRM_DEBUG_DRIVER("HDMI audio: audio conf: 0x%08x\n", tmp);
7641         /* clear N_programing_enable and N_value_index */
7642         tmp &= ~(AUD_CONFIG_N_VALUE_INDEX | AUD_CONFIG_N_PROG_ENABLE);
7643         I915_WRITE(aud_config, tmp);
7644
7645         DRM_DEBUG_DRIVER("ELD on pipe %c\n", pipe_name(pipe));
7646
7647         eldv = AUDIO_ELD_VALID_A << (pipe * 4);
7648
7649         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT)) {
7650                 DRM_DEBUG_DRIVER("ELD: DisplayPort detected\n");
7651                 eld[5] |= (1 << 2);     /* Conn_Type, 0x1 = DisplayPort */
7652                 I915_WRITE(aud_config, AUD_CONFIG_N_VALUE_INDEX); /* 0x1 = DP */
7653         } else {
7654                 I915_WRITE(aud_config, audio_config_hdmi_pixel_clock(mode));
7655         }
7656
7657         if (intel_eld_uptodate(connector,
7658                                aud_cntrl_st2, eldv,
7659                                aud_cntl_st, IBX_ELD_ADDRESS,
7660                                hdmiw_hdmiedid))
7661                 return;
7662
7663         i = I915_READ(aud_cntrl_st2);
7664         i &= ~eldv;
7665         I915_WRITE(aud_cntrl_st2, i);
7666
7667         if (!eld[0])
7668                 return;
7669
7670         i = I915_READ(aud_cntl_st);
7671         i &= ~IBX_ELD_ADDRESS;
7672         I915_WRITE(aud_cntl_st, i);
7673         i = (i >> 29) & DIP_PORT_SEL_MASK;              /* DIP_Port_Select, 0x1 = PortB */
7674         DRM_DEBUG_DRIVER("port num:%d\n", i);
7675
7676         len = min_t(uint8_t, eld[2], 21);       /* 84 bytes of hw ELD buffer */
7677         DRM_DEBUG_DRIVER("ELD size %d\n", len);
7678         for (i = 0; i < len; i++)
7679                 I915_WRITE(hdmiw_hdmiedid, *((uint32_t *)eld + i));
7680
7681         i = I915_READ(aud_cntrl_st2);
7682         i |= eldv;
7683         I915_WRITE(aud_cntrl_st2, i);
7684
7685 }
7686
7687 static void ironlake_write_eld(struct drm_connector *connector,
7688                                struct drm_crtc *crtc,
7689                                struct drm_display_mode *mode)
7690 {
7691         struct drm_i915_private *dev_priv = connector->dev->dev_private;
7692         uint8_t *eld = connector->eld;
7693         uint32_t eldv;
7694         uint32_t i;
7695         int len;
7696         int hdmiw_hdmiedid;
7697         int aud_config;
7698         int aud_cntl_st;
7699         int aud_cntrl_st2;
7700         int pipe = to_intel_crtc(crtc)->pipe;
7701
7702         if (HAS_PCH_IBX(connector->dev)) {
7703                 hdmiw_hdmiedid = IBX_HDMIW_HDMIEDID(pipe);
7704                 aud_config = IBX_AUD_CFG(pipe);
7705                 aud_cntl_st = IBX_AUD_CNTL_ST(pipe);
7706                 aud_cntrl_st2 = IBX_AUD_CNTL_ST2;
7707         } else if (IS_VALLEYVIEW(connector->dev)) {
7708                 hdmiw_hdmiedid = VLV_HDMIW_HDMIEDID(pipe);
7709                 aud_config = VLV_AUD_CFG(pipe);
7710                 aud_cntl_st = VLV_AUD_CNTL_ST(pipe);
7711                 aud_cntrl_st2 = VLV_AUD_CNTL_ST2;
7712         } else {
7713                 hdmiw_hdmiedid = CPT_HDMIW_HDMIEDID(pipe);
7714                 aud_config = CPT_AUD_CFG(pipe);
7715                 aud_cntl_st = CPT_AUD_CNTL_ST(pipe);
7716                 aud_cntrl_st2 = CPT_AUD_CNTRL_ST2;
7717         }
7718
7719         DRM_DEBUG_DRIVER("ELD on pipe %c\n", pipe_name(pipe));
7720
7721         if (IS_VALLEYVIEW(connector->dev))  {
7722                 struct intel_encoder *intel_encoder;
7723                 struct intel_digital_port *intel_dig_port;
7724
7725                 intel_encoder = intel_attached_encoder(connector);
7726                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
7727                 i = intel_dig_port->port;
7728         } else {
7729                 i = I915_READ(aud_cntl_st);
7730                 i = (i >> 29) & DIP_PORT_SEL_MASK;
7731                 /* DIP_Port_Select, 0x1 = PortB */
7732         }
7733
7734         if (!i) {
7735                 DRM_DEBUG_DRIVER("Audio directed to unknown port\n");
7736                 /* operate blindly on all ports */
7737                 eldv = IBX_ELD_VALIDB;
7738                 eldv |= IBX_ELD_VALIDB << 4;
7739                 eldv |= IBX_ELD_VALIDB << 8;
7740         } else {
7741                 DRM_DEBUG_DRIVER("ELD on port %c\n", port_name(i));
7742                 eldv = IBX_ELD_VALIDB << ((i - 1) * 4);
7743         }
7744
7745         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT)) {
7746                 DRM_DEBUG_DRIVER("ELD: DisplayPort detected\n");
7747                 eld[5] |= (1 << 2);     /* Conn_Type, 0x1 = DisplayPort */
7748                 I915_WRITE(aud_config, AUD_CONFIG_N_VALUE_INDEX); /* 0x1 = DP */
7749         } else {
7750                 I915_WRITE(aud_config, audio_config_hdmi_pixel_clock(mode));
7751         }
7752
7753         if (intel_eld_uptodate(connector,
7754                                aud_cntrl_st2, eldv,
7755                                aud_cntl_st, IBX_ELD_ADDRESS,
7756                                hdmiw_hdmiedid))
7757                 return;
7758
7759         i = I915_READ(aud_cntrl_st2);
7760         i &= ~eldv;
7761         I915_WRITE(aud_cntrl_st2, i);
7762
7763         if (!eld[0])
7764                 return;
7765
7766         i = I915_READ(aud_cntl_st);
7767         i &= ~IBX_ELD_ADDRESS;
7768         I915_WRITE(aud_cntl_st, i);
7769
7770         len = min_t(uint8_t, eld[2], 21);       /* 84 bytes of hw ELD buffer */
7771         DRM_DEBUG_DRIVER("ELD size %d\n", len);
7772         for (i = 0; i < len; i++)
7773                 I915_WRITE(hdmiw_hdmiedid, *((uint32_t *)eld + i));
7774
7775         i = I915_READ(aud_cntrl_st2);
7776         i |= eldv;
7777         I915_WRITE(aud_cntrl_st2, i);
7778 }
7779
7780 void intel_write_eld(struct drm_encoder *encoder,
7781                      struct drm_display_mode *mode)
7782 {
7783         struct drm_crtc *crtc = encoder->crtc;
7784         struct drm_connector *connector;
7785         struct drm_device *dev = encoder->dev;
7786         struct drm_i915_private *dev_priv = dev->dev_private;
7787
7788         connector = drm_select_eld(encoder, mode);
7789         if (!connector)
7790                 return;
7791
7792         DRM_DEBUG_DRIVER("ELD on [CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
7793                          connector->base.id,
7794                          drm_get_connector_name(connector),
7795                          connector->encoder->base.id,
7796                          drm_get_encoder_name(connector->encoder));
7797
7798         connector->eld[6] = drm_av_sync_delay(connector, mode) / 2;
7799
7800         if (dev_priv->display.write_eld)
7801                 dev_priv->display.write_eld(connector, crtc, mode);
7802 }
7803
7804 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
7805 {
7806         struct drm_device *dev = crtc->dev;
7807         struct drm_i915_private *dev_priv = dev->dev_private;
7808         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7809         bool visible = base != 0;
7810         u32 cntl;
7811
7812         if (intel_crtc->cursor_visible == visible)
7813                 return;
7814
7815         cntl = I915_READ(_CURACNTR);
7816         if (visible) {
7817                 /* On these chipsets we can only modify the base whilst
7818                  * the cursor is disabled.
7819                  */
7820                 I915_WRITE(_CURABASE, base);
7821
7822                 cntl &= ~(CURSOR_FORMAT_MASK);
7823                 /* XXX width must be 64, stride 256 => 0x00 << 28 */
7824                 cntl |= CURSOR_ENABLE |
7825                         CURSOR_GAMMA_ENABLE |
7826                         CURSOR_FORMAT_ARGB;
7827         } else
7828                 cntl &= ~(CURSOR_ENABLE | CURSOR_GAMMA_ENABLE);
7829         I915_WRITE(_CURACNTR, cntl);
7830
7831         intel_crtc->cursor_visible = visible;
7832 }
7833
7834 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
7835 {
7836         struct drm_device *dev = crtc->dev;
7837         struct drm_i915_private *dev_priv = dev->dev_private;
7838         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7839         int pipe = intel_crtc->pipe;
7840         bool visible = base != 0;
7841
7842         if (intel_crtc->cursor_visible != visible) {
7843                 int16_t width = intel_crtc->cursor_width;
7844                 uint32_t cntl = I915_READ(CURCNTR(pipe));
7845                 if (base) {
7846                         cntl &= ~(CURSOR_MODE | MCURSOR_PIPE_SELECT);
7847                         cntl |= MCURSOR_GAMMA_ENABLE;
7848
7849                         switch (width) {
7850                         case 64:
7851                                 cntl |= CURSOR_MODE_64_ARGB_AX;
7852                                 break;
7853                         case 128:
7854                                 cntl |= CURSOR_MODE_128_ARGB_AX;
7855                                 break;
7856                         case 256:
7857                                 cntl |= CURSOR_MODE_256_ARGB_AX;
7858                                 break;
7859                         default:
7860                                 WARN_ON(1);
7861                                 return;
7862                         }
7863                         cntl |= pipe << 28; /* Connect to correct pipe */
7864                 } else {
7865                         cntl &= ~(CURSOR_MODE | MCURSOR_GAMMA_ENABLE);
7866                         cntl |= CURSOR_MODE_DISABLE;
7867                 }
7868                 I915_WRITE(CURCNTR(pipe), cntl);
7869
7870                 intel_crtc->cursor_visible = visible;
7871         }
7872         /* and commit changes on next vblank */
7873         POSTING_READ(CURCNTR(pipe));
7874         I915_WRITE(CURBASE(pipe), base);
7875         POSTING_READ(CURBASE(pipe));
7876 }
7877
7878 static void ivb_update_cursor(struct drm_crtc *crtc, u32 base)
7879 {
7880         struct drm_device *dev = crtc->dev;
7881         struct drm_i915_private *dev_priv = dev->dev_private;
7882         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7883         int pipe = intel_crtc->pipe;
7884         bool visible = base != 0;
7885
7886         if (intel_crtc->cursor_visible != visible) {
7887                 int16_t width = intel_crtc->cursor_width;
7888                 uint32_t cntl = I915_READ(CURCNTR_IVB(pipe));
7889                 if (base) {
7890                         cntl &= ~CURSOR_MODE;
7891                         cntl |= MCURSOR_GAMMA_ENABLE;
7892                         switch (width) {
7893                         case 64:
7894                                 cntl |= CURSOR_MODE_64_ARGB_AX;
7895                                 break;
7896                         case 128:
7897                                 cntl |= CURSOR_MODE_128_ARGB_AX;
7898                                 break;
7899                         case 256:
7900                                 cntl |= CURSOR_MODE_256_ARGB_AX;
7901                                 break;
7902                         default:
7903                                 WARN_ON(1);
7904                                 return;
7905                         }
7906                 } else {
7907                         cntl &= ~(CURSOR_MODE | MCURSOR_GAMMA_ENABLE);
7908                         cntl |= CURSOR_MODE_DISABLE;
7909                 }
7910                 if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7911                         cntl |= CURSOR_PIPE_CSC_ENABLE;
7912                         cntl &= ~CURSOR_TRICKLE_FEED_DISABLE;
7913                 }
7914                 I915_WRITE(CURCNTR_IVB(pipe), cntl);
7915
7916                 intel_crtc->cursor_visible = visible;
7917         }
7918         /* and commit changes on next vblank */
7919         POSTING_READ(CURCNTR_IVB(pipe));
7920         I915_WRITE(CURBASE_IVB(pipe), base);
7921         POSTING_READ(CURBASE_IVB(pipe));
7922 }
7923
7924 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
7925 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
7926                                      bool on)
7927 {
7928         struct drm_device *dev = crtc->dev;
7929         struct drm_i915_private *dev_priv = dev->dev_private;
7930         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7931         int pipe = intel_crtc->pipe;
7932         int x = intel_crtc->cursor_x;
7933         int y = intel_crtc->cursor_y;
7934         u32 base = 0, pos = 0;
7935         bool visible;
7936
7937         if (on)
7938                 base = intel_crtc->cursor_addr;
7939
7940         if (x >= intel_crtc->config.pipe_src_w)
7941                 base = 0;
7942
7943         if (y >= intel_crtc->config.pipe_src_h)
7944                 base = 0;
7945
7946         if (x < 0) {
7947                 if (x + intel_crtc->cursor_width <= 0)
7948                         base = 0;
7949
7950                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
7951                 x = -x;
7952         }
7953         pos |= x << CURSOR_X_SHIFT;
7954
7955         if (y < 0) {
7956                 if (y + intel_crtc->cursor_height <= 0)
7957                         base = 0;
7958
7959                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
7960                 y = -y;
7961         }
7962         pos |= y << CURSOR_Y_SHIFT;
7963
7964         visible = base != 0;
7965         if (!visible && !intel_crtc->cursor_visible)
7966                 return;
7967
7968         if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7969                 I915_WRITE(CURPOS_IVB(pipe), pos);
7970                 ivb_update_cursor(crtc, base);
7971         } else {
7972                 I915_WRITE(CURPOS(pipe), pos);
7973                 if (IS_845G(dev) || IS_I865G(dev))
7974                         i845_update_cursor(crtc, base);
7975                 else
7976                         i9xx_update_cursor(crtc, base);
7977         }
7978 }
7979
7980 static int intel_crtc_cursor_set(struct drm_crtc *crtc,
7981                                  struct drm_file *file,
7982                                  uint32_t handle,
7983                                  uint32_t width, uint32_t height)
7984 {
7985         struct drm_device *dev = crtc->dev;
7986         struct drm_i915_private *dev_priv = dev->dev_private;
7987         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7988         struct drm_i915_gem_object *obj;
7989         unsigned old_width;
7990         uint32_t addr;
7991         int ret;
7992
7993         /* if we want to turn off the cursor ignore width and height */
7994         if (!handle) {
7995                 DRM_DEBUG_KMS("cursor off\n");
7996                 addr = 0;
7997                 obj = NULL;
7998                 mutex_lock(&dev->struct_mutex);
7999                 goto finish;
8000         }
8001
8002         /* Check for which cursor types we support */
8003         if (!((width == 64 && height == 64) ||
8004                         (width == 128 && height == 128 && !IS_GEN2(dev)) ||
8005                         (width == 256 && height == 256 && !IS_GEN2(dev)))) {
8006                 DRM_DEBUG("Cursor dimension not supported\n");
8007                 return -EINVAL;
8008         }
8009
8010         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
8011         if (&obj->base == NULL)
8012                 return -ENOENT;
8013
8014         if (obj->base.size < width * height * 4) {
8015                 DRM_DEBUG_KMS("buffer is to small\n");
8016                 ret = -ENOMEM;
8017                 goto fail;
8018         }
8019
8020         /* we only need to pin inside GTT if cursor is non-phy */
8021         mutex_lock(&dev->struct_mutex);
8022         if (!INTEL_INFO(dev)->cursor_needs_physical) {
8023                 unsigned alignment;
8024
8025                 if (obj->tiling_mode) {
8026                         DRM_DEBUG_KMS("cursor cannot be tiled\n");
8027                         ret = -EINVAL;
8028                         goto fail_locked;
8029                 }
8030
8031                 /* Note that the w/a also requires 2 PTE of padding following
8032                  * the bo. We currently fill all unused PTE with the shadow
8033                  * page and so we should always have valid PTE following the
8034                  * cursor preventing the VT-d warning.
8035                  */
8036                 alignment = 0;
8037                 if (need_vtd_wa(dev))
8038                         alignment = 64*1024;
8039
8040                 ret = i915_gem_object_pin_to_display_plane(obj, alignment, NULL);
8041                 if (ret) {
8042                         DRM_DEBUG_KMS("failed to move cursor bo into the GTT\n");
8043                         goto fail_locked;
8044                 }
8045
8046                 ret = i915_gem_object_put_fence(obj);
8047                 if (ret) {
8048                         DRM_DEBUG_KMS("failed to release fence for cursor");
8049                         goto fail_unpin;
8050                 }
8051
8052                 addr = i915_gem_obj_ggtt_offset(obj);
8053         } else {
8054                 int align = IS_I830(dev) ? 16 * 1024 : 256;
8055                 ret = i915_gem_attach_phys_object(dev, obj,
8056                                                   (intel_crtc->pipe == 0) ? I915_GEM_PHYS_CURSOR_0 : I915_GEM_PHYS_CURSOR_1,
8057                                                   align);
8058                 if (ret) {
8059                         DRM_DEBUG_KMS("failed to attach phys object\n");
8060                         goto fail_locked;
8061                 }
8062                 addr = obj->phys_obj->handle->busaddr;
8063         }
8064
8065         if (IS_GEN2(dev))
8066                 I915_WRITE(CURSIZE, (height << 12) | width);
8067
8068  finish:
8069         if (intel_crtc->cursor_bo) {
8070                 if (INTEL_INFO(dev)->cursor_needs_physical) {
8071                         if (intel_crtc->cursor_bo != obj)
8072                                 i915_gem_detach_phys_object(dev, intel_crtc->cursor_bo);
8073                 } else
8074                         i915_gem_object_unpin_from_display_plane(intel_crtc->cursor_bo);
8075                 drm_gem_object_unreference(&intel_crtc->cursor_bo->base);
8076         }
8077
8078         mutex_unlock(&dev->struct_mutex);
8079
8080         old_width = intel_crtc->cursor_width;
8081
8082         intel_crtc->cursor_addr = addr;
8083         intel_crtc->cursor_bo = obj;
8084         intel_crtc->cursor_width = width;
8085         intel_crtc->cursor_height = height;
8086
8087         if (intel_crtc->active) {
8088                 if (old_width != width)
8089                         intel_update_watermarks(crtc);
8090                 intel_crtc_update_cursor(crtc, intel_crtc->cursor_bo != NULL);
8091         }
8092
8093         return 0;
8094 fail_unpin:
8095         i915_gem_object_unpin_from_display_plane(obj);
8096 fail_locked:
8097         mutex_unlock(&dev->struct_mutex);
8098 fail:
8099         drm_gem_object_unreference_unlocked(&obj->base);
8100         return ret;
8101 }
8102
8103 static int intel_crtc_cursor_move(struct drm_crtc *crtc, int x, int y)
8104 {
8105         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8106
8107         intel_crtc->cursor_x = clamp_t(int, x, SHRT_MIN, SHRT_MAX);
8108         intel_crtc->cursor_y = clamp_t(int, y, SHRT_MIN, SHRT_MAX);
8109
8110         if (intel_crtc->active)
8111                 intel_crtc_update_cursor(crtc, intel_crtc->cursor_bo != NULL);
8112
8113         return 0;
8114 }
8115
8116 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
8117                                  u16 *blue, uint32_t start, uint32_t size)
8118 {
8119         int end = (start + size > 256) ? 256 : start + size, i;
8120         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8121
8122         for (i = start; i < end; i++) {
8123                 intel_crtc->lut_r[i] = red[i] >> 8;
8124                 intel_crtc->lut_g[i] = green[i] >> 8;
8125                 intel_crtc->lut_b[i] = blue[i] >> 8;
8126         }
8127
8128         intel_crtc_load_lut(crtc);
8129 }
8130
8131 /* VESA 640x480x72Hz mode to set on the pipe */
8132 static struct drm_display_mode load_detect_mode = {
8133         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
8134                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
8135 };
8136
8137 struct drm_framebuffer *
8138 __intel_framebuffer_create(struct drm_device *dev,
8139                            struct drm_mode_fb_cmd2 *mode_cmd,
8140                            struct drm_i915_gem_object *obj)
8141 {
8142         struct intel_framebuffer *intel_fb;
8143         int ret;
8144
8145         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8146         if (!intel_fb) {
8147                 drm_gem_object_unreference_unlocked(&obj->base);
8148                 return ERR_PTR(-ENOMEM);
8149         }
8150
8151         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
8152         if (ret)
8153                 goto err;
8154
8155         return &intel_fb->base;
8156 err:
8157         drm_gem_object_unreference_unlocked(&obj->base);
8158         kfree(intel_fb);
8159
8160         return ERR_PTR(ret);
8161 }
8162
8163 static struct drm_framebuffer *
8164 intel_framebuffer_create(struct drm_device *dev,
8165                          struct drm_mode_fb_cmd2 *mode_cmd,
8166                          struct drm_i915_gem_object *obj)
8167 {
8168         struct drm_framebuffer *fb;
8169         int ret;
8170
8171         ret = i915_mutex_lock_interruptible(dev);
8172         if (ret)
8173                 return ERR_PTR(ret);
8174         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
8175         mutex_unlock(&dev->struct_mutex);
8176
8177         return fb;
8178 }
8179
8180 static u32
8181 intel_framebuffer_pitch_for_width(int width, int bpp)
8182 {
8183         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
8184         return ALIGN(pitch, 64);
8185 }
8186
8187 static u32
8188 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
8189 {
8190         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
8191         return ALIGN(pitch * mode->vdisplay, PAGE_SIZE);
8192 }
8193
8194 static struct drm_framebuffer *
8195 intel_framebuffer_create_for_mode(struct drm_device *dev,
8196                                   struct drm_display_mode *mode,
8197                                   int depth, int bpp)
8198 {
8199         struct drm_i915_gem_object *obj;
8200         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
8201
8202         obj = i915_gem_alloc_object(dev,
8203                                     intel_framebuffer_size_for_mode(mode, bpp));
8204         if (obj == NULL)
8205                 return ERR_PTR(-ENOMEM);
8206
8207         mode_cmd.width = mode->hdisplay;
8208         mode_cmd.height = mode->vdisplay;
8209         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
8210                                                                 bpp);
8211         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
8212
8213         return intel_framebuffer_create(dev, &mode_cmd, obj);
8214 }
8215
8216 static struct drm_framebuffer *
8217 mode_fits_in_fbdev(struct drm_device *dev,
8218                    struct drm_display_mode *mode)
8219 {
8220 #ifdef CONFIG_DRM_I915_FBDEV
8221         struct drm_i915_private *dev_priv = dev->dev_private;
8222         struct drm_i915_gem_object *obj;
8223         struct drm_framebuffer *fb;
8224
8225         if (!dev_priv->fbdev)
8226                 return NULL;
8227
8228         if (!dev_priv->fbdev->fb)
8229                 return NULL;
8230
8231         obj = dev_priv->fbdev->fb->obj;
8232         BUG_ON(!obj);
8233
8234         fb = &dev_priv->fbdev->fb->base;
8235         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
8236                                                                fb->bits_per_pixel))
8237                 return NULL;
8238
8239         if (obj->base.size < mode->vdisplay * fb->pitches[0])
8240                 return NULL;
8241
8242         return fb;
8243 #else
8244         return NULL;
8245 #endif
8246 }
8247
8248 bool intel_get_load_detect_pipe(struct drm_connector *connector,
8249                                 struct drm_display_mode *mode,
8250                                 struct intel_load_detect_pipe *old)
8251 {
8252         struct intel_crtc *intel_crtc;
8253         struct intel_encoder *intel_encoder =
8254                 intel_attached_encoder(connector);
8255         struct drm_crtc *possible_crtc;
8256         struct drm_encoder *encoder = &intel_encoder->base;
8257         struct drm_crtc *crtc = NULL;
8258         struct drm_device *dev = encoder->dev;
8259         struct drm_framebuffer *fb;
8260         int i = -1;
8261
8262         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8263                       connector->base.id, drm_get_connector_name(connector),
8264                       encoder->base.id, drm_get_encoder_name(encoder));
8265
8266         /*
8267          * Algorithm gets a little messy:
8268          *
8269          *   - if the connector already has an assigned crtc, use it (but make
8270          *     sure it's on first)
8271          *
8272          *   - try to find the first unused crtc that can drive this connector,
8273          *     and use that if we find one
8274          */
8275
8276         /* See if we already have a CRTC for this connector */
8277         if (encoder->crtc) {
8278                 crtc = encoder->crtc;
8279
8280                 mutex_lock(&crtc->mutex);
8281
8282                 old->dpms_mode = connector->dpms;
8283                 old->load_detect_temp = false;
8284
8285                 /* Make sure the crtc and connector are running */
8286                 if (connector->dpms != DRM_MODE_DPMS_ON)
8287                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
8288
8289                 return true;
8290         }
8291
8292         /* Find an unused one (if possible) */
8293         for_each_crtc(dev, possible_crtc) {
8294                 i++;
8295                 if (!(encoder->possible_crtcs & (1 << i)))
8296                         continue;
8297                 if (!possible_crtc->enabled) {
8298                         crtc = possible_crtc;
8299                         break;
8300                 }
8301         }
8302
8303         /*
8304          * If we didn't find an unused CRTC, don't use any.
8305          */
8306         if (!crtc) {
8307                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
8308                 return false;
8309         }
8310
8311         mutex_lock(&crtc->mutex);
8312         intel_encoder->new_crtc = to_intel_crtc(crtc);
8313         to_intel_connector(connector)->new_encoder = intel_encoder;
8314
8315         intel_crtc = to_intel_crtc(crtc);
8316         intel_crtc->new_enabled = true;
8317         intel_crtc->new_config = &intel_crtc->config;
8318         old->dpms_mode = connector->dpms;
8319         old->load_detect_temp = true;
8320         old->release_fb = NULL;
8321
8322         if (!mode)
8323                 mode = &load_detect_mode;
8324
8325         /* We need a framebuffer large enough to accommodate all accesses
8326          * that the plane may generate whilst we perform load detection.
8327          * We can not rely on the fbcon either being present (we get called
8328          * during its initialisation to detect all boot displays, or it may
8329          * not even exist) or that it is large enough to satisfy the
8330          * requested mode.
8331          */
8332         fb = mode_fits_in_fbdev(dev, mode);
8333         if (fb == NULL) {
8334                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
8335                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
8336                 old->release_fb = fb;
8337         } else
8338                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
8339         if (IS_ERR(fb)) {
8340                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
8341                 goto fail;
8342         }
8343
8344         if (intel_set_mode(crtc, mode, 0, 0, fb)) {
8345                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
8346                 if (old->release_fb)
8347                         old->release_fb->funcs->destroy(old->release_fb);
8348                 goto fail;
8349         }
8350
8351         /* let the connector get through one full cycle before testing */
8352         intel_wait_for_vblank(dev, intel_crtc->pipe);
8353         return true;
8354
8355  fail:
8356         intel_crtc->new_enabled = crtc->enabled;
8357         if (intel_crtc->new_enabled)
8358                 intel_crtc->new_config = &intel_crtc->config;
8359         else
8360                 intel_crtc->new_config = NULL;
8361         mutex_unlock(&crtc->mutex);
8362         return false;
8363 }
8364
8365 void intel_release_load_detect_pipe(struct drm_connector *connector,
8366                                     struct intel_load_detect_pipe *old)
8367 {
8368         struct intel_encoder *intel_encoder =
8369                 intel_attached_encoder(connector);
8370         struct drm_encoder *encoder = &intel_encoder->base;
8371         struct drm_crtc *crtc = encoder->crtc;
8372         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8373
8374         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8375                       connector->base.id, drm_get_connector_name(connector),
8376                       encoder->base.id, drm_get_encoder_name(encoder));
8377
8378         if (old->load_detect_temp) {
8379                 to_intel_connector(connector)->new_encoder = NULL;
8380                 intel_encoder->new_crtc = NULL;
8381                 intel_crtc->new_enabled = false;
8382                 intel_crtc->new_config = NULL;
8383                 intel_set_mode(crtc, NULL, 0, 0, NULL);
8384
8385                 if (old->release_fb) {
8386                         drm_framebuffer_unregister_private(old->release_fb);
8387                         drm_framebuffer_unreference(old->release_fb);
8388                 }
8389
8390                 mutex_unlock(&crtc->mutex);
8391                 return;
8392         }
8393
8394         /* Switch crtc and encoder back off if necessary */
8395         if (old->dpms_mode != DRM_MODE_DPMS_ON)
8396                 connector->funcs->dpms(connector, old->dpms_mode);
8397
8398         mutex_unlock(&crtc->mutex);
8399 }
8400
8401 static int i9xx_pll_refclk(struct drm_device *dev,
8402                            const struct intel_crtc_config *pipe_config)
8403 {
8404         struct drm_i915_private *dev_priv = dev->dev_private;
8405         u32 dpll = pipe_config->dpll_hw_state.dpll;
8406
8407         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
8408                 return dev_priv->vbt.lvds_ssc_freq;
8409         else if (HAS_PCH_SPLIT(dev))
8410                 return 120000;
8411         else if (!IS_GEN2(dev))
8412                 return 96000;
8413         else
8414                 return 48000;
8415 }
8416
8417 /* Returns the clock of the currently programmed mode of the given pipe. */
8418 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
8419                                 struct intel_crtc_config *pipe_config)
8420 {
8421         struct drm_device *dev = crtc->base.dev;
8422         struct drm_i915_private *dev_priv = dev->dev_private;
8423         int pipe = pipe_config->cpu_transcoder;
8424         u32 dpll = pipe_config->dpll_hw_state.dpll;
8425         u32 fp;
8426         intel_clock_t clock;
8427         int refclk = i9xx_pll_refclk(dev, pipe_config);
8428
8429         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
8430                 fp = pipe_config->dpll_hw_state.fp0;
8431         else
8432                 fp = pipe_config->dpll_hw_state.fp1;
8433
8434         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
8435         if (IS_PINEVIEW(dev)) {
8436                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
8437                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
8438         } else {
8439                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
8440                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
8441         }
8442
8443         if (!IS_GEN2(dev)) {
8444                 if (IS_PINEVIEW(dev))
8445                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
8446                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
8447                 else
8448                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
8449                                DPLL_FPA01_P1_POST_DIV_SHIFT);
8450
8451                 switch (dpll & DPLL_MODE_MASK) {
8452                 case DPLLB_MODE_DAC_SERIAL:
8453                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
8454                                 5 : 10;
8455                         break;
8456                 case DPLLB_MODE_LVDS:
8457                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
8458                                 7 : 14;
8459                         break;
8460                 default:
8461                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
8462                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
8463                         return;
8464                 }
8465
8466                 if (IS_PINEVIEW(dev))
8467                         pineview_clock(refclk, &clock);
8468                 else
8469                         i9xx_clock(refclk, &clock);
8470         } else {
8471                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
8472                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
8473
8474                 if (is_lvds) {
8475                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
8476                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
8477
8478                         if (lvds & LVDS_CLKB_POWER_UP)
8479                                 clock.p2 = 7;
8480                         else
8481                                 clock.p2 = 14;
8482                 } else {
8483                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
8484                                 clock.p1 = 2;
8485                         else {
8486                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
8487                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
8488                         }
8489                         if (dpll & PLL_P2_DIVIDE_BY_4)
8490                                 clock.p2 = 4;
8491                         else
8492                                 clock.p2 = 2;
8493                 }
8494
8495                 i9xx_clock(refclk, &clock);
8496         }
8497
8498         /*
8499          * This value includes pixel_multiplier. We will use
8500          * port_clock to compute adjusted_mode.crtc_clock in the
8501          * encoder's get_config() function.
8502          */
8503         pipe_config->port_clock = clock.dot;
8504 }
8505
8506 int intel_dotclock_calculate(int link_freq,
8507                              const struct intel_link_m_n *m_n)
8508 {
8509         /*
8510          * The calculation for the data clock is:
8511          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
8512          * But we want to avoid losing precison if possible, so:
8513          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
8514          *
8515          * and the link clock is simpler:
8516          * link_clock = (m * link_clock) / n
8517          */
8518
8519         if (!m_n->link_n)
8520                 return 0;
8521
8522         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
8523 }
8524
8525 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
8526                                    struct intel_crtc_config *pipe_config)
8527 {
8528         struct drm_device *dev = crtc->base.dev;
8529
8530         /* read out port_clock from the DPLL */
8531         i9xx_crtc_clock_get(crtc, pipe_config);
8532
8533         /*
8534          * This value does not include pixel_multiplier.
8535          * We will check that port_clock and adjusted_mode.crtc_clock
8536          * agree once we know their relationship in the encoder's
8537          * get_config() function.
8538          */
8539         pipe_config->adjusted_mode.crtc_clock =
8540                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
8541                                          &pipe_config->fdi_m_n);
8542 }
8543
8544 /** Returns the currently programmed mode of the given pipe. */
8545 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
8546                                              struct drm_crtc *crtc)
8547 {
8548         struct drm_i915_private *dev_priv = dev->dev_private;
8549         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8550         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
8551         struct drm_display_mode *mode;
8552         struct intel_crtc_config pipe_config;
8553         int htot = I915_READ(HTOTAL(cpu_transcoder));
8554         int hsync = I915_READ(HSYNC(cpu_transcoder));
8555         int vtot = I915_READ(VTOTAL(cpu_transcoder));
8556         int vsync = I915_READ(VSYNC(cpu_transcoder));
8557         enum pipe pipe = intel_crtc->pipe;
8558
8559         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
8560         if (!mode)
8561                 return NULL;
8562
8563         /*
8564          * Construct a pipe_config sufficient for getting the clock info
8565          * back out of crtc_clock_get.
8566          *
8567          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
8568          * to use a real value here instead.
8569          */
8570         pipe_config.cpu_transcoder = (enum transcoder) pipe;
8571         pipe_config.pixel_multiplier = 1;
8572         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
8573         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
8574         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
8575         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
8576
8577         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
8578         mode->hdisplay = (htot & 0xffff) + 1;
8579         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
8580         mode->hsync_start = (hsync & 0xffff) + 1;
8581         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
8582         mode->vdisplay = (vtot & 0xffff) + 1;
8583         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
8584         mode->vsync_start = (vsync & 0xffff) + 1;
8585         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
8586
8587         drm_mode_set_name(mode);
8588
8589         return mode;
8590 }
8591
8592 static void intel_increase_pllclock(struct drm_crtc *crtc)
8593 {
8594         struct drm_device *dev = crtc->dev;
8595         struct drm_i915_private *dev_priv = dev->dev_private;
8596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8597         int pipe = intel_crtc->pipe;
8598         int dpll_reg = DPLL(pipe);
8599         int dpll;
8600
8601         if (HAS_PCH_SPLIT(dev))
8602                 return;
8603
8604         if (!dev_priv->lvds_downclock_avail)
8605                 return;
8606
8607         dpll = I915_READ(dpll_reg);
8608         if (!HAS_PIPE_CXSR(dev) && (dpll & DISPLAY_RATE_SELECT_FPA1)) {
8609                 DRM_DEBUG_DRIVER("upclocking LVDS\n");
8610
8611                 assert_panel_unlocked(dev_priv, pipe);
8612
8613                 dpll &= ~DISPLAY_RATE_SELECT_FPA1;
8614                 I915_WRITE(dpll_reg, dpll);
8615                 intel_wait_for_vblank(dev, pipe);
8616
8617                 dpll = I915_READ(dpll_reg);
8618                 if (dpll & DISPLAY_RATE_SELECT_FPA1)
8619                         DRM_DEBUG_DRIVER("failed to upclock LVDS!\n");
8620         }
8621 }
8622
8623 static void intel_decrease_pllclock(struct drm_crtc *crtc)
8624 {
8625         struct drm_device *dev = crtc->dev;
8626         struct drm_i915_private *dev_priv = dev->dev_private;
8627         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8628
8629         if (HAS_PCH_SPLIT(dev))
8630                 return;
8631
8632         if (!dev_priv->lvds_downclock_avail)
8633                 return;
8634
8635         /*
8636          * Since this is called by a timer, we should never get here in
8637          * the manual case.
8638          */
8639         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
8640                 int pipe = intel_crtc->pipe;
8641                 int dpll_reg = DPLL(pipe);
8642                 int dpll;
8643
8644                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
8645
8646                 assert_panel_unlocked(dev_priv, pipe);
8647
8648                 dpll = I915_READ(dpll_reg);
8649                 dpll |= DISPLAY_RATE_SELECT_FPA1;
8650                 I915_WRITE(dpll_reg, dpll);
8651                 intel_wait_for_vblank(dev, pipe);
8652                 dpll = I915_READ(dpll_reg);
8653                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
8654                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
8655         }
8656
8657 }
8658
8659 void intel_mark_busy(struct drm_device *dev)
8660 {
8661         struct drm_i915_private *dev_priv = dev->dev_private;
8662
8663         if (dev_priv->mm.busy)
8664                 return;
8665
8666         intel_runtime_pm_get(dev_priv);
8667         i915_update_gfx_val(dev_priv);
8668         dev_priv->mm.busy = true;
8669 }
8670
8671 void intel_mark_idle(struct drm_device *dev)
8672 {
8673         struct drm_i915_private *dev_priv = dev->dev_private;
8674         struct drm_crtc *crtc;
8675
8676         if (!dev_priv->mm.busy)
8677                 return;
8678
8679         dev_priv->mm.busy = false;
8680
8681         if (!i915.powersave)
8682                 goto out;
8683
8684         for_each_crtc(dev, crtc) {
8685                 if (!crtc->primary->fb)
8686                         continue;
8687
8688                 intel_decrease_pllclock(crtc);
8689         }
8690
8691         if (INTEL_INFO(dev)->gen >= 6)
8692                 gen6_rps_idle(dev->dev_private);
8693
8694 out:
8695         intel_runtime_pm_put(dev_priv);
8696 }
8697
8698 void intel_mark_fb_busy(struct drm_i915_gem_object *obj,
8699                         struct intel_ring_buffer *ring)
8700 {
8701         struct drm_device *dev = obj->base.dev;
8702         struct drm_crtc *crtc;
8703
8704         if (!i915.powersave)
8705                 return;
8706
8707         for_each_crtc(dev, crtc) {
8708                 if (!crtc->primary->fb)
8709                         continue;
8710
8711                 if (to_intel_framebuffer(crtc->primary->fb)->obj != obj)
8712                         continue;
8713
8714                 intel_increase_pllclock(crtc);
8715                 if (ring && intel_fbc_enabled(dev))
8716                         ring->fbc_dirty = true;
8717         }
8718 }
8719
8720 static void intel_crtc_destroy(struct drm_crtc *crtc)
8721 {
8722         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8723         struct drm_device *dev = crtc->dev;
8724         struct intel_unpin_work *work;
8725         unsigned long flags;
8726
8727         spin_lock_irqsave(&dev->event_lock, flags);
8728         work = intel_crtc->unpin_work;
8729         intel_crtc->unpin_work = NULL;
8730         spin_unlock_irqrestore(&dev->event_lock, flags);
8731
8732         if (work) {
8733                 cancel_work_sync(&work->work);
8734                 kfree(work);
8735         }
8736
8737         intel_crtc_cursor_set(crtc, NULL, 0, 0, 0);
8738
8739         drm_crtc_cleanup(crtc);
8740
8741         kfree(intel_crtc);
8742 }
8743
8744 static void intel_unpin_work_fn(struct work_struct *__work)
8745 {
8746         struct intel_unpin_work *work =
8747                 container_of(__work, struct intel_unpin_work, work);
8748         struct drm_device *dev = work->crtc->dev;
8749
8750         mutex_lock(&dev->struct_mutex);
8751         intel_unpin_fb_obj(work->old_fb_obj);
8752         drm_gem_object_unreference(&work->pending_flip_obj->base);
8753         drm_gem_object_unreference(&work->old_fb_obj->base);
8754
8755         intel_update_fbc(dev);
8756         mutex_unlock(&dev->struct_mutex);
8757
8758         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
8759         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
8760
8761         kfree(work);
8762 }
8763
8764 static void do_intel_finish_page_flip(struct drm_device *dev,
8765                                       struct drm_crtc *crtc)
8766 {
8767         struct drm_i915_private *dev_priv = dev->dev_private;
8768         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8769         struct intel_unpin_work *work;
8770         unsigned long flags;
8771
8772         /* Ignore early vblank irqs */
8773         if (intel_crtc == NULL)
8774                 return;
8775
8776         spin_lock_irqsave(&dev->event_lock, flags);
8777         work = intel_crtc->unpin_work;
8778
8779         /* Ensure we don't miss a work->pending update ... */
8780         smp_rmb();
8781
8782         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
8783                 spin_unlock_irqrestore(&dev->event_lock, flags);
8784                 return;
8785         }
8786
8787         /* and that the unpin work is consistent wrt ->pending. */
8788         smp_rmb();
8789
8790         intel_crtc->unpin_work = NULL;
8791
8792         if (work->event)
8793                 drm_send_vblank_event(dev, intel_crtc->pipe, work->event);
8794
8795         drm_vblank_put(dev, intel_crtc->pipe);
8796
8797         spin_unlock_irqrestore(&dev->event_lock, flags);
8798
8799         wake_up_all(&dev_priv->pending_flip_queue);
8800
8801         queue_work(dev_priv->wq, &work->work);
8802
8803         trace_i915_flip_complete(intel_crtc->plane, work->pending_flip_obj);
8804 }
8805
8806 void intel_finish_page_flip(struct drm_device *dev, int pipe)
8807 {
8808         struct drm_i915_private *dev_priv = dev->dev_private;
8809         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
8810
8811         do_intel_finish_page_flip(dev, crtc);
8812 }
8813
8814 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
8815 {
8816         struct drm_i915_private *dev_priv = dev->dev_private;
8817         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
8818
8819         do_intel_finish_page_flip(dev, crtc);
8820 }
8821
8822 void intel_prepare_page_flip(struct drm_device *dev, int plane)
8823 {
8824         struct drm_i915_private *dev_priv = dev->dev_private;
8825         struct intel_crtc *intel_crtc =
8826                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
8827         unsigned long flags;
8828
8829         /* NB: An MMIO update of the plane base pointer will also
8830          * generate a page-flip completion irq, i.e. every modeset
8831          * is also accompanied by a spurious intel_prepare_page_flip().
8832          */
8833         spin_lock_irqsave(&dev->event_lock, flags);
8834         if (intel_crtc->unpin_work)
8835                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
8836         spin_unlock_irqrestore(&dev->event_lock, flags);
8837 }
8838
8839 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
8840 {
8841         /* Ensure that the work item is consistent when activating it ... */
8842         smp_wmb();
8843         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
8844         /* and that it is marked active as soon as the irq could fire. */
8845         smp_wmb();
8846 }
8847
8848 static int intel_gen2_queue_flip(struct drm_device *dev,
8849                                  struct drm_crtc *crtc,
8850                                  struct drm_framebuffer *fb,
8851                                  struct drm_i915_gem_object *obj,
8852                                  uint32_t flags)
8853 {
8854         struct drm_i915_private *dev_priv = dev->dev_private;
8855         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8856         u32 flip_mask;
8857         struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
8858         int ret;
8859
8860         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
8861         if (ret)
8862                 goto err;
8863
8864         ret = intel_ring_begin(ring, 6);
8865         if (ret)
8866                 goto err_unpin;
8867
8868         /* Can't queue multiple flips, so wait for the previous
8869          * one to finish before executing the next.
8870          */
8871         if (intel_crtc->plane)
8872                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
8873         else
8874                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
8875         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
8876         intel_ring_emit(ring, MI_NOOP);
8877         intel_ring_emit(ring, MI_DISPLAY_FLIP |
8878                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
8879         intel_ring_emit(ring, fb->pitches[0]);
8880         intel_ring_emit(ring, i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
8881         intel_ring_emit(ring, 0); /* aux display base address, unused */
8882
8883         intel_mark_page_flip_active(intel_crtc);
8884         __intel_ring_advance(ring);
8885         return 0;
8886
8887 err_unpin:
8888         intel_unpin_fb_obj(obj);
8889 err:
8890         return ret;
8891 }
8892
8893 static int intel_gen3_queue_flip(struct drm_device *dev,
8894                                  struct drm_crtc *crtc,
8895                                  struct drm_framebuffer *fb,
8896                                  struct drm_i915_gem_object *obj,
8897                                  uint32_t flags)
8898 {
8899         struct drm_i915_private *dev_priv = dev->dev_private;
8900         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8901         u32 flip_mask;
8902         struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
8903         int ret;
8904
8905         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
8906         if (ret)
8907                 goto err;
8908
8909         ret = intel_ring_begin(ring, 6);
8910         if (ret)
8911                 goto err_unpin;
8912
8913         if (intel_crtc->plane)
8914                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
8915         else
8916                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
8917         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
8918         intel_ring_emit(ring, MI_NOOP);
8919         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
8920                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
8921         intel_ring_emit(ring, fb->pitches[0]);
8922         intel_ring_emit(ring, i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
8923         intel_ring_emit(ring, MI_NOOP);
8924
8925         intel_mark_page_flip_active(intel_crtc);
8926         __intel_ring_advance(ring);
8927         return 0;
8928
8929 err_unpin:
8930         intel_unpin_fb_obj(obj);
8931 err:
8932         return ret;
8933 }
8934
8935 static int intel_gen4_queue_flip(struct drm_device *dev,
8936                                  struct drm_crtc *crtc,
8937                                  struct drm_framebuffer *fb,
8938                                  struct drm_i915_gem_object *obj,
8939                                  uint32_t flags)
8940 {
8941         struct drm_i915_private *dev_priv = dev->dev_private;
8942         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8943         uint32_t pf, pipesrc;
8944         struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
8945         int ret;
8946
8947         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
8948         if (ret)
8949                 goto err;
8950
8951         ret = intel_ring_begin(ring, 4);
8952         if (ret)
8953                 goto err_unpin;
8954
8955         /* i965+ uses the linear or tiled offsets from the
8956          * Display Registers (which do not change across a page-flip)
8957          * so we need only reprogram the base address.
8958          */
8959         intel_ring_emit(ring, MI_DISPLAY_FLIP |
8960                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
8961         intel_ring_emit(ring, fb->pitches[0]);
8962         intel_ring_emit(ring,
8963                         (i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset) |
8964                         obj->tiling_mode);
8965
8966         /* XXX Enabling the panel-fitter across page-flip is so far
8967          * untested on non-native modes, so ignore it for now.
8968          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
8969          */
8970         pf = 0;
8971         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
8972         intel_ring_emit(ring, pf | pipesrc);
8973
8974         intel_mark_page_flip_active(intel_crtc);
8975         __intel_ring_advance(ring);
8976         return 0;
8977
8978 err_unpin:
8979         intel_unpin_fb_obj(obj);
8980 err:
8981         return ret;
8982 }
8983
8984 static int intel_gen6_queue_flip(struct drm_device *dev,
8985                                  struct drm_crtc *crtc,
8986                                  struct drm_framebuffer *fb,
8987                                  struct drm_i915_gem_object *obj,
8988                                  uint32_t flags)
8989 {
8990         struct drm_i915_private *dev_priv = dev->dev_private;
8991         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8992         struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
8993         uint32_t pf, pipesrc;
8994         int ret;
8995
8996         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
8997         if (ret)
8998                 goto err;
8999
9000         ret = intel_ring_begin(ring, 4);
9001         if (ret)
9002                 goto err_unpin;
9003
9004         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9005                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9006         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
9007         intel_ring_emit(ring, i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
9008
9009         /* Contrary to the suggestions in the documentation,
9010          * "Enable Panel Fitter" does not seem to be required when page
9011          * flipping with a non-native mode, and worse causes a normal
9012          * modeset to fail.
9013          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
9014          */
9015         pf = 0;
9016         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9017         intel_ring_emit(ring, pf | pipesrc);
9018
9019         intel_mark_page_flip_active(intel_crtc);
9020         __intel_ring_advance(ring);
9021         return 0;
9022
9023 err_unpin:
9024         intel_unpin_fb_obj(obj);
9025 err:
9026         return ret;
9027 }
9028
9029 static int intel_gen7_queue_flip(struct drm_device *dev,
9030                                  struct drm_crtc *crtc,
9031                                  struct drm_framebuffer *fb,
9032                                  struct drm_i915_gem_object *obj,
9033                                  uint32_t flags)
9034 {
9035         struct drm_i915_private *dev_priv = dev->dev_private;
9036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9037         struct intel_ring_buffer *ring;
9038         uint32_t plane_bit = 0;
9039         int len, ret;
9040
9041         ring = obj->ring;
9042         if (IS_VALLEYVIEW(dev) || ring == NULL || ring->id != RCS)
9043                 ring = &dev_priv->ring[BCS];
9044
9045         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
9046         if (ret)
9047                 goto err;
9048
9049         switch (intel_crtc->plane) {
9050         case PLANE_A:
9051                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
9052                 break;
9053         case PLANE_B:
9054                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
9055                 break;
9056         case PLANE_C:
9057                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
9058                 break;
9059         default:
9060                 WARN_ONCE(1, "unknown plane in flip command\n");
9061                 ret = -ENODEV;
9062                 goto err_unpin;
9063         }
9064
9065         len = 4;
9066         if (ring->id == RCS) {
9067                 len += 6;
9068                 /*
9069                  * On Gen 8, SRM is now taking an extra dword to accommodate
9070                  * 48bits addresses, and we need a NOOP for the batch size to
9071                  * stay even.
9072                  */
9073                 if (IS_GEN8(dev))
9074                         len += 2;
9075         }
9076
9077         /*
9078          * BSpec MI_DISPLAY_FLIP for IVB:
9079          * "The full packet must be contained within the same cache line."
9080          *
9081          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
9082          * cacheline, if we ever start emitting more commands before
9083          * the MI_DISPLAY_FLIP we may need to first emit everything else,
9084          * then do the cacheline alignment, and finally emit the
9085          * MI_DISPLAY_FLIP.
9086          */
9087         ret = intel_ring_cacheline_align(ring);
9088         if (ret)
9089                 goto err_unpin;
9090
9091         ret = intel_ring_begin(ring, len);
9092         if (ret)
9093                 goto err_unpin;
9094
9095         /* Unmask the flip-done completion message. Note that the bspec says that
9096          * we should do this for both the BCS and RCS, and that we must not unmask
9097          * more than one flip event at any time (or ensure that one flip message
9098          * can be sent by waiting for flip-done prior to queueing new flips).
9099          * Experimentation says that BCS works despite DERRMR masking all
9100          * flip-done completion events and that unmasking all planes at once
9101          * for the RCS also doesn't appear to drop events. Setting the DERRMR
9102          * to zero does lead to lockups within MI_DISPLAY_FLIP.
9103          */
9104         if (ring->id == RCS) {
9105                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9106                 intel_ring_emit(ring, DERRMR);
9107                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9108                                         DERRMR_PIPEB_PRI_FLIP_DONE |
9109                                         DERRMR_PIPEC_PRI_FLIP_DONE));
9110                 if (IS_GEN8(dev))
9111                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9112                                               MI_SRM_LRM_GLOBAL_GTT);
9113                 else
9114                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
9115                                               MI_SRM_LRM_GLOBAL_GTT);
9116                 intel_ring_emit(ring, DERRMR);
9117                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9118                 if (IS_GEN8(dev)) {
9119                         intel_ring_emit(ring, 0);
9120                         intel_ring_emit(ring, MI_NOOP);
9121                 }
9122         }
9123
9124         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
9125         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
9126         intel_ring_emit(ring, i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
9127         intel_ring_emit(ring, (MI_NOOP));
9128
9129         intel_mark_page_flip_active(intel_crtc);
9130         __intel_ring_advance(ring);
9131         return 0;
9132
9133 err_unpin:
9134         intel_unpin_fb_obj(obj);
9135 err:
9136         return ret;
9137 }
9138
9139 static int intel_default_queue_flip(struct drm_device *dev,
9140                                     struct drm_crtc *crtc,
9141                                     struct drm_framebuffer *fb,
9142                                     struct drm_i915_gem_object *obj,
9143                                     uint32_t flags)
9144 {
9145         return -ENODEV;
9146 }
9147
9148 static int intel_crtc_page_flip(struct drm_crtc *crtc,
9149                                 struct drm_framebuffer *fb,
9150                                 struct drm_pending_vblank_event *event,
9151                                 uint32_t page_flip_flags)
9152 {
9153         struct drm_device *dev = crtc->dev;
9154         struct drm_i915_private *dev_priv = dev->dev_private;
9155         struct drm_framebuffer *old_fb = crtc->primary->fb;
9156         struct drm_i915_gem_object *obj = to_intel_framebuffer(fb)->obj;
9157         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9158         struct intel_unpin_work *work;
9159         unsigned long flags;
9160         int ret;
9161
9162         /* Can't change pixel format via MI display flips. */
9163         if (fb->pixel_format != crtc->primary->fb->pixel_format)
9164                 return -EINVAL;
9165
9166         /*
9167          * TILEOFF/LINOFF registers can't be changed via MI display flips.
9168          * Note that pitch changes could also affect these register.
9169          */
9170         if (INTEL_INFO(dev)->gen > 3 &&
9171             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
9172              fb->pitches[0] != crtc->primary->fb->pitches[0]))
9173                 return -EINVAL;
9174
9175         if (i915_terminally_wedged(&dev_priv->gpu_error))
9176                 goto out_hang;
9177
9178         work = kzalloc(sizeof(*work), GFP_KERNEL);
9179         if (work == NULL)
9180                 return -ENOMEM;
9181
9182         work->event = event;
9183         work->crtc = crtc;
9184         work->old_fb_obj = to_intel_framebuffer(old_fb)->obj;
9185         INIT_WORK(&work->work, intel_unpin_work_fn);
9186
9187         ret = drm_vblank_get(dev, intel_crtc->pipe);
9188         if (ret)
9189                 goto free_work;
9190
9191         /* We borrow the event spin lock for protecting unpin_work */
9192         spin_lock_irqsave(&dev->event_lock, flags);
9193         if (intel_crtc->unpin_work) {
9194                 spin_unlock_irqrestore(&dev->event_lock, flags);
9195                 kfree(work);
9196                 drm_vblank_put(dev, intel_crtc->pipe);
9197
9198                 DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
9199                 return -EBUSY;
9200         }
9201         intel_crtc->unpin_work = work;
9202         spin_unlock_irqrestore(&dev->event_lock, flags);
9203
9204         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
9205                 flush_workqueue(dev_priv->wq);
9206
9207         ret = i915_mutex_lock_interruptible(dev);
9208         if (ret)
9209                 goto cleanup;
9210
9211         /* Reference the objects for the scheduled work. */
9212         drm_gem_object_reference(&work->old_fb_obj->base);
9213         drm_gem_object_reference(&obj->base);
9214
9215         crtc->primary->fb = fb;
9216
9217         work->pending_flip_obj = obj;
9218
9219         work->enable_stall_check = true;
9220
9221         atomic_inc(&intel_crtc->unpin_work_count);
9222         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
9223
9224         ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, page_flip_flags);
9225         if (ret)
9226                 goto cleanup_pending;
9227
9228         intel_disable_fbc(dev);
9229         intel_mark_fb_busy(obj, NULL);
9230         mutex_unlock(&dev->struct_mutex);
9231
9232         trace_i915_flip_request(intel_crtc->plane, obj);
9233
9234         return 0;
9235
9236 cleanup_pending:
9237         atomic_dec(&intel_crtc->unpin_work_count);
9238         crtc->primary->fb = old_fb;
9239         drm_gem_object_unreference(&work->old_fb_obj->base);
9240         drm_gem_object_unreference(&obj->base);
9241         mutex_unlock(&dev->struct_mutex);
9242
9243 cleanup:
9244         spin_lock_irqsave(&dev->event_lock, flags);
9245         intel_crtc->unpin_work = NULL;
9246         spin_unlock_irqrestore(&dev->event_lock, flags);
9247
9248         drm_vblank_put(dev, intel_crtc->pipe);
9249 free_work:
9250         kfree(work);
9251
9252         if (ret == -EIO) {
9253 out_hang:
9254                 intel_crtc_wait_for_pending_flips(crtc);
9255                 ret = intel_pipe_set_base(crtc, crtc->x, crtc->y, fb);
9256                 if (ret == 0 && event)
9257                         drm_send_vblank_event(dev, intel_crtc->pipe, event);
9258         }
9259         return ret;
9260 }
9261
9262 static struct drm_crtc_helper_funcs intel_helper_funcs = {
9263         .mode_set_base_atomic = intel_pipe_set_base_atomic,
9264         .load_lut = intel_crtc_load_lut,
9265 };
9266
9267 /**
9268  * intel_modeset_update_staged_output_state
9269  *
9270  * Updates the staged output configuration state, e.g. after we've read out the
9271  * current hw state.
9272  */
9273 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
9274 {
9275         struct intel_crtc *crtc;
9276         struct intel_encoder *encoder;
9277         struct intel_connector *connector;
9278
9279         list_for_each_entry(connector, &dev->mode_config.connector_list,
9280                             base.head) {
9281                 connector->new_encoder =
9282                         to_intel_encoder(connector->base.encoder);
9283         }
9284
9285         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
9286                             base.head) {
9287                 encoder->new_crtc =
9288                         to_intel_crtc(encoder->base.crtc);
9289         }
9290
9291         for_each_intel_crtc(dev, crtc) {
9292                 crtc->new_enabled = crtc->base.enabled;
9293
9294                 if (crtc->new_enabled)
9295                         crtc->new_config = &crtc->config;
9296                 else
9297                         crtc->new_config = NULL;
9298         }
9299 }
9300
9301 /**
9302  * intel_modeset_commit_output_state
9303  *
9304  * This function copies the stage display pipe configuration to the real one.
9305  */
9306 static void intel_modeset_commit_output_state(struct drm_device *dev)
9307 {
9308         struct intel_crtc *crtc;
9309         struct intel_encoder *encoder;
9310         struct intel_connector *connector;
9311
9312         list_for_each_entry(connector, &dev->mode_config.connector_list,
9313                             base.head) {
9314                 connector->base.encoder = &connector->new_encoder->base;
9315         }
9316
9317         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
9318                             base.head) {
9319                 encoder->base.crtc = &encoder->new_crtc->base;
9320         }
9321
9322         for_each_intel_crtc(dev, crtc) {
9323                 crtc->base.enabled = crtc->new_enabled;
9324         }
9325 }
9326
9327 static void
9328 connected_sink_compute_bpp(struct intel_connector *connector,
9329                            struct intel_crtc_config *pipe_config)
9330 {
9331         int bpp = pipe_config->pipe_bpp;
9332
9333         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
9334                 connector->base.base.id,
9335                 drm_get_connector_name(&connector->base));
9336
9337         /* Don't use an invalid EDID bpc value */
9338         if (connector->base.display_info.bpc &&
9339             connector->base.display_info.bpc * 3 < bpp) {
9340                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
9341                               bpp, connector->base.display_info.bpc*3);
9342                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
9343         }
9344
9345         /* Clamp bpp to 8 on screens without EDID 1.4 */
9346         if (connector->base.display_info.bpc == 0 && bpp > 24) {
9347                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
9348                               bpp);
9349                 pipe_config->pipe_bpp = 24;
9350         }
9351 }
9352
9353 static int
9354 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
9355                           struct drm_framebuffer *fb,
9356                           struct intel_crtc_config *pipe_config)
9357 {
9358         struct drm_device *dev = crtc->base.dev;
9359         struct intel_connector *connector;
9360         int bpp;
9361
9362         switch (fb->pixel_format) {
9363         case DRM_FORMAT_C8:
9364                 bpp = 8*3; /* since we go through a colormap */
9365                 break;
9366         case DRM_FORMAT_XRGB1555:
9367         case DRM_FORMAT_ARGB1555:
9368                 /* checked in intel_framebuffer_init already */
9369                 if (WARN_ON(INTEL_INFO(dev)->gen > 3))
9370                         return -EINVAL;
9371         case DRM_FORMAT_RGB565:
9372                 bpp = 6*3; /* min is 18bpp */
9373                 break;
9374         case DRM_FORMAT_XBGR8888:
9375         case DRM_FORMAT_ABGR8888:
9376                 /* checked in intel_framebuffer_init already */
9377                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
9378                         return -EINVAL;
9379         case DRM_FORMAT_XRGB8888:
9380         case DRM_FORMAT_ARGB8888:
9381                 bpp = 8*3;
9382                 break;
9383         case DRM_FORMAT_XRGB2101010:
9384         case DRM_FORMAT_ARGB2101010:
9385         case DRM_FORMAT_XBGR2101010:
9386         case DRM_FORMAT_ABGR2101010:
9387                 /* checked in intel_framebuffer_init already */
9388                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
9389                         return -EINVAL;
9390                 bpp = 10*3;
9391                 break;
9392         /* TODO: gen4+ supports 16 bpc floating point, too. */
9393         default:
9394                 DRM_DEBUG_KMS("unsupported depth\n");
9395                 return -EINVAL;
9396         }
9397
9398         pipe_config->pipe_bpp = bpp;
9399
9400         /* Clamp display bpp to EDID value */
9401         list_for_each_entry(connector, &dev->mode_config.connector_list,
9402                             base.head) {
9403                 if (!connector->new_encoder ||
9404                     connector->new_encoder->new_crtc != crtc)
9405                         continue;
9406
9407                 connected_sink_compute_bpp(connector, pipe_config);
9408         }
9409
9410         return bpp;
9411 }
9412
9413 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
9414 {
9415         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
9416                         "type: 0x%x flags: 0x%x\n",
9417                 mode->crtc_clock,
9418                 mode->crtc_hdisplay, mode->crtc_hsync_start,
9419                 mode->crtc_hsync_end, mode->crtc_htotal,
9420                 mode->crtc_vdisplay, mode->crtc_vsync_start,
9421                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
9422 }
9423
9424 static void intel_dump_pipe_config(struct intel_crtc *crtc,
9425                                    struct intel_crtc_config *pipe_config,
9426                                    const char *context)
9427 {
9428         DRM_DEBUG_KMS("[CRTC:%d]%s config for pipe %c\n", crtc->base.base.id,
9429                       context, pipe_name(crtc->pipe));
9430
9431         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
9432         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
9433                       pipe_config->pipe_bpp, pipe_config->dither);
9434         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
9435                       pipe_config->has_pch_encoder,
9436                       pipe_config->fdi_lanes,
9437                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
9438                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
9439                       pipe_config->fdi_m_n.tu);
9440         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
9441                       pipe_config->has_dp_encoder,
9442                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
9443                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
9444                       pipe_config->dp_m_n.tu);
9445         DRM_DEBUG_KMS("requested mode:\n");
9446         drm_mode_debug_printmodeline(&pipe_config->requested_mode);
9447         DRM_DEBUG_KMS("adjusted mode:\n");
9448         drm_mode_debug_printmodeline(&pipe_config->adjusted_mode);
9449         intel_dump_crtc_timings(&pipe_config->adjusted_mode);
9450         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
9451         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
9452                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
9453         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
9454                       pipe_config->gmch_pfit.control,
9455                       pipe_config->gmch_pfit.pgm_ratios,
9456                       pipe_config->gmch_pfit.lvds_border_bits);
9457         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
9458                       pipe_config->pch_pfit.pos,
9459                       pipe_config->pch_pfit.size,
9460                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
9461         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
9462         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
9463 }
9464
9465 static bool encoders_cloneable(const struct intel_encoder *a,
9466                                const struct intel_encoder *b)
9467 {
9468         /* masks could be asymmetric, so check both ways */
9469         return a == b || (a->cloneable & (1 << b->type) &&
9470                           b->cloneable & (1 << a->type));
9471 }
9472
9473 static bool check_single_encoder_cloning(struct intel_crtc *crtc,
9474                                          struct intel_encoder *encoder)
9475 {
9476         struct drm_device *dev = crtc->base.dev;
9477         struct intel_encoder *source_encoder;
9478
9479         list_for_each_entry(source_encoder,
9480                             &dev->mode_config.encoder_list, base.head) {
9481                 if (source_encoder->new_crtc != crtc)
9482                         continue;
9483
9484                 if (!encoders_cloneable(encoder, source_encoder))
9485                         return false;
9486         }
9487
9488         return true;
9489 }
9490
9491 static bool check_encoder_cloning(struct intel_crtc *crtc)
9492 {
9493         struct drm_device *dev = crtc->base.dev;
9494         struct intel_encoder *encoder;
9495
9496         list_for_each_entry(encoder,
9497                             &dev->mode_config.encoder_list, base.head) {
9498                 if (encoder->new_crtc != crtc)
9499                         continue;
9500
9501                 if (!check_single_encoder_cloning(crtc, encoder))
9502                         return false;
9503         }
9504
9505         return true;
9506 }
9507
9508 static struct intel_crtc_config *
9509 intel_modeset_pipe_config(struct drm_crtc *crtc,
9510                           struct drm_framebuffer *fb,
9511                           struct drm_display_mode *mode)
9512 {
9513         struct drm_device *dev = crtc->dev;
9514         struct intel_encoder *encoder;
9515         struct intel_crtc_config *pipe_config;
9516         int plane_bpp, ret = -EINVAL;
9517         bool retry = true;
9518
9519         if (!check_encoder_cloning(to_intel_crtc(crtc))) {
9520                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
9521                 return ERR_PTR(-EINVAL);
9522         }
9523
9524         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
9525         if (!pipe_config)
9526                 return ERR_PTR(-ENOMEM);
9527
9528         drm_mode_copy(&pipe_config->adjusted_mode, mode);
9529         drm_mode_copy(&pipe_config->requested_mode, mode);
9530
9531         pipe_config->cpu_transcoder =
9532                 (enum transcoder) to_intel_crtc(crtc)->pipe;
9533         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9534
9535         /*
9536          * Sanitize sync polarity flags based on requested ones. If neither
9537          * positive or negative polarity is requested, treat this as meaning
9538          * negative polarity.
9539          */
9540         if (!(pipe_config->adjusted_mode.flags &
9541               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
9542                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
9543
9544         if (!(pipe_config->adjusted_mode.flags &
9545               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
9546                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
9547
9548         /* Compute a starting value for pipe_config->pipe_bpp taking the source
9549          * plane pixel format and any sink constraints into account. Returns the
9550          * source plane bpp so that dithering can be selected on mismatches
9551          * after encoders and crtc also have had their say. */
9552         plane_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
9553                                               fb, pipe_config);
9554         if (plane_bpp < 0)
9555                 goto fail;
9556
9557         /*
9558          * Determine the real pipe dimensions. Note that stereo modes can
9559          * increase the actual pipe size due to the frame doubling and
9560          * insertion of additional space for blanks between the frame. This
9561          * is stored in the crtc timings. We use the requested mode to do this
9562          * computation to clearly distinguish it from the adjusted mode, which
9563          * can be changed by the connectors in the below retry loop.
9564          */
9565         drm_mode_set_crtcinfo(&pipe_config->requested_mode, CRTC_STEREO_DOUBLE);
9566         pipe_config->pipe_src_w = pipe_config->requested_mode.crtc_hdisplay;
9567         pipe_config->pipe_src_h = pipe_config->requested_mode.crtc_vdisplay;
9568
9569 encoder_retry:
9570         /* Ensure the port clock defaults are reset when retrying. */
9571         pipe_config->port_clock = 0;
9572         pipe_config->pixel_multiplier = 1;
9573
9574         /* Fill in default crtc timings, allow encoders to overwrite them. */
9575         drm_mode_set_crtcinfo(&pipe_config->adjusted_mode, CRTC_STEREO_DOUBLE);
9576
9577         /* Pass our mode to the connectors and the CRTC to give them a chance to
9578          * adjust it according to limitations or connector properties, and also
9579          * a chance to reject the mode entirely.
9580          */
9581         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
9582                             base.head) {
9583
9584                 if (&encoder->new_crtc->base != crtc)
9585                         continue;
9586
9587                 if (!(encoder->compute_config(encoder, pipe_config))) {
9588                         DRM_DEBUG_KMS("Encoder config failure\n");
9589                         goto fail;
9590                 }
9591         }
9592
9593         /* Set default port clock if not overwritten by the encoder. Needs to be
9594          * done afterwards in case the encoder adjusts the mode. */
9595         if (!pipe_config->port_clock)
9596                 pipe_config->port_clock = pipe_config->adjusted_mode.crtc_clock
9597                         * pipe_config->pixel_multiplier;
9598
9599         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
9600         if (ret < 0) {
9601                 DRM_DEBUG_KMS("CRTC fixup failed\n");
9602                 goto fail;
9603         }
9604
9605         if (ret == RETRY) {
9606                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
9607                         ret = -EINVAL;
9608                         goto fail;
9609                 }
9610
9611                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
9612                 retry = false;
9613                 goto encoder_retry;
9614         }
9615
9616         pipe_config->dither = pipe_config->pipe_bpp != plane_bpp;
9617         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
9618                       plane_bpp, pipe_config->pipe_bpp, pipe_config->dither);
9619
9620         return pipe_config;
9621 fail:
9622         kfree(pipe_config);
9623         return ERR_PTR(ret);
9624 }
9625
9626 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
9627  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
9628 static void
9629 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
9630                              unsigned *prepare_pipes, unsigned *disable_pipes)
9631 {
9632         struct intel_crtc *intel_crtc;
9633         struct drm_device *dev = crtc->dev;
9634         struct intel_encoder *encoder;
9635         struct intel_connector *connector;
9636         struct drm_crtc *tmp_crtc;
9637
9638         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
9639
9640         /* Check which crtcs have changed outputs connected to them, these need
9641          * to be part of the prepare_pipes mask. We don't (yet) support global
9642          * modeset across multiple crtcs, so modeset_pipes will only have one
9643          * bit set at most. */
9644         list_for_each_entry(connector, &dev->mode_config.connector_list,
9645                             base.head) {
9646                 if (connector->base.encoder == &connector->new_encoder->base)
9647                         continue;
9648
9649                 if (connector->base.encoder) {
9650                         tmp_crtc = connector->base.encoder->crtc;
9651
9652                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
9653                 }
9654
9655                 if (connector->new_encoder)
9656                         *prepare_pipes |=
9657                                 1 << connector->new_encoder->new_crtc->pipe;
9658         }
9659
9660         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
9661                             base.head) {
9662                 if (encoder->base.crtc == &encoder->new_crtc->base)
9663                         continue;
9664
9665                 if (encoder->base.crtc) {
9666                         tmp_crtc = encoder->base.crtc;
9667
9668                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
9669                 }
9670
9671                 if (encoder->new_crtc)
9672                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
9673         }
9674
9675         /* Check for pipes that will be enabled/disabled ... */
9676         for_each_intel_crtc(dev, intel_crtc) {
9677                 if (intel_crtc->base.enabled == intel_crtc->new_enabled)
9678                         continue;
9679
9680                 if (!intel_crtc->new_enabled)
9681                         *disable_pipes |= 1 << intel_crtc->pipe;
9682                 else
9683                         *prepare_pipes |= 1 << intel_crtc->pipe;
9684         }
9685
9686
9687         /* set_mode is also used to update properties on life display pipes. */
9688         intel_crtc = to_intel_crtc(crtc);
9689         if (intel_crtc->new_enabled)
9690                 *prepare_pipes |= 1 << intel_crtc->pipe;
9691
9692         /*
9693          * For simplicity do a full modeset on any pipe where the output routing
9694          * changed. We could be more clever, but that would require us to be
9695          * more careful with calling the relevant encoder->mode_set functions.
9696          */
9697         if (*prepare_pipes)
9698                 *modeset_pipes = *prepare_pipes;
9699
9700         /* ... and mask these out. */
9701         *modeset_pipes &= ~(*disable_pipes);
9702         *prepare_pipes &= ~(*disable_pipes);
9703
9704         /*
9705          * HACK: We don't (yet) fully support global modesets. intel_set_config
9706          * obies this rule, but the modeset restore mode of
9707          * intel_modeset_setup_hw_state does not.
9708          */
9709         *modeset_pipes &= 1 << intel_crtc->pipe;
9710         *prepare_pipes &= 1 << intel_crtc->pipe;
9711
9712         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
9713                       *modeset_pipes, *prepare_pipes, *disable_pipes);
9714 }
9715
9716 static bool intel_crtc_in_use(struct drm_crtc *crtc)
9717 {
9718         struct drm_encoder *encoder;
9719         struct drm_device *dev = crtc->dev;
9720
9721         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
9722                 if (encoder->crtc == crtc)
9723                         return true;
9724
9725         return false;
9726 }
9727
9728 static void
9729 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
9730 {
9731         struct intel_encoder *intel_encoder;
9732         struct intel_crtc *intel_crtc;
9733         struct drm_connector *connector;
9734
9735         list_for_each_entry(intel_encoder, &dev->mode_config.encoder_list,
9736                             base.head) {
9737                 if (!intel_encoder->base.crtc)
9738                         continue;
9739
9740                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
9741
9742                 if (prepare_pipes & (1 << intel_crtc->pipe))
9743                         intel_encoder->connectors_active = false;
9744         }
9745
9746         intel_modeset_commit_output_state(dev);
9747
9748         /* Double check state. */
9749         for_each_intel_crtc(dev, intel_crtc) {
9750                 WARN_ON(intel_crtc->base.enabled != intel_crtc_in_use(&intel_crtc->base));
9751                 WARN_ON(intel_crtc->new_config &&
9752                         intel_crtc->new_config != &intel_crtc->config);
9753                 WARN_ON(intel_crtc->base.enabled != !!intel_crtc->new_config);
9754         }
9755
9756         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
9757                 if (!connector->encoder || !connector->encoder->crtc)
9758                         continue;
9759
9760                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
9761
9762                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
9763                         struct drm_property *dpms_property =
9764                                 dev->mode_config.dpms_property;
9765
9766                         connector->dpms = DRM_MODE_DPMS_ON;
9767                         drm_object_property_set_value(&connector->base,
9768                                                          dpms_property,
9769                                                          DRM_MODE_DPMS_ON);
9770
9771                         intel_encoder = to_intel_encoder(connector->encoder);
9772                         intel_encoder->connectors_active = true;
9773                 }
9774         }
9775
9776 }
9777
9778 static bool intel_fuzzy_clock_check(int clock1, int clock2)
9779 {
9780         int diff;
9781
9782         if (clock1 == clock2)
9783                 return true;
9784
9785         if (!clock1 || !clock2)
9786                 return false;
9787
9788         diff = abs(clock1 - clock2);
9789
9790         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
9791                 return true;
9792
9793         return false;
9794 }
9795
9796 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
9797         list_for_each_entry((intel_crtc), \
9798                             &(dev)->mode_config.crtc_list, \
9799                             base.head) \
9800                 if (mask & (1 <<(intel_crtc)->pipe))
9801
9802 static bool
9803 intel_pipe_config_compare(struct drm_device *dev,
9804                           struct intel_crtc_config *current_config,
9805                           struct intel_crtc_config *pipe_config)
9806 {
9807 #define PIPE_CONF_CHECK_X(name) \
9808         if (current_config->name != pipe_config->name) { \
9809                 DRM_ERROR("mismatch in " #name " " \
9810                           "(expected 0x%08x, found 0x%08x)\n", \
9811                           current_config->name, \
9812                           pipe_config->name); \
9813                 return false; \
9814         }
9815
9816 #define PIPE_CONF_CHECK_I(name) \
9817         if (current_config->name != pipe_config->name) { \
9818                 DRM_ERROR("mismatch in " #name " " \
9819                           "(expected %i, found %i)\n", \
9820                           current_config->name, \
9821                           pipe_config->name); \
9822                 return false; \
9823         }
9824
9825 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
9826         if ((current_config->name ^ pipe_config->name) & (mask)) { \
9827                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
9828                           "(expected %i, found %i)\n", \
9829                           current_config->name & (mask), \
9830                           pipe_config->name & (mask)); \
9831                 return false; \
9832         }
9833
9834 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
9835         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
9836                 DRM_ERROR("mismatch in " #name " " \
9837                           "(expected %i, found %i)\n", \
9838                           current_config->name, \
9839                           pipe_config->name); \
9840                 return false; \
9841         }
9842
9843 #define PIPE_CONF_QUIRK(quirk)  \
9844         ((current_config->quirks | pipe_config->quirks) & (quirk))
9845
9846         PIPE_CONF_CHECK_I(cpu_transcoder);
9847
9848         PIPE_CONF_CHECK_I(has_pch_encoder);
9849         PIPE_CONF_CHECK_I(fdi_lanes);
9850         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
9851         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
9852         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
9853         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
9854         PIPE_CONF_CHECK_I(fdi_m_n.tu);
9855
9856         PIPE_CONF_CHECK_I(has_dp_encoder);
9857         PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
9858         PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
9859         PIPE_CONF_CHECK_I(dp_m_n.link_m);
9860         PIPE_CONF_CHECK_I(dp_m_n.link_n);
9861         PIPE_CONF_CHECK_I(dp_m_n.tu);
9862
9863         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hdisplay);
9864         PIPE_CONF_CHECK_I(adjusted_mode.crtc_htotal);
9865         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hblank_start);
9866         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hblank_end);
9867         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hsync_start);
9868         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hsync_end);
9869
9870         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vdisplay);
9871         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vtotal);
9872         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vblank_start);
9873         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vblank_end);
9874         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vsync_start);
9875         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vsync_end);
9876
9877         PIPE_CONF_CHECK_I(pixel_multiplier);
9878         PIPE_CONF_CHECK_I(has_hdmi_sink);
9879         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
9880             IS_VALLEYVIEW(dev))
9881                 PIPE_CONF_CHECK_I(limited_color_range);
9882
9883         PIPE_CONF_CHECK_I(has_audio);
9884
9885         PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
9886                               DRM_MODE_FLAG_INTERLACE);
9887
9888         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
9889                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
9890                                       DRM_MODE_FLAG_PHSYNC);
9891                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
9892                                       DRM_MODE_FLAG_NHSYNC);
9893                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
9894                                       DRM_MODE_FLAG_PVSYNC);
9895                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
9896                                       DRM_MODE_FLAG_NVSYNC);
9897         }
9898
9899         PIPE_CONF_CHECK_I(pipe_src_w);
9900         PIPE_CONF_CHECK_I(pipe_src_h);
9901
9902         /*
9903          * FIXME: BIOS likes to set up a cloned config with lvds+external
9904          * screen. Since we don't yet re-compute the pipe config when moving
9905          * just the lvds port away to another pipe the sw tracking won't match.
9906          *
9907          * Proper atomic modesets with recomputed global state will fix this.
9908          * Until then just don't check gmch state for inherited modes.
9909          */
9910         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
9911                 PIPE_CONF_CHECK_I(gmch_pfit.control);
9912                 /* pfit ratios are autocomputed by the hw on gen4+ */
9913                 if (INTEL_INFO(dev)->gen < 4)
9914                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
9915                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
9916         }
9917
9918         PIPE_CONF_CHECK_I(pch_pfit.enabled);
9919         if (current_config->pch_pfit.enabled) {
9920                 PIPE_CONF_CHECK_I(pch_pfit.pos);
9921                 PIPE_CONF_CHECK_I(pch_pfit.size);
9922         }
9923
9924         /* BDW+ don't expose a synchronous way to read the state */
9925         if (IS_HASWELL(dev))
9926                 PIPE_CONF_CHECK_I(ips_enabled);
9927
9928         PIPE_CONF_CHECK_I(double_wide);
9929
9930         PIPE_CONF_CHECK_I(shared_dpll);
9931         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
9932         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
9933         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
9934         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
9935
9936         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
9937                 PIPE_CONF_CHECK_I(pipe_bpp);
9938
9939         PIPE_CONF_CHECK_CLOCK_FUZZY(adjusted_mode.crtc_clock);
9940         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
9941
9942 #undef PIPE_CONF_CHECK_X
9943 #undef PIPE_CONF_CHECK_I
9944 #undef PIPE_CONF_CHECK_FLAGS
9945 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
9946 #undef PIPE_CONF_QUIRK
9947
9948         return true;
9949 }
9950
9951 static void
9952 check_connector_state(struct drm_device *dev)
9953 {
9954         struct intel_connector *connector;
9955
9956         list_for_each_entry(connector, &dev->mode_config.connector_list,
9957                             base.head) {
9958                 /* This also checks the encoder/connector hw state with the
9959                  * ->get_hw_state callbacks. */
9960                 intel_connector_check_state(connector);
9961
9962                 WARN(&connector->new_encoder->base != connector->base.encoder,
9963                      "connector's staged encoder doesn't match current encoder\n");
9964         }
9965 }
9966
9967 static void
9968 check_encoder_state(struct drm_device *dev)
9969 {
9970         struct intel_encoder *encoder;
9971         struct intel_connector *connector;
9972
9973         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
9974                             base.head) {
9975                 bool enabled = false;
9976                 bool active = false;
9977                 enum pipe pipe, tracked_pipe;
9978
9979                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
9980                               encoder->base.base.id,
9981                               drm_get_encoder_name(&encoder->base));
9982
9983                 WARN(&encoder->new_crtc->base != encoder->base.crtc,
9984                      "encoder's stage crtc doesn't match current crtc\n");
9985                 WARN(encoder->connectors_active && !encoder->base.crtc,
9986                      "encoder's active_connectors set, but no crtc\n");
9987
9988                 list_for_each_entry(connector, &dev->mode_config.connector_list,
9989                                     base.head) {
9990                         if (connector->base.encoder != &encoder->base)
9991                                 continue;
9992                         enabled = true;
9993                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
9994                                 active = true;
9995                 }
9996                 WARN(!!encoder->base.crtc != enabled,
9997                      "encoder's enabled state mismatch "
9998                      "(expected %i, found %i)\n",
9999                      !!encoder->base.crtc, enabled);
10000                 WARN(active && !encoder->base.crtc,
10001                      "active encoder with no crtc\n");
10002
10003                 WARN(encoder->connectors_active != active,
10004                      "encoder's computed active state doesn't match tracked active state "
10005                      "(expected %i, found %i)\n", active, encoder->connectors_active);
10006
10007                 active = encoder->get_hw_state(encoder, &pipe);
10008                 WARN(active != encoder->connectors_active,
10009                      "encoder's hw state doesn't match sw tracking "
10010                      "(expected %i, found %i)\n",
10011                      encoder->connectors_active, active);
10012
10013                 if (!encoder->base.crtc)
10014                         continue;
10015
10016                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
10017                 WARN(active && pipe != tracked_pipe,
10018                      "active encoder's pipe doesn't match"
10019                      "(expected %i, found %i)\n",
10020                      tracked_pipe, pipe);
10021
10022         }
10023 }
10024
10025 static void
10026 check_crtc_state(struct drm_device *dev)
10027 {
10028         struct drm_i915_private *dev_priv = dev->dev_private;
10029         struct intel_crtc *crtc;
10030         struct intel_encoder *encoder;
10031         struct intel_crtc_config pipe_config;
10032
10033         for_each_intel_crtc(dev, crtc) {
10034                 bool enabled = false;
10035                 bool active = false;
10036
10037                 memset(&pipe_config, 0, sizeof(pipe_config));
10038
10039                 DRM_DEBUG_KMS("[CRTC:%d]\n",
10040                               crtc->base.base.id);
10041
10042                 WARN(crtc->active && !crtc->base.enabled,
10043                      "active crtc, but not enabled in sw tracking\n");
10044
10045                 list_for_each_entry(encoder, &dev->mode_config.encoder_list,
10046                                     base.head) {
10047                         if (encoder->base.crtc != &crtc->base)
10048                                 continue;
10049                         enabled = true;
10050                         if (encoder->connectors_active)
10051                                 active = true;
10052                 }
10053
10054                 WARN(active != crtc->active,
10055                      "crtc's computed active state doesn't match tracked active state "
10056                      "(expected %i, found %i)\n", active, crtc->active);
10057                 WARN(enabled != crtc->base.enabled,
10058                      "crtc's computed enabled state doesn't match tracked enabled state "
10059                      "(expected %i, found %i)\n", enabled, crtc->base.enabled);
10060
10061                 active = dev_priv->display.get_pipe_config(crtc,
10062                                                            &pipe_config);
10063
10064                 /* hw state is inconsistent with the pipe A quirk */
10065                 if (crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE)
10066                         active = crtc->active;
10067
10068                 list_for_each_entry(encoder, &dev->mode_config.encoder_list,
10069                                     base.head) {
10070                         enum pipe pipe;
10071                         if (encoder->base.crtc != &crtc->base)
10072                                 continue;
10073                         if (encoder->get_hw_state(encoder, &pipe))
10074                                 encoder->get_config(encoder, &pipe_config);
10075                 }
10076
10077                 WARN(crtc->active != active,
10078                      "crtc active state doesn't match with hw state "
10079                      "(expected %i, found %i)\n", crtc->active, active);
10080
10081                 if (active &&
10082                     !intel_pipe_config_compare(dev, &crtc->config, &pipe_config)) {
10083                         WARN(1, "pipe state doesn't match!\n");
10084                         intel_dump_pipe_config(crtc, &pipe_config,
10085                                                "[hw state]");
10086                         intel_dump_pipe_config(crtc, &crtc->config,
10087                                                "[sw state]");
10088                 }
10089         }
10090 }
10091
10092 static void
10093 check_shared_dpll_state(struct drm_device *dev)
10094 {
10095         struct drm_i915_private *dev_priv = dev->dev_private;
10096         struct intel_crtc *crtc;
10097         struct intel_dpll_hw_state dpll_hw_state;
10098         int i;
10099
10100         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
10101                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
10102                 int enabled_crtcs = 0, active_crtcs = 0;
10103                 bool active;
10104
10105                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
10106
10107                 DRM_DEBUG_KMS("%s\n", pll->name);
10108
10109                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
10110
10111                 WARN(pll->active > pll->refcount,
10112                      "more active pll users than references: %i vs %i\n",
10113                      pll->active, pll->refcount);
10114                 WARN(pll->active && !pll->on,
10115                      "pll in active use but not on in sw tracking\n");
10116                 WARN(pll->on && !pll->active,
10117                      "pll in on but not on in use in sw tracking\n");
10118                 WARN(pll->on != active,
10119                      "pll on state mismatch (expected %i, found %i)\n",
10120                      pll->on, active);
10121
10122                 for_each_intel_crtc(dev, crtc) {
10123                         if (crtc->base.enabled && intel_crtc_to_shared_dpll(crtc) == pll)
10124                                 enabled_crtcs++;
10125                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
10126                                 active_crtcs++;
10127                 }
10128                 WARN(pll->active != active_crtcs,
10129                      "pll active crtcs mismatch (expected %i, found %i)\n",
10130                      pll->active, active_crtcs);
10131                 WARN(pll->refcount != enabled_crtcs,
10132                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
10133                      pll->refcount, enabled_crtcs);
10134
10135                 WARN(pll->on && memcmp(&pll->hw_state, &dpll_hw_state,
10136                                        sizeof(dpll_hw_state)),
10137                      "pll hw state mismatch\n");
10138         }
10139 }
10140
10141 void
10142 intel_modeset_check_state(struct drm_device *dev)
10143 {
10144         check_connector_state(dev);
10145         check_encoder_state(dev);
10146         check_crtc_state(dev);
10147         check_shared_dpll_state(dev);
10148 }
10149
10150 void ironlake_check_encoder_dotclock(const struct intel_crtc_config *pipe_config,
10151                                      int dotclock)
10152 {
10153         /*
10154          * FDI already provided one idea for the dotclock.
10155          * Yell if the encoder disagrees.
10156          */
10157         WARN(!intel_fuzzy_clock_check(pipe_config->adjusted_mode.crtc_clock, dotclock),
10158              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
10159              pipe_config->adjusted_mode.crtc_clock, dotclock);
10160 }
10161
10162 static int __intel_set_mode(struct drm_crtc *crtc,
10163                             struct drm_display_mode *mode,
10164                             int x, int y, struct drm_framebuffer *fb)
10165 {
10166         struct drm_device *dev = crtc->dev;
10167         struct drm_i915_private *dev_priv = dev->dev_private;
10168         struct drm_display_mode *saved_mode;
10169         struct intel_crtc_config *pipe_config = NULL;
10170         struct intel_crtc *intel_crtc;
10171         unsigned disable_pipes, prepare_pipes, modeset_pipes;
10172         int ret = 0;
10173
10174         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
10175         if (!saved_mode)
10176                 return -ENOMEM;
10177
10178         intel_modeset_affected_pipes(crtc, &modeset_pipes,
10179                                      &prepare_pipes, &disable_pipes);
10180
10181         *saved_mode = crtc->mode;
10182
10183         /* Hack: Because we don't (yet) support global modeset on multiple
10184          * crtcs, we don't keep track of the new mode for more than one crtc.
10185          * Hence simply check whether any bit is set in modeset_pipes in all the
10186          * pieces of code that are not yet converted to deal with mutliple crtcs
10187          * changing their mode at the same time. */
10188         if (modeset_pipes) {
10189                 pipe_config = intel_modeset_pipe_config(crtc, fb, mode);
10190                 if (IS_ERR(pipe_config)) {
10191                         ret = PTR_ERR(pipe_config);
10192                         pipe_config = NULL;
10193
10194                         goto out;
10195                 }
10196                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
10197                                        "[modeset]");
10198                 to_intel_crtc(crtc)->new_config = pipe_config;
10199         }
10200
10201         /*
10202          * See if the config requires any additional preparation, e.g.
10203          * to adjust global state with pipes off.  We need to do this
10204          * here so we can get the modeset_pipe updated config for the new
10205          * mode set on this crtc.  For other crtcs we need to use the
10206          * adjusted_mode bits in the crtc directly.
10207          */
10208         if (IS_VALLEYVIEW(dev)) {
10209                 valleyview_modeset_global_pipes(dev, &prepare_pipes);
10210
10211                 /* may have added more to prepare_pipes than we should */
10212                 prepare_pipes &= ~disable_pipes;
10213         }
10214
10215         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
10216                 intel_crtc_disable(&intel_crtc->base);
10217
10218         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
10219                 if (intel_crtc->base.enabled)
10220                         dev_priv->display.crtc_disable(&intel_crtc->base);
10221         }
10222
10223         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
10224          * to set it here already despite that we pass it down the callchain.
10225          */
10226         if (modeset_pipes) {
10227                 crtc->mode = *mode;
10228                 /* mode_set/enable/disable functions rely on a correct pipe
10229                  * config. */
10230                 to_intel_crtc(crtc)->config = *pipe_config;
10231                 to_intel_crtc(crtc)->new_config = &to_intel_crtc(crtc)->config;
10232
10233                 /*
10234                  * Calculate and store various constants which
10235                  * are later needed by vblank and swap-completion
10236                  * timestamping. They are derived from true hwmode.
10237                  */
10238                 drm_calc_timestamping_constants(crtc,
10239                                                 &pipe_config->adjusted_mode);
10240         }
10241
10242         /* Only after disabling all output pipelines that will be changed can we
10243          * update the the output configuration. */
10244         intel_modeset_update_state(dev, prepare_pipes);
10245
10246         if (dev_priv->display.modeset_global_resources)
10247                 dev_priv->display.modeset_global_resources(dev);
10248
10249         /* Set up the DPLL and any encoders state that needs to adjust or depend
10250          * on the DPLL.
10251          */
10252         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
10253                 struct drm_framebuffer *old_fb;
10254
10255                 mutex_lock(&dev->struct_mutex);
10256                 ret = intel_pin_and_fence_fb_obj(dev,
10257                                                  to_intel_framebuffer(fb)->obj,
10258                                                  NULL);
10259                 if (ret != 0) {
10260                         DRM_ERROR("pin & fence failed\n");
10261                         mutex_unlock(&dev->struct_mutex);
10262                         goto done;
10263                 }
10264                 old_fb = crtc->primary->fb;
10265                 if (old_fb)
10266                         intel_unpin_fb_obj(to_intel_framebuffer(old_fb)->obj);
10267                 mutex_unlock(&dev->struct_mutex);
10268
10269                 crtc->primary->fb = fb;
10270                 crtc->x = x;
10271                 crtc->y = y;
10272
10273                 ret = dev_priv->display.crtc_mode_set(&intel_crtc->base,
10274                                                       x, y, fb);
10275                 if (ret)
10276                         goto done;
10277         }
10278
10279         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
10280         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc)
10281                 dev_priv->display.crtc_enable(&intel_crtc->base);
10282
10283         /* FIXME: add subpixel order */
10284 done:
10285         if (ret && crtc->enabled)
10286                 crtc->mode = *saved_mode;
10287
10288 out:
10289         kfree(pipe_config);
10290         kfree(saved_mode);
10291         return ret;
10292 }
10293
10294 static int intel_set_mode(struct drm_crtc *crtc,
10295                           struct drm_display_mode *mode,
10296                           int x, int y, struct drm_framebuffer *fb)
10297 {
10298         int ret;
10299
10300         ret = __intel_set_mode(crtc, mode, x, y, fb);
10301
10302         if (ret == 0)
10303                 intel_modeset_check_state(crtc->dev);
10304
10305         return ret;
10306 }
10307
10308 void intel_crtc_restore_mode(struct drm_crtc *crtc)
10309 {
10310         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb);
10311 }
10312
10313 #undef for_each_intel_crtc_masked
10314
10315 static void intel_set_config_free(struct intel_set_config *config)
10316 {
10317         if (!config)
10318                 return;
10319
10320         kfree(config->save_connector_encoders);
10321         kfree(config->save_encoder_crtcs);
10322         kfree(config->save_crtc_enabled);
10323         kfree(config);
10324 }
10325
10326 static int intel_set_config_save_state(struct drm_device *dev,
10327                                        struct intel_set_config *config)
10328 {
10329         struct drm_crtc *crtc;
10330         struct drm_encoder *encoder;
10331         struct drm_connector *connector;
10332         int count;
10333
10334         config->save_crtc_enabled =
10335                 kcalloc(dev->mode_config.num_crtc,
10336                         sizeof(bool), GFP_KERNEL);
10337         if (!config->save_crtc_enabled)
10338                 return -ENOMEM;
10339
10340         config->save_encoder_crtcs =
10341                 kcalloc(dev->mode_config.num_encoder,
10342                         sizeof(struct drm_crtc *), GFP_KERNEL);
10343         if (!config->save_encoder_crtcs)
10344                 return -ENOMEM;
10345
10346         config->save_connector_encoders =
10347                 kcalloc(dev->mode_config.num_connector,
10348                         sizeof(struct drm_encoder *), GFP_KERNEL);
10349         if (!config->save_connector_encoders)
10350                 return -ENOMEM;
10351
10352         /* Copy data. Note that driver private data is not affected.
10353          * Should anything bad happen only the expected state is
10354          * restored, not the drivers personal bookkeeping.
10355          */
10356         count = 0;
10357         for_each_crtc(dev, crtc) {
10358                 config->save_crtc_enabled[count++] = crtc->enabled;
10359         }
10360
10361         count = 0;
10362         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
10363                 config->save_encoder_crtcs[count++] = encoder->crtc;
10364         }
10365
10366         count = 0;
10367         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10368                 config->save_connector_encoders[count++] = connector->encoder;
10369         }
10370
10371         return 0;
10372 }
10373
10374 static void intel_set_config_restore_state(struct drm_device *dev,
10375                                            struct intel_set_config *config)
10376 {
10377         struct intel_crtc *crtc;
10378         struct intel_encoder *encoder;
10379         struct intel_connector *connector;
10380         int count;
10381
10382         count = 0;
10383         for_each_intel_crtc(dev, crtc) {
10384                 crtc->new_enabled = config->save_crtc_enabled[count++];
10385
10386                 if (crtc->new_enabled)
10387                         crtc->new_config = &crtc->config;
10388                 else
10389                         crtc->new_config = NULL;
10390         }
10391
10392         count = 0;
10393         list_for_each_entry(encoder, &dev->mode_config.encoder_list, base.head) {
10394                 encoder->new_crtc =
10395                         to_intel_crtc(config->save_encoder_crtcs[count++]);
10396         }
10397
10398         count = 0;
10399         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
10400                 connector->new_encoder =
10401                         to_intel_encoder(config->save_connector_encoders[count++]);
10402         }
10403 }
10404
10405 static bool
10406 is_crtc_connector_off(struct drm_mode_set *set)
10407 {
10408         int i;
10409
10410         if (set->num_connectors == 0)
10411                 return false;
10412
10413         if (WARN_ON(set->connectors == NULL))
10414                 return false;
10415
10416         for (i = 0; i < set->num_connectors; i++)
10417                 if (set->connectors[i]->encoder &&
10418                     set->connectors[i]->encoder->crtc == set->crtc &&
10419                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
10420                         return true;
10421
10422         return false;
10423 }
10424
10425 static void
10426 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
10427                                       struct intel_set_config *config)
10428 {
10429
10430         /* We should be able to check here if the fb has the same properties
10431          * and then just flip_or_move it */
10432         if (is_crtc_connector_off(set)) {
10433                 config->mode_changed = true;
10434         } else if (set->crtc->primary->fb != set->fb) {
10435                 /* If we have no fb then treat it as a full mode set */
10436                 if (set->crtc->primary->fb == NULL) {
10437                         struct intel_crtc *intel_crtc =
10438                                 to_intel_crtc(set->crtc);
10439
10440                         if (intel_crtc->active && i915.fastboot) {
10441                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
10442                                 config->fb_changed = true;
10443                         } else {
10444                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
10445                                 config->mode_changed = true;
10446                         }
10447                 } else if (set->fb == NULL) {
10448                         config->mode_changed = true;
10449                 } else if (set->fb->pixel_format !=
10450                            set->crtc->primary->fb->pixel_format) {
10451                         config->mode_changed = true;
10452                 } else {
10453                         config->fb_changed = true;
10454                 }
10455         }
10456
10457         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
10458                 config->fb_changed = true;
10459
10460         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
10461                 DRM_DEBUG_KMS("modes are different, full mode set\n");
10462                 drm_mode_debug_printmodeline(&set->crtc->mode);
10463                 drm_mode_debug_printmodeline(set->mode);
10464                 config->mode_changed = true;
10465         }
10466
10467         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
10468                         set->crtc->base.id, config->mode_changed, config->fb_changed);
10469 }
10470
10471 static int
10472 intel_modeset_stage_output_state(struct drm_device *dev,
10473                                  struct drm_mode_set *set,
10474                                  struct intel_set_config *config)
10475 {
10476         struct intel_connector *connector;
10477         struct intel_encoder *encoder;
10478         struct intel_crtc *crtc;
10479         int ro;
10480
10481         /* The upper layers ensure that we either disable a crtc or have a list
10482          * of connectors. For paranoia, double-check this. */
10483         WARN_ON(!set->fb && (set->num_connectors != 0));
10484         WARN_ON(set->fb && (set->num_connectors == 0));
10485
10486         list_for_each_entry(connector, &dev->mode_config.connector_list,
10487                             base.head) {
10488                 /* Otherwise traverse passed in connector list and get encoders
10489                  * for them. */
10490                 for (ro = 0; ro < set->num_connectors; ro++) {
10491                         if (set->connectors[ro] == &connector->base) {
10492                                 connector->new_encoder = connector->encoder;
10493                                 break;
10494                         }
10495                 }
10496
10497                 /* If we disable the crtc, disable all its connectors. Also, if
10498                  * the connector is on the changing crtc but not on the new
10499                  * connector list, disable it. */
10500                 if ((!set->fb || ro == set->num_connectors) &&
10501                     connector->base.encoder &&
10502                     connector->base.encoder->crtc == set->crtc) {
10503                         connector->new_encoder = NULL;
10504
10505                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
10506                                 connector->base.base.id,
10507                                 drm_get_connector_name(&connector->base));
10508                 }
10509
10510
10511                 if (&connector->new_encoder->base != connector->base.encoder) {
10512                         DRM_DEBUG_KMS("encoder changed, full mode switch\n");
10513                         config->mode_changed = true;
10514                 }
10515         }
10516         /* connector->new_encoder is now updated for all connectors. */
10517
10518         /* Update crtc of enabled connectors. */
10519         list_for_each_entry(connector, &dev->mode_config.connector_list,
10520                             base.head) {
10521                 struct drm_crtc *new_crtc;
10522
10523                 if (!connector->new_encoder)
10524                         continue;
10525
10526                 new_crtc = connector->new_encoder->base.crtc;
10527
10528                 for (ro = 0; ro < set->num_connectors; ro++) {
10529                         if (set->connectors[ro] == &connector->base)
10530                                 new_crtc = set->crtc;
10531                 }
10532
10533                 /* Make sure the new CRTC will work with the encoder */
10534                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
10535                                          new_crtc)) {
10536                         return -EINVAL;
10537                 }
10538                 connector->encoder->new_crtc = to_intel_crtc(new_crtc);
10539
10540                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
10541                         connector->base.base.id,
10542                         drm_get_connector_name(&connector->base),
10543                         new_crtc->base.id);
10544         }
10545
10546         /* Check for any encoders that needs to be disabled. */
10547         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
10548                             base.head) {
10549                 int num_connectors = 0;
10550                 list_for_each_entry(connector,
10551                                     &dev->mode_config.connector_list,
10552                                     base.head) {
10553                         if (connector->new_encoder == encoder) {
10554                                 WARN_ON(!connector->new_encoder->new_crtc);
10555                                 num_connectors++;
10556                         }
10557                 }
10558
10559                 if (num_connectors == 0)
10560                         encoder->new_crtc = NULL;
10561                 else if (num_connectors > 1)
10562                         return -EINVAL;
10563
10564                 /* Only now check for crtc changes so we don't miss encoders
10565                  * that will be disabled. */
10566                 if (&encoder->new_crtc->base != encoder->base.crtc) {
10567                         DRM_DEBUG_KMS("crtc changed, full mode switch\n");
10568                         config->mode_changed = true;
10569                 }
10570         }
10571         /* Now we've also updated encoder->new_crtc for all encoders. */
10572
10573         for_each_intel_crtc(dev, crtc) {
10574                 crtc->new_enabled = false;
10575
10576                 list_for_each_entry(encoder,
10577                                     &dev->mode_config.encoder_list,
10578                                     base.head) {
10579                         if (encoder->new_crtc == crtc) {
10580                                 crtc->new_enabled = true;
10581                                 break;
10582                         }
10583                 }
10584
10585                 if (crtc->new_enabled != crtc->base.enabled) {
10586                         DRM_DEBUG_KMS("crtc %sabled, full mode switch\n",
10587                                       crtc->new_enabled ? "en" : "dis");
10588                         config->mode_changed = true;
10589                 }
10590
10591                 if (crtc->new_enabled)
10592                         crtc->new_config = &crtc->config;
10593                 else
10594                         crtc->new_config = NULL;
10595         }
10596
10597         return 0;
10598 }
10599
10600 static void disable_crtc_nofb(struct intel_crtc *crtc)
10601 {
10602         struct drm_device *dev = crtc->base.dev;
10603         struct intel_encoder *encoder;
10604         struct intel_connector *connector;
10605
10606         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
10607                       pipe_name(crtc->pipe));
10608
10609         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
10610                 if (connector->new_encoder &&
10611                     connector->new_encoder->new_crtc == crtc)
10612                         connector->new_encoder = NULL;
10613         }
10614
10615         list_for_each_entry(encoder, &dev->mode_config.encoder_list, base.head) {
10616                 if (encoder->new_crtc == crtc)
10617                         encoder->new_crtc = NULL;
10618         }
10619
10620         crtc->new_enabled = false;
10621         crtc->new_config = NULL;
10622 }
10623
10624 static int intel_crtc_set_config(struct drm_mode_set *set)
10625 {
10626         struct drm_device *dev;
10627         struct drm_mode_set save_set;
10628         struct intel_set_config *config;
10629         int ret;
10630
10631         BUG_ON(!set);
10632         BUG_ON(!set->crtc);
10633         BUG_ON(!set->crtc->helper_private);
10634
10635         /* Enforce sane interface api - has been abused by the fb helper. */
10636         BUG_ON(!set->mode && set->fb);
10637         BUG_ON(set->fb && set->num_connectors == 0);
10638
10639         if (set->fb) {
10640                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
10641                                 set->crtc->base.id, set->fb->base.id,
10642                                 (int)set->num_connectors, set->x, set->y);
10643         } else {
10644                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
10645         }
10646
10647         dev = set->crtc->dev;
10648
10649         ret = -ENOMEM;
10650         config = kzalloc(sizeof(*config), GFP_KERNEL);
10651         if (!config)
10652                 goto out_config;
10653
10654         ret = intel_set_config_save_state(dev, config);
10655         if (ret)
10656                 goto out_config;
10657
10658         save_set.crtc = set->crtc;
10659         save_set.mode = &set->crtc->mode;
10660         save_set.x = set->crtc->x;
10661         save_set.y = set->crtc->y;
10662         save_set.fb = set->crtc->primary->fb;
10663
10664         /* Compute whether we need a full modeset, only an fb base update or no
10665          * change at all. In the future we might also check whether only the
10666          * mode changed, e.g. for LVDS where we only change the panel fitter in
10667          * such cases. */
10668         intel_set_config_compute_mode_changes(set, config);
10669
10670         ret = intel_modeset_stage_output_state(dev, set, config);
10671         if (ret)
10672                 goto fail;
10673
10674         if (config->mode_changed) {
10675                 ret = intel_set_mode(set->crtc, set->mode,
10676                                      set->x, set->y, set->fb);
10677         } else if (config->fb_changed) {
10678                 intel_crtc_wait_for_pending_flips(set->crtc);
10679
10680                 ret = intel_pipe_set_base(set->crtc,
10681                                           set->x, set->y, set->fb);
10682                 /*
10683                  * In the fastboot case this may be our only check of the
10684                  * state after boot.  It would be better to only do it on
10685                  * the first update, but we don't have a nice way of doing that
10686                  * (and really, set_config isn't used much for high freq page
10687                  * flipping, so increasing its cost here shouldn't be a big
10688                  * deal).
10689                  */
10690                 if (i915.fastboot && ret == 0)
10691                         intel_modeset_check_state(set->crtc->dev);
10692         }
10693
10694         if (ret) {
10695                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
10696                               set->crtc->base.id, ret);
10697 fail:
10698                 intel_set_config_restore_state(dev, config);
10699
10700                 /*
10701                  * HACK: if the pipe was on, but we didn't have a framebuffer,
10702                  * force the pipe off to avoid oopsing in the modeset code
10703                  * due to fb==NULL. This should only happen during boot since
10704                  * we don't yet reconstruct the FB from the hardware state.
10705                  */
10706                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
10707                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
10708
10709                 /* Try to restore the config */
10710                 if (config->mode_changed &&
10711                     intel_set_mode(save_set.crtc, save_set.mode,
10712                                    save_set.x, save_set.y, save_set.fb))
10713                         DRM_ERROR("failed to restore config after modeset failure\n");
10714         }
10715
10716 out_config:
10717         intel_set_config_free(config);
10718         return ret;
10719 }
10720
10721 static const struct drm_crtc_funcs intel_crtc_funcs = {
10722         .cursor_set = intel_crtc_cursor_set,
10723         .cursor_move = intel_crtc_cursor_move,
10724         .gamma_set = intel_crtc_gamma_set,
10725         .set_config = intel_crtc_set_config,
10726         .destroy = intel_crtc_destroy,
10727         .page_flip = intel_crtc_page_flip,
10728 };
10729
10730 static void intel_cpu_pll_init(struct drm_device *dev)
10731 {
10732         if (HAS_DDI(dev))
10733                 intel_ddi_pll_init(dev);
10734 }
10735
10736 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
10737                                       struct intel_shared_dpll *pll,
10738                                       struct intel_dpll_hw_state *hw_state)
10739 {
10740         uint32_t val;
10741
10742         val = I915_READ(PCH_DPLL(pll->id));
10743         hw_state->dpll = val;
10744         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
10745         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
10746
10747         return val & DPLL_VCO_ENABLE;
10748 }
10749
10750 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
10751                                   struct intel_shared_dpll *pll)
10752 {
10753         I915_WRITE(PCH_FP0(pll->id), pll->hw_state.fp0);
10754         I915_WRITE(PCH_FP1(pll->id), pll->hw_state.fp1);
10755 }
10756
10757 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
10758                                 struct intel_shared_dpll *pll)
10759 {
10760         /* PCH refclock must be enabled first */
10761         ibx_assert_pch_refclk_enabled(dev_priv);
10762
10763         I915_WRITE(PCH_DPLL(pll->id), pll->hw_state.dpll);
10764
10765         /* Wait for the clocks to stabilize. */
10766         POSTING_READ(PCH_DPLL(pll->id));
10767         udelay(150);
10768
10769         /* The pixel multiplier can only be updated once the
10770          * DPLL is enabled and the clocks are stable.
10771          *
10772          * So write it again.
10773          */
10774         I915_WRITE(PCH_DPLL(pll->id), pll->hw_state.dpll);
10775         POSTING_READ(PCH_DPLL(pll->id));
10776         udelay(200);
10777 }
10778
10779 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
10780                                  struct intel_shared_dpll *pll)
10781 {
10782         struct drm_device *dev = dev_priv->dev;
10783         struct intel_crtc *crtc;
10784
10785         /* Make sure no transcoder isn't still depending on us. */
10786         for_each_intel_crtc(dev, crtc) {
10787                 if (intel_crtc_to_shared_dpll(crtc) == pll)
10788                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
10789         }
10790
10791         I915_WRITE(PCH_DPLL(pll->id), 0);
10792         POSTING_READ(PCH_DPLL(pll->id));
10793         udelay(200);
10794 }
10795
10796 static char *ibx_pch_dpll_names[] = {
10797         "PCH DPLL A",
10798         "PCH DPLL B",
10799 };
10800
10801 static void ibx_pch_dpll_init(struct drm_device *dev)
10802 {
10803         struct drm_i915_private *dev_priv = dev->dev_private;
10804         int i;
10805
10806         dev_priv->num_shared_dpll = 2;
10807
10808         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
10809                 dev_priv->shared_dplls[i].id = i;
10810                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
10811                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
10812                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
10813                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
10814                 dev_priv->shared_dplls[i].get_hw_state =
10815                         ibx_pch_dpll_get_hw_state;
10816         }
10817 }
10818
10819 static void intel_shared_dpll_init(struct drm_device *dev)
10820 {
10821         struct drm_i915_private *dev_priv = dev->dev_private;
10822
10823         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
10824                 ibx_pch_dpll_init(dev);
10825         else
10826                 dev_priv->num_shared_dpll = 0;
10827
10828         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
10829 }
10830
10831 static void intel_crtc_init(struct drm_device *dev, int pipe)
10832 {
10833         struct drm_i915_private *dev_priv = dev->dev_private;
10834         struct intel_crtc *intel_crtc;
10835         int i;
10836
10837         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
10838         if (intel_crtc == NULL)
10839                 return;
10840
10841         drm_crtc_init(dev, &intel_crtc->base, &intel_crtc_funcs);
10842
10843         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
10844         for (i = 0; i < 256; i++) {
10845                 intel_crtc->lut_r[i] = i;
10846                 intel_crtc->lut_g[i] = i;
10847                 intel_crtc->lut_b[i] = i;
10848         }
10849
10850         /*
10851          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
10852          * is hooked to plane B. Hence we want plane A feeding pipe B.
10853          */
10854         intel_crtc->pipe = pipe;
10855         intel_crtc->plane = pipe;
10856         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
10857                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
10858                 intel_crtc->plane = !pipe;
10859         }
10860
10861         init_waitqueue_head(&intel_crtc->vbl_wait);
10862
10863         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
10864                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
10865         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
10866         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
10867
10868         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
10869 }
10870
10871 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
10872 {
10873         struct drm_encoder *encoder = connector->base.encoder;
10874
10875         WARN_ON(!mutex_is_locked(&connector->base.dev->mode_config.mutex));
10876
10877         if (!encoder)
10878                 return INVALID_PIPE;
10879
10880         return to_intel_crtc(encoder->crtc)->pipe;
10881 }
10882
10883 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
10884                                 struct drm_file *file)
10885 {
10886         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
10887         struct drm_mode_object *drmmode_obj;
10888         struct intel_crtc *crtc;
10889
10890         if (!drm_core_check_feature(dev, DRIVER_MODESET))
10891                 return -ENODEV;
10892
10893         drmmode_obj = drm_mode_object_find(dev, pipe_from_crtc_id->crtc_id,
10894                         DRM_MODE_OBJECT_CRTC);
10895
10896         if (!drmmode_obj) {
10897                 DRM_ERROR("no such CRTC id\n");
10898                 return -ENOENT;
10899         }
10900
10901         crtc = to_intel_crtc(obj_to_crtc(drmmode_obj));
10902         pipe_from_crtc_id->pipe = crtc->pipe;
10903
10904         return 0;
10905 }
10906
10907 static int intel_encoder_clones(struct intel_encoder *encoder)
10908 {
10909         struct drm_device *dev = encoder->base.dev;
10910         struct intel_encoder *source_encoder;
10911         int index_mask = 0;
10912         int entry = 0;
10913
10914         list_for_each_entry(source_encoder,
10915                             &dev->mode_config.encoder_list, base.head) {
10916                 if (encoders_cloneable(encoder, source_encoder))
10917                         index_mask |= (1 << entry);
10918
10919                 entry++;
10920         }
10921
10922         return index_mask;
10923 }
10924
10925 static bool has_edp_a(struct drm_device *dev)
10926 {
10927         struct drm_i915_private *dev_priv = dev->dev_private;
10928
10929         if (!IS_MOBILE(dev))
10930                 return false;
10931
10932         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
10933                 return false;
10934
10935         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
10936                 return false;
10937
10938         return true;
10939 }
10940
10941 const char *intel_output_name(int output)
10942 {
10943         static const char *names[] = {
10944                 [INTEL_OUTPUT_UNUSED] = "Unused",
10945                 [INTEL_OUTPUT_ANALOG] = "Analog",
10946                 [INTEL_OUTPUT_DVO] = "DVO",
10947                 [INTEL_OUTPUT_SDVO] = "SDVO",
10948                 [INTEL_OUTPUT_LVDS] = "LVDS",
10949                 [INTEL_OUTPUT_TVOUT] = "TV",
10950                 [INTEL_OUTPUT_HDMI] = "HDMI",
10951                 [INTEL_OUTPUT_DISPLAYPORT] = "DisplayPort",
10952                 [INTEL_OUTPUT_EDP] = "eDP",
10953                 [INTEL_OUTPUT_DSI] = "DSI",
10954                 [INTEL_OUTPUT_UNKNOWN] = "Unknown",
10955         };
10956
10957         if (output < 0 || output >= ARRAY_SIZE(names) || !names[output])
10958                 return "Invalid";
10959
10960         return names[output];
10961 }
10962
10963 static void intel_setup_outputs(struct drm_device *dev)
10964 {
10965         struct drm_i915_private *dev_priv = dev->dev_private;
10966         struct intel_encoder *encoder;
10967         bool dpd_is_edp = false;
10968
10969         intel_lvds_init(dev);
10970
10971         if (!IS_ULT(dev) && !IS_CHERRYVIEW(dev))
10972                 intel_crt_init(dev);
10973
10974         if (HAS_DDI(dev)) {
10975                 int found;
10976
10977                 /* Haswell uses DDI functions to detect digital outputs */
10978                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
10979                 /* DDI A only supports eDP */
10980                 if (found)
10981                         intel_ddi_init(dev, PORT_A);
10982
10983                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
10984                  * register */
10985                 found = I915_READ(SFUSE_STRAP);
10986
10987                 if (found & SFUSE_STRAP_DDIB_DETECTED)
10988                         intel_ddi_init(dev, PORT_B);
10989                 if (found & SFUSE_STRAP_DDIC_DETECTED)
10990                         intel_ddi_init(dev, PORT_C);
10991                 if (found & SFUSE_STRAP_DDID_DETECTED)
10992                         intel_ddi_init(dev, PORT_D);
10993         } else if (HAS_PCH_SPLIT(dev)) {
10994                 int found;
10995                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
10996
10997                 if (has_edp_a(dev))
10998                         intel_dp_init(dev, DP_A, PORT_A);
10999
11000                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
11001                         /* PCH SDVOB multiplex with HDMIB */
11002                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
11003                         if (!found)
11004                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
11005                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
11006                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
11007                 }
11008
11009                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
11010                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
11011
11012                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
11013                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
11014
11015                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
11016                         intel_dp_init(dev, PCH_DP_C, PORT_C);
11017
11018                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
11019                         intel_dp_init(dev, PCH_DP_D, PORT_D);
11020         } else if (IS_VALLEYVIEW(dev)) {
11021                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED) {
11022                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
11023                                         PORT_B);
11024                         if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED)
11025                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
11026                 }
11027
11028                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED) {
11029                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
11030                                         PORT_C);
11031                         if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED)
11032                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
11033                 }
11034
11035                 intel_dsi_init(dev);
11036         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
11037                 bool found = false;
11038
11039                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
11040                         DRM_DEBUG_KMS("probing SDVOB\n");
11041                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
11042                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
11043                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
11044                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
11045                         }
11046
11047                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
11048                                 intel_dp_init(dev, DP_B, PORT_B);
11049                 }
11050
11051                 /* Before G4X SDVOC doesn't have its own detect register */
11052
11053                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
11054                         DRM_DEBUG_KMS("probing SDVOC\n");
11055                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
11056                 }
11057
11058                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
11059
11060                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
11061                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
11062                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
11063                         }
11064                         if (SUPPORTS_INTEGRATED_DP(dev))
11065                                 intel_dp_init(dev, DP_C, PORT_C);
11066                 }
11067
11068                 if (SUPPORTS_INTEGRATED_DP(dev) &&
11069                     (I915_READ(DP_D) & DP_DETECTED))
11070                         intel_dp_init(dev, DP_D, PORT_D);
11071         } else if (IS_GEN2(dev))
11072                 intel_dvo_init(dev);
11073
11074         if (SUPPORTS_TV(dev))
11075                 intel_tv_init(dev);
11076
11077         list_for_each_entry(encoder, &dev->mode_config.encoder_list, base.head) {
11078                 encoder->base.possible_crtcs = encoder->crtc_mask;
11079                 encoder->base.possible_clones =
11080                         intel_encoder_clones(encoder);
11081         }
11082
11083         intel_init_pch_refclk(dev);
11084
11085         drm_helper_move_panel_connectors_to_head(dev);
11086 }
11087
11088 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
11089 {
11090         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
11091
11092         drm_framebuffer_cleanup(fb);
11093         WARN_ON(!intel_fb->obj->framebuffer_references--);
11094         drm_gem_object_unreference_unlocked(&intel_fb->obj->base);
11095         kfree(intel_fb);
11096 }
11097
11098 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
11099                                                 struct drm_file *file,
11100                                                 unsigned int *handle)
11101 {
11102         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
11103         struct drm_i915_gem_object *obj = intel_fb->obj;
11104
11105         return drm_gem_handle_create(file, &obj->base, handle);
11106 }
11107
11108 static const struct drm_framebuffer_funcs intel_fb_funcs = {
11109         .destroy = intel_user_framebuffer_destroy,
11110         .create_handle = intel_user_framebuffer_create_handle,
11111 };
11112
11113 static int intel_framebuffer_init(struct drm_device *dev,
11114                                   struct intel_framebuffer *intel_fb,
11115                                   struct drm_mode_fb_cmd2 *mode_cmd,
11116                                   struct drm_i915_gem_object *obj)
11117 {
11118         int aligned_height;
11119         int pitch_limit;
11120         int ret;
11121
11122         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
11123
11124         if (obj->tiling_mode == I915_TILING_Y) {
11125                 DRM_DEBUG("hardware does not support tiling Y\n");
11126                 return -EINVAL;
11127         }
11128
11129         if (mode_cmd->pitches[0] & 63) {
11130                 DRM_DEBUG("pitch (%d) must be at least 64 byte aligned\n",
11131                           mode_cmd->pitches[0]);
11132                 return -EINVAL;
11133         }
11134
11135         if (INTEL_INFO(dev)->gen >= 5 && !IS_VALLEYVIEW(dev)) {
11136                 pitch_limit = 32*1024;
11137         } else if (INTEL_INFO(dev)->gen >= 4) {
11138                 if (obj->tiling_mode)
11139                         pitch_limit = 16*1024;
11140                 else
11141                         pitch_limit = 32*1024;
11142         } else if (INTEL_INFO(dev)->gen >= 3) {
11143                 if (obj->tiling_mode)
11144                         pitch_limit = 8*1024;
11145                 else
11146                         pitch_limit = 16*1024;
11147         } else
11148                 /* XXX DSPC is limited to 4k tiled */
11149                 pitch_limit = 8*1024;
11150
11151         if (mode_cmd->pitches[0] > pitch_limit) {
11152                 DRM_DEBUG("%s pitch (%d) must be at less than %d\n",
11153                           obj->tiling_mode ? "tiled" : "linear",
11154                           mode_cmd->pitches[0], pitch_limit);
11155                 return -EINVAL;
11156         }
11157
11158         if (obj->tiling_mode != I915_TILING_NONE &&
11159             mode_cmd->pitches[0] != obj->stride) {
11160                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
11161                           mode_cmd->pitches[0], obj->stride);
11162                 return -EINVAL;
11163         }
11164
11165         /* Reject formats not supported by any plane early. */
11166         switch (mode_cmd->pixel_format) {
11167         case DRM_FORMAT_C8:
11168         case DRM_FORMAT_RGB565:
11169         case DRM_FORMAT_XRGB8888:
11170         case DRM_FORMAT_ARGB8888:
11171                 break;
11172         case DRM_FORMAT_XRGB1555:
11173         case DRM_FORMAT_ARGB1555:
11174                 if (INTEL_INFO(dev)->gen > 3) {
11175                         DRM_DEBUG("unsupported pixel format: %s\n",
11176                                   drm_get_format_name(mode_cmd->pixel_format));
11177                         return -EINVAL;
11178                 }
11179                 break;
11180         case DRM_FORMAT_XBGR8888:
11181         case DRM_FORMAT_ABGR8888:
11182         case DRM_FORMAT_XRGB2101010:
11183         case DRM_FORMAT_ARGB2101010:
11184         case DRM_FORMAT_XBGR2101010:
11185         case DRM_FORMAT_ABGR2101010:
11186                 if (INTEL_INFO(dev)->gen < 4) {
11187                         DRM_DEBUG("unsupported pixel format: %s\n",
11188                                   drm_get_format_name(mode_cmd->pixel_format));
11189                         return -EINVAL;
11190                 }
11191                 break;
11192         case DRM_FORMAT_YUYV:
11193         case DRM_FORMAT_UYVY:
11194         case DRM_FORMAT_YVYU:
11195         case DRM_FORMAT_VYUY:
11196                 if (INTEL_INFO(dev)->gen < 5) {
11197                         DRM_DEBUG("unsupported pixel format: %s\n",
11198                                   drm_get_format_name(mode_cmd->pixel_format));
11199                         return -EINVAL;
11200                 }
11201                 break;
11202         default:
11203                 DRM_DEBUG("unsupported pixel format: %s\n",
11204                           drm_get_format_name(mode_cmd->pixel_format));
11205                 return -EINVAL;
11206         }
11207
11208         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
11209         if (mode_cmd->offsets[0] != 0)
11210                 return -EINVAL;
11211
11212         aligned_height = intel_align_height(dev, mode_cmd->height,
11213                                             obj->tiling_mode);
11214         /* FIXME drm helper for size checks (especially planar formats)? */
11215         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
11216                 return -EINVAL;
11217
11218         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
11219         intel_fb->obj = obj;
11220         intel_fb->obj->framebuffer_references++;
11221
11222         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
11223         if (ret) {
11224                 DRM_ERROR("framebuffer init failed %d\n", ret);
11225                 return ret;
11226         }
11227
11228         return 0;
11229 }
11230
11231 static struct drm_framebuffer *
11232 intel_user_framebuffer_create(struct drm_device *dev,
11233                               struct drm_file *filp,
11234                               struct drm_mode_fb_cmd2 *mode_cmd)
11235 {
11236         struct drm_i915_gem_object *obj;
11237
11238         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
11239                                                 mode_cmd->handles[0]));
11240         if (&obj->base == NULL)
11241                 return ERR_PTR(-ENOENT);
11242
11243         return intel_framebuffer_create(dev, mode_cmd, obj);
11244 }
11245
11246 #ifndef CONFIG_DRM_I915_FBDEV
11247 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
11248 {
11249 }
11250 #endif
11251
11252 static const struct drm_mode_config_funcs intel_mode_funcs = {
11253         .fb_create = intel_user_framebuffer_create,
11254         .output_poll_changed = intel_fbdev_output_poll_changed,
11255 };
11256
11257 /* Set up chip specific display functions */
11258 static void intel_init_display(struct drm_device *dev)
11259 {
11260         struct drm_i915_private *dev_priv = dev->dev_private;
11261
11262         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
11263                 dev_priv->display.find_dpll = g4x_find_best_dpll;
11264         else if (IS_CHERRYVIEW(dev))
11265                 dev_priv->display.find_dpll = chv_find_best_dpll;
11266         else if (IS_VALLEYVIEW(dev))
11267                 dev_priv->display.find_dpll = vlv_find_best_dpll;
11268         else if (IS_PINEVIEW(dev))
11269                 dev_priv->display.find_dpll = pnv_find_best_dpll;
11270         else
11271                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
11272
11273         if (HAS_DDI(dev)) {
11274                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
11275                 dev_priv->display.get_plane_config = ironlake_get_plane_config;
11276                 dev_priv->display.crtc_mode_set = haswell_crtc_mode_set;
11277                 dev_priv->display.crtc_enable = haswell_crtc_enable;
11278                 dev_priv->display.crtc_disable = haswell_crtc_disable;
11279                 dev_priv->display.off = haswell_crtc_off;
11280                 dev_priv->display.update_primary_plane =
11281                         ironlake_update_primary_plane;
11282         } else if (HAS_PCH_SPLIT(dev)) {
11283                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
11284                 dev_priv->display.get_plane_config = ironlake_get_plane_config;
11285                 dev_priv->display.crtc_mode_set = ironlake_crtc_mode_set;
11286                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
11287                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
11288                 dev_priv->display.off = ironlake_crtc_off;
11289                 dev_priv->display.update_primary_plane =
11290                         ironlake_update_primary_plane;
11291         } else if (IS_VALLEYVIEW(dev)) {
11292                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
11293                 dev_priv->display.get_plane_config = i9xx_get_plane_config;
11294                 dev_priv->display.crtc_mode_set = i9xx_crtc_mode_set;
11295                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
11296                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
11297                 dev_priv->display.off = i9xx_crtc_off;
11298                 dev_priv->display.update_primary_plane =
11299                         i9xx_update_primary_plane;
11300         } else {
11301                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
11302                 dev_priv->display.get_plane_config = i9xx_get_plane_config;
11303                 dev_priv->display.crtc_mode_set = i9xx_crtc_mode_set;
11304                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
11305                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
11306                 dev_priv->display.off = i9xx_crtc_off;
11307                 dev_priv->display.update_primary_plane =
11308                         i9xx_update_primary_plane;
11309         }
11310
11311         /* Returns the core display clock speed */
11312         if (IS_VALLEYVIEW(dev))
11313                 dev_priv->display.get_display_clock_speed =
11314                         valleyview_get_display_clock_speed;
11315         else if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
11316                 dev_priv->display.get_display_clock_speed =
11317                         i945_get_display_clock_speed;
11318         else if (IS_I915G(dev))
11319                 dev_priv->display.get_display_clock_speed =
11320                         i915_get_display_clock_speed;
11321         else if (IS_I945GM(dev) || IS_845G(dev))
11322                 dev_priv->display.get_display_clock_speed =
11323                         i9xx_misc_get_display_clock_speed;
11324         else if (IS_PINEVIEW(dev))
11325                 dev_priv->display.get_display_clock_speed =
11326                         pnv_get_display_clock_speed;
11327         else if (IS_I915GM(dev))
11328                 dev_priv->display.get_display_clock_speed =
11329                         i915gm_get_display_clock_speed;
11330         else if (IS_I865G(dev))
11331                 dev_priv->display.get_display_clock_speed =
11332                         i865_get_display_clock_speed;
11333         else if (IS_I85X(dev))
11334                 dev_priv->display.get_display_clock_speed =
11335                         i855_get_display_clock_speed;
11336         else /* 852, 830 */
11337                 dev_priv->display.get_display_clock_speed =
11338                         i830_get_display_clock_speed;
11339
11340         if (HAS_PCH_SPLIT(dev)) {
11341                 if (IS_GEN5(dev)) {
11342                         dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
11343                         dev_priv->display.write_eld = ironlake_write_eld;
11344                 } else if (IS_GEN6(dev)) {
11345                         dev_priv->display.fdi_link_train = gen6_fdi_link_train;
11346                         dev_priv->display.write_eld = ironlake_write_eld;
11347                         dev_priv->display.modeset_global_resources =
11348                                 snb_modeset_global_resources;
11349                 } else if (IS_IVYBRIDGE(dev)) {
11350                         /* FIXME: detect B0+ stepping and use auto training */
11351                         dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
11352                         dev_priv->display.write_eld = ironlake_write_eld;
11353                         dev_priv->display.modeset_global_resources =
11354                                 ivb_modeset_global_resources;
11355                 } else if (IS_HASWELL(dev) || IS_GEN8(dev)) {
11356                         dev_priv->display.fdi_link_train = hsw_fdi_link_train;
11357                         dev_priv->display.write_eld = haswell_write_eld;
11358                         dev_priv->display.modeset_global_resources =
11359                                 haswell_modeset_global_resources;
11360                 }
11361         } else if (IS_G4X(dev)) {
11362                 dev_priv->display.write_eld = g4x_write_eld;
11363         } else if (IS_VALLEYVIEW(dev)) {
11364                 dev_priv->display.modeset_global_resources =
11365                         valleyview_modeset_global_resources;
11366                 dev_priv->display.write_eld = ironlake_write_eld;
11367         }
11368
11369         /* Default just returns -ENODEV to indicate unsupported */
11370         dev_priv->display.queue_flip = intel_default_queue_flip;
11371
11372         switch (INTEL_INFO(dev)->gen) {
11373         case 2:
11374                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
11375                 break;
11376
11377         case 3:
11378                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
11379                 break;
11380
11381         case 4:
11382         case 5:
11383                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
11384                 break;
11385
11386         case 6:
11387                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
11388                 break;
11389         case 7:
11390         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
11391                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
11392                 break;
11393         }
11394
11395         intel_panel_init_backlight_funcs(dev);
11396 }
11397
11398 /*
11399  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
11400  * resume, or other times.  This quirk makes sure that's the case for
11401  * affected systems.
11402  */
11403 static void quirk_pipea_force(struct drm_device *dev)
11404 {
11405         struct drm_i915_private *dev_priv = dev->dev_private;
11406
11407         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
11408         DRM_INFO("applying pipe a force quirk\n");
11409 }
11410
11411 /*
11412  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
11413  */
11414 static void quirk_ssc_force_disable(struct drm_device *dev)
11415 {
11416         struct drm_i915_private *dev_priv = dev->dev_private;
11417         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
11418         DRM_INFO("applying lvds SSC disable quirk\n");
11419 }
11420
11421 /*
11422  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
11423  * brightness value
11424  */
11425 static void quirk_invert_brightness(struct drm_device *dev)
11426 {
11427         struct drm_i915_private *dev_priv = dev->dev_private;
11428         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
11429         DRM_INFO("applying inverted panel brightness quirk\n");
11430 }
11431
11432 struct intel_quirk {
11433         int device;
11434         int subsystem_vendor;
11435         int subsystem_device;
11436         void (*hook)(struct drm_device *dev);
11437 };
11438
11439 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
11440 struct intel_dmi_quirk {
11441         void (*hook)(struct drm_device *dev);
11442         const struct dmi_system_id (*dmi_id_list)[];
11443 };
11444
11445 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
11446 {
11447         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
11448         return 1;
11449 }
11450
11451 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
11452         {
11453                 .dmi_id_list = &(const struct dmi_system_id[]) {
11454                         {
11455                                 .callback = intel_dmi_reverse_brightness,
11456                                 .ident = "NCR Corporation",
11457                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
11458                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
11459                                 },
11460                         },
11461                         { }  /* terminating entry */
11462                 },
11463                 .hook = quirk_invert_brightness,
11464         },
11465 };
11466
11467 static struct intel_quirk intel_quirks[] = {
11468         /* HP Mini needs pipe A force quirk (LP: #322104) */
11469         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
11470
11471         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
11472         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
11473
11474         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
11475         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
11476
11477         /* 830 needs to leave pipe A & dpll A up */
11478         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
11479
11480         /* Lenovo U160 cannot use SSC on LVDS */
11481         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
11482
11483         /* Sony Vaio Y cannot use SSC on LVDS */
11484         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
11485
11486         /* Acer Aspire 5734Z must invert backlight brightness */
11487         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
11488
11489         /* Acer/eMachines G725 */
11490         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
11491
11492         /* Acer/eMachines e725 */
11493         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
11494
11495         /* Acer/Packard Bell NCL20 */
11496         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
11497
11498         /* Acer Aspire 4736Z */
11499         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
11500
11501         /* Acer Aspire 5336 */
11502         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
11503 };
11504
11505 static void intel_init_quirks(struct drm_device *dev)
11506 {
11507         struct pci_dev *d = dev->pdev;
11508         int i;
11509
11510         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
11511                 struct intel_quirk *q = &intel_quirks[i];
11512
11513                 if (d->device == q->device &&
11514                     (d->subsystem_vendor == q->subsystem_vendor ||
11515                      q->subsystem_vendor == PCI_ANY_ID) &&
11516                     (d->subsystem_device == q->subsystem_device ||
11517                      q->subsystem_device == PCI_ANY_ID))
11518                         q->hook(dev);
11519         }
11520         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
11521                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
11522                         intel_dmi_quirks[i].hook(dev);
11523         }
11524 }
11525
11526 /* Disable the VGA plane that we never use */
11527 static void i915_disable_vga(struct drm_device *dev)
11528 {
11529         struct drm_i915_private *dev_priv = dev->dev_private;
11530         u8 sr1;
11531         u32 vga_reg = i915_vgacntrl_reg(dev);
11532
11533         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
11534         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
11535         outb(SR01, VGA_SR_INDEX);
11536         sr1 = inb(VGA_SR_DATA);
11537         outb(sr1 | 1<<5, VGA_SR_DATA);
11538         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
11539         udelay(300);
11540
11541         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
11542         POSTING_READ(vga_reg);
11543 }
11544
11545 void intel_modeset_init_hw(struct drm_device *dev)
11546 {
11547         intel_prepare_ddi(dev);
11548
11549         intel_init_clock_gating(dev);
11550
11551         intel_reset_dpio(dev);
11552
11553         intel_enable_gt_powersave(dev);
11554 }
11555
11556 void intel_modeset_suspend_hw(struct drm_device *dev)
11557 {
11558         intel_suspend_hw(dev);
11559 }
11560
11561 void intel_modeset_init(struct drm_device *dev)
11562 {
11563         struct drm_i915_private *dev_priv = dev->dev_private;
11564         int sprite, ret;
11565         enum pipe pipe;
11566         struct intel_crtc *crtc;
11567
11568         drm_mode_config_init(dev);
11569
11570         dev->mode_config.min_width = 0;
11571         dev->mode_config.min_height = 0;
11572
11573         dev->mode_config.preferred_depth = 24;
11574         dev->mode_config.prefer_shadow = 1;
11575
11576         dev->mode_config.funcs = &intel_mode_funcs;
11577
11578         intel_init_quirks(dev);
11579
11580         intel_init_pm(dev);
11581
11582         if (INTEL_INFO(dev)->num_pipes == 0)
11583                 return;
11584
11585         intel_init_display(dev);
11586
11587         if (IS_GEN2(dev)) {
11588                 dev->mode_config.max_width = 2048;
11589                 dev->mode_config.max_height = 2048;
11590         } else if (IS_GEN3(dev)) {
11591                 dev->mode_config.max_width = 4096;
11592                 dev->mode_config.max_height = 4096;
11593         } else {
11594                 dev->mode_config.max_width = 8192;
11595                 dev->mode_config.max_height = 8192;
11596         }
11597
11598         if (IS_GEN2(dev)) {
11599                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
11600                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
11601         } else {
11602                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
11603                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
11604         }
11605
11606         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
11607
11608         DRM_DEBUG_KMS("%d display pipe%s available.\n",
11609                       INTEL_INFO(dev)->num_pipes,
11610                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
11611
11612         for_each_pipe(pipe) {
11613                 intel_crtc_init(dev, pipe);
11614                 for_each_sprite(pipe, sprite) {
11615                         ret = intel_plane_init(dev, pipe, sprite);
11616                         if (ret)
11617                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
11618                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
11619                 }
11620         }
11621
11622         intel_init_dpio(dev);
11623         intel_reset_dpio(dev);
11624
11625         intel_cpu_pll_init(dev);
11626         intel_shared_dpll_init(dev);
11627
11628         /* Just disable it once at startup */
11629         i915_disable_vga(dev);
11630         intel_setup_outputs(dev);
11631
11632         /* Just in case the BIOS is doing something questionable. */
11633         intel_disable_fbc(dev);
11634
11635         mutex_lock(&dev->mode_config.mutex);
11636         intel_modeset_setup_hw_state(dev, false);
11637         mutex_unlock(&dev->mode_config.mutex);
11638
11639         for_each_intel_crtc(dev, crtc) {
11640                 if (!crtc->active)
11641                         continue;
11642
11643                 /*
11644                  * Note that reserving the BIOS fb up front prevents us
11645                  * from stuffing other stolen allocations like the ring
11646                  * on top.  This prevents some ugliness at boot time, and
11647                  * can even allow for smooth boot transitions if the BIOS
11648                  * fb is large enough for the active pipe configuration.
11649                  */
11650                 if (dev_priv->display.get_plane_config) {
11651                         dev_priv->display.get_plane_config(crtc,
11652                                                            &crtc->plane_config);
11653                         /*
11654                          * If the fb is shared between multiple heads, we'll
11655                          * just get the first one.
11656                          */
11657                         intel_find_plane_obj(crtc, &crtc->plane_config);
11658                 }
11659         }
11660 }
11661
11662 static void
11663 intel_connector_break_all_links(struct intel_connector *connector)
11664 {
11665         connector->base.dpms = DRM_MODE_DPMS_OFF;
11666         connector->base.encoder = NULL;
11667         connector->encoder->connectors_active = false;
11668         connector->encoder->base.crtc = NULL;
11669 }
11670
11671 static void intel_enable_pipe_a(struct drm_device *dev)
11672 {
11673         struct intel_connector *connector;
11674         struct drm_connector *crt = NULL;
11675         struct intel_load_detect_pipe load_detect_temp;
11676
11677         /* We can't just switch on the pipe A, we need to set things up with a
11678          * proper mode and output configuration. As a gross hack, enable pipe A
11679          * by enabling the load detect pipe once. */
11680         list_for_each_entry(connector,
11681                             &dev->mode_config.connector_list,
11682                             base.head) {
11683                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
11684                         crt = &connector->base;
11685                         break;
11686                 }
11687         }
11688
11689         if (!crt)
11690                 return;
11691
11692         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp))
11693                 intel_release_load_detect_pipe(crt, &load_detect_temp);
11694
11695
11696 }
11697
11698 static bool
11699 intel_check_plane_mapping(struct intel_crtc *crtc)
11700 {
11701         struct drm_device *dev = crtc->base.dev;
11702         struct drm_i915_private *dev_priv = dev->dev_private;
11703         u32 reg, val;
11704
11705         if (INTEL_INFO(dev)->num_pipes == 1)
11706                 return true;
11707
11708         reg = DSPCNTR(!crtc->plane);
11709         val = I915_READ(reg);
11710
11711         if ((val & DISPLAY_PLANE_ENABLE) &&
11712             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
11713                 return false;
11714
11715         return true;
11716 }
11717
11718 static void intel_sanitize_crtc(struct intel_crtc *crtc)
11719 {
11720         struct drm_device *dev = crtc->base.dev;
11721         struct drm_i915_private *dev_priv = dev->dev_private;
11722         u32 reg;
11723
11724         /* Clear any frame start delays used for debugging left by the BIOS */
11725         reg = PIPECONF(crtc->config.cpu_transcoder);
11726         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
11727
11728         /* We need to sanitize the plane -> pipe mapping first because this will
11729          * disable the crtc (and hence change the state) if it is wrong. Note
11730          * that gen4+ has a fixed plane -> pipe mapping.  */
11731         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
11732                 struct intel_connector *connector;
11733                 bool plane;
11734
11735                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
11736                               crtc->base.base.id);
11737
11738                 /* Pipe has the wrong plane attached and the plane is active.
11739                  * Temporarily change the plane mapping and disable everything
11740                  * ...  */
11741                 plane = crtc->plane;
11742                 crtc->plane = !plane;
11743                 dev_priv->display.crtc_disable(&crtc->base);
11744                 crtc->plane = plane;
11745
11746                 /* ... and break all links. */
11747                 list_for_each_entry(connector, &dev->mode_config.connector_list,
11748                                     base.head) {
11749                         if (connector->encoder->base.crtc != &crtc->base)
11750                                 continue;
11751
11752                         intel_connector_break_all_links(connector);
11753                 }
11754
11755                 WARN_ON(crtc->active);
11756                 crtc->base.enabled = false;
11757         }
11758
11759         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
11760             crtc->pipe == PIPE_A && !crtc->active) {
11761                 /* BIOS forgot to enable pipe A, this mostly happens after
11762                  * resume. Force-enable the pipe to fix this, the update_dpms
11763                  * call below we restore the pipe to the right state, but leave
11764                  * the required bits on. */
11765                 intel_enable_pipe_a(dev);
11766         }
11767
11768         /* Adjust the state of the output pipe according to whether we
11769          * have active connectors/encoders. */
11770         intel_crtc_update_dpms(&crtc->base);
11771
11772         if (crtc->active != crtc->base.enabled) {
11773                 struct intel_encoder *encoder;
11774
11775                 /* This can happen either due to bugs in the get_hw_state
11776                  * functions or because the pipe is force-enabled due to the
11777                  * pipe A quirk. */
11778                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
11779                               crtc->base.base.id,
11780                               crtc->base.enabled ? "enabled" : "disabled",
11781                               crtc->active ? "enabled" : "disabled");
11782
11783                 crtc->base.enabled = crtc->active;
11784
11785                 /* Because we only establish the connector -> encoder ->
11786                  * crtc links if something is active, this means the
11787                  * crtc is now deactivated. Break the links. connector
11788                  * -> encoder links are only establish when things are
11789                  *  actually up, hence no need to break them. */
11790                 WARN_ON(crtc->active);
11791
11792                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
11793                         WARN_ON(encoder->connectors_active);
11794                         encoder->base.crtc = NULL;
11795                 }
11796         }
11797         if (crtc->active) {
11798                 /*
11799                  * We start out with underrun reporting disabled to avoid races.
11800                  * For correct bookkeeping mark this on active crtcs.
11801                  *
11802                  * No protection against concurrent access is required - at
11803                  * worst a fifo underrun happens which also sets this to false.
11804                  */
11805                 crtc->cpu_fifo_underrun_disabled = true;
11806                 crtc->pch_fifo_underrun_disabled = true;
11807         }
11808 }
11809
11810 static void intel_sanitize_encoder(struct intel_encoder *encoder)
11811 {
11812         struct intel_connector *connector;
11813         struct drm_device *dev = encoder->base.dev;
11814
11815         /* We need to check both for a crtc link (meaning that the
11816          * encoder is active and trying to read from a pipe) and the
11817          * pipe itself being active. */
11818         bool has_active_crtc = encoder->base.crtc &&
11819                 to_intel_crtc(encoder->base.crtc)->active;
11820
11821         if (encoder->connectors_active && !has_active_crtc) {
11822                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
11823                               encoder->base.base.id,
11824                               drm_get_encoder_name(&encoder->base));
11825
11826                 /* Connector is active, but has no active pipe. This is
11827                  * fallout from our resume register restoring. Disable
11828                  * the encoder manually again. */
11829                 if (encoder->base.crtc) {
11830                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
11831                                       encoder->base.base.id,
11832                                       drm_get_encoder_name(&encoder->base));
11833                         encoder->disable(encoder);
11834                 }
11835
11836                 /* Inconsistent output/port/pipe state happens presumably due to
11837                  * a bug in one of the get_hw_state functions. Or someplace else
11838                  * in our code, like the register restore mess on resume. Clamp
11839                  * things to off as a safer default. */
11840                 list_for_each_entry(connector,
11841                                     &dev->mode_config.connector_list,
11842                                     base.head) {
11843                         if (connector->encoder != encoder)
11844                                 continue;
11845
11846                         intel_connector_break_all_links(connector);
11847                 }
11848         }
11849         /* Enabled encoders without active connectors will be fixed in
11850          * the crtc fixup. */
11851 }
11852
11853 void i915_redisable_vga_power_on(struct drm_device *dev)
11854 {
11855         struct drm_i915_private *dev_priv = dev->dev_private;
11856         u32 vga_reg = i915_vgacntrl_reg(dev);
11857
11858         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
11859                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
11860                 i915_disable_vga(dev);
11861         }
11862 }
11863
11864 void i915_redisable_vga(struct drm_device *dev)
11865 {
11866         struct drm_i915_private *dev_priv = dev->dev_private;
11867
11868         /* This function can be called both from intel_modeset_setup_hw_state or
11869          * at a very early point in our resume sequence, where the power well
11870          * structures are not yet restored. Since this function is at a very
11871          * paranoid "someone might have enabled VGA while we were not looking"
11872          * level, just check if the power well is enabled instead of trying to
11873          * follow the "don't touch the power well if we don't need it" policy
11874          * the rest of the driver uses. */
11875         if (!intel_display_power_enabled(dev_priv, POWER_DOMAIN_VGA))
11876                 return;
11877
11878         i915_redisable_vga_power_on(dev);
11879 }
11880
11881 static bool primary_get_hw_state(struct intel_crtc *crtc)
11882 {
11883         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
11884
11885         if (!crtc->active)
11886                 return false;
11887
11888         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
11889 }
11890
11891 static void intel_modeset_readout_hw_state(struct drm_device *dev)
11892 {
11893         struct drm_i915_private *dev_priv = dev->dev_private;
11894         enum pipe pipe;
11895         struct intel_crtc *crtc;
11896         struct intel_encoder *encoder;
11897         struct intel_connector *connector;
11898         int i;
11899
11900         for_each_intel_crtc(dev, crtc) {
11901                 memset(&crtc->config, 0, sizeof(crtc->config));
11902
11903                 crtc->config.quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
11904
11905                 crtc->active = dev_priv->display.get_pipe_config(crtc,
11906                                                                  &crtc->config);
11907
11908                 crtc->base.enabled = crtc->active;
11909                 crtc->primary_enabled = primary_get_hw_state(crtc);
11910
11911                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
11912                               crtc->base.base.id,
11913                               crtc->active ? "enabled" : "disabled");
11914         }
11915
11916         /* FIXME: Smash this into the new shared dpll infrastructure. */
11917         if (HAS_DDI(dev))
11918                 intel_ddi_setup_hw_pll_state(dev);
11919
11920         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11921                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
11922
11923                 pll->on = pll->get_hw_state(dev_priv, pll, &pll->hw_state);
11924                 pll->active = 0;
11925                 for_each_intel_crtc(dev, crtc) {
11926                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
11927                                 pll->active++;
11928                 }
11929                 pll->refcount = pll->active;
11930
11931                 DRM_DEBUG_KMS("%s hw state readout: refcount %i, on %i\n",
11932                               pll->name, pll->refcount, pll->on);
11933         }
11934
11935         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
11936                             base.head) {
11937                 pipe = 0;
11938
11939                 if (encoder->get_hw_state(encoder, &pipe)) {
11940                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
11941                         encoder->base.crtc = &crtc->base;
11942                         encoder->get_config(encoder, &crtc->config);
11943                 } else {
11944                         encoder->base.crtc = NULL;
11945                 }
11946
11947                 encoder->connectors_active = false;
11948                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
11949                               encoder->base.base.id,
11950                               drm_get_encoder_name(&encoder->base),
11951                               encoder->base.crtc ? "enabled" : "disabled",
11952                               pipe_name(pipe));
11953         }
11954
11955         list_for_each_entry(connector, &dev->mode_config.connector_list,
11956                             base.head) {
11957                 if (connector->get_hw_state(connector)) {
11958                         connector->base.dpms = DRM_MODE_DPMS_ON;
11959                         connector->encoder->connectors_active = true;
11960                         connector->base.encoder = &connector->encoder->base;
11961                 } else {
11962                         connector->base.dpms = DRM_MODE_DPMS_OFF;
11963                         connector->base.encoder = NULL;
11964                 }
11965                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
11966                               connector->base.base.id,
11967                               drm_get_connector_name(&connector->base),
11968                               connector->base.encoder ? "enabled" : "disabled");
11969         }
11970 }
11971
11972 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
11973  * and i915 state tracking structures. */
11974 void intel_modeset_setup_hw_state(struct drm_device *dev,
11975                                   bool force_restore)
11976 {
11977         struct drm_i915_private *dev_priv = dev->dev_private;
11978         enum pipe pipe;
11979         struct intel_crtc *crtc;
11980         struct intel_encoder *encoder;
11981         int i;
11982
11983         intel_modeset_readout_hw_state(dev);
11984
11985         /*
11986          * Now that we have the config, copy it to each CRTC struct
11987          * Note that this could go away if we move to using crtc_config
11988          * checking everywhere.
11989          */
11990         for_each_intel_crtc(dev, crtc) {
11991                 if (crtc->active && i915.fastboot) {
11992                         intel_mode_from_pipe_config(&crtc->base.mode, &crtc->config);
11993                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
11994                                       crtc->base.base.id);
11995                         drm_mode_debug_printmodeline(&crtc->base.mode);
11996                 }
11997         }
11998
11999         /* HW state is read out, now we need to sanitize this mess. */
12000         list_for_each_entry(encoder, &dev->mode_config.encoder_list,
12001                             base.head) {
12002                 intel_sanitize_encoder(encoder);
12003         }
12004
12005         for_each_pipe(pipe) {
12006                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
12007                 intel_sanitize_crtc(crtc);
12008                 intel_dump_pipe_config(crtc, &crtc->config, "[setup_hw_state]");
12009         }
12010
12011         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12012                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12013
12014                 if (!pll->on || pll->active)
12015                         continue;
12016
12017                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
12018
12019                 pll->disable(dev_priv, pll);
12020                 pll->on = false;
12021         }
12022
12023         if (HAS_PCH_SPLIT(dev))
12024                 ilk_wm_get_hw_state(dev);
12025
12026         if (force_restore) {
12027                 i915_redisable_vga(dev);
12028
12029                 /*
12030                  * We need to use raw interfaces for restoring state to avoid
12031                  * checking (bogus) intermediate states.
12032                  */
12033                 for_each_pipe(pipe) {
12034                         struct drm_crtc *crtc =
12035                                 dev_priv->pipe_to_crtc_mapping[pipe];
12036
12037                         __intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y,
12038                                          crtc->primary->fb);
12039                 }
12040         } else {
12041                 intel_modeset_update_staged_output_state(dev);
12042         }
12043
12044         intel_modeset_check_state(dev);
12045 }
12046
12047 void intel_modeset_gem_init(struct drm_device *dev)
12048 {
12049         struct drm_crtc *c;
12050         struct intel_framebuffer *fb;
12051
12052         mutex_lock(&dev->struct_mutex);
12053         intel_init_gt_powersave(dev);
12054         mutex_unlock(&dev->struct_mutex);
12055
12056         intel_modeset_init_hw(dev);
12057
12058         intel_setup_overlay(dev);
12059
12060         /*
12061          * Make sure any fbs we allocated at startup are properly
12062          * pinned & fenced.  When we do the allocation it's too early
12063          * for this.
12064          */
12065         mutex_lock(&dev->struct_mutex);
12066         for_each_crtc(dev, c) {
12067                 if (!c->primary->fb)
12068                         continue;
12069
12070                 fb = to_intel_framebuffer(c->primary->fb);
12071                 if (intel_pin_and_fence_fb_obj(dev, fb->obj, NULL)) {
12072                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
12073                                   to_intel_crtc(c)->pipe);
12074                         drm_framebuffer_unreference(c->primary->fb);
12075                         c->primary->fb = NULL;
12076                 }
12077         }
12078         mutex_unlock(&dev->struct_mutex);
12079 }
12080
12081 void intel_connector_unregister(struct intel_connector *intel_connector)
12082 {
12083         struct drm_connector *connector = &intel_connector->base;
12084
12085         intel_panel_destroy_backlight(connector);
12086         drm_sysfs_connector_remove(connector);
12087 }
12088
12089 void intel_modeset_cleanup(struct drm_device *dev)
12090 {
12091         struct drm_i915_private *dev_priv = dev->dev_private;
12092         struct drm_crtc *crtc;
12093         struct drm_connector *connector;
12094
12095         /*
12096          * Interrupts and polling as the first thing to avoid creating havoc.
12097          * Too much stuff here (turning of rps, connectors, ...) would
12098          * experience fancy races otherwise.
12099          */
12100         drm_irq_uninstall(dev);
12101         cancel_work_sync(&dev_priv->hotplug_work);
12102         /*
12103          * Due to the hpd irq storm handling the hotplug work can re-arm the
12104          * poll handlers. Hence disable polling after hpd handling is shut down.
12105          */
12106         drm_kms_helper_poll_fini(dev);
12107
12108         mutex_lock(&dev->struct_mutex);
12109
12110         intel_unregister_dsm_handler();
12111
12112         for_each_crtc(dev, crtc) {
12113                 /* Skip inactive CRTCs */
12114                 if (!crtc->primary->fb)
12115                         continue;
12116
12117                 intel_increase_pllclock(crtc);
12118         }
12119
12120         intel_disable_fbc(dev);
12121
12122         intel_disable_gt_powersave(dev);
12123
12124         ironlake_teardown_rc6(dev);
12125
12126         mutex_unlock(&dev->struct_mutex);
12127
12128         /* flush any delayed tasks or pending work */
12129         flush_scheduled_work();
12130
12131         /* destroy the backlight and sysfs files before encoders/connectors */
12132         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
12133                 struct intel_connector *intel_connector;
12134
12135                 intel_connector = to_intel_connector(connector);
12136                 intel_connector->unregister(intel_connector);
12137         }
12138
12139         drm_mode_config_cleanup(dev);
12140
12141         intel_cleanup_overlay(dev);
12142
12143         mutex_lock(&dev->struct_mutex);
12144         intel_cleanup_gt_powersave(dev);
12145         mutex_unlock(&dev->struct_mutex);
12146 }
12147
12148 /*
12149  * Return which encoder is currently attached for connector.
12150  */
12151 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
12152 {
12153         return &intel_attached_encoder(connector)->base;
12154 }
12155
12156 void intel_connector_attach_encoder(struct intel_connector *connector,
12157                                     struct intel_encoder *encoder)
12158 {
12159         connector->encoder = encoder;
12160         drm_mode_connector_attach_encoder(&connector->base,
12161                                           &encoder->base);
12162 }
12163
12164 /*
12165  * set vga decode state - true == enable VGA decode
12166  */
12167 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
12168 {
12169         struct drm_i915_private *dev_priv = dev->dev_private;
12170         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
12171         u16 gmch_ctrl;
12172
12173         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
12174                 DRM_ERROR("failed to read control word\n");
12175                 return -EIO;
12176         }
12177
12178         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
12179                 return 0;
12180
12181         if (state)
12182                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
12183         else
12184                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
12185
12186         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
12187                 DRM_ERROR("failed to write control word\n");
12188                 return -EIO;
12189         }
12190
12191         return 0;
12192 }
12193
12194 struct intel_display_error_state {
12195
12196         u32 power_well_driver;
12197
12198         int num_transcoders;
12199
12200         struct intel_cursor_error_state {
12201                 u32 control;
12202                 u32 position;
12203                 u32 base;
12204                 u32 size;
12205         } cursor[I915_MAX_PIPES];
12206
12207         struct intel_pipe_error_state {
12208                 bool power_domain_on;
12209                 u32 source;
12210                 u32 stat;
12211         } pipe[I915_MAX_PIPES];
12212
12213         struct intel_plane_error_state {
12214                 u32 control;
12215                 u32 stride;
12216                 u32 size;
12217                 u32 pos;
12218                 u32 addr;
12219                 u32 surface;
12220                 u32 tile_offset;
12221         } plane[I915_MAX_PIPES];
12222
12223         struct intel_transcoder_error_state {
12224                 bool power_domain_on;
12225                 enum transcoder cpu_transcoder;
12226
12227                 u32 conf;
12228
12229                 u32 htotal;
12230                 u32 hblank;
12231                 u32 hsync;
12232                 u32 vtotal;
12233                 u32 vblank;
12234                 u32 vsync;
12235         } transcoder[4];
12236 };
12237
12238 struct intel_display_error_state *
12239 intel_display_capture_error_state(struct drm_device *dev)
12240 {
12241         struct drm_i915_private *dev_priv = dev->dev_private;
12242         struct intel_display_error_state *error;
12243         int transcoders[] = {
12244                 TRANSCODER_A,
12245                 TRANSCODER_B,
12246                 TRANSCODER_C,
12247                 TRANSCODER_EDP,
12248         };
12249         int i;
12250
12251         if (INTEL_INFO(dev)->num_pipes == 0)
12252                 return NULL;
12253
12254         error = kzalloc(sizeof(*error), GFP_ATOMIC);
12255         if (error == NULL)
12256                 return NULL;
12257
12258         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
12259                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
12260
12261         for_each_pipe(i) {
12262                 error->pipe[i].power_domain_on =
12263                         intel_display_power_enabled_sw(dev_priv,
12264                                                        POWER_DOMAIN_PIPE(i));
12265                 if (!error->pipe[i].power_domain_on)
12266                         continue;
12267
12268                 if (INTEL_INFO(dev)->gen <= 6 || IS_VALLEYVIEW(dev)) {
12269                         error->cursor[i].control = I915_READ(CURCNTR(i));
12270                         error->cursor[i].position = I915_READ(CURPOS(i));
12271                         error->cursor[i].base = I915_READ(CURBASE(i));
12272                 } else {
12273                         error->cursor[i].control = I915_READ(CURCNTR_IVB(i));
12274                         error->cursor[i].position = I915_READ(CURPOS_IVB(i));
12275                         error->cursor[i].base = I915_READ(CURBASE_IVB(i));
12276                 }
12277
12278                 error->plane[i].control = I915_READ(DSPCNTR(i));
12279                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
12280                 if (INTEL_INFO(dev)->gen <= 3) {
12281                         error->plane[i].size = I915_READ(DSPSIZE(i));
12282                         error->plane[i].pos = I915_READ(DSPPOS(i));
12283                 }
12284                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
12285                         error->plane[i].addr = I915_READ(DSPADDR(i));
12286                 if (INTEL_INFO(dev)->gen >= 4) {
12287                         error->plane[i].surface = I915_READ(DSPSURF(i));
12288                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
12289                 }
12290
12291                 error->pipe[i].source = I915_READ(PIPESRC(i));
12292
12293                 if (!HAS_PCH_SPLIT(dev))
12294                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
12295         }
12296
12297         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
12298         if (HAS_DDI(dev_priv->dev))
12299                 error->num_transcoders++; /* Account for eDP. */
12300
12301         for (i = 0; i < error->num_transcoders; i++) {
12302                 enum transcoder cpu_transcoder = transcoders[i];
12303
12304                 error->transcoder[i].power_domain_on =
12305                         intel_display_power_enabled_sw(dev_priv,
12306                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
12307                 if (!error->transcoder[i].power_domain_on)
12308                         continue;
12309
12310                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
12311
12312                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
12313                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
12314                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
12315                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
12316                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
12317                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
12318                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
12319         }
12320
12321         return error;
12322 }
12323
12324 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
12325
12326 void
12327 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
12328                                 struct drm_device *dev,
12329                                 struct intel_display_error_state *error)
12330 {
12331         int i;
12332
12333         if (!error)
12334                 return;
12335
12336         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
12337         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
12338                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
12339                            error->power_well_driver);
12340         for_each_pipe(i) {
12341                 err_printf(m, "Pipe [%d]:\n", i);
12342                 err_printf(m, "  Power: %s\n",
12343                            error->pipe[i].power_domain_on ? "on" : "off");
12344                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
12345                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
12346
12347                 err_printf(m, "Plane [%d]:\n", i);
12348                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
12349                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
12350                 if (INTEL_INFO(dev)->gen <= 3) {
12351                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
12352                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
12353                 }
12354                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
12355                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
12356                 if (INTEL_INFO(dev)->gen >= 4) {
12357                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
12358                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
12359                 }
12360
12361                 err_printf(m, "Cursor [%d]:\n", i);
12362                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
12363                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
12364                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
12365         }
12366
12367         for (i = 0; i < error->num_transcoders; i++) {
12368                 err_printf(m, "CPU transcoder: %c\n",
12369                            transcoder_name(error->transcoder[i].cpu_transcoder));
12370                 err_printf(m, "  Power: %s\n",
12371                            error->transcoder[i].power_domain_on ? "on" : "off");
12372                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
12373                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
12374                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
12375                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
12376                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
12377                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
12378                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
12379         }
12380 }