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