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