drm/i915: Make sure DPLL is enabled when kicking the power sequencer on VLV/CHV
[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 <drm/drm_plane_helper.h>
43 #include <drm/drm_rect.h>
44 #include <linux/dma_remapping.h>
45
46 /* Primary plane formats supported by all gen */
47 #define COMMON_PRIMARY_FORMATS \
48         DRM_FORMAT_C8, \
49         DRM_FORMAT_RGB565, \
50         DRM_FORMAT_XRGB8888, \
51         DRM_FORMAT_ARGB8888
52
53 /* Primary plane formats for gen <= 3 */
54 static const uint32_t intel_primary_formats_gen2[] = {
55         COMMON_PRIMARY_FORMATS,
56         DRM_FORMAT_XRGB1555,
57         DRM_FORMAT_ARGB1555,
58 };
59
60 /* Primary plane formats for gen >= 4 */
61 static const uint32_t intel_primary_formats_gen4[] = {
62         COMMON_PRIMARY_FORMATS, \
63         DRM_FORMAT_XBGR8888,
64         DRM_FORMAT_ABGR8888,
65         DRM_FORMAT_XRGB2101010,
66         DRM_FORMAT_ARGB2101010,
67         DRM_FORMAT_XBGR2101010,
68         DRM_FORMAT_ABGR2101010,
69 };
70
71 /* Cursor formats */
72 static const uint32_t intel_cursor_formats[] = {
73         DRM_FORMAT_ARGB8888,
74 };
75
76 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
77
78 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
79                                 struct intel_crtc_config *pipe_config);
80 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
81                                    struct intel_crtc_config *pipe_config);
82
83 static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
84                           int x, int y, struct drm_framebuffer *old_fb);
85 static int intel_framebuffer_init(struct drm_device *dev,
86                                   struct intel_framebuffer *ifb,
87                                   struct drm_mode_fb_cmd2 *mode_cmd,
88                                   struct drm_i915_gem_object *obj);
89 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
90 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
91 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
92                                          struct intel_link_m_n *m_n,
93                                          struct intel_link_m_n *m2_n2);
94 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
95 static void haswell_set_pipeconf(struct drm_crtc *crtc);
96 static void intel_set_pipe_csc(struct drm_crtc *crtc);
97 static void vlv_prepare_pll(struct intel_crtc *crtc,
98                             const struct intel_crtc_config *pipe_config);
99 static void chv_prepare_pll(struct intel_crtc *crtc,
100                             const struct intel_crtc_config *pipe_config);
101
102 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
103 {
104         if (!connector->mst_port)
105                 return connector->encoder;
106         else
107                 return &connector->mst_port->mst_encoders[pipe]->base;
108 }
109
110 typedef struct {
111         int     min, max;
112 } intel_range_t;
113
114 typedef struct {
115         int     dot_limit;
116         int     p2_slow, p2_fast;
117 } intel_p2_t;
118
119 typedef struct intel_limit intel_limit_t;
120 struct intel_limit {
121         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
122         intel_p2_t          p2;
123 };
124
125 int
126 intel_pch_rawclk(struct drm_device *dev)
127 {
128         struct drm_i915_private *dev_priv = dev->dev_private;
129
130         WARN_ON(!HAS_PCH_SPLIT(dev));
131
132         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
133 }
134
135 static inline u32 /* units of 100MHz */
136 intel_fdi_link_freq(struct drm_device *dev)
137 {
138         if (IS_GEN5(dev)) {
139                 struct drm_i915_private *dev_priv = dev->dev_private;
140                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
141         } else
142                 return 27;
143 }
144
145 static const intel_limit_t intel_limits_i8xx_dac = {
146         .dot = { .min = 25000, .max = 350000 },
147         .vco = { .min = 908000, .max = 1512000 },
148         .n = { .min = 2, .max = 16 },
149         .m = { .min = 96, .max = 140 },
150         .m1 = { .min = 18, .max = 26 },
151         .m2 = { .min = 6, .max = 16 },
152         .p = { .min = 4, .max = 128 },
153         .p1 = { .min = 2, .max = 33 },
154         .p2 = { .dot_limit = 165000,
155                 .p2_slow = 4, .p2_fast = 2 },
156 };
157
158 static const intel_limit_t intel_limits_i8xx_dvo = {
159         .dot = { .min = 25000, .max = 350000 },
160         .vco = { .min = 908000, .max = 1512000 },
161         .n = { .min = 2, .max = 16 },
162         .m = { .min = 96, .max = 140 },
163         .m1 = { .min = 18, .max = 26 },
164         .m2 = { .min = 6, .max = 16 },
165         .p = { .min = 4, .max = 128 },
166         .p1 = { .min = 2, .max = 33 },
167         .p2 = { .dot_limit = 165000,
168                 .p2_slow = 4, .p2_fast = 4 },
169 };
170
171 static const intel_limit_t intel_limits_i8xx_lvds = {
172         .dot = { .min = 25000, .max = 350000 },
173         .vco = { .min = 908000, .max = 1512000 },
174         .n = { .min = 2, .max = 16 },
175         .m = { .min = 96, .max = 140 },
176         .m1 = { .min = 18, .max = 26 },
177         .m2 = { .min = 6, .max = 16 },
178         .p = { .min = 4, .max = 128 },
179         .p1 = { .min = 1, .max = 6 },
180         .p2 = { .dot_limit = 165000,
181                 .p2_slow = 14, .p2_fast = 7 },
182 };
183
184 static const intel_limit_t intel_limits_i9xx_sdvo = {
185         .dot = { .min = 20000, .max = 400000 },
186         .vco = { .min = 1400000, .max = 2800000 },
187         .n = { .min = 1, .max = 6 },
188         .m = { .min = 70, .max = 120 },
189         .m1 = { .min = 8, .max = 18 },
190         .m2 = { .min = 3, .max = 7 },
191         .p = { .min = 5, .max = 80 },
192         .p1 = { .min = 1, .max = 8 },
193         .p2 = { .dot_limit = 200000,
194                 .p2_slow = 10, .p2_fast = 5 },
195 };
196
197 static const intel_limit_t intel_limits_i9xx_lvds = {
198         .dot = { .min = 20000, .max = 400000 },
199         .vco = { .min = 1400000, .max = 2800000 },
200         .n = { .min = 1, .max = 6 },
201         .m = { .min = 70, .max = 120 },
202         .m1 = { .min = 8, .max = 18 },
203         .m2 = { .min = 3, .max = 7 },
204         .p = { .min = 7, .max = 98 },
205         .p1 = { .min = 1, .max = 8 },
206         .p2 = { .dot_limit = 112000,
207                 .p2_slow = 14, .p2_fast = 7 },
208 };
209
210
211 static const intel_limit_t intel_limits_g4x_sdvo = {
212         .dot = { .min = 25000, .max = 270000 },
213         .vco = { .min = 1750000, .max = 3500000},
214         .n = { .min = 1, .max = 4 },
215         .m = { .min = 104, .max = 138 },
216         .m1 = { .min = 17, .max = 23 },
217         .m2 = { .min = 5, .max = 11 },
218         .p = { .min = 10, .max = 30 },
219         .p1 = { .min = 1, .max = 3},
220         .p2 = { .dot_limit = 270000,
221                 .p2_slow = 10,
222                 .p2_fast = 10
223         },
224 };
225
226 static const intel_limit_t intel_limits_g4x_hdmi = {
227         .dot = { .min = 22000, .max = 400000 },
228         .vco = { .min = 1750000, .max = 3500000},
229         .n = { .min = 1, .max = 4 },
230         .m = { .min = 104, .max = 138 },
231         .m1 = { .min = 16, .max = 23 },
232         .m2 = { .min = 5, .max = 11 },
233         .p = { .min = 5, .max = 80 },
234         .p1 = { .min = 1, .max = 8},
235         .p2 = { .dot_limit = 165000,
236                 .p2_slow = 10, .p2_fast = 5 },
237 };
238
239 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
240         .dot = { .min = 20000, .max = 115000 },
241         .vco = { .min = 1750000, .max = 3500000 },
242         .n = { .min = 1, .max = 3 },
243         .m = { .min = 104, .max = 138 },
244         .m1 = { .min = 17, .max = 23 },
245         .m2 = { .min = 5, .max = 11 },
246         .p = { .min = 28, .max = 112 },
247         .p1 = { .min = 2, .max = 8 },
248         .p2 = { .dot_limit = 0,
249                 .p2_slow = 14, .p2_fast = 14
250         },
251 };
252
253 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
254         .dot = { .min = 80000, .max = 224000 },
255         .vco = { .min = 1750000, .max = 3500000 },
256         .n = { .min = 1, .max = 3 },
257         .m = { .min = 104, .max = 138 },
258         .m1 = { .min = 17, .max = 23 },
259         .m2 = { .min = 5, .max = 11 },
260         .p = { .min = 14, .max = 42 },
261         .p1 = { .min = 2, .max = 6 },
262         .p2 = { .dot_limit = 0,
263                 .p2_slow = 7, .p2_fast = 7
264         },
265 };
266
267 static const intel_limit_t intel_limits_pineview_sdvo = {
268         .dot = { .min = 20000, .max = 400000},
269         .vco = { .min = 1700000, .max = 3500000 },
270         /* Pineview's Ncounter is a ring counter */
271         .n = { .min = 3, .max = 6 },
272         .m = { .min = 2, .max = 256 },
273         /* Pineview only has one combined m divider, which we treat as m2. */
274         .m1 = { .min = 0, .max = 0 },
275         .m2 = { .min = 0, .max = 254 },
276         .p = { .min = 5, .max = 80 },
277         .p1 = { .min = 1, .max = 8 },
278         .p2 = { .dot_limit = 200000,
279                 .p2_slow = 10, .p2_fast = 5 },
280 };
281
282 static const intel_limit_t intel_limits_pineview_lvds = {
283         .dot = { .min = 20000, .max = 400000 },
284         .vco = { .min = 1700000, .max = 3500000 },
285         .n = { .min = 3, .max = 6 },
286         .m = { .min = 2, .max = 256 },
287         .m1 = { .min = 0, .max = 0 },
288         .m2 = { .min = 0, .max = 254 },
289         .p = { .min = 7, .max = 112 },
290         .p1 = { .min = 1, .max = 8 },
291         .p2 = { .dot_limit = 112000,
292                 .p2_slow = 14, .p2_fast = 14 },
293 };
294
295 /* Ironlake / Sandybridge
296  *
297  * We calculate clock using (register_value + 2) for N/M1/M2, so here
298  * the range value for them is (actual_value - 2).
299  */
300 static const intel_limit_t intel_limits_ironlake_dac = {
301         .dot = { .min = 25000, .max = 350000 },
302         .vco = { .min = 1760000, .max = 3510000 },
303         .n = { .min = 1, .max = 5 },
304         .m = { .min = 79, .max = 127 },
305         .m1 = { .min = 12, .max = 22 },
306         .m2 = { .min = 5, .max = 9 },
307         .p = { .min = 5, .max = 80 },
308         .p1 = { .min = 1, .max = 8 },
309         .p2 = { .dot_limit = 225000,
310                 .p2_slow = 10, .p2_fast = 5 },
311 };
312
313 static const intel_limit_t intel_limits_ironlake_single_lvds = {
314         .dot = { .min = 25000, .max = 350000 },
315         .vco = { .min = 1760000, .max = 3510000 },
316         .n = { .min = 1, .max = 3 },
317         .m = { .min = 79, .max = 118 },
318         .m1 = { .min = 12, .max = 22 },
319         .m2 = { .min = 5, .max = 9 },
320         .p = { .min = 28, .max = 112 },
321         .p1 = { .min = 2, .max = 8 },
322         .p2 = { .dot_limit = 225000,
323                 .p2_slow = 14, .p2_fast = 14 },
324 };
325
326 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
327         .dot = { .min = 25000, .max = 350000 },
328         .vco = { .min = 1760000, .max = 3510000 },
329         .n = { .min = 1, .max = 3 },
330         .m = { .min = 79, .max = 127 },
331         .m1 = { .min = 12, .max = 22 },
332         .m2 = { .min = 5, .max = 9 },
333         .p = { .min = 14, .max = 56 },
334         .p1 = { .min = 2, .max = 8 },
335         .p2 = { .dot_limit = 225000,
336                 .p2_slow = 7, .p2_fast = 7 },
337 };
338
339 /* LVDS 100mhz refclk limits. */
340 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
341         .dot = { .min = 25000, .max = 350000 },
342         .vco = { .min = 1760000, .max = 3510000 },
343         .n = { .min = 1, .max = 2 },
344         .m = { .min = 79, .max = 126 },
345         .m1 = { .min = 12, .max = 22 },
346         .m2 = { .min = 5, .max = 9 },
347         .p = { .min = 28, .max = 112 },
348         .p1 = { .min = 2, .max = 8 },
349         .p2 = { .dot_limit = 225000,
350                 .p2_slow = 14, .p2_fast = 14 },
351 };
352
353 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
354         .dot = { .min = 25000, .max = 350000 },
355         .vco = { .min = 1760000, .max = 3510000 },
356         .n = { .min = 1, .max = 3 },
357         .m = { .min = 79, .max = 126 },
358         .m1 = { .min = 12, .max = 22 },
359         .m2 = { .min = 5, .max = 9 },
360         .p = { .min = 14, .max = 42 },
361         .p1 = { .min = 2, .max = 6 },
362         .p2 = { .dot_limit = 225000,
363                 .p2_slow = 7, .p2_fast = 7 },
364 };
365
366 static const intel_limit_t intel_limits_vlv = {
367          /*
368           * These are the data rate limits (measured in fast clocks)
369           * since those are the strictest limits we have. The fast
370           * clock and actual rate limits are more relaxed, so checking
371           * them would make no difference.
372           */
373         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
374         .vco = { .min = 4000000, .max = 6000000 },
375         .n = { .min = 1, .max = 7 },
376         .m1 = { .min = 2, .max = 3 },
377         .m2 = { .min = 11, .max = 156 },
378         .p1 = { .min = 2, .max = 3 },
379         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
380 };
381
382 static const intel_limit_t intel_limits_chv = {
383         /*
384          * These are the data rate limits (measured in fast clocks)
385          * since those are the strictest limits we have.  The fast
386          * clock and actual rate limits are more relaxed, so checking
387          * them would make no difference.
388          */
389         .dot = { .min = 25000 * 5, .max = 540000 * 5},
390         .vco = { .min = 4860000, .max = 6700000 },
391         .n = { .min = 1, .max = 1 },
392         .m1 = { .min = 2, .max = 2 },
393         .m2 = { .min = 24 << 22, .max = 175 << 22 },
394         .p1 = { .min = 2, .max = 4 },
395         .p2 = { .p2_slow = 1, .p2_fast = 14 },
396 };
397
398 static void vlv_clock(int refclk, intel_clock_t *clock)
399 {
400         clock->m = clock->m1 * clock->m2;
401         clock->p = clock->p1 * clock->p2;
402         if (WARN_ON(clock->n == 0 || clock->p == 0))
403                 return;
404         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
405         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
406 }
407
408 /**
409  * Returns whether any output on the specified pipe is of the specified type
410  */
411 bool intel_pipe_has_type(struct intel_crtc *crtc, int type)
412 {
413         struct drm_device *dev = crtc->base.dev;
414         struct intel_encoder *encoder;
415
416         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
417                 if (encoder->type == type)
418                         return true;
419
420         return false;
421 }
422
423 static const intel_limit_t *intel_ironlake_limit(struct intel_crtc *crtc,
424                                                 int refclk)
425 {
426         struct drm_device *dev = crtc->base.dev;
427         const intel_limit_t *limit;
428
429         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
430                 if (intel_is_dual_link_lvds(dev)) {
431                         if (refclk == 100000)
432                                 limit = &intel_limits_ironlake_dual_lvds_100m;
433                         else
434                                 limit = &intel_limits_ironlake_dual_lvds;
435                 } else {
436                         if (refclk == 100000)
437                                 limit = &intel_limits_ironlake_single_lvds_100m;
438                         else
439                                 limit = &intel_limits_ironlake_single_lvds;
440                 }
441         } else
442                 limit = &intel_limits_ironlake_dac;
443
444         return limit;
445 }
446
447 static const intel_limit_t *intel_g4x_limit(struct intel_crtc *crtc)
448 {
449         struct drm_device *dev = crtc->base.dev;
450         const intel_limit_t *limit;
451
452         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
453                 if (intel_is_dual_link_lvds(dev))
454                         limit = &intel_limits_g4x_dual_channel_lvds;
455                 else
456                         limit = &intel_limits_g4x_single_channel_lvds;
457         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI) ||
458                    intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG)) {
459                 limit = &intel_limits_g4x_hdmi;
460         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_SDVO)) {
461                 limit = &intel_limits_g4x_sdvo;
462         } else /* The option is for other outputs */
463                 limit = &intel_limits_i9xx_sdvo;
464
465         return limit;
466 }
467
468 static const intel_limit_t *intel_limit(struct intel_crtc *crtc, int refclk)
469 {
470         struct drm_device *dev = crtc->base.dev;
471         const intel_limit_t *limit;
472
473         if (HAS_PCH_SPLIT(dev))
474                 limit = intel_ironlake_limit(crtc, refclk);
475         else if (IS_G4X(dev)) {
476                 limit = intel_g4x_limit(crtc);
477         } else if (IS_PINEVIEW(dev)) {
478                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
479                         limit = &intel_limits_pineview_lvds;
480                 else
481                         limit = &intel_limits_pineview_sdvo;
482         } else if (IS_CHERRYVIEW(dev)) {
483                 limit = &intel_limits_chv;
484         } else if (IS_VALLEYVIEW(dev)) {
485                 limit = &intel_limits_vlv;
486         } else if (!IS_GEN2(dev)) {
487                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
488                         limit = &intel_limits_i9xx_lvds;
489                 else
490                         limit = &intel_limits_i9xx_sdvo;
491         } else {
492                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
493                         limit = &intel_limits_i8xx_lvds;
494                 else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO))
495                         limit = &intel_limits_i8xx_dvo;
496                 else
497                         limit = &intel_limits_i8xx_dac;
498         }
499         return limit;
500 }
501
502 /* m1 is reserved as 0 in Pineview, n is a ring counter */
503 static void pineview_clock(int refclk, intel_clock_t *clock)
504 {
505         clock->m = clock->m2 + 2;
506         clock->p = clock->p1 * clock->p2;
507         if (WARN_ON(clock->n == 0 || clock->p == 0))
508                 return;
509         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
510         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
511 }
512
513 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
514 {
515         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
516 }
517
518 static void i9xx_clock(int refclk, intel_clock_t *clock)
519 {
520         clock->m = i9xx_dpll_compute_m(clock);
521         clock->p = clock->p1 * clock->p2;
522         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
523                 return;
524         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
525         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
526 }
527
528 static void chv_clock(int refclk, intel_clock_t *clock)
529 {
530         clock->m = clock->m1 * clock->m2;
531         clock->p = clock->p1 * clock->p2;
532         if (WARN_ON(clock->n == 0 || clock->p == 0))
533                 return;
534         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
535                         clock->n << 22);
536         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
537 }
538
539 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
540 /**
541  * Returns whether the given set of divisors are valid for a given refclk with
542  * the given connectors.
543  */
544
545 static bool intel_PLL_is_valid(struct drm_device *dev,
546                                const intel_limit_t *limit,
547                                const intel_clock_t *clock)
548 {
549         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
550                 INTELPllInvalid("n out of range\n");
551         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
552                 INTELPllInvalid("p1 out of range\n");
553         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
554                 INTELPllInvalid("m2 out of range\n");
555         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
556                 INTELPllInvalid("m1 out of range\n");
557
558         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
559                 if (clock->m1 <= clock->m2)
560                         INTELPllInvalid("m1 <= m2\n");
561
562         if (!IS_VALLEYVIEW(dev)) {
563                 if (clock->p < limit->p.min || limit->p.max < clock->p)
564                         INTELPllInvalid("p out of range\n");
565                 if (clock->m < limit->m.min || limit->m.max < clock->m)
566                         INTELPllInvalid("m out of range\n");
567         }
568
569         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
570                 INTELPllInvalid("vco out of range\n");
571         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
572          * connector, etc., rather than just a single range.
573          */
574         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
575                 INTELPllInvalid("dot out of range\n");
576
577         return true;
578 }
579
580 static bool
581 i9xx_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
582                     int target, int refclk, intel_clock_t *match_clock,
583                     intel_clock_t *best_clock)
584 {
585         struct drm_device *dev = crtc->base.dev;
586         intel_clock_t clock;
587         int err = target;
588
589         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
590                 /*
591                  * For LVDS just rely on its current settings for dual-channel.
592                  * We haven't figured out how to reliably set up different
593                  * single/dual channel state, if we even can.
594                  */
595                 if (intel_is_dual_link_lvds(dev))
596                         clock.p2 = limit->p2.p2_fast;
597                 else
598                         clock.p2 = limit->p2.p2_slow;
599         } else {
600                 if (target < limit->p2.dot_limit)
601                         clock.p2 = limit->p2.p2_slow;
602                 else
603                         clock.p2 = limit->p2.p2_fast;
604         }
605
606         memset(best_clock, 0, sizeof(*best_clock));
607
608         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
609              clock.m1++) {
610                 for (clock.m2 = limit->m2.min;
611                      clock.m2 <= limit->m2.max; clock.m2++) {
612                         if (clock.m2 >= clock.m1)
613                                 break;
614                         for (clock.n = limit->n.min;
615                              clock.n <= limit->n.max; clock.n++) {
616                                 for (clock.p1 = limit->p1.min;
617                                         clock.p1 <= limit->p1.max; clock.p1++) {
618                                         int this_err;
619
620                                         i9xx_clock(refclk, &clock);
621                                         if (!intel_PLL_is_valid(dev, limit,
622                                                                 &clock))
623                                                 continue;
624                                         if (match_clock &&
625                                             clock.p != match_clock->p)
626                                                 continue;
627
628                                         this_err = abs(clock.dot - target);
629                                         if (this_err < err) {
630                                                 *best_clock = clock;
631                                                 err = this_err;
632                                         }
633                                 }
634                         }
635                 }
636         }
637
638         return (err != target);
639 }
640
641 static bool
642 pnv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
643                    int target, int refclk, intel_clock_t *match_clock,
644                    intel_clock_t *best_clock)
645 {
646         struct drm_device *dev = crtc->base.dev;
647         intel_clock_t clock;
648         int err = target;
649
650         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
651                 /*
652                  * For LVDS just rely on its current settings for dual-channel.
653                  * We haven't figured out how to reliably set up different
654                  * single/dual channel state, if we even can.
655                  */
656                 if (intel_is_dual_link_lvds(dev))
657                         clock.p2 = limit->p2.p2_fast;
658                 else
659                         clock.p2 = limit->p2.p2_slow;
660         } else {
661                 if (target < limit->p2.dot_limit)
662                         clock.p2 = limit->p2.p2_slow;
663                 else
664                         clock.p2 = limit->p2.p2_fast;
665         }
666
667         memset(best_clock, 0, sizeof(*best_clock));
668
669         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
670              clock.m1++) {
671                 for (clock.m2 = limit->m2.min;
672                      clock.m2 <= limit->m2.max; clock.m2++) {
673                         for (clock.n = limit->n.min;
674                              clock.n <= limit->n.max; clock.n++) {
675                                 for (clock.p1 = limit->p1.min;
676                                         clock.p1 <= limit->p1.max; clock.p1++) {
677                                         int this_err;
678
679                                         pineview_clock(refclk, &clock);
680                                         if (!intel_PLL_is_valid(dev, limit,
681                                                                 &clock))
682                                                 continue;
683                                         if (match_clock &&
684                                             clock.p != match_clock->p)
685                                                 continue;
686
687                                         this_err = abs(clock.dot - target);
688                                         if (this_err < err) {
689                                                 *best_clock = clock;
690                                                 err = this_err;
691                                         }
692                                 }
693                         }
694                 }
695         }
696
697         return (err != target);
698 }
699
700 static bool
701 g4x_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
702                    int target, int refclk, intel_clock_t *match_clock,
703                    intel_clock_t *best_clock)
704 {
705         struct drm_device *dev = crtc->base.dev;
706         intel_clock_t clock;
707         int max_n;
708         bool found;
709         /* approximately equals target * 0.00585 */
710         int err_most = (target >> 8) + (target >> 9);
711         found = false;
712
713         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
714                 if (intel_is_dual_link_lvds(dev))
715                         clock.p2 = limit->p2.p2_fast;
716                 else
717                         clock.p2 = limit->p2.p2_slow;
718         } else {
719                 if (target < limit->p2.dot_limit)
720                         clock.p2 = limit->p2.p2_slow;
721                 else
722                         clock.p2 = limit->p2.p2_fast;
723         }
724
725         memset(best_clock, 0, sizeof(*best_clock));
726         max_n = limit->n.max;
727         /* based on hardware requirement, prefer smaller n to precision */
728         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
729                 /* based on hardware requirement, prefere larger m1,m2 */
730                 for (clock.m1 = limit->m1.max;
731                      clock.m1 >= limit->m1.min; clock.m1--) {
732                         for (clock.m2 = limit->m2.max;
733                              clock.m2 >= limit->m2.min; clock.m2--) {
734                                 for (clock.p1 = limit->p1.max;
735                                      clock.p1 >= limit->p1.min; clock.p1--) {
736                                         int this_err;
737
738                                         i9xx_clock(refclk, &clock);
739                                         if (!intel_PLL_is_valid(dev, limit,
740                                                                 &clock))
741                                                 continue;
742
743                                         this_err = abs(clock.dot - target);
744                                         if (this_err < err_most) {
745                                                 *best_clock = clock;
746                                                 err_most = this_err;
747                                                 max_n = clock.n;
748                                                 found = true;
749                                         }
750                                 }
751                         }
752                 }
753         }
754         return found;
755 }
756
757 static bool
758 vlv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
759                    int target, int refclk, intel_clock_t *match_clock,
760                    intel_clock_t *best_clock)
761 {
762         struct drm_device *dev = crtc->base.dev;
763         intel_clock_t clock;
764         unsigned int bestppm = 1000000;
765         /* min update 19.2 MHz */
766         int max_n = min(limit->n.max, refclk / 19200);
767         bool found = false;
768
769         target *= 5; /* fast clock */
770
771         memset(best_clock, 0, sizeof(*best_clock));
772
773         /* based on hardware requirement, prefer smaller n to precision */
774         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
775                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
776                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
777                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
778                                 clock.p = clock.p1 * clock.p2;
779                                 /* based on hardware requirement, prefer bigger m1,m2 values */
780                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
781                                         unsigned int ppm, diff;
782
783                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
784                                                                      refclk * clock.m1);
785
786                                         vlv_clock(refclk, &clock);
787
788                                         if (!intel_PLL_is_valid(dev, limit,
789                                                                 &clock))
790                                                 continue;
791
792                                         diff = abs(clock.dot - target);
793                                         ppm = div_u64(1000000ULL * diff, target);
794
795                                         if (ppm < 100 && clock.p > best_clock->p) {
796                                                 bestppm = 0;
797                                                 *best_clock = clock;
798                                                 found = true;
799                                         }
800
801                                         if (bestppm >= 10 && ppm < bestppm - 10) {
802                                                 bestppm = ppm;
803                                                 *best_clock = clock;
804                                                 found = true;
805                                         }
806                                 }
807                         }
808                 }
809         }
810
811         return found;
812 }
813
814 static bool
815 chv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
816                    int target, int refclk, intel_clock_t *match_clock,
817                    intel_clock_t *best_clock)
818 {
819         struct drm_device *dev = crtc->base.dev;
820         intel_clock_t clock;
821         uint64_t m2;
822         int found = false;
823
824         memset(best_clock, 0, sizeof(*best_clock));
825
826         /*
827          * Based on hardware doc, the n always set to 1, and m1 always
828          * set to 2.  If requires to support 200Mhz refclk, we need to
829          * revisit this because n may not 1 anymore.
830          */
831         clock.n = 1, clock.m1 = 2;
832         target *= 5;    /* fast clock */
833
834         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
835                 for (clock.p2 = limit->p2.p2_fast;
836                                 clock.p2 >= limit->p2.p2_slow;
837                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
838
839                         clock.p = clock.p1 * clock.p2;
840
841                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
842                                         clock.n) << 22, refclk * clock.m1);
843
844                         if (m2 > INT_MAX/clock.m1)
845                                 continue;
846
847                         clock.m2 = m2;
848
849                         chv_clock(refclk, &clock);
850
851                         if (!intel_PLL_is_valid(dev, limit, &clock))
852                                 continue;
853
854                         /* based on hardware requirement, prefer bigger p
855                          */
856                         if (clock.p > best_clock->p) {
857                                 *best_clock = clock;
858                                 found = true;
859                         }
860                 }
861         }
862
863         return found;
864 }
865
866 bool intel_crtc_active(struct drm_crtc *crtc)
867 {
868         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
869
870         /* Be paranoid as we can arrive here with only partial
871          * state retrieved from the hardware during setup.
872          *
873          * We can ditch the adjusted_mode.crtc_clock check as soon
874          * as Haswell has gained clock readout/fastboot support.
875          *
876          * We can ditch the crtc->primary->fb check as soon as we can
877          * properly reconstruct framebuffers.
878          */
879         return intel_crtc->active && crtc->primary->fb &&
880                 intel_crtc->config.adjusted_mode.crtc_clock;
881 }
882
883 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
884                                              enum pipe pipe)
885 {
886         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
887         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
888
889         return intel_crtc->config.cpu_transcoder;
890 }
891
892 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
893 {
894         struct drm_i915_private *dev_priv = dev->dev_private;
895         u32 reg = PIPEDSL(pipe);
896         u32 line1, line2;
897         u32 line_mask;
898
899         if (IS_GEN2(dev))
900                 line_mask = DSL_LINEMASK_GEN2;
901         else
902                 line_mask = DSL_LINEMASK_GEN3;
903
904         line1 = I915_READ(reg) & line_mask;
905         mdelay(5);
906         line2 = I915_READ(reg) & line_mask;
907
908         return line1 == line2;
909 }
910
911 /*
912  * intel_wait_for_pipe_off - wait for pipe to turn off
913  * @crtc: crtc whose pipe to wait for
914  *
915  * After disabling a pipe, we can't wait for vblank in the usual way,
916  * spinning on the vblank interrupt status bit, since we won't actually
917  * see an interrupt when the pipe is disabled.
918  *
919  * On Gen4 and above:
920  *   wait for the pipe register state bit to turn off
921  *
922  * Otherwise:
923  *   wait for the display line value to settle (it usually
924  *   ends up stopping at the start of the next frame).
925  *
926  */
927 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
928 {
929         struct drm_device *dev = crtc->base.dev;
930         struct drm_i915_private *dev_priv = dev->dev_private;
931         enum transcoder cpu_transcoder = crtc->config.cpu_transcoder;
932         enum pipe pipe = crtc->pipe;
933
934         if (INTEL_INFO(dev)->gen >= 4) {
935                 int reg = PIPECONF(cpu_transcoder);
936
937                 /* Wait for the Pipe State to go off */
938                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
939                              100))
940                         WARN(1, "pipe_off wait timed out\n");
941         } else {
942                 /* Wait for the display line to settle */
943                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
944                         WARN(1, "pipe_off wait timed out\n");
945         }
946 }
947
948 /*
949  * ibx_digital_port_connected - is the specified port connected?
950  * @dev_priv: i915 private structure
951  * @port: the port to test
952  *
953  * Returns true if @port is connected, false otherwise.
954  */
955 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
956                                 struct intel_digital_port *port)
957 {
958         u32 bit;
959
960         if (HAS_PCH_IBX(dev_priv->dev)) {
961                 switch (port->port) {
962                 case PORT_B:
963                         bit = SDE_PORTB_HOTPLUG;
964                         break;
965                 case PORT_C:
966                         bit = SDE_PORTC_HOTPLUG;
967                         break;
968                 case PORT_D:
969                         bit = SDE_PORTD_HOTPLUG;
970                         break;
971                 default:
972                         return true;
973                 }
974         } else {
975                 switch (port->port) {
976                 case PORT_B:
977                         bit = SDE_PORTB_HOTPLUG_CPT;
978                         break;
979                 case PORT_C:
980                         bit = SDE_PORTC_HOTPLUG_CPT;
981                         break;
982                 case PORT_D:
983                         bit = SDE_PORTD_HOTPLUG_CPT;
984                         break;
985                 default:
986                         return true;
987                 }
988         }
989
990         return I915_READ(SDEISR) & bit;
991 }
992
993 static const char *state_string(bool enabled)
994 {
995         return enabled ? "on" : "off";
996 }
997
998 /* Only for pre-ILK configs */
999 void assert_pll(struct drm_i915_private *dev_priv,
1000                 enum pipe pipe, bool state)
1001 {
1002         int reg;
1003         u32 val;
1004         bool cur_state;
1005
1006         reg = DPLL(pipe);
1007         val = I915_READ(reg);
1008         cur_state = !!(val & DPLL_VCO_ENABLE);
1009         WARN(cur_state != state,
1010              "PLL state assertion failure (expected %s, current %s)\n",
1011              state_string(state), state_string(cur_state));
1012 }
1013
1014 /* XXX: the dsi pll is shared between MIPI DSI ports */
1015 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1016 {
1017         u32 val;
1018         bool cur_state;
1019
1020         mutex_lock(&dev_priv->dpio_lock);
1021         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1022         mutex_unlock(&dev_priv->dpio_lock);
1023
1024         cur_state = val & DSI_PLL_VCO_EN;
1025         WARN(cur_state != state,
1026              "DSI PLL state assertion failure (expected %s, current %s)\n",
1027              state_string(state), state_string(cur_state));
1028 }
1029 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1030 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1031
1032 struct intel_shared_dpll *
1033 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1034 {
1035         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1036
1037         if (crtc->config.shared_dpll < 0)
1038                 return NULL;
1039
1040         return &dev_priv->shared_dplls[crtc->config.shared_dpll];
1041 }
1042
1043 /* For ILK+ */
1044 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1045                         struct intel_shared_dpll *pll,
1046                         bool state)
1047 {
1048         bool cur_state;
1049         struct intel_dpll_hw_state hw_state;
1050
1051         if (WARN (!pll,
1052                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1053                 return;
1054
1055         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1056         WARN(cur_state != state,
1057              "%s assertion failure (expected %s, current %s)\n",
1058              pll->name, state_string(state), state_string(cur_state));
1059 }
1060
1061 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1062                           enum pipe pipe, bool state)
1063 {
1064         int reg;
1065         u32 val;
1066         bool cur_state;
1067         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1068                                                                       pipe);
1069
1070         if (HAS_DDI(dev_priv->dev)) {
1071                 /* DDI does not have a specific FDI_TX register */
1072                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1073                 val = I915_READ(reg);
1074                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1075         } else {
1076                 reg = FDI_TX_CTL(pipe);
1077                 val = I915_READ(reg);
1078                 cur_state = !!(val & FDI_TX_ENABLE);
1079         }
1080         WARN(cur_state != state,
1081              "FDI TX state assertion failure (expected %s, current %s)\n",
1082              state_string(state), state_string(cur_state));
1083 }
1084 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1085 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1086
1087 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1088                           enum pipe pipe, bool state)
1089 {
1090         int reg;
1091         u32 val;
1092         bool cur_state;
1093
1094         reg = FDI_RX_CTL(pipe);
1095         val = I915_READ(reg);
1096         cur_state = !!(val & FDI_RX_ENABLE);
1097         WARN(cur_state != state,
1098              "FDI RX state assertion failure (expected %s, current %s)\n",
1099              state_string(state), state_string(cur_state));
1100 }
1101 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1102 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1103
1104 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1105                                       enum pipe pipe)
1106 {
1107         int reg;
1108         u32 val;
1109
1110         /* ILK FDI PLL is always enabled */
1111         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1112                 return;
1113
1114         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1115         if (HAS_DDI(dev_priv->dev))
1116                 return;
1117
1118         reg = FDI_TX_CTL(pipe);
1119         val = I915_READ(reg);
1120         WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1121 }
1122
1123 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1124                        enum pipe pipe, bool state)
1125 {
1126         int reg;
1127         u32 val;
1128         bool cur_state;
1129
1130         reg = FDI_RX_CTL(pipe);
1131         val = I915_READ(reg);
1132         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1133         WARN(cur_state != state,
1134              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1135              state_string(state), state_string(cur_state));
1136 }
1137
1138 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1139                            enum pipe pipe)
1140 {
1141         struct drm_device *dev = dev_priv->dev;
1142         int pp_reg;
1143         u32 val;
1144         enum pipe panel_pipe = PIPE_A;
1145         bool locked = true;
1146
1147         if (WARN_ON(HAS_DDI(dev)))
1148                 return;
1149
1150         if (HAS_PCH_SPLIT(dev)) {
1151                 u32 port_sel;
1152
1153                 pp_reg = PCH_PP_CONTROL;
1154                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1155
1156                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1157                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1158                         panel_pipe = PIPE_B;
1159                 /* XXX: else fix for eDP */
1160         } else if (IS_VALLEYVIEW(dev)) {
1161                 /* presumably write lock depends on pipe, not port select */
1162                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1163                 panel_pipe = pipe;
1164         } else {
1165                 pp_reg = PP_CONTROL;
1166                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1167                         panel_pipe = PIPE_B;
1168         }
1169
1170         val = I915_READ(pp_reg);
1171         if (!(val & PANEL_POWER_ON) ||
1172             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1173                 locked = false;
1174
1175         WARN(panel_pipe == pipe && locked,
1176              "panel assertion failure, pipe %c regs locked\n",
1177              pipe_name(pipe));
1178 }
1179
1180 static void assert_cursor(struct drm_i915_private *dev_priv,
1181                           enum pipe pipe, bool state)
1182 {
1183         struct drm_device *dev = dev_priv->dev;
1184         bool cur_state;
1185
1186         if (IS_845G(dev) || IS_I865G(dev))
1187                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1188         else
1189                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1190
1191         WARN(cur_state != state,
1192              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1193              pipe_name(pipe), state_string(state), state_string(cur_state));
1194 }
1195 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1196 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1197
1198 void assert_pipe(struct drm_i915_private *dev_priv,
1199                  enum pipe pipe, bool state)
1200 {
1201         int reg;
1202         u32 val;
1203         bool cur_state;
1204         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1205                                                                       pipe);
1206
1207         /* if we need the pipe quirk it must be always on */
1208         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1209             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1210                 state = true;
1211
1212         if (!intel_display_power_is_enabled(dev_priv,
1213                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1214                 cur_state = false;
1215         } else {
1216                 reg = PIPECONF(cpu_transcoder);
1217                 val = I915_READ(reg);
1218                 cur_state = !!(val & PIPECONF_ENABLE);
1219         }
1220
1221         WARN(cur_state != state,
1222              "pipe %c assertion failure (expected %s, current %s)\n",
1223              pipe_name(pipe), state_string(state), state_string(cur_state));
1224 }
1225
1226 static void assert_plane(struct drm_i915_private *dev_priv,
1227                          enum plane plane, bool state)
1228 {
1229         int reg;
1230         u32 val;
1231         bool cur_state;
1232
1233         reg = DSPCNTR(plane);
1234         val = I915_READ(reg);
1235         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1236         WARN(cur_state != state,
1237              "plane %c assertion failure (expected %s, current %s)\n",
1238              plane_name(plane), state_string(state), state_string(cur_state));
1239 }
1240
1241 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1242 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1243
1244 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1245                                    enum pipe pipe)
1246 {
1247         struct drm_device *dev = dev_priv->dev;
1248         int reg, i;
1249         u32 val;
1250         int cur_pipe;
1251
1252         /* Primary planes are fixed to pipes on gen4+ */
1253         if (INTEL_INFO(dev)->gen >= 4) {
1254                 reg = DSPCNTR(pipe);
1255                 val = I915_READ(reg);
1256                 WARN(val & DISPLAY_PLANE_ENABLE,
1257                      "plane %c assertion failure, should be disabled but not\n",
1258                      plane_name(pipe));
1259                 return;
1260         }
1261
1262         /* Need to check both planes against the pipe */
1263         for_each_pipe(dev_priv, i) {
1264                 reg = DSPCNTR(i);
1265                 val = I915_READ(reg);
1266                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1267                         DISPPLANE_SEL_PIPE_SHIFT;
1268                 WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1269                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1270                      plane_name(i), pipe_name(pipe));
1271         }
1272 }
1273
1274 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1275                                     enum pipe pipe)
1276 {
1277         struct drm_device *dev = dev_priv->dev;
1278         int reg, sprite;
1279         u32 val;
1280
1281         if (INTEL_INFO(dev)->gen >= 9) {
1282                 for_each_sprite(pipe, sprite) {
1283                         val = I915_READ(PLANE_CTL(pipe, sprite));
1284                         WARN(val & PLANE_CTL_ENABLE,
1285                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1286                              sprite, pipe_name(pipe));
1287                 }
1288         } else if (IS_VALLEYVIEW(dev)) {
1289                 for_each_sprite(pipe, sprite) {
1290                         reg = SPCNTR(pipe, sprite);
1291                         val = I915_READ(reg);
1292                         WARN(val & SP_ENABLE,
1293                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1294                              sprite_name(pipe, sprite), pipe_name(pipe));
1295                 }
1296         } else if (INTEL_INFO(dev)->gen >= 7) {
1297                 reg = SPRCTL(pipe);
1298                 val = I915_READ(reg);
1299                 WARN(val & SPRITE_ENABLE,
1300                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1301                      plane_name(pipe), pipe_name(pipe));
1302         } else if (INTEL_INFO(dev)->gen >= 5) {
1303                 reg = DVSCNTR(pipe);
1304                 val = I915_READ(reg);
1305                 WARN(val & DVS_ENABLE,
1306                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1307                      plane_name(pipe), pipe_name(pipe));
1308         }
1309 }
1310
1311 static void assert_vblank_disabled(struct drm_crtc *crtc)
1312 {
1313         if (WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1314                 drm_crtc_vblank_put(crtc);
1315 }
1316
1317 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1318 {
1319         u32 val;
1320         bool enabled;
1321
1322         WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1323
1324         val = I915_READ(PCH_DREF_CONTROL);
1325         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1326                             DREF_SUPERSPREAD_SOURCE_MASK));
1327         WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1328 }
1329
1330 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1331                                            enum pipe pipe)
1332 {
1333         int reg;
1334         u32 val;
1335         bool enabled;
1336
1337         reg = PCH_TRANSCONF(pipe);
1338         val = I915_READ(reg);
1339         enabled = !!(val & TRANS_ENABLE);
1340         WARN(enabled,
1341              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1342              pipe_name(pipe));
1343 }
1344
1345 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1346                             enum pipe pipe, u32 port_sel, u32 val)
1347 {
1348         if ((val & DP_PORT_EN) == 0)
1349                 return false;
1350
1351         if (HAS_PCH_CPT(dev_priv->dev)) {
1352                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1353                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1354                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1355                         return false;
1356         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1357                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1358                         return false;
1359         } else {
1360                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1361                         return false;
1362         }
1363         return true;
1364 }
1365
1366 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1367                               enum pipe pipe, u32 val)
1368 {
1369         if ((val & SDVO_ENABLE) == 0)
1370                 return false;
1371
1372         if (HAS_PCH_CPT(dev_priv->dev)) {
1373                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1374                         return false;
1375         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1376                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1377                         return false;
1378         } else {
1379                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1380                         return false;
1381         }
1382         return true;
1383 }
1384
1385 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1386                               enum pipe pipe, u32 val)
1387 {
1388         if ((val & LVDS_PORT_EN) == 0)
1389                 return false;
1390
1391         if (HAS_PCH_CPT(dev_priv->dev)) {
1392                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1393                         return false;
1394         } else {
1395                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1396                         return false;
1397         }
1398         return true;
1399 }
1400
1401 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1402                               enum pipe pipe, u32 val)
1403 {
1404         if ((val & ADPA_DAC_ENABLE) == 0)
1405                 return false;
1406         if (HAS_PCH_CPT(dev_priv->dev)) {
1407                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1408                         return false;
1409         } else {
1410                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1411                         return false;
1412         }
1413         return true;
1414 }
1415
1416 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1417                                    enum pipe pipe, int reg, u32 port_sel)
1418 {
1419         u32 val = I915_READ(reg);
1420         WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1421              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1422              reg, pipe_name(pipe));
1423
1424         WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1425              && (val & DP_PIPEB_SELECT),
1426              "IBX PCH dp port still using transcoder B\n");
1427 }
1428
1429 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1430                                      enum pipe pipe, int reg)
1431 {
1432         u32 val = I915_READ(reg);
1433         WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1434              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1435              reg, pipe_name(pipe));
1436
1437         WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1438              && (val & SDVO_PIPE_B_SELECT),
1439              "IBX PCH hdmi port still using transcoder B\n");
1440 }
1441
1442 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1443                                       enum pipe pipe)
1444 {
1445         int reg;
1446         u32 val;
1447
1448         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1449         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1450         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1451
1452         reg = PCH_ADPA;
1453         val = I915_READ(reg);
1454         WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1455              "PCH VGA enabled on transcoder %c, should be disabled\n",
1456              pipe_name(pipe));
1457
1458         reg = PCH_LVDS;
1459         val = I915_READ(reg);
1460         WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1461              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1462              pipe_name(pipe));
1463
1464         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1465         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1466         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1467 }
1468
1469 static void intel_init_dpio(struct drm_device *dev)
1470 {
1471         struct drm_i915_private *dev_priv = dev->dev_private;
1472
1473         if (!IS_VALLEYVIEW(dev))
1474                 return;
1475
1476         /*
1477          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1478          * CHV x1 PHY (DP/HDMI D)
1479          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1480          */
1481         if (IS_CHERRYVIEW(dev)) {
1482                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1483                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1484         } else {
1485                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1486         }
1487 }
1488
1489 static void vlv_enable_pll(struct intel_crtc *crtc,
1490                            const struct intel_crtc_config *pipe_config)
1491 {
1492         struct drm_device *dev = crtc->base.dev;
1493         struct drm_i915_private *dev_priv = dev->dev_private;
1494         int reg = DPLL(crtc->pipe);
1495         u32 dpll = pipe_config->dpll_hw_state.dpll;
1496
1497         assert_pipe_disabled(dev_priv, crtc->pipe);
1498
1499         /* No really, not for ILK+ */
1500         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1501
1502         /* PLL is protected by panel, make sure we can write it */
1503         if (IS_MOBILE(dev_priv->dev))
1504                 assert_panel_unlocked(dev_priv, crtc->pipe);
1505
1506         I915_WRITE(reg, dpll);
1507         POSTING_READ(reg);
1508         udelay(150);
1509
1510         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1511                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1512
1513         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1514         POSTING_READ(DPLL_MD(crtc->pipe));
1515
1516         /* We do this three times for luck */
1517         I915_WRITE(reg, dpll);
1518         POSTING_READ(reg);
1519         udelay(150); /* wait for warmup */
1520         I915_WRITE(reg, dpll);
1521         POSTING_READ(reg);
1522         udelay(150); /* wait for warmup */
1523         I915_WRITE(reg, dpll);
1524         POSTING_READ(reg);
1525         udelay(150); /* wait for warmup */
1526 }
1527
1528 static void chv_enable_pll(struct intel_crtc *crtc,
1529                            const struct intel_crtc_config *pipe_config)
1530 {
1531         struct drm_device *dev = crtc->base.dev;
1532         struct drm_i915_private *dev_priv = dev->dev_private;
1533         int pipe = crtc->pipe;
1534         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1535         u32 tmp;
1536
1537         assert_pipe_disabled(dev_priv, crtc->pipe);
1538
1539         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1540
1541         mutex_lock(&dev_priv->dpio_lock);
1542
1543         /* Enable back the 10bit clock to display controller */
1544         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1545         tmp |= DPIO_DCLKP_EN;
1546         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1547
1548         /*
1549          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1550          */
1551         udelay(1);
1552
1553         /* Enable PLL */
1554         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1555
1556         /* Check PLL is locked */
1557         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1558                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1559
1560         /* not sure when this should be written */
1561         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1562         POSTING_READ(DPLL_MD(pipe));
1563
1564         mutex_unlock(&dev_priv->dpio_lock);
1565 }
1566
1567 static int intel_num_dvo_pipes(struct drm_device *dev)
1568 {
1569         struct intel_crtc *crtc;
1570         int count = 0;
1571
1572         for_each_intel_crtc(dev, crtc)
1573                 count += crtc->active &&
1574                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1575
1576         return count;
1577 }
1578
1579 static void i9xx_enable_pll(struct intel_crtc *crtc)
1580 {
1581         struct drm_device *dev = crtc->base.dev;
1582         struct drm_i915_private *dev_priv = dev->dev_private;
1583         int reg = DPLL(crtc->pipe);
1584         u32 dpll = crtc->config.dpll_hw_state.dpll;
1585
1586         assert_pipe_disabled(dev_priv, crtc->pipe);
1587
1588         /* No really, not for ILK+ */
1589         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1590
1591         /* PLL is protected by panel, make sure we can write it */
1592         if (IS_MOBILE(dev) && !IS_I830(dev))
1593                 assert_panel_unlocked(dev_priv, crtc->pipe);
1594
1595         /* Enable DVO 2x clock on both PLLs if necessary */
1596         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1597                 /*
1598                  * It appears to be important that we don't enable this
1599                  * for the current pipe before otherwise configuring the
1600                  * PLL. No idea how this should be handled if multiple
1601                  * DVO outputs are enabled simultaneosly.
1602                  */
1603                 dpll |= DPLL_DVO_2X_MODE;
1604                 I915_WRITE(DPLL(!crtc->pipe),
1605                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1606         }
1607
1608         /* Wait for the clocks to stabilize. */
1609         POSTING_READ(reg);
1610         udelay(150);
1611
1612         if (INTEL_INFO(dev)->gen >= 4) {
1613                 I915_WRITE(DPLL_MD(crtc->pipe),
1614                            crtc->config.dpll_hw_state.dpll_md);
1615         } else {
1616                 /* The pixel multiplier can only be updated once the
1617                  * DPLL is enabled and the clocks are stable.
1618                  *
1619                  * So write it again.
1620                  */
1621                 I915_WRITE(reg, dpll);
1622         }
1623
1624         /* We do this three times for luck */
1625         I915_WRITE(reg, dpll);
1626         POSTING_READ(reg);
1627         udelay(150); /* wait for warmup */
1628         I915_WRITE(reg, dpll);
1629         POSTING_READ(reg);
1630         udelay(150); /* wait for warmup */
1631         I915_WRITE(reg, dpll);
1632         POSTING_READ(reg);
1633         udelay(150); /* wait for warmup */
1634 }
1635
1636 /**
1637  * i9xx_disable_pll - disable a PLL
1638  * @dev_priv: i915 private structure
1639  * @pipe: pipe PLL to disable
1640  *
1641  * Disable the PLL for @pipe, making sure the pipe is off first.
1642  *
1643  * Note!  This is for pre-ILK only.
1644  */
1645 static void i9xx_disable_pll(struct intel_crtc *crtc)
1646 {
1647         struct drm_device *dev = crtc->base.dev;
1648         struct drm_i915_private *dev_priv = dev->dev_private;
1649         enum pipe pipe = crtc->pipe;
1650
1651         /* Disable DVO 2x clock on both PLLs if necessary */
1652         if (IS_I830(dev) &&
1653             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1654             intel_num_dvo_pipes(dev) == 1) {
1655                 I915_WRITE(DPLL(PIPE_B),
1656                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1657                 I915_WRITE(DPLL(PIPE_A),
1658                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1659         }
1660
1661         /* Don't disable pipe or pipe PLLs if needed */
1662         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1663             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1664                 return;
1665
1666         /* Make sure the pipe isn't still relying on us */
1667         assert_pipe_disabled(dev_priv, pipe);
1668
1669         I915_WRITE(DPLL(pipe), 0);
1670         POSTING_READ(DPLL(pipe));
1671 }
1672
1673 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1674 {
1675         u32 val = 0;
1676
1677         /* Make sure the pipe isn't still relying on us */
1678         assert_pipe_disabled(dev_priv, pipe);
1679
1680         /*
1681          * Leave integrated clock source and reference clock enabled for pipe B.
1682          * The latter is needed for VGA hotplug / manual detection.
1683          */
1684         if (pipe == PIPE_B)
1685                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1686         I915_WRITE(DPLL(pipe), val);
1687         POSTING_READ(DPLL(pipe));
1688
1689 }
1690
1691 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1692 {
1693         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1694         u32 val;
1695
1696         /* Make sure the pipe isn't still relying on us */
1697         assert_pipe_disabled(dev_priv, pipe);
1698
1699         /* Set PLL en = 0 */
1700         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1701         if (pipe != PIPE_A)
1702                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1703         I915_WRITE(DPLL(pipe), val);
1704         POSTING_READ(DPLL(pipe));
1705
1706         mutex_lock(&dev_priv->dpio_lock);
1707
1708         /* Disable 10bit clock to display controller */
1709         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1710         val &= ~DPIO_DCLKP_EN;
1711         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1712
1713         /* disable left/right clock distribution */
1714         if (pipe != PIPE_B) {
1715                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1716                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1717                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1718         } else {
1719                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1720                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1721                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1722         }
1723
1724         mutex_unlock(&dev_priv->dpio_lock);
1725 }
1726
1727 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1728                 struct intel_digital_port *dport)
1729 {
1730         u32 port_mask;
1731         int dpll_reg;
1732
1733         switch (dport->port) {
1734         case PORT_B:
1735                 port_mask = DPLL_PORTB_READY_MASK;
1736                 dpll_reg = DPLL(0);
1737                 break;
1738         case PORT_C:
1739                 port_mask = DPLL_PORTC_READY_MASK;
1740                 dpll_reg = DPLL(0);
1741                 break;
1742         case PORT_D:
1743                 port_mask = DPLL_PORTD_READY_MASK;
1744                 dpll_reg = DPIO_PHY_STATUS;
1745                 break;
1746         default:
1747                 BUG();
1748         }
1749
1750         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1751                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1752                      port_name(dport->port), I915_READ(dpll_reg));
1753 }
1754
1755 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1756 {
1757         struct drm_device *dev = crtc->base.dev;
1758         struct drm_i915_private *dev_priv = dev->dev_private;
1759         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1760
1761         if (WARN_ON(pll == NULL))
1762                 return;
1763
1764         WARN_ON(!pll->refcount);
1765         if (pll->active == 0) {
1766                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1767                 WARN_ON(pll->on);
1768                 assert_shared_dpll_disabled(dev_priv, pll);
1769
1770                 pll->mode_set(dev_priv, pll);
1771         }
1772 }
1773
1774 /**
1775  * intel_enable_shared_dpll - enable PCH PLL
1776  * @dev_priv: i915 private structure
1777  * @pipe: pipe PLL to enable
1778  *
1779  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1780  * drives the transcoder clock.
1781  */
1782 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1783 {
1784         struct drm_device *dev = crtc->base.dev;
1785         struct drm_i915_private *dev_priv = dev->dev_private;
1786         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1787
1788         if (WARN_ON(pll == NULL))
1789                 return;
1790
1791         if (WARN_ON(pll->refcount == 0))
1792                 return;
1793
1794         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1795                       pll->name, pll->active, pll->on,
1796                       crtc->base.base.id);
1797
1798         if (pll->active++) {
1799                 WARN_ON(!pll->on);
1800                 assert_shared_dpll_enabled(dev_priv, pll);
1801                 return;
1802         }
1803         WARN_ON(pll->on);
1804
1805         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1806
1807         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1808         pll->enable(dev_priv, pll);
1809         pll->on = true;
1810 }
1811
1812 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1813 {
1814         struct drm_device *dev = crtc->base.dev;
1815         struct drm_i915_private *dev_priv = dev->dev_private;
1816         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1817
1818         /* PCH only available on ILK+ */
1819         BUG_ON(INTEL_INFO(dev)->gen < 5);
1820         if (WARN_ON(pll == NULL))
1821                return;
1822
1823         if (WARN_ON(pll->refcount == 0))
1824                 return;
1825
1826         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1827                       pll->name, pll->active, pll->on,
1828                       crtc->base.base.id);
1829
1830         if (WARN_ON(pll->active == 0)) {
1831                 assert_shared_dpll_disabled(dev_priv, pll);
1832                 return;
1833         }
1834
1835         assert_shared_dpll_enabled(dev_priv, pll);
1836         WARN_ON(!pll->on);
1837         if (--pll->active)
1838                 return;
1839
1840         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1841         pll->disable(dev_priv, pll);
1842         pll->on = false;
1843
1844         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1845 }
1846
1847 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1848                                            enum pipe pipe)
1849 {
1850         struct drm_device *dev = dev_priv->dev;
1851         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1852         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1853         uint32_t reg, val, pipeconf_val;
1854
1855         /* PCH only available on ILK+ */
1856         BUG_ON(!HAS_PCH_SPLIT(dev));
1857
1858         /* Make sure PCH DPLL is enabled */
1859         assert_shared_dpll_enabled(dev_priv,
1860                                    intel_crtc_to_shared_dpll(intel_crtc));
1861
1862         /* FDI must be feeding us bits for PCH ports */
1863         assert_fdi_tx_enabled(dev_priv, pipe);
1864         assert_fdi_rx_enabled(dev_priv, pipe);
1865
1866         if (HAS_PCH_CPT(dev)) {
1867                 /* Workaround: Set the timing override bit before enabling the
1868                  * pch transcoder. */
1869                 reg = TRANS_CHICKEN2(pipe);
1870                 val = I915_READ(reg);
1871                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1872                 I915_WRITE(reg, val);
1873         }
1874
1875         reg = PCH_TRANSCONF(pipe);
1876         val = I915_READ(reg);
1877         pipeconf_val = I915_READ(PIPECONF(pipe));
1878
1879         if (HAS_PCH_IBX(dev_priv->dev)) {
1880                 /*
1881                  * make the BPC in transcoder be consistent with
1882                  * that in pipeconf reg.
1883                  */
1884                 val &= ~PIPECONF_BPC_MASK;
1885                 val |= pipeconf_val & PIPECONF_BPC_MASK;
1886         }
1887
1888         val &= ~TRANS_INTERLACE_MASK;
1889         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1890                 if (HAS_PCH_IBX(dev_priv->dev) &&
1891                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1892                         val |= TRANS_LEGACY_INTERLACED_ILK;
1893                 else
1894                         val |= TRANS_INTERLACED;
1895         else
1896                 val |= TRANS_PROGRESSIVE;
1897
1898         I915_WRITE(reg, val | TRANS_ENABLE);
1899         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1900                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1901 }
1902
1903 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1904                                       enum transcoder cpu_transcoder)
1905 {
1906         u32 val, pipeconf_val;
1907
1908         /* PCH only available on ILK+ */
1909         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1910
1911         /* FDI must be feeding us bits for PCH ports */
1912         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1913         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1914
1915         /* Workaround: set timing override bit. */
1916         val = I915_READ(_TRANSA_CHICKEN2);
1917         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1918         I915_WRITE(_TRANSA_CHICKEN2, val);
1919
1920         val = TRANS_ENABLE;
1921         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1922
1923         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1924             PIPECONF_INTERLACED_ILK)
1925                 val |= TRANS_INTERLACED;
1926         else
1927                 val |= TRANS_PROGRESSIVE;
1928
1929         I915_WRITE(LPT_TRANSCONF, val);
1930         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1931                 DRM_ERROR("Failed to enable PCH transcoder\n");
1932 }
1933
1934 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1935                                             enum pipe pipe)
1936 {
1937         struct drm_device *dev = dev_priv->dev;
1938         uint32_t reg, val;
1939
1940         /* FDI relies on the transcoder */
1941         assert_fdi_tx_disabled(dev_priv, pipe);
1942         assert_fdi_rx_disabled(dev_priv, pipe);
1943
1944         /* Ports must be off as well */
1945         assert_pch_ports_disabled(dev_priv, pipe);
1946
1947         reg = PCH_TRANSCONF(pipe);
1948         val = I915_READ(reg);
1949         val &= ~TRANS_ENABLE;
1950         I915_WRITE(reg, val);
1951         /* wait for PCH transcoder off, transcoder state */
1952         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1953                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1954
1955         if (!HAS_PCH_IBX(dev)) {
1956                 /* Workaround: Clear the timing override chicken bit again. */
1957                 reg = TRANS_CHICKEN2(pipe);
1958                 val = I915_READ(reg);
1959                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1960                 I915_WRITE(reg, val);
1961         }
1962 }
1963
1964 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1965 {
1966         u32 val;
1967
1968         val = I915_READ(LPT_TRANSCONF);
1969         val &= ~TRANS_ENABLE;
1970         I915_WRITE(LPT_TRANSCONF, val);
1971         /* wait for PCH transcoder off, transcoder state */
1972         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1973                 DRM_ERROR("Failed to disable PCH transcoder\n");
1974
1975         /* Workaround: clear timing override bit. */
1976         val = I915_READ(_TRANSA_CHICKEN2);
1977         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1978         I915_WRITE(_TRANSA_CHICKEN2, val);
1979 }
1980
1981 /**
1982  * intel_enable_pipe - enable a pipe, asserting requirements
1983  * @crtc: crtc responsible for the pipe
1984  *
1985  * Enable @crtc's pipe, making sure that various hardware specific requirements
1986  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1987  */
1988 static void intel_enable_pipe(struct intel_crtc *crtc)
1989 {
1990         struct drm_device *dev = crtc->base.dev;
1991         struct drm_i915_private *dev_priv = dev->dev_private;
1992         enum pipe pipe = crtc->pipe;
1993         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1994                                                                       pipe);
1995         enum pipe pch_transcoder;
1996         int reg;
1997         u32 val;
1998
1999         assert_planes_disabled(dev_priv, pipe);
2000         assert_cursor_disabled(dev_priv, pipe);
2001         assert_sprites_disabled(dev_priv, pipe);
2002
2003         if (HAS_PCH_LPT(dev_priv->dev))
2004                 pch_transcoder = TRANSCODER_A;
2005         else
2006                 pch_transcoder = pipe;
2007
2008         /*
2009          * A pipe without a PLL won't actually be able to drive bits from
2010          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2011          * need the check.
2012          */
2013         if (!HAS_PCH_SPLIT(dev_priv->dev))
2014                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2015                         assert_dsi_pll_enabled(dev_priv);
2016                 else
2017                         assert_pll_enabled(dev_priv, pipe);
2018         else {
2019                 if (crtc->config.has_pch_encoder) {
2020                         /* if driving the PCH, we need FDI enabled */
2021                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2022                         assert_fdi_tx_pll_enabled(dev_priv,
2023                                                   (enum pipe) cpu_transcoder);
2024                 }
2025                 /* FIXME: assert CPU port conditions for SNB+ */
2026         }
2027
2028         reg = PIPECONF(cpu_transcoder);
2029         val = I915_READ(reg);
2030         if (val & PIPECONF_ENABLE) {
2031                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2032                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2033                 return;
2034         }
2035
2036         I915_WRITE(reg, val | PIPECONF_ENABLE);
2037         POSTING_READ(reg);
2038 }
2039
2040 /**
2041  * intel_disable_pipe - disable a pipe, asserting requirements
2042  * @crtc: crtc whose pipes is to be disabled
2043  *
2044  * Disable the pipe of @crtc, making sure that various hardware
2045  * specific requirements are met, if applicable, e.g. plane
2046  * disabled, panel fitter off, etc.
2047  *
2048  * Will wait until the pipe has shut down before returning.
2049  */
2050 static void intel_disable_pipe(struct intel_crtc *crtc)
2051 {
2052         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2053         enum transcoder cpu_transcoder = crtc->config.cpu_transcoder;
2054         enum pipe pipe = crtc->pipe;
2055         int reg;
2056         u32 val;
2057
2058         /*
2059          * Make sure planes won't keep trying to pump pixels to us,
2060          * or we might hang the display.
2061          */
2062         assert_planes_disabled(dev_priv, pipe);
2063         assert_cursor_disabled(dev_priv, pipe);
2064         assert_sprites_disabled(dev_priv, pipe);
2065
2066         reg = PIPECONF(cpu_transcoder);
2067         val = I915_READ(reg);
2068         if ((val & PIPECONF_ENABLE) == 0)
2069                 return;
2070
2071         /*
2072          * Double wide has implications for planes
2073          * so best keep it disabled when not needed.
2074          */
2075         if (crtc->config.double_wide)
2076                 val &= ~PIPECONF_DOUBLE_WIDE;
2077
2078         /* Don't disable pipe or pipe PLLs if needed */
2079         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2080             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2081                 val &= ~PIPECONF_ENABLE;
2082
2083         I915_WRITE(reg, val);
2084         if ((val & PIPECONF_ENABLE) == 0)
2085                 intel_wait_for_pipe_off(crtc);
2086 }
2087
2088 /*
2089  * Plane regs are double buffered, going from enabled->disabled needs a
2090  * trigger in order to latch.  The display address reg provides this.
2091  */
2092 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2093                                enum plane plane)
2094 {
2095         struct drm_device *dev = dev_priv->dev;
2096         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2097
2098         I915_WRITE(reg, I915_READ(reg));
2099         POSTING_READ(reg);
2100 }
2101
2102 /**
2103  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2104  * @plane:  plane to be enabled
2105  * @crtc: crtc for the plane
2106  *
2107  * Enable @plane on @crtc, making sure that the pipe is running first.
2108  */
2109 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2110                                           struct drm_crtc *crtc)
2111 {
2112         struct drm_device *dev = plane->dev;
2113         struct drm_i915_private *dev_priv = dev->dev_private;
2114         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2115
2116         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2117         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2118
2119         if (intel_crtc->primary_enabled)
2120                 return;
2121
2122         intel_crtc->primary_enabled = true;
2123
2124         dev_priv->display.update_primary_plane(crtc, plane->fb,
2125                                                crtc->x, crtc->y);
2126
2127         /*
2128          * BDW signals flip done immediately if the plane
2129          * is disabled, even if the plane enable is already
2130          * armed to occur at the next vblank :(
2131          */
2132         if (IS_BROADWELL(dev))
2133                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2134 }
2135
2136 /**
2137  * intel_disable_primary_hw_plane - disable the primary hardware plane
2138  * @plane: plane to be disabled
2139  * @crtc: crtc for the plane
2140  *
2141  * Disable @plane on @crtc, making sure that the pipe is running first.
2142  */
2143 static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2144                                            struct drm_crtc *crtc)
2145 {
2146         struct drm_device *dev = plane->dev;
2147         struct drm_i915_private *dev_priv = dev->dev_private;
2148         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2149
2150         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2151
2152         if (!intel_crtc->primary_enabled)
2153                 return;
2154
2155         intel_crtc->primary_enabled = false;
2156
2157         dev_priv->display.update_primary_plane(crtc, plane->fb,
2158                                                crtc->x, crtc->y);
2159 }
2160
2161 static bool need_vtd_wa(struct drm_device *dev)
2162 {
2163 #ifdef CONFIG_INTEL_IOMMU
2164         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2165                 return true;
2166 #endif
2167         return false;
2168 }
2169
2170 static int intel_align_height(struct drm_device *dev, int height, bool tiled)
2171 {
2172         int tile_height;
2173
2174         tile_height = tiled ? (IS_GEN2(dev) ? 16 : 8) : 1;
2175         return ALIGN(height, tile_height);
2176 }
2177
2178 int
2179 intel_pin_and_fence_fb_obj(struct drm_device *dev,
2180                            struct drm_i915_gem_object *obj,
2181                            struct intel_engine_cs *pipelined)
2182 {
2183         struct drm_i915_private *dev_priv = dev->dev_private;
2184         u32 alignment;
2185         int ret;
2186
2187         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2188
2189         switch (obj->tiling_mode) {
2190         case I915_TILING_NONE:
2191                 if (INTEL_INFO(dev)->gen >= 9)
2192                         alignment = 256 * 1024;
2193                 else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2194                         alignment = 128 * 1024;
2195                 else if (INTEL_INFO(dev)->gen >= 4)
2196                         alignment = 4 * 1024;
2197                 else
2198                         alignment = 64 * 1024;
2199                 break;
2200         case I915_TILING_X:
2201                 if (INTEL_INFO(dev)->gen >= 9)
2202                         alignment = 256 * 1024;
2203                 else {
2204                         /* pin() will align the object as required by fence */
2205                         alignment = 0;
2206                 }
2207                 break;
2208         case I915_TILING_Y:
2209                 WARN(1, "Y tiled bo slipped through, driver bug!\n");
2210                 return -EINVAL;
2211         default:
2212                 BUG();
2213         }
2214
2215         /* Note that the w/a also requires 64 PTE of padding following the
2216          * bo. We currently fill all unused PTE with the shadow page and so
2217          * we should always have valid PTE following the scanout preventing
2218          * the VT-d warning.
2219          */
2220         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2221                 alignment = 256 * 1024;
2222
2223         /*
2224          * Global gtt pte registers are special registers which actually forward
2225          * writes to a chunk of system memory. Which means that there is no risk
2226          * that the register values disappear as soon as we call
2227          * intel_runtime_pm_put(), so it is correct to wrap only the
2228          * pin/unpin/fence and not more.
2229          */
2230         intel_runtime_pm_get(dev_priv);
2231
2232         dev_priv->mm.interruptible = false;
2233         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined);
2234         if (ret)
2235                 goto err_interruptible;
2236
2237         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2238          * fence, whereas 965+ only requires a fence if using
2239          * framebuffer compression.  For simplicity, we always install
2240          * a fence as the cost is not that onerous.
2241          */
2242         ret = i915_gem_object_get_fence(obj);
2243         if (ret)
2244                 goto err_unpin;
2245
2246         i915_gem_object_pin_fence(obj);
2247
2248         dev_priv->mm.interruptible = true;
2249         intel_runtime_pm_put(dev_priv);
2250         return 0;
2251
2252 err_unpin:
2253         i915_gem_object_unpin_from_display_plane(obj);
2254 err_interruptible:
2255         dev_priv->mm.interruptible = true;
2256         intel_runtime_pm_put(dev_priv);
2257         return ret;
2258 }
2259
2260 void intel_unpin_fb_obj(struct drm_i915_gem_object *obj)
2261 {
2262         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2263
2264         i915_gem_object_unpin_fence(obj);
2265         i915_gem_object_unpin_from_display_plane(obj);
2266 }
2267
2268 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2269  * is assumed to be a power-of-two. */
2270 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2271                                              unsigned int tiling_mode,
2272                                              unsigned int cpp,
2273                                              unsigned int pitch)
2274 {
2275         if (tiling_mode != I915_TILING_NONE) {
2276                 unsigned int tile_rows, tiles;
2277
2278                 tile_rows = *y / 8;
2279                 *y %= 8;
2280
2281                 tiles = *x / (512/cpp);
2282                 *x %= 512/cpp;
2283
2284                 return tile_rows * pitch * 8 + tiles * 4096;
2285         } else {
2286                 unsigned int offset;
2287
2288                 offset = *y * pitch + *x * cpp;
2289                 *y = 0;
2290                 *x = (offset & 4095) / cpp;
2291                 return offset & -4096;
2292         }
2293 }
2294
2295 int intel_format_to_fourcc(int format)
2296 {
2297         switch (format) {
2298         case DISPPLANE_8BPP:
2299                 return DRM_FORMAT_C8;
2300         case DISPPLANE_BGRX555:
2301                 return DRM_FORMAT_XRGB1555;
2302         case DISPPLANE_BGRX565:
2303                 return DRM_FORMAT_RGB565;
2304         default:
2305         case DISPPLANE_BGRX888:
2306                 return DRM_FORMAT_XRGB8888;
2307         case DISPPLANE_RGBX888:
2308                 return DRM_FORMAT_XBGR8888;
2309         case DISPPLANE_BGRX101010:
2310                 return DRM_FORMAT_XRGB2101010;
2311         case DISPPLANE_RGBX101010:
2312                 return DRM_FORMAT_XBGR2101010;
2313         }
2314 }
2315
2316 static bool intel_alloc_plane_obj(struct intel_crtc *crtc,
2317                                   struct intel_plane_config *plane_config)
2318 {
2319         struct drm_device *dev = crtc->base.dev;
2320         struct drm_i915_gem_object *obj = NULL;
2321         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2322         u32 base = plane_config->base;
2323
2324         if (plane_config->size == 0)
2325                 return false;
2326
2327         obj = i915_gem_object_create_stolen_for_preallocated(dev, base, base,
2328                                                              plane_config->size);
2329         if (!obj)
2330                 return false;
2331
2332         if (plane_config->tiled) {
2333                 obj->tiling_mode = I915_TILING_X;
2334                 obj->stride = crtc->base.primary->fb->pitches[0];
2335         }
2336
2337         mode_cmd.pixel_format = crtc->base.primary->fb->pixel_format;
2338         mode_cmd.width = crtc->base.primary->fb->width;
2339         mode_cmd.height = crtc->base.primary->fb->height;
2340         mode_cmd.pitches[0] = crtc->base.primary->fb->pitches[0];
2341
2342         mutex_lock(&dev->struct_mutex);
2343
2344         if (intel_framebuffer_init(dev, to_intel_framebuffer(crtc->base.primary->fb),
2345                                    &mode_cmd, obj)) {
2346                 DRM_DEBUG_KMS("intel fb init failed\n");
2347                 goto out_unref_obj;
2348         }
2349
2350         obj->frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(crtc->pipe);
2351         mutex_unlock(&dev->struct_mutex);
2352
2353         DRM_DEBUG_KMS("plane fb obj %p\n", obj);
2354         return true;
2355
2356 out_unref_obj:
2357         drm_gem_object_unreference(&obj->base);
2358         mutex_unlock(&dev->struct_mutex);
2359         return false;
2360 }
2361
2362 static void intel_find_plane_obj(struct intel_crtc *intel_crtc,
2363                                  struct intel_plane_config *plane_config)
2364 {
2365         struct drm_device *dev = intel_crtc->base.dev;
2366         struct drm_i915_private *dev_priv = dev->dev_private;
2367         struct drm_crtc *c;
2368         struct intel_crtc *i;
2369         struct drm_i915_gem_object *obj;
2370
2371         if (!intel_crtc->base.primary->fb)
2372                 return;
2373
2374         if (intel_alloc_plane_obj(intel_crtc, plane_config))
2375                 return;
2376
2377         kfree(intel_crtc->base.primary->fb);
2378         intel_crtc->base.primary->fb = NULL;
2379
2380         /*
2381          * Failed to alloc the obj, check to see if we should share
2382          * an fb with another CRTC instead
2383          */
2384         for_each_crtc(dev, c) {
2385                 i = to_intel_crtc(c);
2386
2387                 if (c == &intel_crtc->base)
2388                         continue;
2389
2390                 if (!i->active)
2391                         continue;
2392
2393                 obj = intel_fb_obj(c->primary->fb);
2394                 if (obj == NULL)
2395                         continue;
2396
2397                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2398                         if (obj->tiling_mode != I915_TILING_NONE)
2399                                 dev_priv->preserve_bios_swizzle = true;
2400
2401                         drm_framebuffer_reference(c->primary->fb);
2402                         intel_crtc->base.primary->fb = c->primary->fb;
2403                         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2404                         break;
2405                 }
2406         }
2407 }
2408
2409 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2410                                       struct drm_framebuffer *fb,
2411                                       int x, int y)
2412 {
2413         struct drm_device *dev = crtc->dev;
2414         struct drm_i915_private *dev_priv = dev->dev_private;
2415         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2416         struct drm_i915_gem_object *obj;
2417         int plane = intel_crtc->plane;
2418         unsigned long linear_offset;
2419         u32 dspcntr;
2420         u32 reg = DSPCNTR(plane);
2421         int pixel_size;
2422
2423         if (!intel_crtc->primary_enabled) {
2424                 I915_WRITE(reg, 0);
2425                 if (INTEL_INFO(dev)->gen >= 4)
2426                         I915_WRITE(DSPSURF(plane), 0);
2427                 else
2428                         I915_WRITE(DSPADDR(plane), 0);
2429                 POSTING_READ(reg);
2430                 return;
2431         }
2432
2433         obj = intel_fb_obj(fb);
2434         if (WARN_ON(obj == NULL))
2435                 return;
2436
2437         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2438
2439         dspcntr = DISPPLANE_GAMMA_ENABLE;
2440
2441         dspcntr |= DISPLAY_PLANE_ENABLE;
2442
2443         if (INTEL_INFO(dev)->gen < 4) {
2444                 if (intel_crtc->pipe == PIPE_B)
2445                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2446
2447                 /* pipesrc and dspsize control the size that is scaled from,
2448                  * which should always be the user's requested size.
2449                  */
2450                 I915_WRITE(DSPSIZE(plane),
2451                            ((intel_crtc->config.pipe_src_h - 1) << 16) |
2452                            (intel_crtc->config.pipe_src_w - 1));
2453                 I915_WRITE(DSPPOS(plane), 0);
2454         }
2455
2456         switch (fb->pixel_format) {
2457         case DRM_FORMAT_C8:
2458                 dspcntr |= DISPPLANE_8BPP;
2459                 break;
2460         case DRM_FORMAT_XRGB1555:
2461         case DRM_FORMAT_ARGB1555:
2462                 dspcntr |= DISPPLANE_BGRX555;
2463                 break;
2464         case DRM_FORMAT_RGB565:
2465                 dspcntr |= DISPPLANE_BGRX565;
2466                 break;
2467         case DRM_FORMAT_XRGB8888:
2468         case DRM_FORMAT_ARGB8888:
2469                 dspcntr |= DISPPLANE_BGRX888;
2470                 break;
2471         case DRM_FORMAT_XBGR8888:
2472         case DRM_FORMAT_ABGR8888:
2473                 dspcntr |= DISPPLANE_RGBX888;
2474                 break;
2475         case DRM_FORMAT_XRGB2101010:
2476         case DRM_FORMAT_ARGB2101010:
2477                 dspcntr |= DISPPLANE_BGRX101010;
2478                 break;
2479         case DRM_FORMAT_XBGR2101010:
2480         case DRM_FORMAT_ABGR2101010:
2481                 dspcntr |= DISPPLANE_RGBX101010;
2482                 break;
2483         default:
2484                 BUG();
2485         }
2486
2487         if (INTEL_INFO(dev)->gen >= 4 &&
2488             obj->tiling_mode != I915_TILING_NONE)
2489                 dspcntr |= DISPPLANE_TILED;
2490
2491         if (IS_G4X(dev))
2492                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2493
2494         linear_offset = y * fb->pitches[0] + x * pixel_size;
2495
2496         if (INTEL_INFO(dev)->gen >= 4) {
2497                 intel_crtc->dspaddr_offset =
2498                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2499                                                        pixel_size,
2500                                                        fb->pitches[0]);
2501                 linear_offset -= intel_crtc->dspaddr_offset;
2502         } else {
2503                 intel_crtc->dspaddr_offset = linear_offset;
2504         }
2505
2506         if (to_intel_plane(crtc->primary)->rotation == BIT(DRM_ROTATE_180)) {
2507                 dspcntr |= DISPPLANE_ROTATE_180;
2508
2509                 x += (intel_crtc->config.pipe_src_w - 1);
2510                 y += (intel_crtc->config.pipe_src_h - 1);
2511
2512                 /* Finding the last pixel of the last line of the display
2513                 data and adding to linear_offset*/
2514                 linear_offset +=
2515                         (intel_crtc->config.pipe_src_h - 1) * fb->pitches[0] +
2516                         (intel_crtc->config.pipe_src_w - 1) * pixel_size;
2517         }
2518
2519         I915_WRITE(reg, dspcntr);
2520
2521         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2522                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2523                       fb->pitches[0]);
2524         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2525         if (INTEL_INFO(dev)->gen >= 4) {
2526                 I915_WRITE(DSPSURF(plane),
2527                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2528                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2529                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2530         } else
2531                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2532         POSTING_READ(reg);
2533 }
2534
2535 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2536                                           struct drm_framebuffer *fb,
2537                                           int x, int y)
2538 {
2539         struct drm_device *dev = crtc->dev;
2540         struct drm_i915_private *dev_priv = dev->dev_private;
2541         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2542         struct drm_i915_gem_object *obj;
2543         int plane = intel_crtc->plane;
2544         unsigned long linear_offset;
2545         u32 dspcntr;
2546         u32 reg = DSPCNTR(plane);
2547         int pixel_size;
2548
2549         if (!intel_crtc->primary_enabled) {
2550                 I915_WRITE(reg, 0);
2551                 I915_WRITE(DSPSURF(plane), 0);
2552                 POSTING_READ(reg);
2553                 return;
2554         }
2555
2556         obj = intel_fb_obj(fb);
2557         if (WARN_ON(obj == NULL))
2558                 return;
2559
2560         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2561
2562         dspcntr = DISPPLANE_GAMMA_ENABLE;
2563
2564         dspcntr |= DISPLAY_PLANE_ENABLE;
2565
2566         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2567                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2568
2569         switch (fb->pixel_format) {
2570         case DRM_FORMAT_C8:
2571                 dspcntr |= DISPPLANE_8BPP;
2572                 break;
2573         case DRM_FORMAT_RGB565:
2574                 dspcntr |= DISPPLANE_BGRX565;
2575                 break;
2576         case DRM_FORMAT_XRGB8888:
2577         case DRM_FORMAT_ARGB8888:
2578                 dspcntr |= DISPPLANE_BGRX888;
2579                 break;
2580         case DRM_FORMAT_XBGR8888:
2581         case DRM_FORMAT_ABGR8888:
2582                 dspcntr |= DISPPLANE_RGBX888;
2583                 break;
2584         case DRM_FORMAT_XRGB2101010:
2585         case DRM_FORMAT_ARGB2101010:
2586                 dspcntr |= DISPPLANE_BGRX101010;
2587                 break;
2588         case DRM_FORMAT_XBGR2101010:
2589         case DRM_FORMAT_ABGR2101010:
2590                 dspcntr |= DISPPLANE_RGBX101010;
2591                 break;
2592         default:
2593                 BUG();
2594         }
2595
2596         if (obj->tiling_mode != I915_TILING_NONE)
2597                 dspcntr |= DISPPLANE_TILED;
2598
2599         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2600                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2601
2602         linear_offset = y * fb->pitches[0] + x * pixel_size;
2603         intel_crtc->dspaddr_offset =
2604                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2605                                                pixel_size,
2606                                                fb->pitches[0]);
2607         linear_offset -= intel_crtc->dspaddr_offset;
2608         if (to_intel_plane(crtc->primary)->rotation == BIT(DRM_ROTATE_180)) {
2609                 dspcntr |= DISPPLANE_ROTATE_180;
2610
2611                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2612                         x += (intel_crtc->config.pipe_src_w - 1);
2613                         y += (intel_crtc->config.pipe_src_h - 1);
2614
2615                         /* Finding the last pixel of the last line of the display
2616                         data and adding to linear_offset*/
2617                         linear_offset +=
2618                                 (intel_crtc->config.pipe_src_h - 1) * fb->pitches[0] +
2619                                 (intel_crtc->config.pipe_src_w - 1) * pixel_size;
2620                 }
2621         }
2622
2623         I915_WRITE(reg, dspcntr);
2624
2625         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2626                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2627                       fb->pitches[0]);
2628         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2629         I915_WRITE(DSPSURF(plane),
2630                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2631         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2632                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2633         } else {
2634                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2635                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2636         }
2637         POSTING_READ(reg);
2638 }
2639
2640 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2641                                          struct drm_framebuffer *fb,
2642                                          int x, int y)
2643 {
2644         struct drm_device *dev = crtc->dev;
2645         struct drm_i915_private *dev_priv = dev->dev_private;
2646         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2647         struct intel_framebuffer *intel_fb;
2648         struct drm_i915_gem_object *obj;
2649         int pipe = intel_crtc->pipe;
2650         u32 plane_ctl, stride;
2651
2652         if (!intel_crtc->primary_enabled) {
2653                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
2654                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
2655                 POSTING_READ(PLANE_CTL(pipe, 0));
2656                 return;
2657         }
2658
2659         plane_ctl = PLANE_CTL_ENABLE |
2660                     PLANE_CTL_PIPE_GAMMA_ENABLE |
2661                     PLANE_CTL_PIPE_CSC_ENABLE;
2662
2663         switch (fb->pixel_format) {
2664         case DRM_FORMAT_RGB565:
2665                 plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
2666                 break;
2667         case DRM_FORMAT_XRGB8888:
2668                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2669                 break;
2670         case DRM_FORMAT_XBGR8888:
2671                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2672                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2673                 break;
2674         case DRM_FORMAT_XRGB2101010:
2675                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2676                 break;
2677         case DRM_FORMAT_XBGR2101010:
2678                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2679                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2680                 break;
2681         default:
2682                 BUG();
2683         }
2684
2685         intel_fb = to_intel_framebuffer(fb);
2686         obj = intel_fb->obj;
2687
2688         /*
2689          * The stride is either expressed as a multiple of 64 bytes chunks for
2690          * linear buffers or in number of tiles for tiled buffers.
2691          */
2692         switch (obj->tiling_mode) {
2693         case I915_TILING_NONE:
2694                 stride = fb->pitches[0] >> 6;
2695                 break;
2696         case I915_TILING_X:
2697                 plane_ctl |= PLANE_CTL_TILED_X;
2698                 stride = fb->pitches[0] >> 9;
2699                 break;
2700         default:
2701                 BUG();
2702         }
2703
2704         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
2705         if (to_intel_plane(crtc->primary)->rotation == BIT(DRM_ROTATE_180))
2706                 plane_ctl |= PLANE_CTL_ROTATE_180;
2707
2708         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
2709
2710         DRM_DEBUG_KMS("Writing base %08lX %d,%d,%d,%d pitch=%d\n",
2711                       i915_gem_obj_ggtt_offset(obj),
2712                       x, y, fb->width, fb->height,
2713                       fb->pitches[0]);
2714
2715         I915_WRITE(PLANE_POS(pipe, 0), 0);
2716         I915_WRITE(PLANE_OFFSET(pipe, 0), (y << 16) | x);
2717         I915_WRITE(PLANE_SIZE(pipe, 0),
2718                    (intel_crtc->config.pipe_src_h - 1) << 16 |
2719                    (intel_crtc->config.pipe_src_w - 1));
2720         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
2721         I915_WRITE(PLANE_SURF(pipe, 0), i915_gem_obj_ggtt_offset(obj));
2722
2723         POSTING_READ(PLANE_SURF(pipe, 0));
2724 }
2725
2726 /* Assume fb object is pinned & idle & fenced and just update base pointers */
2727 static int
2728 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2729                            int x, int y, enum mode_set_atomic state)
2730 {
2731         struct drm_device *dev = crtc->dev;
2732         struct drm_i915_private *dev_priv = dev->dev_private;
2733
2734         if (dev_priv->display.disable_fbc)
2735                 dev_priv->display.disable_fbc(dev);
2736
2737         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2738
2739         return 0;
2740 }
2741
2742 void intel_display_handle_reset(struct drm_device *dev)
2743 {
2744         struct drm_i915_private *dev_priv = dev->dev_private;
2745         struct drm_crtc *crtc;
2746
2747         /*
2748          * Flips in the rings have been nuked by the reset,
2749          * so complete all pending flips so that user space
2750          * will get its events and not get stuck.
2751          *
2752          * Also update the base address of all primary
2753          * planes to the the last fb to make sure we're
2754          * showing the correct fb after a reset.
2755          *
2756          * Need to make two loops over the crtcs so that we
2757          * don't try to grab a crtc mutex before the
2758          * pending_flip_queue really got woken up.
2759          */
2760
2761         for_each_crtc(dev, crtc) {
2762                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2763                 enum plane plane = intel_crtc->plane;
2764
2765                 intel_prepare_page_flip(dev, plane);
2766                 intel_finish_page_flip_plane(dev, plane);
2767         }
2768
2769         for_each_crtc(dev, crtc) {
2770                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2771
2772                 drm_modeset_lock(&crtc->mutex, NULL);
2773                 /*
2774                  * FIXME: Once we have proper support for primary planes (and
2775                  * disabling them without disabling the entire crtc) allow again
2776                  * a NULL crtc->primary->fb.
2777                  */
2778                 if (intel_crtc->active && crtc->primary->fb)
2779                         dev_priv->display.update_primary_plane(crtc,
2780                                                                crtc->primary->fb,
2781                                                                crtc->x,
2782                                                                crtc->y);
2783                 drm_modeset_unlock(&crtc->mutex);
2784         }
2785 }
2786
2787 static int
2788 intel_finish_fb(struct drm_framebuffer *old_fb)
2789 {
2790         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
2791         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2792         bool was_interruptible = dev_priv->mm.interruptible;
2793         int ret;
2794
2795         /* Big Hammer, we also need to ensure that any pending
2796          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
2797          * current scanout is retired before unpinning the old
2798          * framebuffer.
2799          *
2800          * This should only fail upon a hung GPU, in which case we
2801          * can safely continue.
2802          */
2803         dev_priv->mm.interruptible = false;
2804         ret = i915_gem_object_finish_gpu(obj);
2805         dev_priv->mm.interruptible = was_interruptible;
2806
2807         return ret;
2808 }
2809
2810 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
2811 {
2812         struct drm_device *dev = crtc->dev;
2813         struct drm_i915_private *dev_priv = dev->dev_private;
2814         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2815         bool pending;
2816
2817         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
2818             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
2819                 return false;
2820
2821         spin_lock_irq(&dev->event_lock);
2822         pending = to_intel_crtc(crtc)->unpin_work != NULL;
2823         spin_unlock_irq(&dev->event_lock);
2824
2825         return pending;
2826 }
2827
2828 static void intel_update_pipe_size(struct intel_crtc *crtc)
2829 {
2830         struct drm_device *dev = crtc->base.dev;
2831         struct drm_i915_private *dev_priv = dev->dev_private;
2832         const struct drm_display_mode *adjusted_mode;
2833
2834         if (!i915.fastboot)
2835                 return;
2836
2837         /*
2838          * Update pipe size and adjust fitter if needed: the reason for this is
2839          * that in compute_mode_changes we check the native mode (not the pfit
2840          * mode) to see if we can flip rather than do a full mode set. In the
2841          * fastboot case, we'll flip, but if we don't update the pipesrc and
2842          * pfit state, we'll end up with a big fb scanned out into the wrong
2843          * sized surface.
2844          *
2845          * To fix this properly, we need to hoist the checks up into
2846          * compute_mode_changes (or above), check the actual pfit state and
2847          * whether the platform allows pfit disable with pipe active, and only
2848          * then update the pipesrc and pfit state, even on the flip path.
2849          */
2850
2851         adjusted_mode = &crtc->config.adjusted_mode;
2852
2853         I915_WRITE(PIPESRC(crtc->pipe),
2854                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
2855                    (adjusted_mode->crtc_vdisplay - 1));
2856         if (!crtc->config.pch_pfit.enabled &&
2857             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
2858              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
2859                 I915_WRITE(PF_CTL(crtc->pipe), 0);
2860                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
2861                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
2862         }
2863         crtc->config.pipe_src_w = adjusted_mode->crtc_hdisplay;
2864         crtc->config.pipe_src_h = adjusted_mode->crtc_vdisplay;
2865 }
2866
2867 static int
2868 intel_pipe_set_base(struct drm_crtc *crtc, int x, int y,
2869                     struct drm_framebuffer *fb)
2870 {
2871         struct drm_device *dev = crtc->dev;
2872         struct drm_i915_private *dev_priv = dev->dev_private;
2873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2874         enum pipe pipe = intel_crtc->pipe;
2875         struct drm_framebuffer *old_fb = crtc->primary->fb;
2876         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2877         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_fb);
2878         int ret;
2879
2880         if (intel_crtc_has_pending_flip(crtc)) {
2881                 DRM_ERROR("pipe is still busy with an old pageflip\n");
2882                 return -EBUSY;
2883         }
2884
2885         /* no fb bound */
2886         if (!fb) {
2887                 DRM_ERROR("No FB bound\n");
2888                 return 0;
2889         }
2890
2891         if (intel_crtc->plane > INTEL_INFO(dev)->num_pipes) {
2892                 DRM_ERROR("no plane for crtc: plane %c, num_pipes %d\n",
2893                           plane_name(intel_crtc->plane),
2894                           INTEL_INFO(dev)->num_pipes);
2895                 return -EINVAL;
2896         }
2897
2898         mutex_lock(&dev->struct_mutex);
2899         ret = intel_pin_and_fence_fb_obj(dev, obj, NULL);
2900         if (ret == 0)
2901                 i915_gem_track_fb(old_obj, obj,
2902                                   INTEL_FRONTBUFFER_PRIMARY(pipe));
2903         mutex_unlock(&dev->struct_mutex);
2904         if (ret != 0) {
2905                 DRM_ERROR("pin & fence failed\n");
2906                 return ret;
2907         }
2908
2909         intel_update_pipe_size(intel_crtc);
2910
2911         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2912
2913         if (intel_crtc->active)
2914                 intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
2915
2916         crtc->primary->fb = fb;
2917         crtc->x = x;
2918         crtc->y = y;
2919
2920         if (old_fb) {
2921                 if (intel_crtc->active && old_fb != fb)
2922                         intel_wait_for_vblank(dev, intel_crtc->pipe);
2923                 mutex_lock(&dev->struct_mutex);
2924                 intel_unpin_fb_obj(old_obj);
2925                 mutex_unlock(&dev->struct_mutex);
2926         }
2927
2928         mutex_lock(&dev->struct_mutex);
2929         intel_update_fbc(dev);
2930         mutex_unlock(&dev->struct_mutex);
2931
2932         return 0;
2933 }
2934
2935 static void intel_fdi_normal_train(struct drm_crtc *crtc)
2936 {
2937         struct drm_device *dev = crtc->dev;
2938         struct drm_i915_private *dev_priv = dev->dev_private;
2939         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2940         int pipe = intel_crtc->pipe;
2941         u32 reg, temp;
2942
2943         /* enable normal train */
2944         reg = FDI_TX_CTL(pipe);
2945         temp = I915_READ(reg);
2946         if (IS_IVYBRIDGE(dev)) {
2947                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
2948                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
2949         } else {
2950                 temp &= ~FDI_LINK_TRAIN_NONE;
2951                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
2952         }
2953         I915_WRITE(reg, temp);
2954
2955         reg = FDI_RX_CTL(pipe);
2956         temp = I915_READ(reg);
2957         if (HAS_PCH_CPT(dev)) {
2958                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
2959                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
2960         } else {
2961                 temp &= ~FDI_LINK_TRAIN_NONE;
2962                 temp |= FDI_LINK_TRAIN_NONE;
2963         }
2964         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
2965
2966         /* wait one idle pattern time */
2967         POSTING_READ(reg);
2968         udelay(1000);
2969
2970         /* IVB wants error correction enabled */
2971         if (IS_IVYBRIDGE(dev))
2972                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
2973                            FDI_FE_ERRC_ENABLE);
2974 }
2975
2976 static bool pipe_has_enabled_pch(struct intel_crtc *crtc)
2977 {
2978         return crtc->base.enabled && crtc->active &&
2979                 crtc->config.has_pch_encoder;
2980 }
2981
2982 static void ivb_modeset_global_resources(struct drm_device *dev)
2983 {
2984         struct drm_i915_private *dev_priv = dev->dev_private;
2985         struct intel_crtc *pipe_B_crtc =
2986                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
2987         struct intel_crtc *pipe_C_crtc =
2988                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_C]);
2989         uint32_t temp;
2990
2991         /*
2992          * When everything is off disable fdi C so that we could enable fdi B
2993          * with all lanes. Note that we don't care about enabled pipes without
2994          * an enabled pch encoder.
2995          */
2996         if (!pipe_has_enabled_pch(pipe_B_crtc) &&
2997             !pipe_has_enabled_pch(pipe_C_crtc)) {
2998                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
2999                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3000
3001                 temp = I915_READ(SOUTH_CHICKEN1);
3002                 temp &= ~FDI_BC_BIFURCATION_SELECT;
3003                 DRM_DEBUG_KMS("disabling fdi C rx\n");
3004                 I915_WRITE(SOUTH_CHICKEN1, temp);
3005         }
3006 }
3007
3008 /* The FDI link training functions for ILK/Ibexpeak. */
3009 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3010 {
3011         struct drm_device *dev = crtc->dev;
3012         struct drm_i915_private *dev_priv = dev->dev_private;
3013         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3014         int pipe = intel_crtc->pipe;
3015         u32 reg, temp, tries;
3016
3017         /* FDI needs bits from pipe first */
3018         assert_pipe_enabled(dev_priv, pipe);
3019
3020         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3021            for train result */
3022         reg = FDI_RX_IMR(pipe);
3023         temp = I915_READ(reg);
3024         temp &= ~FDI_RX_SYMBOL_LOCK;
3025         temp &= ~FDI_RX_BIT_LOCK;
3026         I915_WRITE(reg, temp);
3027         I915_READ(reg);
3028         udelay(150);
3029
3030         /* enable CPU FDI TX and PCH FDI RX */
3031         reg = FDI_TX_CTL(pipe);
3032         temp = I915_READ(reg);
3033         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3034         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3035         temp &= ~FDI_LINK_TRAIN_NONE;
3036         temp |= FDI_LINK_TRAIN_PATTERN_1;
3037         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3038
3039         reg = FDI_RX_CTL(pipe);
3040         temp = I915_READ(reg);
3041         temp &= ~FDI_LINK_TRAIN_NONE;
3042         temp |= FDI_LINK_TRAIN_PATTERN_1;
3043         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3044
3045         POSTING_READ(reg);
3046         udelay(150);
3047
3048         /* Ironlake workaround, enable clock pointer after FDI enable*/
3049         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3050         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3051                    FDI_RX_PHASE_SYNC_POINTER_EN);
3052
3053         reg = FDI_RX_IIR(pipe);
3054         for (tries = 0; tries < 5; tries++) {
3055                 temp = I915_READ(reg);
3056                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3057
3058                 if ((temp & FDI_RX_BIT_LOCK)) {
3059                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3060                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3061                         break;
3062                 }
3063         }
3064         if (tries == 5)
3065                 DRM_ERROR("FDI train 1 fail!\n");
3066
3067         /* Train 2 */
3068         reg = FDI_TX_CTL(pipe);
3069         temp = I915_READ(reg);
3070         temp &= ~FDI_LINK_TRAIN_NONE;
3071         temp |= FDI_LINK_TRAIN_PATTERN_2;
3072         I915_WRITE(reg, temp);
3073
3074         reg = FDI_RX_CTL(pipe);
3075         temp = I915_READ(reg);
3076         temp &= ~FDI_LINK_TRAIN_NONE;
3077         temp |= FDI_LINK_TRAIN_PATTERN_2;
3078         I915_WRITE(reg, temp);
3079
3080         POSTING_READ(reg);
3081         udelay(150);
3082
3083         reg = FDI_RX_IIR(pipe);
3084         for (tries = 0; tries < 5; tries++) {
3085                 temp = I915_READ(reg);
3086                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3087
3088                 if (temp & FDI_RX_SYMBOL_LOCK) {
3089                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3090                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3091                         break;
3092                 }
3093         }
3094         if (tries == 5)
3095                 DRM_ERROR("FDI train 2 fail!\n");
3096
3097         DRM_DEBUG_KMS("FDI train done\n");
3098
3099 }
3100
3101 static const int snb_b_fdi_train_param[] = {
3102         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3103         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3104         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3105         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3106 };
3107
3108 /* The FDI link training functions for SNB/Cougarpoint. */
3109 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3110 {
3111         struct drm_device *dev = crtc->dev;
3112         struct drm_i915_private *dev_priv = dev->dev_private;
3113         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3114         int pipe = intel_crtc->pipe;
3115         u32 reg, temp, i, retry;
3116
3117         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3118            for train result */
3119         reg = FDI_RX_IMR(pipe);
3120         temp = I915_READ(reg);
3121         temp &= ~FDI_RX_SYMBOL_LOCK;
3122         temp &= ~FDI_RX_BIT_LOCK;
3123         I915_WRITE(reg, temp);
3124
3125         POSTING_READ(reg);
3126         udelay(150);
3127
3128         /* enable CPU FDI TX and PCH FDI RX */
3129         reg = FDI_TX_CTL(pipe);
3130         temp = I915_READ(reg);
3131         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3132         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3133         temp &= ~FDI_LINK_TRAIN_NONE;
3134         temp |= FDI_LINK_TRAIN_PATTERN_1;
3135         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3136         /* SNB-B */
3137         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3138         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3139
3140         I915_WRITE(FDI_RX_MISC(pipe),
3141                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3142
3143         reg = FDI_RX_CTL(pipe);
3144         temp = I915_READ(reg);
3145         if (HAS_PCH_CPT(dev)) {
3146                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3147                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3148         } else {
3149                 temp &= ~FDI_LINK_TRAIN_NONE;
3150                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3151         }
3152         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3153
3154         POSTING_READ(reg);
3155         udelay(150);
3156
3157         for (i = 0; i < 4; i++) {
3158                 reg = FDI_TX_CTL(pipe);
3159                 temp = I915_READ(reg);
3160                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3161                 temp |= snb_b_fdi_train_param[i];
3162                 I915_WRITE(reg, temp);
3163
3164                 POSTING_READ(reg);
3165                 udelay(500);
3166
3167                 for (retry = 0; retry < 5; retry++) {
3168                         reg = FDI_RX_IIR(pipe);
3169                         temp = I915_READ(reg);
3170                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3171                         if (temp & FDI_RX_BIT_LOCK) {
3172                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3173                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3174                                 break;
3175                         }
3176                         udelay(50);
3177                 }
3178                 if (retry < 5)
3179                         break;
3180         }
3181         if (i == 4)
3182                 DRM_ERROR("FDI train 1 fail!\n");
3183
3184         /* Train 2 */
3185         reg = FDI_TX_CTL(pipe);
3186         temp = I915_READ(reg);
3187         temp &= ~FDI_LINK_TRAIN_NONE;
3188         temp |= FDI_LINK_TRAIN_PATTERN_2;
3189         if (IS_GEN6(dev)) {
3190                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3191                 /* SNB-B */
3192                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3193         }
3194         I915_WRITE(reg, temp);
3195
3196         reg = FDI_RX_CTL(pipe);
3197         temp = I915_READ(reg);
3198         if (HAS_PCH_CPT(dev)) {
3199                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3200                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3201         } else {
3202                 temp &= ~FDI_LINK_TRAIN_NONE;
3203                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3204         }
3205         I915_WRITE(reg, temp);
3206
3207         POSTING_READ(reg);
3208         udelay(150);
3209
3210         for (i = 0; i < 4; i++) {
3211                 reg = FDI_TX_CTL(pipe);
3212                 temp = I915_READ(reg);
3213                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3214                 temp |= snb_b_fdi_train_param[i];
3215                 I915_WRITE(reg, temp);
3216
3217                 POSTING_READ(reg);
3218                 udelay(500);
3219
3220                 for (retry = 0; retry < 5; retry++) {
3221                         reg = FDI_RX_IIR(pipe);
3222                         temp = I915_READ(reg);
3223                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3224                         if (temp & FDI_RX_SYMBOL_LOCK) {
3225                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3226                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3227                                 break;
3228                         }
3229                         udelay(50);
3230                 }
3231                 if (retry < 5)
3232                         break;
3233         }
3234         if (i == 4)
3235                 DRM_ERROR("FDI train 2 fail!\n");
3236
3237         DRM_DEBUG_KMS("FDI train done.\n");
3238 }
3239
3240 /* Manual link training for Ivy Bridge A0 parts */
3241 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3242 {
3243         struct drm_device *dev = crtc->dev;
3244         struct drm_i915_private *dev_priv = dev->dev_private;
3245         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3246         int pipe = intel_crtc->pipe;
3247         u32 reg, temp, i, j;
3248
3249         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3250            for train result */
3251         reg = FDI_RX_IMR(pipe);
3252         temp = I915_READ(reg);
3253         temp &= ~FDI_RX_SYMBOL_LOCK;
3254         temp &= ~FDI_RX_BIT_LOCK;
3255         I915_WRITE(reg, temp);
3256
3257         POSTING_READ(reg);
3258         udelay(150);
3259
3260         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3261                       I915_READ(FDI_RX_IIR(pipe)));
3262
3263         /* Try each vswing and preemphasis setting twice before moving on */
3264         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3265                 /* disable first in case we need to retry */
3266                 reg = FDI_TX_CTL(pipe);
3267                 temp = I915_READ(reg);
3268                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3269                 temp &= ~FDI_TX_ENABLE;
3270                 I915_WRITE(reg, temp);
3271
3272                 reg = FDI_RX_CTL(pipe);
3273                 temp = I915_READ(reg);
3274                 temp &= ~FDI_LINK_TRAIN_AUTO;
3275                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3276                 temp &= ~FDI_RX_ENABLE;
3277                 I915_WRITE(reg, temp);
3278
3279                 /* enable CPU FDI TX and PCH FDI RX */
3280                 reg = FDI_TX_CTL(pipe);
3281                 temp = I915_READ(reg);
3282                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3283                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3284                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3285                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3286                 temp |= snb_b_fdi_train_param[j/2];
3287                 temp |= FDI_COMPOSITE_SYNC;
3288                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3289
3290                 I915_WRITE(FDI_RX_MISC(pipe),
3291                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3292
3293                 reg = FDI_RX_CTL(pipe);
3294                 temp = I915_READ(reg);
3295                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3296                 temp |= FDI_COMPOSITE_SYNC;
3297                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3298
3299                 POSTING_READ(reg);
3300                 udelay(1); /* should be 0.5us */
3301
3302                 for (i = 0; i < 4; i++) {
3303                         reg = FDI_RX_IIR(pipe);
3304                         temp = I915_READ(reg);
3305                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3306
3307                         if (temp & FDI_RX_BIT_LOCK ||
3308                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3309                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3310                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3311                                               i);
3312                                 break;
3313                         }
3314                         udelay(1); /* should be 0.5us */
3315                 }
3316                 if (i == 4) {
3317                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3318                         continue;
3319                 }
3320
3321                 /* Train 2 */
3322                 reg = FDI_TX_CTL(pipe);
3323                 temp = I915_READ(reg);
3324                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3325                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3326                 I915_WRITE(reg, temp);
3327
3328                 reg = FDI_RX_CTL(pipe);
3329                 temp = I915_READ(reg);
3330                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3331                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3332                 I915_WRITE(reg, temp);
3333
3334                 POSTING_READ(reg);
3335                 udelay(2); /* should be 1.5us */
3336
3337                 for (i = 0; i < 4; i++) {
3338                         reg = FDI_RX_IIR(pipe);
3339                         temp = I915_READ(reg);
3340                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3341
3342                         if (temp & FDI_RX_SYMBOL_LOCK ||
3343                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3344                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3345                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3346                                               i);
3347                                 goto train_done;
3348                         }
3349                         udelay(2); /* should be 1.5us */
3350                 }
3351                 if (i == 4)
3352                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3353         }
3354
3355 train_done:
3356         DRM_DEBUG_KMS("FDI train done.\n");
3357 }
3358
3359 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3360 {
3361         struct drm_device *dev = intel_crtc->base.dev;
3362         struct drm_i915_private *dev_priv = dev->dev_private;
3363         int pipe = intel_crtc->pipe;
3364         u32 reg, temp;
3365
3366
3367         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3368         reg = FDI_RX_CTL(pipe);
3369         temp = I915_READ(reg);
3370         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3371         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config.fdi_lanes);
3372         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3373         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3374
3375         POSTING_READ(reg);
3376         udelay(200);
3377
3378         /* Switch from Rawclk to PCDclk */
3379         temp = I915_READ(reg);
3380         I915_WRITE(reg, temp | FDI_PCDCLK);
3381
3382         POSTING_READ(reg);
3383         udelay(200);
3384
3385         /* Enable CPU FDI TX PLL, always on for Ironlake */
3386         reg = FDI_TX_CTL(pipe);
3387         temp = I915_READ(reg);
3388         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3389                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3390
3391                 POSTING_READ(reg);
3392                 udelay(100);
3393         }
3394 }
3395
3396 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3397 {
3398         struct drm_device *dev = intel_crtc->base.dev;
3399         struct drm_i915_private *dev_priv = dev->dev_private;
3400         int pipe = intel_crtc->pipe;
3401         u32 reg, temp;
3402
3403         /* Switch from PCDclk to Rawclk */
3404         reg = FDI_RX_CTL(pipe);
3405         temp = I915_READ(reg);
3406         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3407
3408         /* Disable CPU FDI TX PLL */
3409         reg = FDI_TX_CTL(pipe);
3410         temp = I915_READ(reg);
3411         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3412
3413         POSTING_READ(reg);
3414         udelay(100);
3415
3416         reg = FDI_RX_CTL(pipe);
3417         temp = I915_READ(reg);
3418         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3419
3420         /* Wait for the clocks to turn off. */
3421         POSTING_READ(reg);
3422         udelay(100);
3423 }
3424
3425 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3426 {
3427         struct drm_device *dev = crtc->dev;
3428         struct drm_i915_private *dev_priv = dev->dev_private;
3429         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3430         int pipe = intel_crtc->pipe;
3431         u32 reg, temp;
3432
3433         /* disable CPU FDI tx and PCH FDI rx */
3434         reg = FDI_TX_CTL(pipe);
3435         temp = I915_READ(reg);
3436         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3437         POSTING_READ(reg);
3438
3439         reg = FDI_RX_CTL(pipe);
3440         temp = I915_READ(reg);
3441         temp &= ~(0x7 << 16);
3442         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3443         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3444
3445         POSTING_READ(reg);
3446         udelay(100);
3447
3448         /* Ironlake workaround, disable clock pointer after downing FDI */
3449         if (HAS_PCH_IBX(dev))
3450                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3451
3452         /* still set train pattern 1 */
3453         reg = FDI_TX_CTL(pipe);
3454         temp = I915_READ(reg);
3455         temp &= ~FDI_LINK_TRAIN_NONE;
3456         temp |= FDI_LINK_TRAIN_PATTERN_1;
3457         I915_WRITE(reg, temp);
3458
3459         reg = FDI_RX_CTL(pipe);
3460         temp = I915_READ(reg);
3461         if (HAS_PCH_CPT(dev)) {
3462                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3463                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3464         } else {
3465                 temp &= ~FDI_LINK_TRAIN_NONE;
3466                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3467         }
3468         /* BPC in FDI rx is consistent with that in PIPECONF */
3469         temp &= ~(0x07 << 16);
3470         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3471         I915_WRITE(reg, temp);
3472
3473         POSTING_READ(reg);
3474         udelay(100);
3475 }
3476
3477 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3478 {
3479         struct intel_crtc *crtc;
3480
3481         /* Note that we don't need to be called with mode_config.lock here
3482          * as our list of CRTC objects is static for the lifetime of the
3483          * device and so cannot disappear as we iterate. Similarly, we can
3484          * happily treat the predicates as racy, atomic checks as userspace
3485          * cannot claim and pin a new fb without at least acquring the
3486          * struct_mutex and so serialising with us.
3487          */
3488         for_each_intel_crtc(dev, crtc) {
3489                 if (atomic_read(&crtc->unpin_work_count) == 0)
3490                         continue;
3491
3492                 if (crtc->unpin_work)
3493                         intel_wait_for_vblank(dev, crtc->pipe);
3494
3495                 return true;
3496         }
3497
3498         return false;
3499 }
3500
3501 static void page_flip_completed(struct intel_crtc *intel_crtc)
3502 {
3503         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3504         struct intel_unpin_work *work = intel_crtc->unpin_work;
3505
3506         /* ensure that the unpin work is consistent wrt ->pending. */
3507         smp_rmb();
3508         intel_crtc->unpin_work = NULL;
3509
3510         if (work->event)
3511                 drm_send_vblank_event(intel_crtc->base.dev,
3512                                       intel_crtc->pipe,
3513                                       work->event);
3514
3515         drm_crtc_vblank_put(&intel_crtc->base);
3516
3517         wake_up_all(&dev_priv->pending_flip_queue);
3518         queue_work(dev_priv->wq, &work->work);
3519
3520         trace_i915_flip_complete(intel_crtc->plane,
3521                                  work->pending_flip_obj);
3522 }
3523
3524 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3525 {
3526         struct drm_device *dev = crtc->dev;
3527         struct drm_i915_private *dev_priv = dev->dev_private;
3528
3529         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3530         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3531                                        !intel_crtc_has_pending_flip(crtc),
3532                                        60*HZ) == 0)) {
3533                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3534
3535                 spin_lock_irq(&dev->event_lock);
3536                 if (intel_crtc->unpin_work) {
3537                         WARN_ONCE(1, "Removing stuck page flip\n");
3538                         page_flip_completed(intel_crtc);
3539                 }
3540                 spin_unlock_irq(&dev->event_lock);
3541         }
3542
3543         if (crtc->primary->fb) {
3544                 mutex_lock(&dev->struct_mutex);
3545                 intel_finish_fb(crtc->primary->fb);
3546                 mutex_unlock(&dev->struct_mutex);
3547         }
3548 }
3549
3550 /* Program iCLKIP clock to the desired frequency */
3551 static void lpt_program_iclkip(struct drm_crtc *crtc)
3552 {
3553         struct drm_device *dev = crtc->dev;
3554         struct drm_i915_private *dev_priv = dev->dev_private;
3555         int clock = to_intel_crtc(crtc)->config.adjusted_mode.crtc_clock;
3556         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3557         u32 temp;
3558
3559         mutex_lock(&dev_priv->dpio_lock);
3560
3561         /* It is necessary to ungate the pixclk gate prior to programming
3562          * the divisors, and gate it back when it is done.
3563          */
3564         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3565
3566         /* Disable SSCCTL */
3567         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3568                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3569                                 SBI_SSCCTL_DISABLE,
3570                         SBI_ICLK);
3571
3572         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3573         if (clock == 20000) {
3574                 auxdiv = 1;
3575                 divsel = 0x41;
3576                 phaseinc = 0x20;
3577         } else {
3578                 /* The iCLK virtual clock root frequency is in MHz,
3579                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3580                  * divisors, it is necessary to divide one by another, so we
3581                  * convert the virtual clock precision to KHz here for higher
3582                  * precision.
3583                  */
3584                 u32 iclk_virtual_root_freq = 172800 * 1000;
3585                 u32 iclk_pi_range = 64;
3586                 u32 desired_divisor, msb_divisor_value, pi_value;
3587
3588                 desired_divisor = (iclk_virtual_root_freq / clock);
3589                 msb_divisor_value = desired_divisor / iclk_pi_range;
3590                 pi_value = desired_divisor % iclk_pi_range;
3591
3592                 auxdiv = 0;
3593                 divsel = msb_divisor_value - 2;
3594                 phaseinc = pi_value;
3595         }
3596
3597         /* This should not happen with any sane values */
3598         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3599                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3600         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3601                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3602
3603         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3604                         clock,
3605                         auxdiv,
3606                         divsel,
3607                         phasedir,
3608                         phaseinc);
3609
3610         /* Program SSCDIVINTPHASE6 */
3611         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3612         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3613         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3614         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3615         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3616         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3617         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3618         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3619
3620         /* Program SSCAUXDIV */
3621         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3622         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3623         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3624         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3625
3626         /* Enable modulator and associated divider */
3627         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3628         temp &= ~SBI_SSCCTL_DISABLE;
3629         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3630
3631         /* Wait for initialization time */
3632         udelay(24);
3633
3634         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3635
3636         mutex_unlock(&dev_priv->dpio_lock);
3637 }
3638
3639 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3640                                                 enum pipe pch_transcoder)
3641 {
3642         struct drm_device *dev = crtc->base.dev;
3643         struct drm_i915_private *dev_priv = dev->dev_private;
3644         enum transcoder cpu_transcoder = crtc->config.cpu_transcoder;
3645
3646         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3647                    I915_READ(HTOTAL(cpu_transcoder)));
3648         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3649                    I915_READ(HBLANK(cpu_transcoder)));
3650         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3651                    I915_READ(HSYNC(cpu_transcoder)));
3652
3653         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3654                    I915_READ(VTOTAL(cpu_transcoder)));
3655         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3656                    I915_READ(VBLANK(cpu_transcoder)));
3657         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3658                    I915_READ(VSYNC(cpu_transcoder)));
3659         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3660                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3661 }
3662
3663 static void cpt_enable_fdi_bc_bifurcation(struct drm_device *dev)
3664 {
3665         struct drm_i915_private *dev_priv = dev->dev_private;
3666         uint32_t temp;
3667
3668         temp = I915_READ(SOUTH_CHICKEN1);
3669         if (temp & FDI_BC_BIFURCATION_SELECT)
3670                 return;
3671
3672         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3673         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3674
3675         temp |= FDI_BC_BIFURCATION_SELECT;
3676         DRM_DEBUG_KMS("enabling fdi C rx\n");
3677         I915_WRITE(SOUTH_CHICKEN1, temp);
3678         POSTING_READ(SOUTH_CHICKEN1);
3679 }
3680
3681 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3682 {
3683         struct drm_device *dev = intel_crtc->base.dev;
3684         struct drm_i915_private *dev_priv = dev->dev_private;
3685
3686         switch (intel_crtc->pipe) {
3687         case PIPE_A:
3688                 break;
3689         case PIPE_B:
3690                 if (intel_crtc->config.fdi_lanes > 2)
3691                         WARN_ON(I915_READ(SOUTH_CHICKEN1) & FDI_BC_BIFURCATION_SELECT);
3692                 else
3693                         cpt_enable_fdi_bc_bifurcation(dev);
3694
3695                 break;
3696         case PIPE_C:
3697                 cpt_enable_fdi_bc_bifurcation(dev);
3698
3699                 break;
3700         default:
3701                 BUG();
3702         }
3703 }
3704
3705 /*
3706  * Enable PCH resources required for PCH ports:
3707  *   - PCH PLLs
3708  *   - FDI training & RX/TX
3709  *   - update transcoder timings
3710  *   - DP transcoding bits
3711  *   - transcoder
3712  */
3713 static void ironlake_pch_enable(struct drm_crtc *crtc)
3714 {
3715         struct drm_device *dev = crtc->dev;
3716         struct drm_i915_private *dev_priv = dev->dev_private;
3717         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3718         int pipe = intel_crtc->pipe;
3719         u32 reg, temp;
3720
3721         assert_pch_transcoder_disabled(dev_priv, pipe);
3722
3723         if (IS_IVYBRIDGE(dev))
3724                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
3725
3726         /* Write the TU size bits before fdi link training, so that error
3727          * detection works. */
3728         I915_WRITE(FDI_RX_TUSIZE1(pipe),
3729                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
3730
3731         /* For PCH output, training FDI link */
3732         dev_priv->display.fdi_link_train(crtc);
3733
3734         /* We need to program the right clock selection before writing the pixel
3735          * mutliplier into the DPLL. */
3736         if (HAS_PCH_CPT(dev)) {
3737                 u32 sel;
3738
3739                 temp = I915_READ(PCH_DPLL_SEL);
3740                 temp |= TRANS_DPLL_ENABLE(pipe);
3741                 sel = TRANS_DPLLB_SEL(pipe);
3742                 if (intel_crtc->config.shared_dpll == DPLL_ID_PCH_PLL_B)
3743                         temp |= sel;
3744                 else
3745                         temp &= ~sel;
3746                 I915_WRITE(PCH_DPLL_SEL, temp);
3747         }
3748
3749         /* XXX: pch pll's can be enabled any time before we enable the PCH
3750          * transcoder, and we actually should do this to not upset any PCH
3751          * transcoder that already use the clock when we share it.
3752          *
3753          * Note that enable_shared_dpll tries to do the right thing, but
3754          * get_shared_dpll unconditionally resets the pll - we need that to have
3755          * the right LVDS enable sequence. */
3756         intel_enable_shared_dpll(intel_crtc);
3757
3758         /* set transcoder timing, panel must allow it */
3759         assert_panel_unlocked(dev_priv, pipe);
3760         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
3761
3762         intel_fdi_normal_train(crtc);
3763
3764         /* For PCH DP, enable TRANS_DP_CTL */
3765         if (HAS_PCH_CPT(dev) &&
3766             (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DISPLAYPORT) ||
3767              intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_EDP))) {
3768                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
3769                 reg = TRANS_DP_CTL(pipe);
3770                 temp = I915_READ(reg);
3771                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
3772                           TRANS_DP_SYNC_MASK |
3773                           TRANS_DP_BPC_MASK);
3774                 temp |= (TRANS_DP_OUTPUT_ENABLE |
3775                          TRANS_DP_ENH_FRAMING);
3776                 temp |= bpc << 9; /* same format but at 11:9 */
3777
3778                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
3779                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
3780                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
3781                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
3782
3783                 switch (intel_trans_dp_port_sel(crtc)) {
3784                 case PCH_DP_B:
3785                         temp |= TRANS_DP_PORT_SEL_B;
3786                         break;
3787                 case PCH_DP_C:
3788                         temp |= TRANS_DP_PORT_SEL_C;
3789                         break;
3790                 case PCH_DP_D:
3791                         temp |= TRANS_DP_PORT_SEL_D;
3792                         break;
3793                 default:
3794                         BUG();
3795                 }
3796
3797                 I915_WRITE(reg, temp);
3798         }
3799
3800         ironlake_enable_pch_transcoder(dev_priv, pipe);
3801 }
3802
3803 static void lpt_pch_enable(struct drm_crtc *crtc)
3804 {
3805         struct drm_device *dev = crtc->dev;
3806         struct drm_i915_private *dev_priv = dev->dev_private;
3807         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3808         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
3809
3810         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
3811
3812         lpt_program_iclkip(crtc);
3813
3814         /* Set transcoder timing. */
3815         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
3816
3817         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
3818 }
3819
3820 void intel_put_shared_dpll(struct intel_crtc *crtc)
3821 {
3822         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3823
3824         if (pll == NULL)
3825                 return;
3826
3827         if (pll->refcount == 0) {
3828                 WARN(1, "bad %s refcount\n", pll->name);
3829                 return;
3830         }
3831
3832         if (--pll->refcount == 0) {
3833                 WARN_ON(pll->on);
3834                 WARN_ON(pll->active);
3835         }
3836
3837         crtc->config.shared_dpll = DPLL_ID_PRIVATE;
3838 }
3839
3840 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc)
3841 {
3842         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
3843         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3844         enum intel_dpll_id i;
3845
3846         if (pll) {
3847                 DRM_DEBUG_KMS("CRTC:%d dropping existing %s\n",
3848                               crtc->base.base.id, pll->name);
3849                 intel_put_shared_dpll(crtc);
3850         }
3851
3852         if (HAS_PCH_IBX(dev_priv->dev)) {
3853                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
3854                 i = (enum intel_dpll_id) crtc->pipe;
3855                 pll = &dev_priv->shared_dplls[i];
3856
3857                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
3858                               crtc->base.base.id, pll->name);
3859
3860                 WARN_ON(pll->refcount);
3861
3862                 goto found;
3863         }
3864
3865         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3866                 pll = &dev_priv->shared_dplls[i];
3867
3868                 /* Only want to check enabled timings first */
3869                 if (pll->refcount == 0)
3870                         continue;
3871
3872                 if (memcmp(&crtc->config.dpll_hw_state, &pll->hw_state,
3873                            sizeof(pll->hw_state)) == 0) {
3874                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (refcount %d, ative %d)\n",
3875                                       crtc->base.base.id,
3876                                       pll->name, pll->refcount, pll->active);
3877
3878                         goto found;
3879                 }
3880         }
3881
3882         /* Ok no matching timings, maybe there's a free one? */
3883         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
3884                 pll = &dev_priv->shared_dplls[i];
3885                 if (pll->refcount == 0) {
3886                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
3887                                       crtc->base.base.id, pll->name);
3888                         goto found;
3889                 }
3890         }
3891
3892         return NULL;
3893
3894 found:
3895         if (pll->refcount == 0)
3896                 pll->hw_state = crtc->config.dpll_hw_state;
3897
3898         crtc->config.shared_dpll = i;
3899         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
3900                          pipe_name(crtc->pipe));
3901
3902         pll->refcount++;
3903
3904         return pll;
3905 }
3906
3907 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
3908 {
3909         struct drm_i915_private *dev_priv = dev->dev_private;
3910         int dslreg = PIPEDSL(pipe);
3911         u32 temp;
3912
3913         temp = I915_READ(dslreg);
3914         udelay(500);
3915         if (wait_for(I915_READ(dslreg) != temp, 5)) {
3916                 if (wait_for(I915_READ(dslreg) != temp, 5))
3917                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
3918         }
3919 }
3920
3921 static void ironlake_pfit_enable(struct intel_crtc *crtc)
3922 {
3923         struct drm_device *dev = crtc->base.dev;
3924         struct drm_i915_private *dev_priv = dev->dev_private;
3925         int pipe = crtc->pipe;
3926
3927         if (crtc->config.pch_pfit.enabled) {
3928                 /* Force use of hard-coded filter coefficients
3929                  * as some pre-programmed values are broken,
3930                  * e.g. x201.
3931                  */
3932                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
3933                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
3934                                                  PF_PIPE_SEL_IVB(pipe));
3935                 else
3936                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
3937                 I915_WRITE(PF_WIN_POS(pipe), crtc->config.pch_pfit.pos);
3938                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config.pch_pfit.size);
3939         }
3940 }
3941
3942 static void intel_enable_planes(struct drm_crtc *crtc)
3943 {
3944         struct drm_device *dev = crtc->dev;
3945         enum pipe pipe = to_intel_crtc(crtc)->pipe;
3946         struct drm_plane *plane;
3947         struct intel_plane *intel_plane;
3948
3949         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
3950                 intel_plane = to_intel_plane(plane);
3951                 if (intel_plane->pipe == pipe)
3952                         intel_plane_restore(&intel_plane->base);
3953         }
3954 }
3955
3956 static void intel_disable_planes(struct drm_crtc *crtc)
3957 {
3958         struct drm_device *dev = crtc->dev;
3959         enum pipe pipe = to_intel_crtc(crtc)->pipe;
3960         struct drm_plane *plane;
3961         struct intel_plane *intel_plane;
3962
3963         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
3964                 intel_plane = to_intel_plane(plane);
3965                 if (intel_plane->pipe == pipe)
3966                         intel_plane_disable(&intel_plane->base);
3967         }
3968 }
3969
3970 void hsw_enable_ips(struct intel_crtc *crtc)
3971 {
3972         struct drm_device *dev = crtc->base.dev;
3973         struct drm_i915_private *dev_priv = dev->dev_private;
3974
3975         if (!crtc->config.ips_enabled)
3976                 return;
3977
3978         /* We can only enable IPS after we enable a plane and wait for a vblank */
3979         intel_wait_for_vblank(dev, crtc->pipe);
3980
3981         assert_plane_enabled(dev_priv, crtc->plane);
3982         if (IS_BROADWELL(dev)) {
3983                 mutex_lock(&dev_priv->rps.hw_lock);
3984                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
3985                 mutex_unlock(&dev_priv->rps.hw_lock);
3986                 /* Quoting Art Runyan: "its not safe to expect any particular
3987                  * value in IPS_CTL bit 31 after enabling IPS through the
3988                  * mailbox." Moreover, the mailbox may return a bogus state,
3989                  * so we need to just enable it and continue on.
3990                  */
3991         } else {
3992                 I915_WRITE(IPS_CTL, IPS_ENABLE);
3993                 /* The bit only becomes 1 in the next vblank, so this wait here
3994                  * is essentially intel_wait_for_vblank. If we don't have this
3995                  * and don't wait for vblanks until the end of crtc_enable, then
3996                  * the HW state readout code will complain that the expected
3997                  * IPS_CTL value is not the one we read. */
3998                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
3999                         DRM_ERROR("Timed out waiting for IPS enable\n");
4000         }
4001 }
4002
4003 void hsw_disable_ips(struct intel_crtc *crtc)
4004 {
4005         struct drm_device *dev = crtc->base.dev;
4006         struct drm_i915_private *dev_priv = dev->dev_private;
4007
4008         if (!crtc->config.ips_enabled)
4009                 return;
4010
4011         assert_plane_enabled(dev_priv, crtc->plane);
4012         if (IS_BROADWELL(dev)) {
4013                 mutex_lock(&dev_priv->rps.hw_lock);
4014                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4015                 mutex_unlock(&dev_priv->rps.hw_lock);
4016                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4017                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4018                         DRM_ERROR("Timed out waiting for IPS disable\n");
4019         } else {
4020                 I915_WRITE(IPS_CTL, 0);
4021                 POSTING_READ(IPS_CTL);
4022         }
4023
4024         /* We need to wait for a vblank before we can disable the plane. */
4025         intel_wait_for_vblank(dev, crtc->pipe);
4026 }
4027
4028 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4029 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4030 {
4031         struct drm_device *dev = crtc->dev;
4032         struct drm_i915_private *dev_priv = dev->dev_private;
4033         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4034         enum pipe pipe = intel_crtc->pipe;
4035         int palreg = PALETTE(pipe);
4036         int i;
4037         bool reenable_ips = false;
4038
4039         /* The clocks have to be on to load the palette. */
4040         if (!crtc->enabled || !intel_crtc->active)
4041                 return;
4042
4043         if (!HAS_PCH_SPLIT(dev_priv->dev)) {
4044                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4045                         assert_dsi_pll_enabled(dev_priv);
4046                 else
4047                         assert_pll_enabled(dev_priv, pipe);
4048         }
4049
4050         /* use legacy palette for Ironlake */
4051         if (!HAS_GMCH_DISPLAY(dev))
4052                 palreg = LGC_PALETTE(pipe);
4053
4054         /* Workaround : Do not read or write the pipe palette/gamma data while
4055          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4056          */
4057         if (IS_HASWELL(dev) && intel_crtc->config.ips_enabled &&
4058             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4059              GAMMA_MODE_MODE_SPLIT)) {
4060                 hsw_disable_ips(intel_crtc);
4061                 reenable_ips = true;
4062         }
4063
4064         for (i = 0; i < 256; i++) {
4065                 I915_WRITE(palreg + 4 * i,
4066                            (intel_crtc->lut_r[i] << 16) |
4067                            (intel_crtc->lut_g[i] << 8) |
4068                            intel_crtc->lut_b[i]);
4069         }
4070
4071         if (reenable_ips)
4072                 hsw_enable_ips(intel_crtc);
4073 }
4074
4075 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4076 {
4077         if (!enable && intel_crtc->overlay) {
4078                 struct drm_device *dev = intel_crtc->base.dev;
4079                 struct drm_i915_private *dev_priv = dev->dev_private;
4080
4081                 mutex_lock(&dev->struct_mutex);
4082                 dev_priv->mm.interruptible = false;
4083                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4084                 dev_priv->mm.interruptible = true;
4085                 mutex_unlock(&dev->struct_mutex);
4086         }
4087
4088         /* Let userspace switch the overlay on again. In most cases userspace
4089          * has to recompute where to put it anyway.
4090          */
4091 }
4092
4093 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4094 {
4095         struct drm_device *dev = crtc->dev;
4096         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4097         int pipe = intel_crtc->pipe;
4098
4099         intel_enable_primary_hw_plane(crtc->primary, crtc);
4100         intel_enable_planes(crtc);
4101         intel_crtc_update_cursor(crtc, true);
4102         intel_crtc_dpms_overlay(intel_crtc, true);
4103
4104         hsw_enable_ips(intel_crtc);
4105
4106         mutex_lock(&dev->struct_mutex);
4107         intel_update_fbc(dev);
4108         mutex_unlock(&dev->struct_mutex);
4109
4110         /*
4111          * FIXME: Once we grow proper nuclear flip support out of this we need
4112          * to compute the mask of flip planes precisely. For the time being
4113          * consider this a flip from a NULL plane.
4114          */
4115         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4116 }
4117
4118 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4119 {
4120         struct drm_device *dev = crtc->dev;
4121         struct drm_i915_private *dev_priv = dev->dev_private;
4122         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4123         int pipe = intel_crtc->pipe;
4124         int plane = intel_crtc->plane;
4125
4126         intel_crtc_wait_for_pending_flips(crtc);
4127
4128         if (dev_priv->fbc.plane == plane)
4129                 intel_disable_fbc(dev);
4130
4131         hsw_disable_ips(intel_crtc);
4132
4133         intel_crtc_dpms_overlay(intel_crtc, false);
4134         intel_crtc_update_cursor(crtc, false);
4135         intel_disable_planes(crtc);
4136         intel_disable_primary_hw_plane(crtc->primary, crtc);
4137
4138         /*
4139          * FIXME: Once we grow proper nuclear flip support out of this we need
4140          * to compute the mask of flip planes precisely. For the time being
4141          * consider this a flip to a NULL plane.
4142          */
4143         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4144 }
4145
4146 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4147 {
4148         struct drm_device *dev = crtc->dev;
4149         struct drm_i915_private *dev_priv = dev->dev_private;
4150         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4151         struct intel_encoder *encoder;
4152         int pipe = intel_crtc->pipe;
4153
4154         WARN_ON(!crtc->enabled);
4155
4156         if (intel_crtc->active)
4157                 return;
4158
4159         if (intel_crtc->config.has_pch_encoder)
4160                 intel_prepare_shared_dpll(intel_crtc);
4161
4162         if (intel_crtc->config.has_dp_encoder)
4163                 intel_dp_set_m_n(intel_crtc);
4164
4165         intel_set_pipe_timings(intel_crtc);
4166
4167         if (intel_crtc->config.has_pch_encoder) {
4168                 intel_cpu_transcoder_set_m_n(intel_crtc,
4169                                      &intel_crtc->config.fdi_m_n, NULL);
4170         }
4171
4172         ironlake_set_pipeconf(crtc);
4173
4174         intel_crtc->active = true;
4175
4176         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4177         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4178
4179         for_each_encoder_on_crtc(dev, crtc, encoder)
4180                 if (encoder->pre_enable)
4181                         encoder->pre_enable(encoder);
4182
4183         if (intel_crtc->config.has_pch_encoder) {
4184                 /* Note: FDI PLL enabling _must_ be done before we enable the
4185                  * cpu pipes, hence this is separate from all the other fdi/pch
4186                  * enabling. */
4187                 ironlake_fdi_pll_enable(intel_crtc);
4188         } else {
4189                 assert_fdi_tx_disabled(dev_priv, pipe);
4190                 assert_fdi_rx_disabled(dev_priv, pipe);
4191         }
4192
4193         ironlake_pfit_enable(intel_crtc);
4194
4195         /*
4196          * On ILK+ LUT must be loaded before the pipe is running but with
4197          * clocks enabled
4198          */
4199         intel_crtc_load_lut(crtc);
4200
4201         intel_update_watermarks(crtc);
4202         intel_enable_pipe(intel_crtc);
4203
4204         if (intel_crtc->config.has_pch_encoder)
4205                 ironlake_pch_enable(crtc);
4206
4207         for_each_encoder_on_crtc(dev, crtc, encoder)
4208                 encoder->enable(encoder);
4209
4210         if (HAS_PCH_CPT(dev))
4211                 cpt_verify_modeset(dev, intel_crtc->pipe);
4212
4213         assert_vblank_disabled(crtc);
4214         drm_crtc_vblank_on(crtc);
4215
4216         intel_crtc_enable_planes(crtc);
4217 }
4218
4219 /* IPS only exists on ULT machines and is tied to pipe A. */
4220 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4221 {
4222         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4223 }
4224
4225 /*
4226  * This implements the workaround described in the "notes" section of the mode
4227  * set sequence documentation. When going from no pipes or single pipe to
4228  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4229  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4230  */
4231 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4232 {
4233         struct drm_device *dev = crtc->base.dev;
4234         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4235
4236         /* We want to get the other_active_crtc only if there's only 1 other
4237          * active crtc. */
4238         for_each_intel_crtc(dev, crtc_it) {
4239                 if (!crtc_it->active || crtc_it == crtc)
4240                         continue;
4241
4242                 if (other_active_crtc)
4243                         return;
4244
4245                 other_active_crtc = crtc_it;
4246         }
4247         if (!other_active_crtc)
4248                 return;
4249
4250         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4251         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4252 }
4253
4254 static void haswell_crtc_enable(struct drm_crtc *crtc)
4255 {
4256         struct drm_device *dev = crtc->dev;
4257         struct drm_i915_private *dev_priv = dev->dev_private;
4258         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4259         struct intel_encoder *encoder;
4260         int pipe = intel_crtc->pipe;
4261
4262         WARN_ON(!crtc->enabled);
4263
4264         if (intel_crtc->active)
4265                 return;
4266
4267         if (intel_crtc_to_shared_dpll(intel_crtc))
4268                 intel_enable_shared_dpll(intel_crtc);
4269
4270         if (intel_crtc->config.has_dp_encoder)
4271                 intel_dp_set_m_n(intel_crtc);
4272
4273         intel_set_pipe_timings(intel_crtc);
4274
4275         if (intel_crtc->config.cpu_transcoder != TRANSCODER_EDP) {
4276                 I915_WRITE(PIPE_MULT(intel_crtc->config.cpu_transcoder),
4277                            intel_crtc->config.pixel_multiplier - 1);
4278         }
4279
4280         if (intel_crtc->config.has_pch_encoder) {
4281                 intel_cpu_transcoder_set_m_n(intel_crtc,
4282                                      &intel_crtc->config.fdi_m_n, NULL);
4283         }
4284
4285         haswell_set_pipeconf(crtc);
4286
4287         intel_set_pipe_csc(crtc);
4288
4289         intel_crtc->active = true;
4290
4291         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4292         for_each_encoder_on_crtc(dev, crtc, encoder)
4293                 if (encoder->pre_enable)
4294                         encoder->pre_enable(encoder);
4295
4296         if (intel_crtc->config.has_pch_encoder) {
4297                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4298                                                       true);
4299                 dev_priv->display.fdi_link_train(crtc);
4300         }
4301
4302         intel_ddi_enable_pipe_clock(intel_crtc);
4303
4304         ironlake_pfit_enable(intel_crtc);
4305
4306         /*
4307          * On ILK+ LUT must be loaded before the pipe is running but with
4308          * clocks enabled
4309          */
4310         intel_crtc_load_lut(crtc);
4311
4312         intel_ddi_set_pipe_settings(crtc);
4313         intel_ddi_enable_transcoder_func(crtc);
4314
4315         intel_update_watermarks(crtc);
4316         intel_enable_pipe(intel_crtc);
4317
4318         if (intel_crtc->config.has_pch_encoder)
4319                 lpt_pch_enable(crtc);
4320
4321         if (intel_crtc->config.dp_encoder_is_mst)
4322                 intel_ddi_set_vc_payload_alloc(crtc, true);
4323
4324         for_each_encoder_on_crtc(dev, crtc, encoder) {
4325                 encoder->enable(encoder);
4326                 intel_opregion_notify_encoder(encoder, true);
4327         }
4328
4329         assert_vblank_disabled(crtc);
4330         drm_crtc_vblank_on(crtc);
4331
4332         /* If we change the relative order between pipe/planes enabling, we need
4333          * to change the workaround. */
4334         haswell_mode_set_planes_workaround(intel_crtc);
4335         intel_crtc_enable_planes(crtc);
4336 }
4337
4338 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4339 {
4340         struct drm_device *dev = crtc->base.dev;
4341         struct drm_i915_private *dev_priv = dev->dev_private;
4342         int pipe = crtc->pipe;
4343
4344         /* To avoid upsetting the power well on haswell only disable the pfit if
4345          * it's in use. The hw state code will make sure we get this right. */
4346         if (crtc->config.pch_pfit.enabled) {
4347                 I915_WRITE(PF_CTL(pipe), 0);
4348                 I915_WRITE(PF_WIN_POS(pipe), 0);
4349                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4350         }
4351 }
4352
4353 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4354 {
4355         struct drm_device *dev = crtc->dev;
4356         struct drm_i915_private *dev_priv = dev->dev_private;
4357         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4358         struct intel_encoder *encoder;
4359         int pipe = intel_crtc->pipe;
4360         u32 reg, temp;
4361
4362         if (!intel_crtc->active)
4363                 return;
4364
4365         intel_crtc_disable_planes(crtc);
4366
4367         drm_crtc_vblank_off(crtc);
4368         assert_vblank_disabled(crtc);
4369
4370         for_each_encoder_on_crtc(dev, crtc, encoder)
4371                 encoder->disable(encoder);
4372
4373         if (intel_crtc->config.has_pch_encoder)
4374                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4375
4376         intel_disable_pipe(intel_crtc);
4377
4378         ironlake_pfit_disable(intel_crtc);
4379
4380         for_each_encoder_on_crtc(dev, crtc, encoder)
4381                 if (encoder->post_disable)
4382                         encoder->post_disable(encoder);
4383
4384         if (intel_crtc->config.has_pch_encoder) {
4385                 ironlake_fdi_disable(crtc);
4386
4387                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4388                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4389
4390                 if (HAS_PCH_CPT(dev)) {
4391                         /* disable TRANS_DP_CTL */
4392                         reg = TRANS_DP_CTL(pipe);
4393                         temp = I915_READ(reg);
4394                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4395                                   TRANS_DP_PORT_SEL_MASK);
4396                         temp |= TRANS_DP_PORT_SEL_NONE;
4397                         I915_WRITE(reg, temp);
4398
4399                         /* disable DPLL_SEL */
4400                         temp = I915_READ(PCH_DPLL_SEL);
4401                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4402                         I915_WRITE(PCH_DPLL_SEL, temp);
4403                 }
4404
4405                 /* disable PCH DPLL */
4406                 intel_disable_shared_dpll(intel_crtc);
4407
4408                 ironlake_fdi_pll_disable(intel_crtc);
4409         }
4410
4411         intel_crtc->active = false;
4412         intel_update_watermarks(crtc);
4413
4414         mutex_lock(&dev->struct_mutex);
4415         intel_update_fbc(dev);
4416         mutex_unlock(&dev->struct_mutex);
4417 }
4418
4419 static void haswell_crtc_disable(struct drm_crtc *crtc)
4420 {
4421         struct drm_device *dev = crtc->dev;
4422         struct drm_i915_private *dev_priv = dev->dev_private;
4423         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4424         struct intel_encoder *encoder;
4425         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
4426
4427         if (!intel_crtc->active)
4428                 return;
4429
4430         intel_crtc_disable_planes(crtc);
4431
4432         drm_crtc_vblank_off(crtc);
4433         assert_vblank_disabled(crtc);
4434
4435         for_each_encoder_on_crtc(dev, crtc, encoder) {
4436                 intel_opregion_notify_encoder(encoder, false);
4437                 encoder->disable(encoder);
4438         }
4439
4440         if (intel_crtc->config.has_pch_encoder)
4441                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4442                                                       false);
4443         intel_disable_pipe(intel_crtc);
4444
4445         if (intel_crtc->config.dp_encoder_is_mst)
4446                 intel_ddi_set_vc_payload_alloc(crtc, false);
4447
4448         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4449
4450         ironlake_pfit_disable(intel_crtc);
4451
4452         intel_ddi_disable_pipe_clock(intel_crtc);
4453
4454         if (intel_crtc->config.has_pch_encoder) {
4455                 lpt_disable_pch_transcoder(dev_priv);
4456                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4457                                                       true);
4458                 intel_ddi_fdi_disable(crtc);
4459         }
4460
4461         for_each_encoder_on_crtc(dev, crtc, encoder)
4462                 if (encoder->post_disable)
4463                         encoder->post_disable(encoder);
4464
4465         intel_crtc->active = false;
4466         intel_update_watermarks(crtc);
4467
4468         mutex_lock(&dev->struct_mutex);
4469         intel_update_fbc(dev);
4470         mutex_unlock(&dev->struct_mutex);
4471
4472         if (intel_crtc_to_shared_dpll(intel_crtc))
4473                 intel_disable_shared_dpll(intel_crtc);
4474 }
4475
4476 static void ironlake_crtc_off(struct drm_crtc *crtc)
4477 {
4478         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4479         intel_put_shared_dpll(intel_crtc);
4480 }
4481
4482
4483 static void i9xx_pfit_enable(struct intel_crtc *crtc)
4484 {
4485         struct drm_device *dev = crtc->base.dev;
4486         struct drm_i915_private *dev_priv = dev->dev_private;
4487         struct intel_crtc_config *pipe_config = &crtc->config;
4488
4489         if (!crtc->config.gmch_pfit.control)
4490                 return;
4491
4492         /*
4493          * The panel fitter should only be adjusted whilst the pipe is disabled,
4494          * according to register description and PRM.
4495          */
4496         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
4497         assert_pipe_disabled(dev_priv, crtc->pipe);
4498
4499         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
4500         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
4501
4502         /* Border color in case we don't scale up to the full screen. Black by
4503          * default, change to something else for debugging. */
4504         I915_WRITE(BCLRPAT(crtc->pipe), 0);
4505 }
4506
4507 static enum intel_display_power_domain port_to_power_domain(enum port port)
4508 {
4509         switch (port) {
4510         case PORT_A:
4511                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
4512         case PORT_B:
4513                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
4514         case PORT_C:
4515                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
4516         case PORT_D:
4517                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
4518         default:
4519                 WARN_ON_ONCE(1);
4520                 return POWER_DOMAIN_PORT_OTHER;
4521         }
4522 }
4523
4524 #define for_each_power_domain(domain, mask)                             \
4525         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
4526                 if ((1 << (domain)) & (mask))
4527
4528 enum intel_display_power_domain
4529 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
4530 {
4531         struct drm_device *dev = intel_encoder->base.dev;
4532         struct intel_digital_port *intel_dig_port;
4533
4534         switch (intel_encoder->type) {
4535         case INTEL_OUTPUT_UNKNOWN:
4536                 /* Only DDI platforms should ever use this output type */
4537                 WARN_ON_ONCE(!HAS_DDI(dev));
4538         case INTEL_OUTPUT_DISPLAYPORT:
4539         case INTEL_OUTPUT_HDMI:
4540         case INTEL_OUTPUT_EDP:
4541                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
4542                 return port_to_power_domain(intel_dig_port->port);
4543         case INTEL_OUTPUT_DP_MST:
4544                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
4545                 return port_to_power_domain(intel_dig_port->port);
4546         case INTEL_OUTPUT_ANALOG:
4547                 return POWER_DOMAIN_PORT_CRT;
4548         case INTEL_OUTPUT_DSI:
4549                 return POWER_DOMAIN_PORT_DSI;
4550         default:
4551                 return POWER_DOMAIN_PORT_OTHER;
4552         }
4553 }
4554
4555 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
4556 {
4557         struct drm_device *dev = crtc->dev;
4558         struct intel_encoder *intel_encoder;
4559         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4560         enum pipe pipe = intel_crtc->pipe;
4561         unsigned long mask;
4562         enum transcoder transcoder;
4563
4564         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
4565
4566         mask = BIT(POWER_DOMAIN_PIPE(pipe));
4567         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
4568         if (intel_crtc->config.pch_pfit.enabled ||
4569             intel_crtc->config.pch_pfit.force_thru)
4570                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
4571
4572         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4573                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
4574
4575         return mask;
4576 }
4577
4578 static void modeset_update_crtc_power_domains(struct drm_device *dev)
4579 {
4580         struct drm_i915_private *dev_priv = dev->dev_private;
4581         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
4582         struct intel_crtc *crtc;
4583
4584         /*
4585          * First get all needed power domains, then put all unneeded, to avoid
4586          * any unnecessary toggling of the power wells.
4587          */
4588         for_each_intel_crtc(dev, crtc) {
4589                 enum intel_display_power_domain domain;
4590
4591                 if (!crtc->base.enabled)
4592                         continue;
4593
4594                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
4595
4596                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
4597                         intel_display_power_get(dev_priv, domain);
4598         }
4599
4600         for_each_intel_crtc(dev, crtc) {
4601                 enum intel_display_power_domain domain;
4602
4603                 for_each_power_domain(domain, crtc->enabled_power_domains)
4604                         intel_display_power_put(dev_priv, domain);
4605
4606                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
4607         }
4608
4609         intel_display_set_init_power(dev_priv, false);
4610 }
4611
4612 /* returns HPLL frequency in kHz */
4613 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
4614 {
4615         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
4616
4617         /* Obtain SKU information */
4618         mutex_lock(&dev_priv->dpio_lock);
4619         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
4620                 CCK_FUSE_HPLL_FREQ_MASK;
4621         mutex_unlock(&dev_priv->dpio_lock);
4622
4623         return vco_freq[hpll_freq] * 1000;
4624 }
4625
4626 static void vlv_update_cdclk(struct drm_device *dev)
4627 {
4628         struct drm_i915_private *dev_priv = dev->dev_private;
4629
4630         dev_priv->vlv_cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
4631         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
4632                          dev_priv->vlv_cdclk_freq);
4633
4634         /*
4635          * Program the gmbus_freq based on the cdclk frequency.
4636          * BSpec erroneously claims we should aim for 4MHz, but
4637          * in fact 1MHz is the correct frequency.
4638          */
4639         I915_WRITE(GMBUSFREQ_VLV, dev_priv->vlv_cdclk_freq);
4640 }
4641
4642 /* Adjust CDclk dividers to allow high res or save power if possible */
4643 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
4644 {
4645         struct drm_i915_private *dev_priv = dev->dev_private;
4646         u32 val, cmd;
4647
4648         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4649
4650         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
4651                 cmd = 2;
4652         else if (cdclk == 266667)
4653                 cmd = 1;
4654         else
4655                 cmd = 0;
4656
4657         mutex_lock(&dev_priv->rps.hw_lock);
4658         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4659         val &= ~DSPFREQGUAR_MASK;
4660         val |= (cmd << DSPFREQGUAR_SHIFT);
4661         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4662         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4663                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
4664                      50)) {
4665                 DRM_ERROR("timed out waiting for CDclk change\n");
4666         }
4667         mutex_unlock(&dev_priv->rps.hw_lock);
4668
4669         if (cdclk == 400000) {
4670                 u32 divider, vco;
4671
4672                 vco = valleyview_get_vco(dev_priv);
4673                 divider = DIV_ROUND_CLOSEST(vco << 1, cdclk) - 1;
4674
4675                 mutex_lock(&dev_priv->dpio_lock);
4676                 /* adjust cdclk divider */
4677                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
4678                 val &= ~DISPLAY_FREQUENCY_VALUES;
4679                 val |= divider;
4680                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
4681
4682                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
4683                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
4684                              50))
4685                         DRM_ERROR("timed out waiting for CDclk change\n");
4686                 mutex_unlock(&dev_priv->dpio_lock);
4687         }
4688
4689         mutex_lock(&dev_priv->dpio_lock);
4690         /* adjust self-refresh exit latency value */
4691         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
4692         val &= ~0x7f;
4693
4694         /*
4695          * For high bandwidth configs, we set a higher latency in the bunit
4696          * so that the core display fetch happens in time to avoid underruns.
4697          */
4698         if (cdclk == 400000)
4699                 val |= 4500 / 250; /* 4.5 usec */
4700         else
4701                 val |= 3000 / 250; /* 3.0 usec */
4702         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
4703         mutex_unlock(&dev_priv->dpio_lock);
4704
4705         vlv_update_cdclk(dev);
4706 }
4707
4708 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
4709 {
4710         struct drm_i915_private *dev_priv = dev->dev_private;
4711         u32 val, cmd;
4712
4713         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4714
4715         switch (cdclk) {
4716         case 400000:
4717                 cmd = 3;
4718                 break;
4719         case 333333:
4720         case 320000:
4721                 cmd = 2;
4722                 break;
4723         case 266667:
4724                 cmd = 1;
4725                 break;
4726         case 200000:
4727                 cmd = 0;
4728                 break;
4729         default:
4730                 WARN_ON(1);
4731                 return;
4732         }
4733
4734         mutex_lock(&dev_priv->rps.hw_lock);
4735         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4736         val &= ~DSPFREQGUAR_MASK_CHV;
4737         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
4738         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4739         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4740                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
4741                      50)) {
4742                 DRM_ERROR("timed out waiting for CDclk change\n");
4743         }
4744         mutex_unlock(&dev_priv->rps.hw_lock);
4745
4746         vlv_update_cdclk(dev);
4747 }
4748
4749 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
4750                                  int max_pixclk)
4751 {
4752         int vco = valleyview_get_vco(dev_priv);
4753         int freq_320 = (vco <<  1) % 320000 != 0 ? 333333 : 320000;
4754
4755         /* FIXME: Punit isn't quite ready yet */
4756         if (IS_CHERRYVIEW(dev_priv->dev))
4757                 return 400000;
4758
4759         /*
4760          * Really only a few cases to deal with, as only 4 CDclks are supported:
4761          *   200MHz
4762          *   267MHz
4763          *   320/333MHz (depends on HPLL freq)
4764          *   400MHz
4765          * So we check to see whether we're above 90% of the lower bin and
4766          * adjust if needed.
4767          *
4768          * We seem to get an unstable or solid color picture at 200MHz.
4769          * Not sure what's wrong. For now use 200MHz only when all pipes
4770          * are off.
4771          */
4772         if (max_pixclk > freq_320*9/10)
4773                 return 400000;
4774         else if (max_pixclk > 266667*9/10)
4775                 return freq_320;
4776         else if (max_pixclk > 0)
4777                 return 266667;
4778         else
4779                 return 200000;
4780 }
4781
4782 /* compute the max pixel clock for new configuration */
4783 static int intel_mode_max_pixclk(struct drm_i915_private *dev_priv)
4784 {
4785         struct drm_device *dev = dev_priv->dev;
4786         struct intel_crtc *intel_crtc;
4787         int max_pixclk = 0;
4788
4789         for_each_intel_crtc(dev, intel_crtc) {
4790                 if (intel_crtc->new_enabled)
4791                         max_pixclk = max(max_pixclk,
4792                                          intel_crtc->new_config->adjusted_mode.crtc_clock);
4793         }
4794
4795         return max_pixclk;
4796 }
4797
4798 static void valleyview_modeset_global_pipes(struct drm_device *dev,
4799                                             unsigned *prepare_pipes)
4800 {
4801         struct drm_i915_private *dev_priv = dev->dev_private;
4802         struct intel_crtc *intel_crtc;
4803         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4804
4805         if (valleyview_calc_cdclk(dev_priv, max_pixclk) ==
4806             dev_priv->vlv_cdclk_freq)
4807                 return;
4808
4809         /* disable/enable all currently active pipes while we change cdclk */
4810         for_each_intel_crtc(dev, intel_crtc)
4811                 if (intel_crtc->base.enabled)
4812                         *prepare_pipes |= (1 << intel_crtc->pipe);
4813 }
4814
4815 static void valleyview_modeset_global_resources(struct drm_device *dev)
4816 {
4817         struct drm_i915_private *dev_priv = dev->dev_private;
4818         int max_pixclk = intel_mode_max_pixclk(dev_priv);
4819         int req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
4820
4821         if (req_cdclk != dev_priv->vlv_cdclk_freq) {
4822                 if (IS_CHERRYVIEW(dev))
4823                         cherryview_set_cdclk(dev, req_cdclk);
4824                 else
4825                         valleyview_set_cdclk(dev, req_cdclk);
4826         }
4827
4828         modeset_update_crtc_power_domains(dev);
4829 }
4830
4831 static void valleyview_crtc_enable(struct drm_crtc *crtc)
4832 {
4833         struct drm_device *dev = crtc->dev;
4834         struct drm_i915_private *dev_priv = to_i915(dev);
4835         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4836         struct intel_encoder *encoder;
4837         int pipe = intel_crtc->pipe;
4838         bool is_dsi;
4839
4840         WARN_ON(!crtc->enabled);
4841
4842         if (intel_crtc->active)
4843                 return;
4844
4845         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
4846
4847         if (!is_dsi) {
4848                 if (IS_CHERRYVIEW(dev))
4849                         chv_prepare_pll(intel_crtc, &intel_crtc->config);
4850                 else
4851                         vlv_prepare_pll(intel_crtc, &intel_crtc->config);
4852         }
4853
4854         if (intel_crtc->config.has_dp_encoder)
4855                 intel_dp_set_m_n(intel_crtc);
4856
4857         intel_set_pipe_timings(intel_crtc);
4858
4859         i9xx_set_pipeconf(intel_crtc);
4860
4861         intel_crtc->active = true;
4862
4863         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4864
4865         for_each_encoder_on_crtc(dev, crtc, encoder)
4866                 if (encoder->pre_pll_enable)
4867                         encoder->pre_pll_enable(encoder);
4868
4869         if (!is_dsi) {
4870                 if (IS_CHERRYVIEW(dev))
4871                         chv_enable_pll(intel_crtc, &intel_crtc->config);
4872                 else
4873                         vlv_enable_pll(intel_crtc, &intel_crtc->config);
4874         }
4875
4876         for_each_encoder_on_crtc(dev, crtc, encoder)
4877                 if (encoder->pre_enable)
4878                         encoder->pre_enable(encoder);
4879
4880         i9xx_pfit_enable(intel_crtc);
4881
4882         intel_crtc_load_lut(crtc);
4883
4884         intel_update_watermarks(crtc);
4885         intel_enable_pipe(intel_crtc);
4886
4887         for_each_encoder_on_crtc(dev, crtc, encoder)
4888                 encoder->enable(encoder);
4889
4890         assert_vblank_disabled(crtc);
4891         drm_crtc_vblank_on(crtc);
4892
4893         intel_crtc_enable_planes(crtc);
4894
4895         /* Underruns don't raise interrupts, so check manually. */
4896         i9xx_check_fifo_underruns(dev_priv);
4897 }
4898
4899 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
4900 {
4901         struct drm_device *dev = crtc->base.dev;
4902         struct drm_i915_private *dev_priv = dev->dev_private;
4903
4904         I915_WRITE(FP0(crtc->pipe), crtc->config.dpll_hw_state.fp0);
4905         I915_WRITE(FP1(crtc->pipe), crtc->config.dpll_hw_state.fp1);
4906 }
4907
4908 static void i9xx_crtc_enable(struct drm_crtc *crtc)
4909 {
4910         struct drm_device *dev = crtc->dev;
4911         struct drm_i915_private *dev_priv = to_i915(dev);
4912         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4913         struct intel_encoder *encoder;
4914         int pipe = intel_crtc->pipe;
4915
4916         WARN_ON(!crtc->enabled);
4917
4918         if (intel_crtc->active)
4919                 return;
4920
4921         i9xx_set_pll_dividers(intel_crtc);
4922
4923         if (intel_crtc->config.has_dp_encoder)
4924                 intel_dp_set_m_n(intel_crtc);
4925
4926         intel_set_pipe_timings(intel_crtc);
4927
4928         i9xx_set_pipeconf(intel_crtc);
4929
4930         intel_crtc->active = true;
4931
4932         if (!IS_GEN2(dev))
4933                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4934
4935         for_each_encoder_on_crtc(dev, crtc, encoder)
4936                 if (encoder->pre_enable)
4937                         encoder->pre_enable(encoder);
4938
4939         i9xx_enable_pll(intel_crtc);
4940
4941         i9xx_pfit_enable(intel_crtc);
4942
4943         intel_crtc_load_lut(crtc);
4944
4945         intel_update_watermarks(crtc);
4946         intel_enable_pipe(intel_crtc);
4947
4948         for_each_encoder_on_crtc(dev, crtc, encoder)
4949                 encoder->enable(encoder);
4950
4951         assert_vblank_disabled(crtc);
4952         drm_crtc_vblank_on(crtc);
4953
4954         intel_crtc_enable_planes(crtc);
4955
4956         /*
4957          * Gen2 reports pipe underruns whenever all planes are disabled.
4958          * So don't enable underrun reporting before at least some planes
4959          * are enabled.
4960          * FIXME: Need to fix the logic to work when we turn off all planes
4961          * but leave the pipe running.
4962          */
4963         if (IS_GEN2(dev))
4964                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4965
4966         /* Underruns don't raise interrupts, so check manually. */
4967         i9xx_check_fifo_underruns(dev_priv);
4968 }
4969
4970 static void i9xx_pfit_disable(struct intel_crtc *crtc)
4971 {
4972         struct drm_device *dev = crtc->base.dev;
4973         struct drm_i915_private *dev_priv = dev->dev_private;
4974
4975         if (!crtc->config.gmch_pfit.control)
4976                 return;
4977
4978         assert_pipe_disabled(dev_priv, crtc->pipe);
4979
4980         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
4981                          I915_READ(PFIT_CONTROL));
4982         I915_WRITE(PFIT_CONTROL, 0);
4983 }
4984
4985 static void i9xx_crtc_disable(struct drm_crtc *crtc)
4986 {
4987         struct drm_device *dev = crtc->dev;
4988         struct drm_i915_private *dev_priv = dev->dev_private;
4989         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4990         struct intel_encoder *encoder;
4991         int pipe = intel_crtc->pipe;
4992
4993         if (!intel_crtc->active)
4994                 return;
4995
4996         /*
4997          * Gen2 reports pipe underruns whenever all planes are disabled.
4998          * So diasble underrun reporting before all the planes get disabled.
4999          * FIXME: Need to fix the logic to work when we turn off all planes
5000          * but leave the pipe running.
5001          */
5002         if (IS_GEN2(dev))
5003                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5004
5005         /*
5006          * Vblank time updates from the shadow to live plane control register
5007          * are blocked if the memory self-refresh mode is active at that
5008          * moment. So to make sure the plane gets truly disabled, disable
5009          * first the self-refresh mode. The self-refresh enable bit in turn
5010          * will be checked/applied by the HW only at the next frame start
5011          * event which is after the vblank start event, so we need to have a
5012          * wait-for-vblank between disabling the plane and the pipe.
5013          */
5014         intel_set_memory_cxsr(dev_priv, false);
5015         intel_crtc_disable_planes(crtc);
5016
5017         /*
5018          * On gen2 planes are double buffered but the pipe isn't, so we must
5019          * wait for planes to fully turn off before disabling the pipe.
5020          * We also need to wait on all gmch platforms because of the
5021          * self-refresh mode constraint explained above.
5022          */
5023         intel_wait_for_vblank(dev, pipe);
5024
5025         drm_crtc_vblank_off(crtc);
5026         assert_vblank_disabled(crtc);
5027
5028         for_each_encoder_on_crtc(dev, crtc, encoder)
5029                 encoder->disable(encoder);
5030
5031         intel_disable_pipe(intel_crtc);
5032
5033         i9xx_pfit_disable(intel_crtc);
5034
5035         for_each_encoder_on_crtc(dev, crtc, encoder)
5036                 if (encoder->post_disable)
5037                         encoder->post_disable(encoder);
5038
5039         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5040                 if (IS_CHERRYVIEW(dev))
5041                         chv_disable_pll(dev_priv, pipe);
5042                 else if (IS_VALLEYVIEW(dev))
5043                         vlv_disable_pll(dev_priv, pipe);
5044                 else
5045                         i9xx_disable_pll(intel_crtc);
5046         }
5047
5048         if (!IS_GEN2(dev))
5049                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5050
5051         intel_crtc->active = false;
5052         intel_update_watermarks(crtc);
5053
5054         mutex_lock(&dev->struct_mutex);
5055         intel_update_fbc(dev);
5056         mutex_unlock(&dev->struct_mutex);
5057 }
5058
5059 static void i9xx_crtc_off(struct drm_crtc *crtc)
5060 {
5061 }
5062
5063 static void intel_crtc_update_sarea(struct drm_crtc *crtc,
5064                                     bool enabled)
5065 {
5066         struct drm_device *dev = crtc->dev;
5067         struct drm_i915_master_private *master_priv;
5068         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5069         int pipe = intel_crtc->pipe;
5070
5071         if (!dev->primary->master)
5072                 return;
5073
5074         master_priv = dev->primary->master->driver_priv;
5075         if (!master_priv->sarea_priv)
5076                 return;
5077
5078         switch (pipe) {
5079         case 0:
5080                 master_priv->sarea_priv->pipeA_w = enabled ? crtc->mode.hdisplay : 0;
5081                 master_priv->sarea_priv->pipeA_h = enabled ? crtc->mode.vdisplay : 0;
5082                 break;
5083         case 1:
5084                 master_priv->sarea_priv->pipeB_w = enabled ? crtc->mode.hdisplay : 0;
5085                 master_priv->sarea_priv->pipeB_h = enabled ? crtc->mode.vdisplay : 0;
5086                 break;
5087         default:
5088                 DRM_ERROR("Can't update pipe %c in SAREA\n", pipe_name(pipe));
5089                 break;
5090         }
5091 }
5092
5093 /* Master function to enable/disable CRTC and corresponding power wells */
5094 void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5095 {
5096         struct drm_device *dev = crtc->dev;
5097         struct drm_i915_private *dev_priv = dev->dev_private;
5098         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5099         enum intel_display_power_domain domain;
5100         unsigned long domains;
5101
5102         if (enable) {
5103                 if (!intel_crtc->active) {
5104                         domains = get_crtc_power_domains(crtc);
5105                         for_each_power_domain(domain, domains)
5106                                 intel_display_power_get(dev_priv, domain);
5107                         intel_crtc->enabled_power_domains = domains;
5108
5109                         dev_priv->display.crtc_enable(crtc);
5110                 }
5111         } else {
5112                 if (intel_crtc->active) {
5113                         dev_priv->display.crtc_disable(crtc);
5114
5115                         domains = intel_crtc->enabled_power_domains;
5116                         for_each_power_domain(domain, domains)
5117                                 intel_display_power_put(dev_priv, domain);
5118                         intel_crtc->enabled_power_domains = 0;
5119                 }
5120         }
5121 }
5122
5123 /**
5124  * Sets the power management mode of the pipe and plane.
5125  */
5126 void intel_crtc_update_dpms(struct drm_crtc *crtc)
5127 {
5128         struct drm_device *dev = crtc->dev;
5129         struct intel_encoder *intel_encoder;
5130         bool enable = false;
5131
5132         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5133                 enable |= intel_encoder->connectors_active;
5134
5135         intel_crtc_control(crtc, enable);
5136
5137         intel_crtc_update_sarea(crtc, enable);
5138 }
5139
5140 static void intel_crtc_disable(struct drm_crtc *crtc)
5141 {
5142         struct drm_device *dev = crtc->dev;
5143         struct drm_connector *connector;
5144         struct drm_i915_private *dev_priv = dev->dev_private;
5145         struct drm_i915_gem_object *old_obj = intel_fb_obj(crtc->primary->fb);
5146         enum pipe pipe = to_intel_crtc(crtc)->pipe;
5147
5148         /* crtc should still be enabled when we disable it. */
5149         WARN_ON(!crtc->enabled);
5150
5151         dev_priv->display.crtc_disable(crtc);
5152         intel_crtc_update_sarea(crtc, false);
5153         dev_priv->display.off(crtc);
5154
5155         if (crtc->primary->fb) {
5156                 mutex_lock(&dev->struct_mutex);
5157                 intel_unpin_fb_obj(old_obj);
5158                 i915_gem_track_fb(old_obj, NULL,
5159                                   INTEL_FRONTBUFFER_PRIMARY(pipe));
5160                 mutex_unlock(&dev->struct_mutex);
5161                 crtc->primary->fb = NULL;
5162         }
5163
5164         /* Update computed state. */
5165         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
5166                 if (!connector->encoder || !connector->encoder->crtc)
5167                         continue;
5168
5169                 if (connector->encoder->crtc != crtc)
5170                         continue;
5171
5172                 connector->dpms = DRM_MODE_DPMS_OFF;
5173                 to_intel_encoder(connector->encoder)->connectors_active = false;
5174         }
5175 }
5176
5177 void intel_encoder_destroy(struct drm_encoder *encoder)
5178 {
5179         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5180
5181         drm_encoder_cleanup(encoder);
5182         kfree(intel_encoder);
5183 }
5184
5185 /* Simple dpms helper for encoders with just one connector, no cloning and only
5186  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
5187  * state of the entire output pipe. */
5188 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
5189 {
5190         if (mode == DRM_MODE_DPMS_ON) {
5191                 encoder->connectors_active = true;
5192
5193                 intel_crtc_update_dpms(encoder->base.crtc);
5194         } else {
5195                 encoder->connectors_active = false;
5196
5197                 intel_crtc_update_dpms(encoder->base.crtc);
5198         }
5199 }
5200
5201 /* Cross check the actual hw state with our own modeset state tracking (and it's
5202  * internal consistency). */
5203 static void intel_connector_check_state(struct intel_connector *connector)
5204 {
5205         if (connector->get_hw_state(connector)) {
5206                 struct intel_encoder *encoder = connector->encoder;
5207                 struct drm_crtc *crtc;
5208                 bool encoder_enabled;
5209                 enum pipe pipe;
5210
5211                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5212                               connector->base.base.id,
5213                               connector->base.name);
5214
5215                 /* there is no real hw state for MST connectors */
5216                 if (connector->mst_port)
5217                         return;
5218
5219                 WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
5220                      "wrong connector dpms state\n");
5221                 WARN(connector->base.encoder != &encoder->base,
5222                      "active connector not linked to encoder\n");
5223
5224                 if (encoder) {
5225                         WARN(!encoder->connectors_active,
5226                              "encoder->connectors_active not set\n");
5227
5228                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
5229                         WARN(!encoder_enabled, "encoder not enabled\n");
5230                         if (WARN_ON(!encoder->base.crtc))
5231                                 return;
5232
5233                         crtc = encoder->base.crtc;
5234
5235                         WARN(!crtc->enabled, "crtc not enabled\n");
5236                         WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
5237                         WARN(pipe != to_intel_crtc(crtc)->pipe,
5238                              "encoder active on the wrong pipe\n");
5239                 }
5240         }
5241 }
5242
5243 /* Even simpler default implementation, if there's really no special case to
5244  * consider. */
5245 void intel_connector_dpms(struct drm_connector *connector, int mode)
5246 {
5247         /* All the simple cases only support two dpms states. */
5248         if (mode != DRM_MODE_DPMS_ON)
5249                 mode = DRM_MODE_DPMS_OFF;
5250
5251         if (mode == connector->dpms)
5252                 return;
5253
5254         connector->dpms = mode;
5255
5256         /* Only need to change hw state when actually enabled */
5257         if (connector->encoder)
5258                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
5259
5260         intel_modeset_check_state(connector->dev);
5261 }
5262
5263 /* Simple connector->get_hw_state implementation for encoders that support only
5264  * one connector and no cloning and hence the encoder state determines the state
5265  * of the connector. */
5266 bool intel_connector_get_hw_state(struct intel_connector *connector)
5267 {
5268         enum pipe pipe = 0;
5269         struct intel_encoder *encoder = connector->encoder;
5270
5271         return encoder->get_hw_state(encoder, &pipe);
5272 }
5273
5274 static bool ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
5275                                      struct intel_crtc_config *pipe_config)
5276 {
5277         struct drm_i915_private *dev_priv = dev->dev_private;
5278         struct intel_crtc *pipe_B_crtc =
5279                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
5280
5281         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
5282                       pipe_name(pipe), pipe_config->fdi_lanes);
5283         if (pipe_config->fdi_lanes > 4) {
5284                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
5285                               pipe_name(pipe), pipe_config->fdi_lanes);
5286                 return false;
5287         }
5288
5289         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
5290                 if (pipe_config->fdi_lanes > 2) {
5291                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
5292                                       pipe_config->fdi_lanes);
5293                         return false;
5294                 } else {
5295                         return true;
5296                 }
5297         }
5298
5299         if (INTEL_INFO(dev)->num_pipes == 2)
5300                 return true;
5301
5302         /* Ivybridge 3 pipe is really complicated */
5303         switch (pipe) {
5304         case PIPE_A:
5305                 return true;
5306         case PIPE_B:
5307                 if (dev_priv->pipe_to_crtc_mapping[PIPE_C]->enabled &&
5308                     pipe_config->fdi_lanes > 2) {
5309                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5310                                       pipe_name(pipe), pipe_config->fdi_lanes);
5311                         return false;
5312                 }
5313                 return true;
5314         case PIPE_C:
5315                 if (!pipe_has_enabled_pch(pipe_B_crtc) ||
5316                     pipe_B_crtc->config.fdi_lanes <= 2) {
5317                         if (pipe_config->fdi_lanes > 2) {
5318                                 DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5319                                               pipe_name(pipe), pipe_config->fdi_lanes);
5320                                 return false;
5321                         }
5322                 } else {
5323                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
5324                         return false;
5325                 }
5326                 return true;
5327         default:
5328                 BUG();
5329         }
5330 }
5331
5332 #define RETRY 1
5333 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
5334                                        struct intel_crtc_config *pipe_config)
5335 {
5336         struct drm_device *dev = intel_crtc->base.dev;
5337         struct drm_display_mode *adjusted_mode = &pipe_config->adjusted_mode;
5338         int lane, link_bw, fdi_dotclock;
5339         bool setup_ok, needs_recompute = false;
5340
5341 retry:
5342         /* FDI is a binary signal running at ~2.7GHz, encoding
5343          * each output octet as 10 bits. The actual frequency
5344          * is stored as a divider into a 100MHz clock, and the
5345          * mode pixel clock is stored in units of 1KHz.
5346          * Hence the bw of each lane in terms of the mode signal
5347          * is:
5348          */
5349         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
5350
5351         fdi_dotclock = adjusted_mode->crtc_clock;
5352
5353         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
5354                                            pipe_config->pipe_bpp);
5355
5356         pipe_config->fdi_lanes = lane;
5357
5358         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
5359                                link_bw, &pipe_config->fdi_m_n);
5360
5361         setup_ok = ironlake_check_fdi_lanes(intel_crtc->base.dev,
5362                                             intel_crtc->pipe, pipe_config);
5363         if (!setup_ok && pipe_config->pipe_bpp > 6*3) {
5364                 pipe_config->pipe_bpp -= 2*3;
5365                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
5366                               pipe_config->pipe_bpp);
5367                 needs_recompute = true;
5368                 pipe_config->bw_constrained = true;
5369
5370                 goto retry;
5371         }
5372
5373         if (needs_recompute)
5374                 return RETRY;
5375
5376         return setup_ok ? 0 : -EINVAL;
5377 }
5378
5379 static void hsw_compute_ips_config(struct intel_crtc *crtc,
5380                                    struct intel_crtc_config *pipe_config)
5381 {
5382         pipe_config->ips_enabled = i915.enable_ips &&
5383                                    hsw_crtc_supports_ips(crtc) &&
5384                                    pipe_config->pipe_bpp <= 24;
5385 }
5386
5387 static int intel_crtc_compute_config(struct intel_crtc *crtc,
5388                                      struct intel_crtc_config *pipe_config)
5389 {
5390         struct drm_device *dev = crtc->base.dev;
5391         struct drm_display_mode *adjusted_mode = &pipe_config->adjusted_mode;
5392
5393         /* FIXME should check pixel clock limits on all platforms */
5394         if (INTEL_INFO(dev)->gen < 4) {
5395                 struct drm_i915_private *dev_priv = dev->dev_private;
5396                 int clock_limit =
5397                         dev_priv->display.get_display_clock_speed(dev);
5398
5399                 /*
5400                  * Enable pixel doubling when the dot clock
5401                  * is > 90% of the (display) core speed.
5402                  *
5403                  * GDG double wide on either pipe,
5404                  * otherwise pipe A only.
5405                  */
5406                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
5407                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
5408                         clock_limit *= 2;
5409                         pipe_config->double_wide = true;
5410                 }
5411
5412                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
5413                         return -EINVAL;
5414         }
5415
5416         /*
5417          * Pipe horizontal size must be even in:
5418          * - DVO ganged mode
5419          * - LVDS dual channel mode
5420          * - Double wide pipe
5421          */
5422         if ((intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
5423              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
5424                 pipe_config->pipe_src_w &= ~1;
5425
5426         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
5427          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
5428          */
5429         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
5430                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
5431                 return -EINVAL;
5432
5433         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)) && pipe_config->pipe_bpp > 10*3) {
5434                 pipe_config->pipe_bpp = 10*3; /* 12bpc is gen5+ */
5435         } else if (INTEL_INFO(dev)->gen <= 4 && pipe_config->pipe_bpp > 8*3) {
5436                 /* only a 8bpc pipe, with 6bpc dither through the panel fitter
5437                  * for lvds. */
5438                 pipe_config->pipe_bpp = 8*3;
5439         }
5440
5441         if (HAS_IPS(dev))
5442                 hsw_compute_ips_config(crtc, pipe_config);
5443
5444         /*
5445          * XXX: PCH/WRPLL clock sharing is done in ->mode_set, so make sure the
5446          * old clock survives for now.
5447          */
5448         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev) || HAS_DDI(dev))
5449                 pipe_config->shared_dpll = crtc->config.shared_dpll;
5450
5451         if (pipe_config->has_pch_encoder)
5452                 return ironlake_fdi_compute_config(crtc, pipe_config);
5453
5454         return 0;
5455 }
5456
5457 static int valleyview_get_display_clock_speed(struct drm_device *dev)
5458 {
5459         struct drm_i915_private *dev_priv = dev->dev_private;
5460         int vco = valleyview_get_vco(dev_priv);
5461         u32 val;
5462         int divider;
5463
5464         /* FIXME: Punit isn't quite ready yet */
5465         if (IS_CHERRYVIEW(dev))
5466                 return 400000;
5467
5468         mutex_lock(&dev_priv->dpio_lock);
5469         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5470         mutex_unlock(&dev_priv->dpio_lock);
5471
5472         divider = val & DISPLAY_FREQUENCY_VALUES;
5473
5474         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
5475              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5476              "cdclk change in progress\n");
5477
5478         return DIV_ROUND_CLOSEST(vco << 1, divider + 1);
5479 }
5480
5481 static int i945_get_display_clock_speed(struct drm_device *dev)
5482 {
5483         return 400000;
5484 }
5485
5486 static int i915_get_display_clock_speed(struct drm_device *dev)
5487 {
5488         return 333000;
5489 }
5490
5491 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
5492 {
5493         return 200000;
5494 }
5495
5496 static int pnv_get_display_clock_speed(struct drm_device *dev)
5497 {
5498         u16 gcfgc = 0;
5499
5500         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5501
5502         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5503         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
5504                 return 267000;
5505         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
5506                 return 333000;
5507         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
5508                 return 444000;
5509         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
5510                 return 200000;
5511         default:
5512                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
5513         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
5514                 return 133000;
5515         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
5516                 return 167000;
5517         }
5518 }
5519
5520 static int i915gm_get_display_clock_speed(struct drm_device *dev)
5521 {
5522         u16 gcfgc = 0;
5523
5524         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5525
5526         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
5527                 return 133000;
5528         else {
5529                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5530                 case GC_DISPLAY_CLOCK_333_MHZ:
5531                         return 333000;
5532                 default:
5533                 case GC_DISPLAY_CLOCK_190_200_MHZ:
5534                         return 190000;
5535                 }
5536         }
5537 }
5538
5539 static int i865_get_display_clock_speed(struct drm_device *dev)
5540 {
5541         return 266000;
5542 }
5543
5544 static int i855_get_display_clock_speed(struct drm_device *dev)
5545 {
5546         u16 hpllcc = 0;
5547         /* Assume that the hardware is in the high speed state.  This
5548          * should be the default.
5549          */
5550         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
5551         case GC_CLOCK_133_200:
5552         case GC_CLOCK_100_200:
5553                 return 200000;
5554         case GC_CLOCK_166_250:
5555                 return 250000;
5556         case GC_CLOCK_100_133:
5557                 return 133000;
5558         }
5559
5560         /* Shouldn't happen */
5561         return 0;
5562 }
5563
5564 static int i830_get_display_clock_speed(struct drm_device *dev)
5565 {
5566         return 133000;
5567 }
5568
5569 static void
5570 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
5571 {
5572         while (*num > DATA_LINK_M_N_MASK ||
5573                *den > DATA_LINK_M_N_MASK) {
5574                 *num >>= 1;
5575                 *den >>= 1;
5576         }
5577 }
5578
5579 static void compute_m_n(unsigned int m, unsigned int n,
5580                         uint32_t *ret_m, uint32_t *ret_n)
5581 {
5582         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
5583         *ret_m = div_u64((uint64_t) m * *ret_n, n);
5584         intel_reduce_m_n_ratio(ret_m, ret_n);
5585 }
5586
5587 void
5588 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
5589                        int pixel_clock, int link_clock,
5590                        struct intel_link_m_n *m_n)
5591 {
5592         m_n->tu = 64;
5593
5594         compute_m_n(bits_per_pixel * pixel_clock,
5595                     link_clock * nlanes * 8,
5596                     &m_n->gmch_m, &m_n->gmch_n);
5597
5598         compute_m_n(pixel_clock, link_clock,
5599                     &m_n->link_m, &m_n->link_n);
5600 }
5601
5602 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
5603 {
5604         if (i915.panel_use_ssc >= 0)
5605                 return i915.panel_use_ssc != 0;
5606         return dev_priv->vbt.lvds_use_ssc
5607                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
5608 }
5609
5610 static int i9xx_get_refclk(struct intel_crtc *crtc, int num_connectors)
5611 {
5612         struct drm_device *dev = crtc->base.dev;
5613         struct drm_i915_private *dev_priv = dev->dev_private;
5614         int refclk;
5615
5616         if (IS_VALLEYVIEW(dev)) {
5617                 refclk = 100000;
5618         } else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
5619             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
5620                 refclk = dev_priv->vbt.lvds_ssc_freq;
5621                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
5622         } else if (!IS_GEN2(dev)) {
5623                 refclk = 96000;
5624         } else {
5625                 refclk = 48000;
5626         }
5627
5628         return refclk;
5629 }
5630
5631 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
5632 {
5633         return (1 << dpll->n) << 16 | dpll->m2;
5634 }
5635
5636 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
5637 {
5638         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
5639 }
5640
5641 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
5642                                      intel_clock_t *reduced_clock)
5643 {
5644         struct drm_device *dev = crtc->base.dev;
5645         u32 fp, fp2 = 0;
5646
5647         if (IS_PINEVIEW(dev)) {
5648                 fp = pnv_dpll_compute_fp(&crtc->config.dpll);
5649                 if (reduced_clock)
5650                         fp2 = pnv_dpll_compute_fp(reduced_clock);
5651         } else {
5652                 fp = i9xx_dpll_compute_fp(&crtc->config.dpll);
5653                 if (reduced_clock)
5654                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
5655         }
5656
5657         crtc->config.dpll_hw_state.fp0 = fp;
5658
5659         crtc->lowfreq_avail = false;
5660         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
5661             reduced_clock && i915.powersave) {
5662                 crtc->config.dpll_hw_state.fp1 = fp2;
5663                 crtc->lowfreq_avail = true;
5664         } else {
5665                 crtc->config.dpll_hw_state.fp1 = fp;
5666         }
5667 }
5668
5669 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
5670                 pipe)
5671 {
5672         u32 reg_val;
5673
5674         /*
5675          * PLLB opamp always calibrates to max value of 0x3f, force enable it
5676          * and set it to a reasonable value instead.
5677          */
5678         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5679         reg_val &= 0xffffff00;
5680         reg_val |= 0x00000030;
5681         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5682
5683         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5684         reg_val &= 0x8cffffff;
5685         reg_val = 0x8c000000;
5686         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5687
5688         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5689         reg_val &= 0xffffff00;
5690         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5691
5692         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5693         reg_val &= 0x00ffffff;
5694         reg_val |= 0xb0000000;
5695         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5696 }
5697
5698 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
5699                                          struct intel_link_m_n *m_n)
5700 {
5701         struct drm_device *dev = crtc->base.dev;
5702         struct drm_i915_private *dev_priv = dev->dev_private;
5703         int pipe = crtc->pipe;
5704
5705         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5706         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
5707         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
5708         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
5709 }
5710
5711 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
5712                                          struct intel_link_m_n *m_n,
5713                                          struct intel_link_m_n *m2_n2)
5714 {
5715         struct drm_device *dev = crtc->base.dev;
5716         struct drm_i915_private *dev_priv = dev->dev_private;
5717         int pipe = crtc->pipe;
5718         enum transcoder transcoder = crtc->config.cpu_transcoder;
5719
5720         if (INTEL_INFO(dev)->gen >= 5) {
5721                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
5722                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
5723                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
5724                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
5725                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
5726                  * for gen < 8) and if DRRS is supported (to make sure the
5727                  * registers are not unnecessarily accessed).
5728                  */
5729                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
5730                         crtc->config.has_drrs) {
5731                         I915_WRITE(PIPE_DATA_M2(transcoder),
5732                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
5733                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
5734                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
5735                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
5736                 }
5737         } else {
5738                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5739                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
5740                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
5741                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
5742         }
5743 }
5744
5745 void intel_dp_set_m_n(struct intel_crtc *crtc)
5746 {
5747         if (crtc->config.has_pch_encoder)
5748                 intel_pch_transcoder_set_m_n(crtc, &crtc->config.dp_m_n);
5749         else
5750                 intel_cpu_transcoder_set_m_n(crtc, &crtc->config.dp_m_n,
5751                                                    &crtc->config.dp_m2_n2);
5752 }
5753
5754 static void vlv_update_pll(struct intel_crtc *crtc,
5755                            struct intel_crtc_config *pipe_config)
5756 {
5757         u32 dpll, dpll_md;
5758
5759         /*
5760          * Enable DPIO clock input. We should never disable the reference
5761          * clock for pipe B, since VGA hotplug / manual detection depends
5762          * on it.
5763          */
5764         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
5765                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
5766         /* We should never disable this, set it here for state tracking */
5767         if (crtc->pipe == PIPE_B)
5768                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
5769         dpll |= DPLL_VCO_ENABLE;
5770         pipe_config->dpll_hw_state.dpll = dpll;
5771
5772         dpll_md = (pipe_config->pixel_multiplier - 1)
5773                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5774         pipe_config->dpll_hw_state.dpll_md = dpll_md;
5775 }
5776
5777 static void vlv_prepare_pll(struct intel_crtc *crtc,
5778                             const struct intel_crtc_config *pipe_config)
5779 {
5780         struct drm_device *dev = crtc->base.dev;
5781         struct drm_i915_private *dev_priv = dev->dev_private;
5782         int pipe = crtc->pipe;
5783         u32 mdiv;
5784         u32 bestn, bestm1, bestm2, bestp1, bestp2;
5785         u32 coreclk, reg_val;
5786
5787         mutex_lock(&dev_priv->dpio_lock);
5788
5789         bestn = pipe_config->dpll.n;
5790         bestm1 = pipe_config->dpll.m1;
5791         bestm2 = pipe_config->dpll.m2;
5792         bestp1 = pipe_config->dpll.p1;
5793         bestp2 = pipe_config->dpll.p2;
5794
5795         /* See eDP HDMI DPIO driver vbios notes doc */
5796
5797         /* PLL B needs special handling */
5798         if (pipe == PIPE_B)
5799                 vlv_pllb_recal_opamp(dev_priv, pipe);
5800
5801         /* Set up Tx target for periodic Rcomp update */
5802         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
5803
5804         /* Disable target IRef on PLL */
5805         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
5806         reg_val &= 0x00ffffff;
5807         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
5808
5809         /* Disable fast lock */
5810         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
5811
5812         /* Set idtafcrecal before PLL is enabled */
5813         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
5814         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
5815         mdiv |= ((bestn << DPIO_N_SHIFT));
5816         mdiv |= (1 << DPIO_K_SHIFT);
5817
5818         /*
5819          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
5820          * but we don't support that).
5821          * Note: don't use the DAC post divider as it seems unstable.
5822          */
5823         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
5824         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5825
5826         mdiv |= DPIO_ENABLE_CALIBRATION;
5827         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
5828
5829         /* Set HBR and RBR LPF coefficients */
5830         if (pipe_config->port_clock == 162000 ||
5831             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
5832             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
5833                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5834                                  0x009f0003);
5835         else
5836                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
5837                                  0x00d0000f);
5838
5839         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP) ||
5840             intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT)) {
5841                 /* Use SSC source */
5842                 if (pipe == PIPE_A)
5843                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5844                                          0x0df40000);
5845                 else
5846                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5847                                          0x0df70000);
5848         } else { /* HDMI or VGA */
5849                 /* Use bend source */
5850                 if (pipe == PIPE_A)
5851                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5852                                          0x0df70000);
5853                 else
5854                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
5855                                          0x0df40000);
5856         }
5857
5858         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
5859         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
5860         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
5861             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
5862                 coreclk |= 0x01000000;
5863         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
5864
5865         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
5866         mutex_unlock(&dev_priv->dpio_lock);
5867 }
5868
5869 static void chv_update_pll(struct intel_crtc *crtc,
5870                            struct intel_crtc_config *pipe_config)
5871 {
5872         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
5873                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
5874                 DPLL_VCO_ENABLE;
5875         if (crtc->pipe != PIPE_A)
5876                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
5877
5878         pipe_config->dpll_hw_state.dpll_md =
5879                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
5880 }
5881
5882 static void chv_prepare_pll(struct intel_crtc *crtc,
5883                             const struct intel_crtc_config *pipe_config)
5884 {
5885         struct drm_device *dev = crtc->base.dev;
5886         struct drm_i915_private *dev_priv = dev->dev_private;
5887         int pipe = crtc->pipe;
5888         int dpll_reg = DPLL(crtc->pipe);
5889         enum dpio_channel port = vlv_pipe_to_channel(pipe);
5890         u32 loopfilter, intcoeff;
5891         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
5892         int refclk;
5893
5894         bestn = pipe_config->dpll.n;
5895         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
5896         bestm1 = pipe_config->dpll.m1;
5897         bestm2 = pipe_config->dpll.m2 >> 22;
5898         bestp1 = pipe_config->dpll.p1;
5899         bestp2 = pipe_config->dpll.p2;
5900
5901         /*
5902          * Enable Refclk and SSC
5903          */
5904         I915_WRITE(dpll_reg,
5905                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
5906
5907         mutex_lock(&dev_priv->dpio_lock);
5908
5909         /* p1 and p2 divider */
5910         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
5911                         5 << DPIO_CHV_S1_DIV_SHIFT |
5912                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
5913                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
5914                         1 << DPIO_CHV_K_DIV_SHIFT);
5915
5916         /* Feedback post-divider - m2 */
5917         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
5918
5919         /* Feedback refclk divider - n and m1 */
5920         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
5921                         DPIO_CHV_M1_DIV_BY_2 |
5922                         1 << DPIO_CHV_N_DIV_SHIFT);
5923
5924         /* M2 fraction division */
5925         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
5926
5927         /* M2 fraction division enable */
5928         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port),
5929                        DPIO_CHV_FRAC_DIV_EN |
5930                        (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT));
5931
5932         /* Loop filter */
5933         refclk = i9xx_get_refclk(crtc, 0);
5934         loopfilter = 5 << DPIO_CHV_PROP_COEFF_SHIFT |
5935                 2 << DPIO_CHV_GAIN_CTRL_SHIFT;
5936         if (refclk == 100000)
5937                 intcoeff = 11;
5938         else if (refclk == 38400)
5939                 intcoeff = 10;
5940         else
5941                 intcoeff = 9;
5942         loopfilter |= intcoeff << DPIO_CHV_INT_COEFF_SHIFT;
5943         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
5944
5945         /* AFC Recal */
5946         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
5947                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
5948                         DPIO_AFC_RECAL);
5949
5950         mutex_unlock(&dev_priv->dpio_lock);
5951 }
5952
5953 /**
5954  * vlv_force_pll_on - forcibly enable just the PLL
5955  * @dev_priv: i915 private structure
5956  * @pipe: pipe PLL to enable
5957  * @dpll: PLL configuration
5958  *
5959  * Enable the PLL for @pipe using the supplied @dpll config. To be used
5960  * in cases where we need the PLL enabled even when @pipe is not going to
5961  * be enabled.
5962  */
5963 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
5964                       const struct dpll *dpll)
5965 {
5966         struct intel_crtc *crtc =
5967                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
5968         struct intel_crtc_config pipe_config = {
5969                 .pixel_multiplier = 1,
5970                 .dpll = *dpll,
5971         };
5972
5973         if (IS_CHERRYVIEW(dev)) {
5974                 chv_update_pll(crtc, &pipe_config);
5975                 chv_prepare_pll(crtc, &pipe_config);
5976                 chv_enable_pll(crtc, &pipe_config);
5977         } else {
5978                 vlv_update_pll(crtc, &pipe_config);
5979                 vlv_prepare_pll(crtc, &pipe_config);
5980                 vlv_enable_pll(crtc, &pipe_config);
5981         }
5982 }
5983
5984 /**
5985  * vlv_force_pll_off - forcibly disable just the PLL
5986  * @dev_priv: i915 private structure
5987  * @pipe: pipe PLL to disable
5988  *
5989  * Disable the PLL for @pipe. To be used in cases where we need
5990  * the PLL enabled even when @pipe is not going to be enabled.
5991  */
5992 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
5993 {
5994         if (IS_CHERRYVIEW(dev))
5995                 chv_disable_pll(to_i915(dev), pipe);
5996         else
5997                 vlv_disable_pll(to_i915(dev), pipe);
5998 }
5999
6000 static void i9xx_update_pll(struct intel_crtc *crtc,
6001                             intel_clock_t *reduced_clock,
6002                             int num_connectors)
6003 {
6004         struct drm_device *dev = crtc->base.dev;
6005         struct drm_i915_private *dev_priv = dev->dev_private;
6006         u32 dpll;
6007         bool is_sdvo;
6008         struct dpll *clock = &crtc->config.dpll;
6009
6010         i9xx_update_pll_dividers(crtc, reduced_clock);
6011
6012         is_sdvo = intel_pipe_has_type(crtc, INTEL_OUTPUT_SDVO) ||
6013                 intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI);
6014
6015         dpll = DPLL_VGA_MODE_DIS;
6016
6017         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS))
6018                 dpll |= DPLLB_MODE_LVDS;
6019         else
6020                 dpll |= DPLLB_MODE_DAC_SERIAL;
6021
6022         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6023                 dpll |= (crtc->config.pixel_multiplier - 1)
6024                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6025         }
6026
6027         if (is_sdvo)
6028                 dpll |= DPLL_SDVO_HIGH_SPEED;
6029
6030         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT))
6031                 dpll |= DPLL_SDVO_HIGH_SPEED;
6032
6033         /* compute bitmask from p1 value */
6034         if (IS_PINEVIEW(dev))
6035                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6036         else {
6037                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6038                 if (IS_G4X(dev) && reduced_clock)
6039                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6040         }
6041         switch (clock->p2) {
6042         case 5:
6043                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6044                 break;
6045         case 7:
6046                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6047                 break;
6048         case 10:
6049                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6050                 break;
6051         case 14:
6052                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6053                 break;
6054         }
6055         if (INTEL_INFO(dev)->gen >= 4)
6056                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6057
6058         if (crtc->config.sdvo_tv_clock)
6059                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6060         else if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
6061                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6062                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6063         else
6064                 dpll |= PLL_REF_INPUT_DREFCLK;
6065
6066         dpll |= DPLL_VCO_ENABLE;
6067         crtc->config.dpll_hw_state.dpll = dpll;
6068
6069         if (INTEL_INFO(dev)->gen >= 4) {
6070                 u32 dpll_md = (crtc->config.pixel_multiplier - 1)
6071                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6072                 crtc->config.dpll_hw_state.dpll_md = dpll_md;
6073         }
6074 }
6075
6076 static void i8xx_update_pll(struct intel_crtc *crtc,
6077                             intel_clock_t *reduced_clock,
6078                             int num_connectors)
6079 {
6080         struct drm_device *dev = crtc->base.dev;
6081         struct drm_i915_private *dev_priv = dev->dev_private;
6082         u32 dpll;
6083         struct dpll *clock = &crtc->config.dpll;
6084
6085         i9xx_update_pll_dividers(crtc, reduced_clock);
6086
6087         dpll = DPLL_VGA_MODE_DIS;
6088
6089         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS)) {
6090                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6091         } else {
6092                 if (clock->p1 == 2)
6093                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6094                 else
6095                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6096                 if (clock->p2 == 4)
6097                         dpll |= PLL_P2_DIVIDE_BY_4;
6098         }
6099
6100         if (!IS_I830(dev) && intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO))
6101                 dpll |= DPLL_DVO_2X_MODE;
6102
6103         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) &&
6104                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6105                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6106         else
6107                 dpll |= PLL_REF_INPUT_DREFCLK;
6108
6109         dpll |= DPLL_VCO_ENABLE;
6110         crtc->config.dpll_hw_state.dpll = dpll;
6111 }
6112
6113 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6114 {
6115         struct drm_device *dev = intel_crtc->base.dev;
6116         struct drm_i915_private *dev_priv = dev->dev_private;
6117         enum pipe pipe = intel_crtc->pipe;
6118         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
6119         struct drm_display_mode *adjusted_mode =
6120                 &intel_crtc->config.adjusted_mode;
6121         uint32_t crtc_vtotal, crtc_vblank_end;
6122         int vsyncshift = 0;
6123
6124         /* We need to be careful not to changed the adjusted mode, for otherwise
6125          * the hw state checker will get angry at the mismatch. */
6126         crtc_vtotal = adjusted_mode->crtc_vtotal;
6127         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6128
6129         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6130                 /* the chip adds 2 halflines automatically */
6131                 crtc_vtotal -= 1;
6132                 crtc_vblank_end -= 1;
6133
6134                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6135                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6136                 else
6137                         vsyncshift = adjusted_mode->crtc_hsync_start -
6138                                 adjusted_mode->crtc_htotal / 2;
6139                 if (vsyncshift < 0)
6140                         vsyncshift += adjusted_mode->crtc_htotal;
6141         }
6142
6143         if (INTEL_INFO(dev)->gen > 3)
6144                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6145
6146         I915_WRITE(HTOTAL(cpu_transcoder),
6147                    (adjusted_mode->crtc_hdisplay - 1) |
6148                    ((adjusted_mode->crtc_htotal - 1) << 16));
6149         I915_WRITE(HBLANK(cpu_transcoder),
6150                    (adjusted_mode->crtc_hblank_start - 1) |
6151                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6152         I915_WRITE(HSYNC(cpu_transcoder),
6153                    (adjusted_mode->crtc_hsync_start - 1) |
6154                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6155
6156         I915_WRITE(VTOTAL(cpu_transcoder),
6157                    (adjusted_mode->crtc_vdisplay - 1) |
6158                    ((crtc_vtotal - 1) << 16));
6159         I915_WRITE(VBLANK(cpu_transcoder),
6160                    (adjusted_mode->crtc_vblank_start - 1) |
6161                    ((crtc_vblank_end - 1) << 16));
6162         I915_WRITE(VSYNC(cpu_transcoder),
6163                    (adjusted_mode->crtc_vsync_start - 1) |
6164                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6165
6166         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6167          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6168          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6169          * bits. */
6170         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
6171             (pipe == PIPE_B || pipe == PIPE_C))
6172                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6173
6174         /* pipesrc controls the size that is scaled from, which should
6175          * always be the user's requested size.
6176          */
6177         I915_WRITE(PIPESRC(pipe),
6178                    ((intel_crtc->config.pipe_src_w - 1) << 16) |
6179                    (intel_crtc->config.pipe_src_h - 1));
6180 }
6181
6182 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6183                                    struct intel_crtc_config *pipe_config)
6184 {
6185         struct drm_device *dev = crtc->base.dev;
6186         struct drm_i915_private *dev_priv = dev->dev_private;
6187         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6188         uint32_t tmp;
6189
6190         tmp = I915_READ(HTOTAL(cpu_transcoder));
6191         pipe_config->adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6192         pipe_config->adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6193         tmp = I915_READ(HBLANK(cpu_transcoder));
6194         pipe_config->adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6195         pipe_config->adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6196         tmp = I915_READ(HSYNC(cpu_transcoder));
6197         pipe_config->adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6198         pipe_config->adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6199
6200         tmp = I915_READ(VTOTAL(cpu_transcoder));
6201         pipe_config->adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6202         pipe_config->adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6203         tmp = I915_READ(VBLANK(cpu_transcoder));
6204         pipe_config->adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6205         pipe_config->adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6206         tmp = I915_READ(VSYNC(cpu_transcoder));
6207         pipe_config->adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6208         pipe_config->adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6209
6210         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6211                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6212                 pipe_config->adjusted_mode.crtc_vtotal += 1;
6213                 pipe_config->adjusted_mode.crtc_vblank_end += 1;
6214         }
6215
6216         tmp = I915_READ(PIPESRC(crtc->pipe));
6217         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
6218         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
6219
6220         pipe_config->requested_mode.vdisplay = pipe_config->pipe_src_h;
6221         pipe_config->requested_mode.hdisplay = pipe_config->pipe_src_w;
6222 }
6223
6224 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
6225                                  struct intel_crtc_config *pipe_config)
6226 {
6227         mode->hdisplay = pipe_config->adjusted_mode.crtc_hdisplay;
6228         mode->htotal = pipe_config->adjusted_mode.crtc_htotal;
6229         mode->hsync_start = pipe_config->adjusted_mode.crtc_hsync_start;
6230         mode->hsync_end = pipe_config->adjusted_mode.crtc_hsync_end;
6231
6232         mode->vdisplay = pipe_config->adjusted_mode.crtc_vdisplay;
6233         mode->vtotal = pipe_config->adjusted_mode.crtc_vtotal;
6234         mode->vsync_start = pipe_config->adjusted_mode.crtc_vsync_start;
6235         mode->vsync_end = pipe_config->adjusted_mode.crtc_vsync_end;
6236
6237         mode->flags = pipe_config->adjusted_mode.flags;
6238
6239         mode->clock = pipe_config->adjusted_mode.crtc_clock;
6240         mode->flags |= pipe_config->adjusted_mode.flags;
6241 }
6242
6243 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
6244 {
6245         struct drm_device *dev = intel_crtc->base.dev;
6246         struct drm_i915_private *dev_priv = dev->dev_private;
6247         uint32_t pipeconf;
6248
6249         pipeconf = 0;
6250
6251         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
6252             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
6253                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
6254
6255         if (intel_crtc->config.double_wide)
6256                 pipeconf |= PIPECONF_DOUBLE_WIDE;
6257
6258         /* only g4x and later have fancy bpc/dither controls */
6259         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6260                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
6261                 if (intel_crtc->config.dither && intel_crtc->config.pipe_bpp != 30)
6262                         pipeconf |= PIPECONF_DITHER_EN |
6263                                     PIPECONF_DITHER_TYPE_SP;
6264
6265                 switch (intel_crtc->config.pipe_bpp) {
6266                 case 18:
6267                         pipeconf |= PIPECONF_6BPC;
6268                         break;
6269                 case 24:
6270                         pipeconf |= PIPECONF_8BPC;
6271                         break;
6272                 case 30:
6273                         pipeconf |= PIPECONF_10BPC;
6274                         break;
6275                 default:
6276                         /* Case prevented by intel_choose_pipe_bpp_dither. */
6277                         BUG();
6278                 }
6279         }
6280
6281         if (HAS_PIPE_CXSR(dev)) {
6282                 if (intel_crtc->lowfreq_avail) {
6283                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
6284                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
6285                 } else {
6286                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
6287                 }
6288         }
6289
6290         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
6291                 if (INTEL_INFO(dev)->gen < 4 ||
6292                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6293                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
6294                 else
6295                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
6296         } else
6297                 pipeconf |= PIPECONF_PROGRESSIVE;
6298
6299         if (IS_VALLEYVIEW(dev) && intel_crtc->config.limited_color_range)
6300                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
6301
6302         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
6303         POSTING_READ(PIPECONF(intel_crtc->pipe));
6304 }
6305
6306 static int i9xx_crtc_mode_set(struct intel_crtc *crtc,
6307                               int x, int y,
6308                               struct drm_framebuffer *fb)
6309 {
6310         struct drm_device *dev = crtc->base.dev;
6311         struct drm_i915_private *dev_priv = dev->dev_private;
6312         int refclk, num_connectors = 0;
6313         intel_clock_t clock, reduced_clock;
6314         bool ok, has_reduced_clock = false;
6315         bool is_lvds = false, is_dsi = false;
6316         struct intel_encoder *encoder;
6317         const intel_limit_t *limit;
6318
6319         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
6320                 switch (encoder->type) {
6321                 case INTEL_OUTPUT_LVDS:
6322                         is_lvds = true;
6323                         break;
6324                 case INTEL_OUTPUT_DSI:
6325                         is_dsi = true;
6326                         break;
6327                 default:
6328                         break;
6329                 }
6330
6331                 num_connectors++;
6332         }
6333
6334         if (is_dsi)
6335                 return 0;
6336
6337         if (!crtc->config.clock_set) {
6338                 refclk = i9xx_get_refclk(crtc, num_connectors);
6339
6340                 /*
6341                  * Returns a set of divisors for the desired target clock with
6342                  * the given refclk, or FALSE.  The returned values represent
6343                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
6344                  * 2) / p1 / p2.
6345                  */
6346                 limit = intel_limit(crtc, refclk);
6347                 ok = dev_priv->display.find_dpll(limit, crtc,
6348                                                  crtc->config.port_clock,
6349                                                  refclk, NULL, &clock);
6350                 if (!ok) {
6351                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
6352                         return -EINVAL;
6353                 }
6354
6355                 if (is_lvds && dev_priv->lvds_downclock_avail) {
6356                         /*
6357                          * Ensure we match the reduced clock's P to the target
6358                          * clock.  If the clocks don't match, we can't switch
6359                          * the display clock by using the FP0/FP1. In such case
6360                          * we will disable the LVDS downclock feature.
6361                          */
6362                         has_reduced_clock =
6363                                 dev_priv->display.find_dpll(limit, crtc,
6364                                                             dev_priv->lvds_downclock,
6365                                                             refclk, &clock,
6366                                                             &reduced_clock);
6367                 }
6368                 /* Compat-code for transition, will disappear. */
6369                 crtc->config.dpll.n = clock.n;
6370                 crtc->config.dpll.m1 = clock.m1;
6371                 crtc->config.dpll.m2 = clock.m2;
6372                 crtc->config.dpll.p1 = clock.p1;
6373                 crtc->config.dpll.p2 = clock.p2;
6374         }
6375
6376         if (IS_GEN2(dev)) {
6377                 i8xx_update_pll(crtc,
6378                                 has_reduced_clock ? &reduced_clock : NULL,
6379                                 num_connectors);
6380         } else if (IS_CHERRYVIEW(dev)) {
6381                 chv_update_pll(crtc, &crtc->config);
6382         } else if (IS_VALLEYVIEW(dev)) {
6383                 vlv_update_pll(crtc, &crtc->config);
6384         } else {
6385                 i9xx_update_pll(crtc,
6386                                 has_reduced_clock ? &reduced_clock : NULL,
6387                                 num_connectors);
6388         }
6389
6390         return 0;
6391 }
6392
6393 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
6394                                  struct intel_crtc_config *pipe_config)
6395 {
6396         struct drm_device *dev = crtc->base.dev;
6397         struct drm_i915_private *dev_priv = dev->dev_private;
6398         uint32_t tmp;
6399
6400         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
6401                 return;
6402
6403         tmp = I915_READ(PFIT_CONTROL);
6404         if (!(tmp & PFIT_ENABLE))
6405                 return;
6406
6407         /* Check whether the pfit is attached to our pipe. */
6408         if (INTEL_INFO(dev)->gen < 4) {
6409                 if (crtc->pipe != PIPE_B)
6410                         return;
6411         } else {
6412                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
6413                         return;
6414         }
6415
6416         pipe_config->gmch_pfit.control = tmp;
6417         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
6418         if (INTEL_INFO(dev)->gen < 5)
6419                 pipe_config->gmch_pfit.lvds_border_bits =
6420                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
6421 }
6422
6423 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
6424                                struct intel_crtc_config *pipe_config)
6425 {
6426         struct drm_device *dev = crtc->base.dev;
6427         struct drm_i915_private *dev_priv = dev->dev_private;
6428         int pipe = pipe_config->cpu_transcoder;
6429         intel_clock_t clock;
6430         u32 mdiv;
6431         int refclk = 100000;
6432
6433         /* In case of MIPI DPLL will not even be used */
6434         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
6435                 return;
6436
6437         mutex_lock(&dev_priv->dpio_lock);
6438         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
6439         mutex_unlock(&dev_priv->dpio_lock);
6440
6441         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
6442         clock.m2 = mdiv & DPIO_M2DIV_MASK;
6443         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
6444         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
6445         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
6446
6447         vlv_clock(refclk, &clock);
6448
6449         /* clock.dot is the fast clock */
6450         pipe_config->port_clock = clock.dot / 5;
6451 }
6452
6453 static void i9xx_get_plane_config(struct intel_crtc *crtc,
6454                                   struct intel_plane_config *plane_config)
6455 {
6456         struct drm_device *dev = crtc->base.dev;
6457         struct drm_i915_private *dev_priv = dev->dev_private;
6458         u32 val, base, offset;
6459         int pipe = crtc->pipe, plane = crtc->plane;
6460         int fourcc, pixel_format;
6461         int aligned_height;
6462
6463         crtc->base.primary->fb = kzalloc(sizeof(struct intel_framebuffer), GFP_KERNEL);
6464         if (!crtc->base.primary->fb) {
6465                 DRM_DEBUG_KMS("failed to alloc fb\n");
6466                 return;
6467         }
6468
6469         val = I915_READ(DSPCNTR(plane));
6470
6471         if (INTEL_INFO(dev)->gen >= 4)
6472                 if (val & DISPPLANE_TILED)
6473                         plane_config->tiled = true;
6474
6475         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
6476         fourcc = intel_format_to_fourcc(pixel_format);
6477         crtc->base.primary->fb->pixel_format = fourcc;
6478         crtc->base.primary->fb->bits_per_pixel =
6479                 drm_format_plane_cpp(fourcc, 0) * 8;
6480
6481         if (INTEL_INFO(dev)->gen >= 4) {
6482                 if (plane_config->tiled)
6483                         offset = I915_READ(DSPTILEOFF(plane));
6484                 else
6485                         offset = I915_READ(DSPLINOFF(plane));
6486                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
6487         } else {
6488                 base = I915_READ(DSPADDR(plane));
6489         }
6490         plane_config->base = base;
6491
6492         val = I915_READ(PIPESRC(pipe));
6493         crtc->base.primary->fb->width = ((val >> 16) & 0xfff) + 1;
6494         crtc->base.primary->fb->height = ((val >> 0) & 0xfff) + 1;
6495
6496         val = I915_READ(DSPSTRIDE(pipe));
6497         crtc->base.primary->fb->pitches[0] = val & 0xffffffc0;
6498
6499         aligned_height = intel_align_height(dev, crtc->base.primary->fb->height,
6500                                             plane_config->tiled);
6501
6502         plane_config->size = PAGE_ALIGN(crtc->base.primary->fb->pitches[0] *
6503                                         aligned_height);
6504
6505         DRM_DEBUG_KMS("pipe/plane %d/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
6506                       pipe, plane, crtc->base.primary->fb->width,
6507                       crtc->base.primary->fb->height,
6508                       crtc->base.primary->fb->bits_per_pixel, base,
6509                       crtc->base.primary->fb->pitches[0],
6510                       plane_config->size);
6511
6512 }
6513
6514 static void chv_crtc_clock_get(struct intel_crtc *crtc,
6515                                struct intel_crtc_config *pipe_config)
6516 {
6517         struct drm_device *dev = crtc->base.dev;
6518         struct drm_i915_private *dev_priv = dev->dev_private;
6519         int pipe = pipe_config->cpu_transcoder;
6520         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6521         intel_clock_t clock;
6522         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
6523         int refclk = 100000;
6524
6525         mutex_lock(&dev_priv->dpio_lock);
6526         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
6527         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
6528         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
6529         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
6530         mutex_unlock(&dev_priv->dpio_lock);
6531
6532         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
6533         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
6534         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
6535         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
6536         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
6537
6538         chv_clock(refclk, &clock);
6539
6540         /* clock.dot is the fast clock */
6541         pipe_config->port_clock = clock.dot / 5;
6542 }
6543
6544 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
6545                                  struct intel_crtc_config *pipe_config)
6546 {
6547         struct drm_device *dev = crtc->base.dev;
6548         struct drm_i915_private *dev_priv = dev->dev_private;
6549         uint32_t tmp;
6550
6551         if (!intel_display_power_is_enabled(dev_priv,
6552                                             POWER_DOMAIN_PIPE(crtc->pipe)))
6553                 return false;
6554
6555         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
6556         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
6557
6558         tmp = I915_READ(PIPECONF(crtc->pipe));
6559         if (!(tmp & PIPECONF_ENABLE))
6560                 return false;
6561
6562         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6563                 switch (tmp & PIPECONF_BPC_MASK) {
6564                 case PIPECONF_6BPC:
6565                         pipe_config->pipe_bpp = 18;
6566                         break;
6567                 case PIPECONF_8BPC:
6568                         pipe_config->pipe_bpp = 24;
6569                         break;
6570                 case PIPECONF_10BPC:
6571                         pipe_config->pipe_bpp = 30;
6572                         break;
6573                 default:
6574                         break;
6575                 }
6576         }
6577
6578         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
6579                 pipe_config->limited_color_range = true;
6580
6581         if (INTEL_INFO(dev)->gen < 4)
6582                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
6583
6584         intel_get_pipe_timings(crtc, pipe_config);
6585
6586         i9xx_get_pfit_config(crtc, pipe_config);
6587
6588         if (INTEL_INFO(dev)->gen >= 4) {
6589                 tmp = I915_READ(DPLL_MD(crtc->pipe));
6590                 pipe_config->pixel_multiplier =
6591                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
6592                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
6593                 pipe_config->dpll_hw_state.dpll_md = tmp;
6594         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6595                 tmp = I915_READ(DPLL(crtc->pipe));
6596                 pipe_config->pixel_multiplier =
6597                         ((tmp & SDVO_MULTIPLIER_MASK)
6598                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
6599         } else {
6600                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
6601                  * port and will be fixed up in the encoder->get_config
6602                  * function. */
6603                 pipe_config->pixel_multiplier = 1;
6604         }
6605         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
6606         if (!IS_VALLEYVIEW(dev)) {
6607                 /*
6608                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
6609                  * on 830. Filter it out here so that we don't
6610                  * report errors due to that.
6611                  */
6612                 if (IS_I830(dev))
6613                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
6614
6615                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
6616                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
6617         } else {
6618                 /* Mask out read-only status bits. */
6619                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
6620                                                      DPLL_PORTC_READY_MASK |
6621                                                      DPLL_PORTB_READY_MASK);
6622         }
6623
6624         if (IS_CHERRYVIEW(dev))
6625                 chv_crtc_clock_get(crtc, pipe_config);
6626         else if (IS_VALLEYVIEW(dev))
6627                 vlv_crtc_clock_get(crtc, pipe_config);
6628         else
6629                 i9xx_crtc_clock_get(crtc, pipe_config);
6630
6631         return true;
6632 }
6633
6634 static void ironlake_init_pch_refclk(struct drm_device *dev)
6635 {
6636         struct drm_i915_private *dev_priv = dev->dev_private;
6637         struct intel_encoder *encoder;
6638         u32 val, final;
6639         bool has_lvds = false;
6640         bool has_cpu_edp = false;
6641         bool has_panel = false;
6642         bool has_ck505 = false;
6643         bool can_ssc = false;
6644
6645         /* We need to take the global config into account */
6646         for_each_intel_encoder(dev, encoder) {
6647                 switch (encoder->type) {
6648                 case INTEL_OUTPUT_LVDS:
6649                         has_panel = true;
6650                         has_lvds = true;
6651                         break;
6652                 case INTEL_OUTPUT_EDP:
6653                         has_panel = true;
6654                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
6655                                 has_cpu_edp = true;
6656                         break;
6657                 default:
6658                         break;
6659                 }
6660         }
6661
6662         if (HAS_PCH_IBX(dev)) {
6663                 has_ck505 = dev_priv->vbt.display_clock_mode;
6664                 can_ssc = has_ck505;
6665         } else {
6666                 has_ck505 = false;
6667                 can_ssc = true;
6668         }
6669
6670         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
6671                       has_panel, has_lvds, has_ck505);
6672
6673         /* Ironlake: try to setup display ref clock before DPLL
6674          * enabling. This is only under driver's control after
6675          * PCH B stepping, previous chipset stepping should be
6676          * ignoring this setting.
6677          */
6678         val = I915_READ(PCH_DREF_CONTROL);
6679
6680         /* As we must carefully and slowly disable/enable each source in turn,
6681          * compute the final state we want first and check if we need to
6682          * make any changes at all.
6683          */
6684         final = val;
6685         final &= ~DREF_NONSPREAD_SOURCE_MASK;
6686         if (has_ck505)
6687                 final |= DREF_NONSPREAD_CK505_ENABLE;
6688         else
6689                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
6690
6691         final &= ~DREF_SSC_SOURCE_MASK;
6692         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6693         final &= ~DREF_SSC1_ENABLE;
6694
6695         if (has_panel) {
6696                 final |= DREF_SSC_SOURCE_ENABLE;
6697
6698                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
6699                         final |= DREF_SSC1_ENABLE;
6700
6701                 if (has_cpu_edp) {
6702                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
6703                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6704                         else
6705                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6706                 } else
6707                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6708         } else {
6709                 final |= DREF_SSC_SOURCE_DISABLE;
6710                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6711         }
6712
6713         if (final == val)
6714                 return;
6715
6716         /* Always enable nonspread source */
6717         val &= ~DREF_NONSPREAD_SOURCE_MASK;
6718
6719         if (has_ck505)
6720                 val |= DREF_NONSPREAD_CK505_ENABLE;
6721         else
6722                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
6723
6724         if (has_panel) {
6725                 val &= ~DREF_SSC_SOURCE_MASK;
6726                 val |= DREF_SSC_SOURCE_ENABLE;
6727
6728                 /* SSC must be turned on before enabling the CPU output  */
6729                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6730                         DRM_DEBUG_KMS("Using SSC on panel\n");
6731                         val |= DREF_SSC1_ENABLE;
6732                 } else
6733                         val &= ~DREF_SSC1_ENABLE;
6734
6735                 /* Get SSC going before enabling the outputs */
6736                 I915_WRITE(PCH_DREF_CONTROL, val);
6737                 POSTING_READ(PCH_DREF_CONTROL);
6738                 udelay(200);
6739
6740                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6741
6742                 /* Enable CPU source on CPU attached eDP */
6743                 if (has_cpu_edp) {
6744                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6745                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
6746                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6747                         } else
6748                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6749                 } else
6750                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6751
6752                 I915_WRITE(PCH_DREF_CONTROL, val);
6753                 POSTING_READ(PCH_DREF_CONTROL);
6754                 udelay(200);
6755         } else {
6756                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
6757
6758                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6759
6760                 /* Turn off CPU output */
6761                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6762
6763                 I915_WRITE(PCH_DREF_CONTROL, val);
6764                 POSTING_READ(PCH_DREF_CONTROL);
6765                 udelay(200);
6766
6767                 /* Turn off the SSC source */
6768                 val &= ~DREF_SSC_SOURCE_MASK;
6769                 val |= DREF_SSC_SOURCE_DISABLE;
6770
6771                 /* Turn off SSC1 */
6772                 val &= ~DREF_SSC1_ENABLE;
6773
6774                 I915_WRITE(PCH_DREF_CONTROL, val);
6775                 POSTING_READ(PCH_DREF_CONTROL);
6776                 udelay(200);
6777         }
6778
6779         BUG_ON(val != final);
6780 }
6781
6782 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
6783 {
6784         uint32_t tmp;
6785
6786         tmp = I915_READ(SOUTH_CHICKEN2);
6787         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
6788         I915_WRITE(SOUTH_CHICKEN2, tmp);
6789
6790         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
6791                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
6792                 DRM_ERROR("FDI mPHY reset assert timeout\n");
6793
6794         tmp = I915_READ(SOUTH_CHICKEN2);
6795         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
6796         I915_WRITE(SOUTH_CHICKEN2, tmp);
6797
6798         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
6799                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
6800                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
6801 }
6802
6803 /* WaMPhyProgramming:hsw */
6804 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
6805 {
6806         uint32_t tmp;
6807
6808         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
6809         tmp &= ~(0xFF << 24);
6810         tmp |= (0x12 << 24);
6811         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
6812
6813         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
6814         tmp |= (1 << 11);
6815         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
6816
6817         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
6818         tmp |= (1 << 11);
6819         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
6820
6821         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
6822         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6823         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
6824
6825         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
6826         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
6827         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
6828
6829         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
6830         tmp &= ~(7 << 13);
6831         tmp |= (5 << 13);
6832         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
6833
6834         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
6835         tmp &= ~(7 << 13);
6836         tmp |= (5 << 13);
6837         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
6838
6839         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
6840         tmp &= ~0xFF;
6841         tmp |= 0x1C;
6842         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
6843
6844         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
6845         tmp &= ~0xFF;
6846         tmp |= 0x1C;
6847         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
6848
6849         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
6850         tmp &= ~(0xFF << 16);
6851         tmp |= (0x1C << 16);
6852         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
6853
6854         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
6855         tmp &= ~(0xFF << 16);
6856         tmp |= (0x1C << 16);
6857         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
6858
6859         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
6860         tmp |= (1 << 27);
6861         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
6862
6863         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
6864         tmp |= (1 << 27);
6865         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
6866
6867         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
6868         tmp &= ~(0xF << 28);
6869         tmp |= (4 << 28);
6870         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
6871
6872         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
6873         tmp &= ~(0xF << 28);
6874         tmp |= (4 << 28);
6875         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
6876 }
6877
6878 /* Implements 3 different sequences from BSpec chapter "Display iCLK
6879  * Programming" based on the parameters passed:
6880  * - Sequence to enable CLKOUT_DP
6881  * - Sequence to enable CLKOUT_DP without spread
6882  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
6883  */
6884 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
6885                                  bool with_fdi)
6886 {
6887         struct drm_i915_private *dev_priv = dev->dev_private;
6888         uint32_t reg, tmp;
6889
6890         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
6891                 with_spread = true;
6892         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
6893                  with_fdi, "LP PCH doesn't have FDI\n"))
6894                 with_fdi = false;
6895
6896         mutex_lock(&dev_priv->dpio_lock);
6897
6898         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6899         tmp &= ~SBI_SSCCTL_DISABLE;
6900         tmp |= SBI_SSCCTL_PATHALT;
6901         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6902
6903         udelay(24);
6904
6905         if (with_spread) {
6906                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6907                 tmp &= ~SBI_SSCCTL_PATHALT;
6908                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6909
6910                 if (with_fdi) {
6911                         lpt_reset_fdi_mphy(dev_priv);
6912                         lpt_program_fdi_mphy(dev_priv);
6913                 }
6914         }
6915
6916         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
6917                SBI_GEN0 : SBI_DBUFF0;
6918         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
6919         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
6920         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
6921
6922         mutex_unlock(&dev_priv->dpio_lock);
6923 }
6924
6925 /* Sequence to disable CLKOUT_DP */
6926 static void lpt_disable_clkout_dp(struct drm_device *dev)
6927 {
6928         struct drm_i915_private *dev_priv = dev->dev_private;
6929         uint32_t reg, tmp;
6930
6931         mutex_lock(&dev_priv->dpio_lock);
6932
6933         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
6934                SBI_GEN0 : SBI_DBUFF0;
6935         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
6936         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
6937         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
6938
6939         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
6940         if (!(tmp & SBI_SSCCTL_DISABLE)) {
6941                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
6942                         tmp |= SBI_SSCCTL_PATHALT;
6943                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6944                         udelay(32);
6945                 }
6946                 tmp |= SBI_SSCCTL_DISABLE;
6947                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
6948         }
6949
6950         mutex_unlock(&dev_priv->dpio_lock);
6951 }
6952
6953 static void lpt_init_pch_refclk(struct drm_device *dev)
6954 {
6955         struct intel_encoder *encoder;
6956         bool has_vga = false;
6957
6958         for_each_intel_encoder(dev, encoder) {
6959                 switch (encoder->type) {
6960                 case INTEL_OUTPUT_ANALOG:
6961                         has_vga = true;
6962                         break;
6963                 default:
6964                         break;
6965                 }
6966         }
6967
6968         if (has_vga)
6969                 lpt_enable_clkout_dp(dev, true, true);
6970         else
6971                 lpt_disable_clkout_dp(dev);
6972 }
6973
6974 /*
6975  * Initialize reference clocks when the driver loads
6976  */
6977 void intel_init_pch_refclk(struct drm_device *dev)
6978 {
6979         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
6980                 ironlake_init_pch_refclk(dev);
6981         else if (HAS_PCH_LPT(dev))
6982                 lpt_init_pch_refclk(dev);
6983 }
6984
6985 static int ironlake_get_refclk(struct drm_crtc *crtc)
6986 {
6987         struct drm_device *dev = crtc->dev;
6988         struct drm_i915_private *dev_priv = dev->dev_private;
6989         struct intel_encoder *encoder;
6990         int num_connectors = 0;
6991         bool is_lvds = false;
6992
6993         for_each_encoder_on_crtc(dev, crtc, encoder) {
6994                 switch (encoder->type) {
6995                 case INTEL_OUTPUT_LVDS:
6996                         is_lvds = true;
6997                         break;
6998                 default:
6999                         break;
7000                 }
7001                 num_connectors++;
7002         }
7003
7004         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7005                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
7006                               dev_priv->vbt.lvds_ssc_freq);
7007                 return dev_priv->vbt.lvds_ssc_freq;
7008         }
7009
7010         return 120000;
7011 }
7012
7013 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7014 {
7015         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
7016         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7017         int pipe = intel_crtc->pipe;
7018         uint32_t val;
7019
7020         val = 0;
7021
7022         switch (intel_crtc->config.pipe_bpp) {
7023         case 18:
7024                 val |= PIPECONF_6BPC;
7025                 break;
7026         case 24:
7027                 val |= PIPECONF_8BPC;
7028                 break;
7029         case 30:
7030                 val |= PIPECONF_10BPC;
7031                 break;
7032         case 36:
7033                 val |= PIPECONF_12BPC;
7034                 break;
7035         default:
7036                 /* Case prevented by intel_choose_pipe_bpp_dither. */
7037                 BUG();
7038         }
7039
7040         if (intel_crtc->config.dither)
7041                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7042
7043         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7044                 val |= PIPECONF_INTERLACED_ILK;
7045         else
7046                 val |= PIPECONF_PROGRESSIVE;
7047
7048         if (intel_crtc->config.limited_color_range)
7049                 val |= PIPECONF_COLOR_RANGE_SELECT;
7050
7051         I915_WRITE(PIPECONF(pipe), val);
7052         POSTING_READ(PIPECONF(pipe));
7053 }
7054
7055 /*
7056  * Set up the pipe CSC unit.
7057  *
7058  * Currently only full range RGB to limited range RGB conversion
7059  * is supported, but eventually this should handle various
7060  * RGB<->YCbCr scenarios as well.
7061  */
7062 static void intel_set_pipe_csc(struct drm_crtc *crtc)
7063 {
7064         struct drm_device *dev = crtc->dev;
7065         struct drm_i915_private *dev_priv = dev->dev_private;
7066         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7067         int pipe = intel_crtc->pipe;
7068         uint16_t coeff = 0x7800; /* 1.0 */
7069
7070         /*
7071          * TODO: Check what kind of values actually come out of the pipe
7072          * with these coeff/postoff values and adjust to get the best
7073          * accuracy. Perhaps we even need to take the bpc value into
7074          * consideration.
7075          */
7076
7077         if (intel_crtc->config.limited_color_range)
7078                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
7079
7080         /*
7081          * GY/GU and RY/RU should be the other way around according
7082          * to BSpec, but reality doesn't agree. Just set them up in
7083          * a way that results in the correct picture.
7084          */
7085         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
7086         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
7087
7088         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
7089         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
7090
7091         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
7092         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
7093
7094         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
7095         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
7096         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
7097
7098         if (INTEL_INFO(dev)->gen > 6) {
7099                 uint16_t postoff = 0;
7100
7101                 if (intel_crtc->config.limited_color_range)
7102                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
7103
7104                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
7105                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
7106                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
7107
7108                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
7109         } else {
7110                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
7111
7112                 if (intel_crtc->config.limited_color_range)
7113                         mode |= CSC_BLACK_SCREEN_OFFSET;
7114
7115                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
7116         }
7117 }
7118
7119 static void haswell_set_pipeconf(struct drm_crtc *crtc)
7120 {
7121         struct drm_device *dev = crtc->dev;
7122         struct drm_i915_private *dev_priv = dev->dev_private;
7123         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7124         enum pipe pipe = intel_crtc->pipe;
7125         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
7126         uint32_t val;
7127
7128         val = 0;
7129
7130         if (IS_HASWELL(dev) && intel_crtc->config.dither)
7131                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7132
7133         if (intel_crtc->config.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7134                 val |= PIPECONF_INTERLACED_ILK;
7135         else
7136                 val |= PIPECONF_PROGRESSIVE;
7137
7138         I915_WRITE(PIPECONF(cpu_transcoder), val);
7139         POSTING_READ(PIPECONF(cpu_transcoder));
7140
7141         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
7142         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
7143
7144         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
7145                 val = 0;
7146
7147                 switch (intel_crtc->config.pipe_bpp) {
7148                 case 18:
7149                         val |= PIPEMISC_DITHER_6_BPC;
7150                         break;
7151                 case 24:
7152                         val |= PIPEMISC_DITHER_8_BPC;
7153                         break;
7154                 case 30:
7155                         val |= PIPEMISC_DITHER_10_BPC;
7156                         break;
7157                 case 36:
7158                         val |= PIPEMISC_DITHER_12_BPC;
7159                         break;
7160                 default:
7161                         /* Case prevented by pipe_config_set_bpp. */
7162                         BUG();
7163                 }
7164
7165                 if (intel_crtc->config.dither)
7166                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
7167
7168                 I915_WRITE(PIPEMISC(pipe), val);
7169         }
7170 }
7171
7172 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
7173                                     intel_clock_t *clock,
7174                                     bool *has_reduced_clock,
7175                                     intel_clock_t *reduced_clock)
7176 {
7177         struct drm_device *dev = crtc->dev;
7178         struct drm_i915_private *dev_priv = dev->dev_private;
7179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7180         int refclk;
7181         const intel_limit_t *limit;
7182         bool ret, is_lvds = false;
7183
7184         is_lvds = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_LVDS);
7185
7186         refclk = ironlake_get_refclk(crtc);
7187
7188         /*
7189          * Returns a set of divisors for the desired target clock with the given
7190          * refclk, or FALSE.  The returned values represent the clock equation:
7191          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
7192          */
7193         limit = intel_limit(intel_crtc, refclk);
7194         ret = dev_priv->display.find_dpll(limit, intel_crtc,
7195                                           intel_crtc->config.port_clock,
7196                                           refclk, NULL, clock);
7197         if (!ret)
7198                 return false;
7199
7200         if (is_lvds && dev_priv->lvds_downclock_avail) {
7201                 /*
7202                  * Ensure we match the reduced clock's P to the target clock.
7203                  * If the clocks don't match, we can't switch the display clock
7204                  * by using the FP0/FP1. In such case we will disable the LVDS
7205                  * downclock feature.
7206                 */
7207                 *has_reduced_clock =
7208                         dev_priv->display.find_dpll(limit, intel_crtc,
7209                                                     dev_priv->lvds_downclock,
7210                                                     refclk, clock,
7211                                                     reduced_clock);
7212         }
7213
7214         return true;
7215 }
7216
7217 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
7218 {
7219         /*
7220          * Account for spread spectrum to avoid
7221          * oversubscribing the link. Max center spread
7222          * is 2.5%; use 5% for safety's sake.
7223          */
7224         u32 bps = target_clock * bpp * 21 / 20;
7225         return DIV_ROUND_UP(bps, link_bw * 8);
7226 }
7227
7228 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
7229 {
7230         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
7231 }
7232
7233 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
7234                                       u32 *fp,
7235                                       intel_clock_t *reduced_clock, u32 *fp2)
7236 {
7237         struct drm_crtc *crtc = &intel_crtc->base;
7238         struct drm_device *dev = crtc->dev;
7239         struct drm_i915_private *dev_priv = dev->dev_private;
7240         struct intel_encoder *intel_encoder;
7241         uint32_t dpll;
7242         int factor, num_connectors = 0;
7243         bool is_lvds = false, is_sdvo = false;
7244
7245         for_each_encoder_on_crtc(dev, crtc, intel_encoder) {
7246                 switch (intel_encoder->type) {
7247                 case INTEL_OUTPUT_LVDS:
7248                         is_lvds = true;
7249                         break;
7250                 case INTEL_OUTPUT_SDVO:
7251                 case INTEL_OUTPUT_HDMI:
7252                         is_sdvo = true;
7253                         break;
7254                 default:
7255                         break;
7256                 }
7257
7258                 num_connectors++;
7259         }
7260
7261         /* Enable autotuning of the PLL clock (if permissible) */
7262         factor = 21;
7263         if (is_lvds) {
7264                 if ((intel_panel_use_ssc(dev_priv) &&
7265                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
7266                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
7267                         factor = 25;
7268         } else if (intel_crtc->config.sdvo_tv_clock)
7269                 factor = 20;
7270
7271         if (ironlake_needs_fb_cb_tune(&intel_crtc->config.dpll, factor))
7272                 *fp |= FP_CB_TUNE;
7273
7274         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
7275                 *fp2 |= FP_CB_TUNE;
7276
7277         dpll = 0;
7278
7279         if (is_lvds)
7280                 dpll |= DPLLB_MODE_LVDS;
7281         else
7282                 dpll |= DPLLB_MODE_DAC_SERIAL;
7283
7284         dpll |= (intel_crtc->config.pixel_multiplier - 1)
7285                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
7286
7287         if (is_sdvo)
7288                 dpll |= DPLL_SDVO_HIGH_SPEED;
7289         if (intel_crtc->config.has_dp_encoder)
7290                 dpll |= DPLL_SDVO_HIGH_SPEED;
7291
7292         /* compute bitmask from p1 value */
7293         dpll |= (1 << (intel_crtc->config.dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7294         /* also FPA1 */
7295         dpll |= (1 << (intel_crtc->config.dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7296
7297         switch (intel_crtc->config.dpll.p2) {
7298         case 5:
7299                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7300                 break;
7301         case 7:
7302                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7303                 break;
7304         case 10:
7305                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7306                 break;
7307         case 14:
7308                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7309                 break;
7310         }
7311
7312         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7313                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7314         else
7315                 dpll |= PLL_REF_INPUT_DREFCLK;
7316
7317         return dpll | DPLL_VCO_ENABLE;
7318 }
7319
7320 static int ironlake_crtc_mode_set(struct intel_crtc *crtc,
7321                                   int x, int y,
7322                                   struct drm_framebuffer *fb)
7323 {
7324         struct drm_device *dev = crtc->base.dev;
7325         intel_clock_t clock, reduced_clock;
7326         u32 dpll = 0, fp = 0, fp2 = 0;
7327         bool ok, has_reduced_clock = false;
7328         bool is_lvds = false;
7329         struct intel_shared_dpll *pll;
7330
7331         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
7332
7333         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
7334              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
7335
7336         ok = ironlake_compute_clocks(&crtc->base, &clock,
7337                                      &has_reduced_clock, &reduced_clock);
7338         if (!ok && !crtc->config.clock_set) {
7339                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7340                 return -EINVAL;
7341         }
7342         /* Compat-code for transition, will disappear. */
7343         if (!crtc->config.clock_set) {
7344                 crtc->config.dpll.n = clock.n;
7345                 crtc->config.dpll.m1 = clock.m1;
7346                 crtc->config.dpll.m2 = clock.m2;
7347                 crtc->config.dpll.p1 = clock.p1;
7348                 crtc->config.dpll.p2 = clock.p2;
7349         }
7350
7351         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
7352         if (crtc->config.has_pch_encoder) {
7353                 fp = i9xx_dpll_compute_fp(&crtc->config.dpll);
7354                 if (has_reduced_clock)
7355                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
7356
7357                 dpll = ironlake_compute_dpll(crtc,
7358                                              &fp, &reduced_clock,
7359                                              has_reduced_clock ? &fp2 : NULL);
7360
7361                 crtc->config.dpll_hw_state.dpll = dpll;
7362                 crtc->config.dpll_hw_state.fp0 = fp;
7363                 if (has_reduced_clock)
7364                         crtc->config.dpll_hw_state.fp1 = fp2;
7365                 else
7366                         crtc->config.dpll_hw_state.fp1 = fp;
7367
7368                 pll = intel_get_shared_dpll(crtc);
7369                 if (pll == NULL) {
7370                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
7371                                          pipe_name(crtc->pipe));
7372                         return -EINVAL;
7373                 }
7374         } else
7375                 intel_put_shared_dpll(crtc);
7376
7377         if (is_lvds && has_reduced_clock && i915.powersave)
7378                 crtc->lowfreq_avail = true;
7379         else
7380                 crtc->lowfreq_avail = false;
7381
7382         return 0;
7383 }
7384
7385 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
7386                                          struct intel_link_m_n *m_n)
7387 {
7388         struct drm_device *dev = crtc->base.dev;
7389         struct drm_i915_private *dev_priv = dev->dev_private;
7390         enum pipe pipe = crtc->pipe;
7391
7392         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
7393         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
7394         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
7395                 & ~TU_SIZE_MASK;
7396         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
7397         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
7398                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7399 }
7400
7401 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
7402                                          enum transcoder transcoder,
7403                                          struct intel_link_m_n *m_n,
7404                                          struct intel_link_m_n *m2_n2)
7405 {
7406         struct drm_device *dev = crtc->base.dev;
7407         struct drm_i915_private *dev_priv = dev->dev_private;
7408         enum pipe pipe = crtc->pipe;
7409
7410         if (INTEL_INFO(dev)->gen >= 5) {
7411                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
7412                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
7413                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
7414                         & ~TU_SIZE_MASK;
7415                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
7416                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
7417                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7418                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
7419                  * gen < 8) and if DRRS is supported (to make sure the
7420                  * registers are not unnecessarily read).
7421                  */
7422                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
7423                         crtc->config.has_drrs) {
7424                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
7425                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
7426                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
7427                                         & ~TU_SIZE_MASK;
7428                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
7429                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
7430                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7431                 }
7432         } else {
7433                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
7434                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
7435                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
7436                         & ~TU_SIZE_MASK;
7437                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
7438                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
7439                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7440         }
7441 }
7442
7443 void intel_dp_get_m_n(struct intel_crtc *crtc,
7444                       struct intel_crtc_config *pipe_config)
7445 {
7446         if (crtc->config.has_pch_encoder)
7447                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
7448         else
7449                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7450                                              &pipe_config->dp_m_n,
7451                                              &pipe_config->dp_m2_n2);
7452 }
7453
7454 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
7455                                         struct intel_crtc_config *pipe_config)
7456 {
7457         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7458                                      &pipe_config->fdi_m_n, NULL);
7459 }
7460
7461 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
7462                                      struct intel_crtc_config *pipe_config)
7463 {
7464         struct drm_device *dev = crtc->base.dev;
7465         struct drm_i915_private *dev_priv = dev->dev_private;
7466         uint32_t tmp;
7467
7468         tmp = I915_READ(PF_CTL(crtc->pipe));
7469
7470         if (tmp & PF_ENABLE) {
7471                 pipe_config->pch_pfit.enabled = true;
7472                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
7473                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
7474
7475                 /* We currently do not free assignements of panel fitters on
7476                  * ivb/hsw (since we don't use the higher upscaling modes which
7477                  * differentiates them) so just WARN about this case for now. */
7478                 if (IS_GEN7(dev)) {
7479                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
7480                                 PF_PIPE_SEL_IVB(crtc->pipe));
7481                 }
7482         }
7483 }
7484
7485 static void ironlake_get_plane_config(struct intel_crtc *crtc,
7486                                       struct intel_plane_config *plane_config)
7487 {
7488         struct drm_device *dev = crtc->base.dev;
7489         struct drm_i915_private *dev_priv = dev->dev_private;
7490         u32 val, base, offset;
7491         int pipe = crtc->pipe, plane = crtc->plane;
7492         int fourcc, pixel_format;
7493         int aligned_height;
7494
7495         crtc->base.primary->fb = kzalloc(sizeof(struct intel_framebuffer), GFP_KERNEL);
7496         if (!crtc->base.primary->fb) {
7497                 DRM_DEBUG_KMS("failed to alloc fb\n");
7498                 return;
7499         }
7500
7501         val = I915_READ(DSPCNTR(plane));
7502
7503         if (INTEL_INFO(dev)->gen >= 4)
7504                 if (val & DISPPLANE_TILED)
7505                         plane_config->tiled = true;
7506
7507         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7508         fourcc = intel_format_to_fourcc(pixel_format);
7509         crtc->base.primary->fb->pixel_format = fourcc;
7510         crtc->base.primary->fb->bits_per_pixel =
7511                 drm_format_plane_cpp(fourcc, 0) * 8;
7512
7513         base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7514         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7515                 offset = I915_READ(DSPOFFSET(plane));
7516         } else {
7517                 if (plane_config->tiled)
7518                         offset = I915_READ(DSPTILEOFF(plane));
7519                 else
7520                         offset = I915_READ(DSPLINOFF(plane));
7521         }
7522         plane_config->base = base;
7523
7524         val = I915_READ(PIPESRC(pipe));
7525         crtc->base.primary->fb->width = ((val >> 16) & 0xfff) + 1;
7526         crtc->base.primary->fb->height = ((val >> 0) & 0xfff) + 1;
7527
7528         val = I915_READ(DSPSTRIDE(pipe));
7529         crtc->base.primary->fb->pitches[0] = val & 0xffffffc0;
7530
7531         aligned_height = intel_align_height(dev, crtc->base.primary->fb->height,
7532                                             plane_config->tiled);
7533
7534         plane_config->size = PAGE_ALIGN(crtc->base.primary->fb->pitches[0] *
7535                                         aligned_height);
7536
7537         DRM_DEBUG_KMS("pipe/plane %d/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7538                       pipe, plane, crtc->base.primary->fb->width,
7539                       crtc->base.primary->fb->height,
7540                       crtc->base.primary->fb->bits_per_pixel, base,
7541                       crtc->base.primary->fb->pitches[0],
7542                       plane_config->size);
7543 }
7544
7545 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
7546                                      struct intel_crtc_config *pipe_config)
7547 {
7548         struct drm_device *dev = crtc->base.dev;
7549         struct drm_i915_private *dev_priv = dev->dev_private;
7550         uint32_t tmp;
7551
7552         if (!intel_display_power_is_enabled(dev_priv,
7553                                             POWER_DOMAIN_PIPE(crtc->pipe)))
7554                 return false;
7555
7556         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7557         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7558
7559         tmp = I915_READ(PIPECONF(crtc->pipe));
7560         if (!(tmp & PIPECONF_ENABLE))
7561                 return false;
7562
7563         switch (tmp & PIPECONF_BPC_MASK) {
7564         case PIPECONF_6BPC:
7565                 pipe_config->pipe_bpp = 18;
7566                 break;
7567         case PIPECONF_8BPC:
7568                 pipe_config->pipe_bpp = 24;
7569                 break;
7570         case PIPECONF_10BPC:
7571                 pipe_config->pipe_bpp = 30;
7572                 break;
7573         case PIPECONF_12BPC:
7574                 pipe_config->pipe_bpp = 36;
7575                 break;
7576         default:
7577                 break;
7578         }
7579
7580         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
7581                 pipe_config->limited_color_range = true;
7582
7583         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
7584                 struct intel_shared_dpll *pll;
7585
7586                 pipe_config->has_pch_encoder = true;
7587
7588                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
7589                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7590                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7591
7592                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7593
7594                 if (HAS_PCH_IBX(dev_priv->dev)) {
7595                         pipe_config->shared_dpll =
7596                                 (enum intel_dpll_id) crtc->pipe;
7597                 } else {
7598                         tmp = I915_READ(PCH_DPLL_SEL);
7599                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
7600                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
7601                         else
7602                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
7603                 }
7604
7605                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
7606
7607                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
7608                                            &pipe_config->dpll_hw_state));
7609
7610                 tmp = pipe_config->dpll_hw_state.dpll;
7611                 pipe_config->pixel_multiplier =
7612                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
7613                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
7614
7615                 ironlake_pch_clock_get(crtc, pipe_config);
7616         } else {
7617                 pipe_config->pixel_multiplier = 1;
7618         }
7619
7620         intel_get_pipe_timings(crtc, pipe_config);
7621
7622         ironlake_get_pfit_config(crtc, pipe_config);
7623
7624         return true;
7625 }
7626
7627 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
7628 {
7629         struct drm_device *dev = dev_priv->dev;
7630         struct intel_crtc *crtc;
7631
7632         for_each_intel_crtc(dev, crtc)
7633                 WARN(crtc->active, "CRTC for pipe %c enabled\n",
7634                      pipe_name(crtc->pipe));
7635
7636         WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
7637         WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
7638         WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
7639         WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
7640         WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
7641         WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
7642              "CPU PWM1 enabled\n");
7643         if (IS_HASWELL(dev))
7644                 WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
7645                      "CPU PWM2 enabled\n");
7646         WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
7647              "PCH PWM1 enabled\n");
7648         WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
7649              "Utility pin enabled\n");
7650         WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
7651
7652         /*
7653          * In theory we can still leave IRQs enabled, as long as only the HPD
7654          * interrupts remain enabled. We used to check for that, but since it's
7655          * gen-specific and since we only disable LCPLL after we fully disable
7656          * the interrupts, the check below should be enough.
7657          */
7658         WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
7659 }
7660
7661 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
7662 {
7663         struct drm_device *dev = dev_priv->dev;
7664
7665         if (IS_HASWELL(dev))
7666                 return I915_READ(D_COMP_HSW);
7667         else
7668                 return I915_READ(D_COMP_BDW);
7669 }
7670
7671 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
7672 {
7673         struct drm_device *dev = dev_priv->dev;
7674
7675         if (IS_HASWELL(dev)) {
7676                 mutex_lock(&dev_priv->rps.hw_lock);
7677                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
7678                                             val))
7679                         DRM_ERROR("Failed to write to D_COMP\n");
7680                 mutex_unlock(&dev_priv->rps.hw_lock);
7681         } else {
7682                 I915_WRITE(D_COMP_BDW, val);
7683                 POSTING_READ(D_COMP_BDW);
7684         }
7685 }
7686
7687 /*
7688  * This function implements pieces of two sequences from BSpec:
7689  * - Sequence for display software to disable LCPLL
7690  * - Sequence for display software to allow package C8+
7691  * The steps implemented here are just the steps that actually touch the LCPLL
7692  * register. Callers should take care of disabling all the display engine
7693  * functions, doing the mode unset, fixing interrupts, etc.
7694  */
7695 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
7696                               bool switch_to_fclk, bool allow_power_down)
7697 {
7698         uint32_t val;
7699
7700         assert_can_disable_lcpll(dev_priv);
7701
7702         val = I915_READ(LCPLL_CTL);
7703
7704         if (switch_to_fclk) {
7705                 val |= LCPLL_CD_SOURCE_FCLK;
7706                 I915_WRITE(LCPLL_CTL, val);
7707
7708                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
7709                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
7710                         DRM_ERROR("Switching to FCLK failed\n");
7711
7712                 val = I915_READ(LCPLL_CTL);
7713         }
7714
7715         val |= LCPLL_PLL_DISABLE;
7716         I915_WRITE(LCPLL_CTL, val);
7717         POSTING_READ(LCPLL_CTL);
7718
7719         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
7720                 DRM_ERROR("LCPLL still locked\n");
7721
7722         val = hsw_read_dcomp(dev_priv);
7723         val |= D_COMP_COMP_DISABLE;
7724         hsw_write_dcomp(dev_priv, val);
7725         ndelay(100);
7726
7727         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
7728                      1))
7729                 DRM_ERROR("D_COMP RCOMP still in progress\n");
7730
7731         if (allow_power_down) {
7732                 val = I915_READ(LCPLL_CTL);
7733                 val |= LCPLL_POWER_DOWN_ALLOW;
7734                 I915_WRITE(LCPLL_CTL, val);
7735                 POSTING_READ(LCPLL_CTL);
7736         }
7737 }
7738
7739 /*
7740  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
7741  * source.
7742  */
7743 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
7744 {
7745         uint32_t val;
7746
7747         val = I915_READ(LCPLL_CTL);
7748
7749         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
7750                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
7751                 return;
7752
7753         /*
7754          * Make sure we're not on PC8 state before disabling PC8, otherwise
7755          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
7756          *
7757          * The other problem is that hsw_restore_lcpll() is called as part of
7758          * the runtime PM resume sequence, so we can't just call
7759          * gen6_gt_force_wake_get() because that function calls
7760          * intel_runtime_pm_get(), and we can't change the runtime PM refcount
7761          * while we are on the resume sequence. So to solve this problem we have
7762          * to call special forcewake code that doesn't touch runtime PM and
7763          * doesn't enable the forcewake delayed work.
7764          */
7765         spin_lock_irq(&dev_priv->uncore.lock);
7766         if (dev_priv->uncore.forcewake_count++ == 0)
7767                 dev_priv->uncore.funcs.force_wake_get(dev_priv, FORCEWAKE_ALL);
7768         spin_unlock_irq(&dev_priv->uncore.lock);
7769
7770         if (val & LCPLL_POWER_DOWN_ALLOW) {
7771                 val &= ~LCPLL_POWER_DOWN_ALLOW;
7772                 I915_WRITE(LCPLL_CTL, val);
7773                 POSTING_READ(LCPLL_CTL);
7774         }
7775
7776         val = hsw_read_dcomp(dev_priv);
7777         val |= D_COMP_COMP_FORCE;
7778         val &= ~D_COMP_COMP_DISABLE;
7779         hsw_write_dcomp(dev_priv, val);
7780
7781         val = I915_READ(LCPLL_CTL);
7782         val &= ~LCPLL_PLL_DISABLE;
7783         I915_WRITE(LCPLL_CTL, val);
7784
7785         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
7786                 DRM_ERROR("LCPLL not locked yet\n");
7787
7788         if (val & LCPLL_CD_SOURCE_FCLK) {
7789                 val = I915_READ(LCPLL_CTL);
7790                 val &= ~LCPLL_CD_SOURCE_FCLK;
7791                 I915_WRITE(LCPLL_CTL, val);
7792
7793                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
7794                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
7795                         DRM_ERROR("Switching back to LCPLL failed\n");
7796         }
7797
7798         /* See the big comment above. */
7799         spin_lock_irq(&dev_priv->uncore.lock);
7800         if (--dev_priv->uncore.forcewake_count == 0)
7801                 dev_priv->uncore.funcs.force_wake_put(dev_priv, FORCEWAKE_ALL);
7802         spin_unlock_irq(&dev_priv->uncore.lock);
7803 }
7804
7805 /*
7806  * Package states C8 and deeper are really deep PC states that can only be
7807  * reached when all the devices on the system allow it, so even if the graphics
7808  * device allows PC8+, it doesn't mean the system will actually get to these
7809  * states. Our driver only allows PC8+ when going into runtime PM.
7810  *
7811  * The requirements for PC8+ are that all the outputs are disabled, the power
7812  * well is disabled and most interrupts are disabled, and these are also
7813  * requirements for runtime PM. When these conditions are met, we manually do
7814  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
7815  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
7816  * hang the machine.
7817  *
7818  * When we really reach PC8 or deeper states (not just when we allow it) we lose
7819  * the state of some registers, so when we come back from PC8+ we need to
7820  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
7821  * need to take care of the registers kept by RC6. Notice that this happens even
7822  * if we don't put the device in PCI D3 state (which is what currently happens
7823  * because of the runtime PM support).
7824  *
7825  * For more, read "Display Sequences for Package C8" on the hardware
7826  * documentation.
7827  */
7828 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
7829 {
7830         struct drm_device *dev = dev_priv->dev;
7831         uint32_t val;
7832
7833         DRM_DEBUG_KMS("Enabling package C8+\n");
7834
7835         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
7836                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
7837                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
7838                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
7839         }
7840
7841         lpt_disable_clkout_dp(dev);
7842         hsw_disable_lcpll(dev_priv, true, true);
7843 }
7844
7845 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
7846 {
7847         struct drm_device *dev = dev_priv->dev;
7848         uint32_t val;
7849
7850         DRM_DEBUG_KMS("Disabling package C8+\n");
7851
7852         hsw_restore_lcpll(dev_priv);
7853         lpt_init_pch_refclk(dev);
7854
7855         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
7856                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
7857                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
7858                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
7859         }
7860
7861         intel_prepare_ddi(dev);
7862 }
7863
7864 static void snb_modeset_global_resources(struct drm_device *dev)
7865 {
7866         modeset_update_crtc_power_domains(dev);
7867 }
7868
7869 static void haswell_modeset_global_resources(struct drm_device *dev)
7870 {
7871         modeset_update_crtc_power_domains(dev);
7872 }
7873
7874 static int haswell_crtc_mode_set(struct intel_crtc *crtc,
7875                                  int x, int y,
7876                                  struct drm_framebuffer *fb)
7877 {
7878         if (!intel_ddi_pll_select(crtc))
7879                 return -EINVAL;
7880
7881         crtc->lowfreq_avail = false;
7882
7883         return 0;
7884 }
7885
7886 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
7887                                 enum port port,
7888                                 struct intel_crtc_config *pipe_config)
7889 {
7890         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
7891
7892         switch (pipe_config->ddi_pll_sel) {
7893         case PORT_CLK_SEL_WRPLL1:
7894                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
7895                 break;
7896         case PORT_CLK_SEL_WRPLL2:
7897                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
7898                 break;
7899         }
7900 }
7901
7902 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
7903                                        struct intel_crtc_config *pipe_config)
7904 {
7905         struct drm_device *dev = crtc->base.dev;
7906         struct drm_i915_private *dev_priv = dev->dev_private;
7907         struct intel_shared_dpll *pll;
7908         enum port port;
7909         uint32_t tmp;
7910
7911         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
7912
7913         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
7914
7915         haswell_get_ddi_pll(dev_priv, port, pipe_config);
7916
7917         if (pipe_config->shared_dpll >= 0) {
7918                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
7919
7920                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
7921                                            &pipe_config->dpll_hw_state));
7922         }
7923
7924         /*
7925          * Haswell has only FDI/PCH transcoder A. It is which is connected to
7926          * DDI E. So just check whether this pipe is wired to DDI E and whether
7927          * the PCH transcoder is on.
7928          */
7929         if (INTEL_INFO(dev)->gen < 9 &&
7930             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
7931                 pipe_config->has_pch_encoder = true;
7932
7933                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
7934                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7935                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7936
7937                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7938         }
7939 }
7940
7941 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
7942                                     struct intel_crtc_config *pipe_config)
7943 {
7944         struct drm_device *dev = crtc->base.dev;
7945         struct drm_i915_private *dev_priv = dev->dev_private;
7946         enum intel_display_power_domain pfit_domain;
7947         uint32_t tmp;
7948
7949         if (!intel_display_power_is_enabled(dev_priv,
7950                                          POWER_DOMAIN_PIPE(crtc->pipe)))
7951                 return false;
7952
7953         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7954         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7955
7956         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
7957         if (tmp & TRANS_DDI_FUNC_ENABLE) {
7958                 enum pipe trans_edp_pipe;
7959                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
7960                 default:
7961                         WARN(1, "unknown pipe linked to edp transcoder\n");
7962                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
7963                 case TRANS_DDI_EDP_INPUT_A_ON:
7964                         trans_edp_pipe = PIPE_A;
7965                         break;
7966                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
7967                         trans_edp_pipe = PIPE_B;
7968                         break;
7969                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
7970                         trans_edp_pipe = PIPE_C;
7971                         break;
7972                 }
7973
7974                 if (trans_edp_pipe == crtc->pipe)
7975                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
7976         }
7977
7978         if (!intel_display_power_is_enabled(dev_priv,
7979                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
7980                 return false;
7981
7982         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
7983         if (!(tmp & PIPECONF_ENABLE))
7984                 return false;
7985
7986         haswell_get_ddi_port_state(crtc, pipe_config);
7987
7988         intel_get_pipe_timings(crtc, pipe_config);
7989
7990         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
7991         if (intel_display_power_is_enabled(dev_priv, pfit_domain))
7992                 ironlake_get_pfit_config(crtc, pipe_config);
7993
7994         if (IS_HASWELL(dev))
7995                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
7996                         (I915_READ(IPS_CTL) & IPS_ENABLE);
7997
7998         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
7999                 pipe_config->pixel_multiplier =
8000                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
8001         } else {
8002                 pipe_config->pixel_multiplier = 1;
8003         }
8004
8005         return true;
8006 }
8007
8008 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
8009 {
8010         struct drm_device *dev = crtc->dev;
8011         struct drm_i915_private *dev_priv = dev->dev_private;
8012         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8013         uint32_t cntl = 0, size = 0;
8014
8015         if (base) {
8016                 unsigned int width = intel_crtc->cursor_width;
8017                 unsigned int height = intel_crtc->cursor_height;
8018                 unsigned int stride = roundup_pow_of_two(width) * 4;
8019
8020                 switch (stride) {
8021                 default:
8022                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
8023                                   width, stride);
8024                         stride = 256;
8025                         /* fallthrough */
8026                 case 256:
8027                 case 512:
8028                 case 1024:
8029                 case 2048:
8030                         break;
8031                 }
8032
8033                 cntl |= CURSOR_ENABLE |
8034                         CURSOR_GAMMA_ENABLE |
8035                         CURSOR_FORMAT_ARGB |
8036                         CURSOR_STRIDE(stride);
8037
8038                 size = (height << 12) | width;
8039         }
8040
8041         if (intel_crtc->cursor_cntl != 0 &&
8042             (intel_crtc->cursor_base != base ||
8043              intel_crtc->cursor_size != size ||
8044              intel_crtc->cursor_cntl != cntl)) {
8045                 /* On these chipsets we can only modify the base/size/stride
8046                  * whilst the cursor is disabled.
8047                  */
8048                 I915_WRITE(_CURACNTR, 0);
8049                 POSTING_READ(_CURACNTR);
8050                 intel_crtc->cursor_cntl = 0;
8051         }
8052
8053         if (intel_crtc->cursor_base != base) {
8054                 I915_WRITE(_CURABASE, base);
8055                 intel_crtc->cursor_base = base;
8056         }
8057
8058         if (intel_crtc->cursor_size != size) {
8059                 I915_WRITE(CURSIZE, size);
8060                 intel_crtc->cursor_size = size;
8061         }
8062
8063         if (intel_crtc->cursor_cntl != cntl) {
8064                 I915_WRITE(_CURACNTR, cntl);
8065                 POSTING_READ(_CURACNTR);
8066                 intel_crtc->cursor_cntl = cntl;
8067         }
8068 }
8069
8070 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
8071 {
8072         struct drm_device *dev = crtc->dev;
8073         struct drm_i915_private *dev_priv = dev->dev_private;
8074         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8075         int pipe = intel_crtc->pipe;
8076         uint32_t cntl;
8077
8078         cntl = 0;
8079         if (base) {
8080                 cntl = MCURSOR_GAMMA_ENABLE;
8081                 switch (intel_crtc->cursor_width) {
8082                         case 64:
8083                                 cntl |= CURSOR_MODE_64_ARGB_AX;
8084                                 break;
8085                         case 128:
8086                                 cntl |= CURSOR_MODE_128_ARGB_AX;
8087                                 break;
8088                         case 256:
8089                                 cntl |= CURSOR_MODE_256_ARGB_AX;
8090                                 break;
8091                         default:
8092                                 WARN_ON(1);
8093                                 return;
8094                 }
8095                 cntl |= pipe << 28; /* Connect to correct pipe */
8096
8097                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
8098                         cntl |= CURSOR_PIPE_CSC_ENABLE;
8099         }
8100
8101         if (to_intel_plane(crtc->cursor)->rotation == BIT(DRM_ROTATE_180))
8102                 cntl |= CURSOR_ROTATE_180;
8103
8104         if (intel_crtc->cursor_cntl != cntl) {
8105                 I915_WRITE(CURCNTR(pipe), cntl);
8106                 POSTING_READ(CURCNTR(pipe));
8107                 intel_crtc->cursor_cntl = cntl;
8108         }
8109
8110         /* and commit changes on next vblank */
8111         I915_WRITE(CURBASE(pipe), base);
8112         POSTING_READ(CURBASE(pipe));
8113
8114         intel_crtc->cursor_base = base;
8115 }
8116
8117 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
8118 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
8119                                      bool on)
8120 {
8121         struct drm_device *dev = crtc->dev;
8122         struct drm_i915_private *dev_priv = dev->dev_private;
8123         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8124         int pipe = intel_crtc->pipe;
8125         int x = crtc->cursor_x;
8126         int y = crtc->cursor_y;
8127         u32 base = 0, pos = 0;
8128
8129         if (on)
8130                 base = intel_crtc->cursor_addr;
8131
8132         if (x >= intel_crtc->config.pipe_src_w)
8133                 base = 0;
8134
8135         if (y >= intel_crtc->config.pipe_src_h)
8136                 base = 0;
8137
8138         if (x < 0) {
8139                 if (x + intel_crtc->cursor_width <= 0)
8140                         base = 0;
8141
8142                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
8143                 x = -x;
8144         }
8145         pos |= x << CURSOR_X_SHIFT;
8146
8147         if (y < 0) {
8148                 if (y + intel_crtc->cursor_height <= 0)
8149                         base = 0;
8150
8151                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
8152                 y = -y;
8153         }
8154         pos |= y << CURSOR_Y_SHIFT;
8155
8156         if (base == 0 && intel_crtc->cursor_base == 0)
8157                 return;
8158
8159         I915_WRITE(CURPOS(pipe), pos);
8160
8161         /* ILK+ do this automagically */
8162         if (HAS_GMCH_DISPLAY(dev) &&
8163                 to_intel_plane(crtc->cursor)->rotation == BIT(DRM_ROTATE_180)) {
8164                 base += (intel_crtc->cursor_height *
8165                         intel_crtc->cursor_width - 1) * 4;
8166         }
8167
8168         if (IS_845G(dev) || IS_I865G(dev))
8169                 i845_update_cursor(crtc, base);
8170         else
8171                 i9xx_update_cursor(crtc, base);
8172 }
8173
8174 static bool cursor_size_ok(struct drm_device *dev,
8175                            uint32_t width, uint32_t height)
8176 {
8177         if (width == 0 || height == 0)
8178                 return false;
8179
8180         /*
8181          * 845g/865g are special in that they are only limited by
8182          * the width of their cursors, the height is arbitrary up to
8183          * the precision of the register. Everything else requires
8184          * square cursors, limited to a few power-of-two sizes.
8185          */
8186         if (IS_845G(dev) || IS_I865G(dev)) {
8187                 if ((width & 63) != 0)
8188                         return false;
8189
8190                 if (width > (IS_845G(dev) ? 64 : 512))
8191                         return false;
8192
8193                 if (height > 1023)
8194                         return false;
8195         } else {
8196                 switch (width | height) {
8197                 case 256:
8198                 case 128:
8199                         if (IS_GEN2(dev))
8200                                 return false;
8201                 case 64:
8202                         break;
8203                 default:
8204                         return false;
8205                 }
8206         }
8207
8208         return true;
8209 }
8210
8211 static int intel_crtc_cursor_set_obj(struct drm_crtc *crtc,
8212                                      struct drm_i915_gem_object *obj,
8213                                      uint32_t width, uint32_t height)
8214 {
8215         struct drm_device *dev = crtc->dev;
8216         struct drm_i915_private *dev_priv = dev->dev_private;
8217         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8218         enum pipe pipe = intel_crtc->pipe;
8219         unsigned old_width;
8220         uint32_t addr;
8221         int ret;
8222
8223         /* if we want to turn off the cursor ignore width and height */
8224         if (!obj) {
8225                 DRM_DEBUG_KMS("cursor off\n");
8226                 addr = 0;
8227                 mutex_lock(&dev->struct_mutex);
8228                 goto finish;
8229         }
8230
8231         /* we only need to pin inside GTT if cursor is non-phy */
8232         mutex_lock(&dev->struct_mutex);
8233         if (!INTEL_INFO(dev)->cursor_needs_physical) {
8234                 unsigned alignment;
8235
8236                 /*
8237                  * Global gtt pte registers are special registers which actually
8238                  * forward writes to a chunk of system memory. Which means that
8239                  * there is no risk that the register values disappear as soon
8240                  * as we call intel_runtime_pm_put(), so it is correct to wrap
8241                  * only the pin/unpin/fence and not more.
8242                  */
8243                 intel_runtime_pm_get(dev_priv);
8244
8245                 /* Note that the w/a also requires 2 PTE of padding following
8246                  * the bo. We currently fill all unused PTE with the shadow
8247                  * page and so we should always have valid PTE following the
8248                  * cursor preventing the VT-d warning.
8249                  */
8250                 alignment = 0;
8251                 if (need_vtd_wa(dev))
8252                         alignment = 64*1024;
8253
8254                 ret = i915_gem_object_pin_to_display_plane(obj, alignment, NULL);
8255                 if (ret) {
8256                         DRM_DEBUG_KMS("failed to move cursor bo into the GTT\n");
8257                         intel_runtime_pm_put(dev_priv);
8258                         goto fail_locked;
8259                 }
8260
8261                 ret = i915_gem_object_put_fence(obj);
8262                 if (ret) {
8263                         DRM_DEBUG_KMS("failed to release fence for cursor");
8264                         intel_runtime_pm_put(dev_priv);
8265                         goto fail_unpin;
8266                 }
8267
8268                 addr = i915_gem_obj_ggtt_offset(obj);
8269
8270                 intel_runtime_pm_put(dev_priv);
8271         } else {
8272                 int align = IS_I830(dev) ? 16 * 1024 : 256;
8273                 ret = i915_gem_object_attach_phys(obj, align);
8274                 if (ret) {
8275                         DRM_DEBUG_KMS("failed to attach phys object\n");
8276                         goto fail_locked;
8277                 }
8278                 addr = obj->phys_handle->busaddr;
8279         }
8280
8281  finish:
8282         if (intel_crtc->cursor_bo) {
8283                 if (!INTEL_INFO(dev)->cursor_needs_physical)
8284                         i915_gem_object_unpin_from_display_plane(intel_crtc->cursor_bo);
8285         }
8286
8287         i915_gem_track_fb(intel_crtc->cursor_bo, obj,
8288                           INTEL_FRONTBUFFER_CURSOR(pipe));
8289         mutex_unlock(&dev->struct_mutex);
8290
8291         old_width = intel_crtc->cursor_width;
8292
8293         intel_crtc->cursor_addr = addr;
8294         intel_crtc->cursor_bo = obj;
8295         intel_crtc->cursor_width = width;
8296         intel_crtc->cursor_height = height;
8297
8298         if (intel_crtc->active) {
8299                 if (old_width != width)
8300                         intel_update_watermarks(crtc);
8301                 intel_crtc_update_cursor(crtc, intel_crtc->cursor_bo != NULL);
8302
8303                 intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_CURSOR(pipe));
8304         }
8305
8306         return 0;
8307 fail_unpin:
8308         i915_gem_object_unpin_from_display_plane(obj);
8309 fail_locked:
8310         mutex_unlock(&dev->struct_mutex);
8311         return ret;
8312 }
8313
8314 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
8315                                  u16 *blue, uint32_t start, uint32_t size)
8316 {
8317         int end = (start + size > 256) ? 256 : start + size, i;
8318         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8319
8320         for (i = start; i < end; i++) {
8321                 intel_crtc->lut_r[i] = red[i] >> 8;
8322                 intel_crtc->lut_g[i] = green[i] >> 8;
8323                 intel_crtc->lut_b[i] = blue[i] >> 8;
8324         }
8325
8326         intel_crtc_load_lut(crtc);
8327 }
8328
8329 /* VESA 640x480x72Hz mode to set on the pipe */
8330 static struct drm_display_mode load_detect_mode = {
8331         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
8332                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
8333 };
8334
8335 struct drm_framebuffer *
8336 __intel_framebuffer_create(struct drm_device *dev,
8337                            struct drm_mode_fb_cmd2 *mode_cmd,
8338                            struct drm_i915_gem_object *obj)
8339 {
8340         struct intel_framebuffer *intel_fb;
8341         int ret;
8342
8343         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8344         if (!intel_fb) {
8345                 drm_gem_object_unreference_unlocked(&obj->base);
8346                 return ERR_PTR(-ENOMEM);
8347         }
8348
8349         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
8350         if (ret)
8351                 goto err;
8352
8353         return &intel_fb->base;
8354 err:
8355         drm_gem_object_unreference_unlocked(&obj->base);
8356         kfree(intel_fb);
8357
8358         return ERR_PTR(ret);
8359 }
8360
8361 static struct drm_framebuffer *
8362 intel_framebuffer_create(struct drm_device *dev,
8363                          struct drm_mode_fb_cmd2 *mode_cmd,
8364                          struct drm_i915_gem_object *obj)
8365 {
8366         struct drm_framebuffer *fb;
8367         int ret;
8368
8369         ret = i915_mutex_lock_interruptible(dev);
8370         if (ret)
8371                 return ERR_PTR(ret);
8372         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
8373         mutex_unlock(&dev->struct_mutex);
8374
8375         return fb;
8376 }
8377
8378 static u32
8379 intel_framebuffer_pitch_for_width(int width, int bpp)
8380 {
8381         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
8382         return ALIGN(pitch, 64);
8383 }
8384
8385 static u32
8386 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
8387 {
8388         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
8389         return PAGE_ALIGN(pitch * mode->vdisplay);
8390 }
8391
8392 static struct drm_framebuffer *
8393 intel_framebuffer_create_for_mode(struct drm_device *dev,
8394                                   struct drm_display_mode *mode,
8395                                   int depth, int bpp)
8396 {
8397         struct drm_i915_gem_object *obj;
8398         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
8399
8400         obj = i915_gem_alloc_object(dev,
8401                                     intel_framebuffer_size_for_mode(mode, bpp));
8402         if (obj == NULL)
8403                 return ERR_PTR(-ENOMEM);
8404
8405         mode_cmd.width = mode->hdisplay;
8406         mode_cmd.height = mode->vdisplay;
8407         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
8408                                                                 bpp);
8409         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
8410
8411         return intel_framebuffer_create(dev, &mode_cmd, obj);
8412 }
8413
8414 static struct drm_framebuffer *
8415 mode_fits_in_fbdev(struct drm_device *dev,
8416                    struct drm_display_mode *mode)
8417 {
8418 #ifdef CONFIG_DRM_I915_FBDEV
8419         struct drm_i915_private *dev_priv = dev->dev_private;
8420         struct drm_i915_gem_object *obj;
8421         struct drm_framebuffer *fb;
8422
8423         if (!dev_priv->fbdev)
8424                 return NULL;
8425
8426         if (!dev_priv->fbdev->fb)
8427                 return NULL;
8428
8429         obj = dev_priv->fbdev->fb->obj;
8430         BUG_ON(!obj);
8431
8432         fb = &dev_priv->fbdev->fb->base;
8433         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
8434                                                                fb->bits_per_pixel))
8435                 return NULL;
8436
8437         if (obj->base.size < mode->vdisplay * fb->pitches[0])
8438                 return NULL;
8439
8440         return fb;
8441 #else
8442         return NULL;
8443 #endif
8444 }
8445
8446 bool intel_get_load_detect_pipe(struct drm_connector *connector,
8447                                 struct drm_display_mode *mode,
8448                                 struct intel_load_detect_pipe *old,
8449                                 struct drm_modeset_acquire_ctx *ctx)
8450 {
8451         struct intel_crtc *intel_crtc;
8452         struct intel_encoder *intel_encoder =
8453                 intel_attached_encoder(connector);
8454         struct drm_crtc *possible_crtc;
8455         struct drm_encoder *encoder = &intel_encoder->base;
8456         struct drm_crtc *crtc = NULL;
8457         struct drm_device *dev = encoder->dev;
8458         struct drm_framebuffer *fb;
8459         struct drm_mode_config *config = &dev->mode_config;
8460         int ret, i = -1;
8461
8462         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8463                       connector->base.id, connector->name,
8464                       encoder->base.id, encoder->name);
8465
8466 retry:
8467         ret = drm_modeset_lock(&config->connection_mutex, ctx);
8468         if (ret)
8469                 goto fail_unlock;
8470
8471         /*
8472          * Algorithm gets a little messy:
8473          *
8474          *   - if the connector already has an assigned crtc, use it (but make
8475          *     sure it's on first)
8476          *
8477          *   - try to find the first unused crtc that can drive this connector,
8478          *     and use that if we find one
8479          */
8480
8481         /* See if we already have a CRTC for this connector */
8482         if (encoder->crtc) {
8483                 crtc = encoder->crtc;
8484
8485                 ret = drm_modeset_lock(&crtc->mutex, ctx);
8486                 if (ret)
8487                         goto fail_unlock;
8488
8489                 old->dpms_mode = connector->dpms;
8490                 old->load_detect_temp = false;
8491
8492                 /* Make sure the crtc and connector are running */
8493                 if (connector->dpms != DRM_MODE_DPMS_ON)
8494                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
8495
8496                 return true;
8497         }
8498
8499         /* Find an unused one (if possible) */
8500         for_each_crtc(dev, possible_crtc) {
8501                 i++;
8502                 if (!(encoder->possible_crtcs & (1 << i)))
8503                         continue;
8504                 if (possible_crtc->enabled)
8505                         continue;
8506                 /* This can occur when applying the pipe A quirk on resume. */
8507                 if (to_intel_crtc(possible_crtc)->new_enabled)
8508                         continue;
8509
8510                 crtc = possible_crtc;
8511                 break;
8512         }
8513
8514         /*
8515          * If we didn't find an unused CRTC, don't use any.
8516          */
8517         if (!crtc) {
8518                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
8519                 goto fail_unlock;
8520         }
8521
8522         ret = drm_modeset_lock(&crtc->mutex, ctx);
8523         if (ret)
8524                 goto fail_unlock;
8525         intel_encoder->new_crtc = to_intel_crtc(crtc);
8526         to_intel_connector(connector)->new_encoder = intel_encoder;
8527
8528         intel_crtc = to_intel_crtc(crtc);
8529         intel_crtc->new_enabled = true;
8530         intel_crtc->new_config = &intel_crtc->config;
8531         old->dpms_mode = connector->dpms;
8532         old->load_detect_temp = true;
8533         old->release_fb = NULL;
8534
8535         if (!mode)
8536                 mode = &load_detect_mode;
8537
8538         /* We need a framebuffer large enough to accommodate all accesses
8539          * that the plane may generate whilst we perform load detection.
8540          * We can not rely on the fbcon either being present (we get called
8541          * during its initialisation to detect all boot displays, or it may
8542          * not even exist) or that it is large enough to satisfy the
8543          * requested mode.
8544          */
8545         fb = mode_fits_in_fbdev(dev, mode);
8546         if (fb == NULL) {
8547                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
8548                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
8549                 old->release_fb = fb;
8550         } else
8551                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
8552         if (IS_ERR(fb)) {
8553                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
8554                 goto fail;
8555         }
8556
8557         if (intel_set_mode(crtc, mode, 0, 0, fb)) {
8558                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
8559                 if (old->release_fb)
8560                         old->release_fb->funcs->destroy(old->release_fb);
8561                 goto fail;
8562         }
8563
8564         /* let the connector get through one full cycle before testing */
8565         intel_wait_for_vblank(dev, intel_crtc->pipe);
8566         return true;
8567
8568  fail:
8569         intel_crtc->new_enabled = crtc->enabled;
8570         if (intel_crtc->new_enabled)
8571                 intel_crtc->new_config = &intel_crtc->config;
8572         else
8573                 intel_crtc->new_config = NULL;
8574 fail_unlock:
8575         if (ret == -EDEADLK) {
8576                 drm_modeset_backoff(ctx);
8577                 goto retry;
8578         }
8579
8580         return false;
8581 }
8582
8583 void intel_release_load_detect_pipe(struct drm_connector *connector,
8584                                     struct intel_load_detect_pipe *old)
8585 {
8586         struct intel_encoder *intel_encoder =
8587                 intel_attached_encoder(connector);
8588         struct drm_encoder *encoder = &intel_encoder->base;
8589         struct drm_crtc *crtc = encoder->crtc;
8590         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8591
8592         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8593                       connector->base.id, connector->name,
8594                       encoder->base.id, encoder->name);
8595
8596         if (old->load_detect_temp) {
8597                 to_intel_connector(connector)->new_encoder = NULL;
8598                 intel_encoder->new_crtc = NULL;
8599                 intel_crtc->new_enabled = false;
8600                 intel_crtc->new_config = NULL;
8601                 intel_set_mode(crtc, NULL, 0, 0, NULL);
8602
8603                 if (old->release_fb) {
8604                         drm_framebuffer_unregister_private(old->release_fb);
8605                         drm_framebuffer_unreference(old->release_fb);
8606                 }
8607
8608                 return;
8609         }
8610
8611         /* Switch crtc and encoder back off if necessary */
8612         if (old->dpms_mode != DRM_MODE_DPMS_ON)
8613                 connector->funcs->dpms(connector, old->dpms_mode);
8614 }
8615
8616 static int i9xx_pll_refclk(struct drm_device *dev,
8617                            const struct intel_crtc_config *pipe_config)
8618 {
8619         struct drm_i915_private *dev_priv = dev->dev_private;
8620         u32 dpll = pipe_config->dpll_hw_state.dpll;
8621
8622         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
8623                 return dev_priv->vbt.lvds_ssc_freq;
8624         else if (HAS_PCH_SPLIT(dev))
8625                 return 120000;
8626         else if (!IS_GEN2(dev))
8627                 return 96000;
8628         else
8629                 return 48000;
8630 }
8631
8632 /* Returns the clock of the currently programmed mode of the given pipe. */
8633 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
8634                                 struct intel_crtc_config *pipe_config)
8635 {
8636         struct drm_device *dev = crtc->base.dev;
8637         struct drm_i915_private *dev_priv = dev->dev_private;
8638         int pipe = pipe_config->cpu_transcoder;
8639         u32 dpll = pipe_config->dpll_hw_state.dpll;
8640         u32 fp;
8641         intel_clock_t clock;
8642         int refclk = i9xx_pll_refclk(dev, pipe_config);
8643
8644         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
8645                 fp = pipe_config->dpll_hw_state.fp0;
8646         else
8647                 fp = pipe_config->dpll_hw_state.fp1;
8648
8649         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
8650         if (IS_PINEVIEW(dev)) {
8651                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
8652                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
8653         } else {
8654                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
8655                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
8656         }
8657
8658         if (!IS_GEN2(dev)) {
8659                 if (IS_PINEVIEW(dev))
8660                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
8661                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
8662                 else
8663                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
8664                                DPLL_FPA01_P1_POST_DIV_SHIFT);
8665
8666                 switch (dpll & DPLL_MODE_MASK) {
8667                 case DPLLB_MODE_DAC_SERIAL:
8668                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
8669                                 5 : 10;
8670                         break;
8671                 case DPLLB_MODE_LVDS:
8672                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
8673                                 7 : 14;
8674                         break;
8675                 default:
8676                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
8677                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
8678                         return;
8679                 }
8680
8681                 if (IS_PINEVIEW(dev))
8682                         pineview_clock(refclk, &clock);
8683                 else
8684                         i9xx_clock(refclk, &clock);
8685         } else {
8686                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
8687                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
8688
8689                 if (is_lvds) {
8690                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
8691                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
8692
8693                         if (lvds & LVDS_CLKB_POWER_UP)
8694                                 clock.p2 = 7;
8695                         else
8696                                 clock.p2 = 14;
8697                 } else {
8698                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
8699                                 clock.p1 = 2;
8700                         else {
8701                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
8702                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
8703                         }
8704                         if (dpll & PLL_P2_DIVIDE_BY_4)
8705                                 clock.p2 = 4;
8706                         else
8707                                 clock.p2 = 2;
8708                 }
8709
8710                 i9xx_clock(refclk, &clock);
8711         }
8712
8713         /*
8714          * This value includes pixel_multiplier. We will use
8715          * port_clock to compute adjusted_mode.crtc_clock in the
8716          * encoder's get_config() function.
8717          */
8718         pipe_config->port_clock = clock.dot;
8719 }
8720
8721 int intel_dotclock_calculate(int link_freq,
8722                              const struct intel_link_m_n *m_n)
8723 {
8724         /*
8725          * The calculation for the data clock is:
8726          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
8727          * But we want to avoid losing precison if possible, so:
8728          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
8729          *
8730          * and the link clock is simpler:
8731          * link_clock = (m * link_clock) / n
8732          */
8733
8734         if (!m_n->link_n)
8735                 return 0;
8736
8737         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
8738 }
8739
8740 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
8741                                    struct intel_crtc_config *pipe_config)
8742 {
8743         struct drm_device *dev = crtc->base.dev;
8744
8745         /* read out port_clock from the DPLL */
8746         i9xx_crtc_clock_get(crtc, pipe_config);
8747
8748         /*
8749          * This value does not include pixel_multiplier.
8750          * We will check that port_clock and adjusted_mode.crtc_clock
8751          * agree once we know their relationship in the encoder's
8752          * get_config() function.
8753          */
8754         pipe_config->adjusted_mode.crtc_clock =
8755                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
8756                                          &pipe_config->fdi_m_n);
8757 }
8758
8759 /** Returns the currently programmed mode of the given pipe. */
8760 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
8761                                              struct drm_crtc *crtc)
8762 {
8763         struct drm_i915_private *dev_priv = dev->dev_private;
8764         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8765         enum transcoder cpu_transcoder = intel_crtc->config.cpu_transcoder;
8766         struct drm_display_mode *mode;
8767         struct intel_crtc_config pipe_config;
8768         int htot = I915_READ(HTOTAL(cpu_transcoder));
8769         int hsync = I915_READ(HSYNC(cpu_transcoder));
8770         int vtot = I915_READ(VTOTAL(cpu_transcoder));
8771         int vsync = I915_READ(VSYNC(cpu_transcoder));
8772         enum pipe pipe = intel_crtc->pipe;
8773
8774         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
8775         if (!mode)
8776                 return NULL;
8777
8778         /*
8779          * Construct a pipe_config sufficient for getting the clock info
8780          * back out of crtc_clock_get.
8781          *
8782          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
8783          * to use a real value here instead.
8784          */
8785         pipe_config.cpu_transcoder = (enum transcoder) pipe;
8786         pipe_config.pixel_multiplier = 1;
8787         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
8788         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
8789         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
8790         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
8791
8792         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
8793         mode->hdisplay = (htot & 0xffff) + 1;
8794         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
8795         mode->hsync_start = (hsync & 0xffff) + 1;
8796         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
8797         mode->vdisplay = (vtot & 0xffff) + 1;
8798         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
8799         mode->vsync_start = (vsync & 0xffff) + 1;
8800         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
8801
8802         drm_mode_set_name(mode);
8803
8804         return mode;
8805 }
8806
8807 static void intel_decrease_pllclock(struct drm_crtc *crtc)
8808 {
8809         struct drm_device *dev = crtc->dev;
8810         struct drm_i915_private *dev_priv = dev->dev_private;
8811         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8812
8813         if (!HAS_GMCH_DISPLAY(dev))
8814                 return;
8815
8816         if (!dev_priv->lvds_downclock_avail)
8817                 return;
8818
8819         /*
8820          * Since this is called by a timer, we should never get here in
8821          * the manual case.
8822          */
8823         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
8824                 int pipe = intel_crtc->pipe;
8825                 int dpll_reg = DPLL(pipe);
8826                 int dpll;
8827
8828                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
8829
8830                 assert_panel_unlocked(dev_priv, pipe);
8831
8832                 dpll = I915_READ(dpll_reg);
8833                 dpll |= DISPLAY_RATE_SELECT_FPA1;
8834                 I915_WRITE(dpll_reg, dpll);
8835                 intel_wait_for_vblank(dev, pipe);
8836                 dpll = I915_READ(dpll_reg);
8837                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
8838                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
8839         }
8840
8841 }
8842
8843 void intel_mark_busy(struct drm_device *dev)
8844 {
8845         struct drm_i915_private *dev_priv = dev->dev_private;
8846
8847         if (dev_priv->mm.busy)
8848                 return;
8849
8850         intel_runtime_pm_get(dev_priv);
8851         i915_update_gfx_val(dev_priv);
8852         dev_priv->mm.busy = true;
8853 }
8854
8855 void intel_mark_idle(struct drm_device *dev)
8856 {
8857         struct drm_i915_private *dev_priv = dev->dev_private;
8858         struct drm_crtc *crtc;
8859
8860         if (!dev_priv->mm.busy)
8861                 return;
8862
8863         dev_priv->mm.busy = false;
8864
8865         if (!i915.powersave)
8866                 goto out;
8867
8868         for_each_crtc(dev, crtc) {
8869                 if (!crtc->primary->fb)
8870                         continue;
8871
8872                 intel_decrease_pllclock(crtc);
8873         }
8874
8875         if (INTEL_INFO(dev)->gen >= 6)
8876                 gen6_rps_idle(dev->dev_private);
8877
8878 out:
8879         intel_runtime_pm_put(dev_priv);
8880 }
8881
8882 static void intel_crtc_destroy(struct drm_crtc *crtc)
8883 {
8884         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8885         struct drm_device *dev = crtc->dev;
8886         struct intel_unpin_work *work;
8887
8888         spin_lock_irq(&dev->event_lock);
8889         work = intel_crtc->unpin_work;
8890         intel_crtc->unpin_work = NULL;
8891         spin_unlock_irq(&dev->event_lock);
8892
8893         if (work) {
8894                 cancel_work_sync(&work->work);
8895                 kfree(work);
8896         }
8897
8898         drm_crtc_cleanup(crtc);
8899
8900         kfree(intel_crtc);
8901 }
8902
8903 static void intel_unpin_work_fn(struct work_struct *__work)
8904 {
8905         struct intel_unpin_work *work =
8906                 container_of(__work, struct intel_unpin_work, work);
8907         struct drm_device *dev = work->crtc->dev;
8908         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
8909
8910         mutex_lock(&dev->struct_mutex);
8911         intel_unpin_fb_obj(work->old_fb_obj);
8912         drm_gem_object_unreference(&work->pending_flip_obj->base);
8913         drm_gem_object_unreference(&work->old_fb_obj->base);
8914
8915         intel_update_fbc(dev);
8916         mutex_unlock(&dev->struct_mutex);
8917
8918         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
8919
8920         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
8921         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
8922
8923         kfree(work);
8924 }
8925
8926 static void do_intel_finish_page_flip(struct drm_device *dev,
8927                                       struct drm_crtc *crtc)
8928 {
8929         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8930         struct intel_unpin_work *work;
8931         unsigned long flags;
8932
8933         /* Ignore early vblank irqs */
8934         if (intel_crtc == NULL)
8935                 return;
8936
8937         /*
8938          * This is called both by irq handlers and the reset code (to complete
8939          * lost pageflips) so needs the full irqsave spinlocks.
8940          */
8941         spin_lock_irqsave(&dev->event_lock, flags);
8942         work = intel_crtc->unpin_work;
8943
8944         /* Ensure we don't miss a work->pending update ... */
8945         smp_rmb();
8946
8947         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
8948                 spin_unlock_irqrestore(&dev->event_lock, flags);
8949                 return;
8950         }
8951
8952         page_flip_completed(intel_crtc);
8953
8954         spin_unlock_irqrestore(&dev->event_lock, flags);
8955 }
8956
8957 void intel_finish_page_flip(struct drm_device *dev, int pipe)
8958 {
8959         struct drm_i915_private *dev_priv = dev->dev_private;
8960         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
8961
8962         do_intel_finish_page_flip(dev, crtc);
8963 }
8964
8965 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
8966 {
8967         struct drm_i915_private *dev_priv = dev->dev_private;
8968         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
8969
8970         do_intel_finish_page_flip(dev, crtc);
8971 }
8972
8973 /* Is 'a' after or equal to 'b'? */
8974 static bool g4x_flip_count_after_eq(u32 a, u32 b)
8975 {
8976         return !((a - b) & 0x80000000);
8977 }
8978
8979 static bool page_flip_finished(struct intel_crtc *crtc)
8980 {
8981         struct drm_device *dev = crtc->base.dev;
8982         struct drm_i915_private *dev_priv = dev->dev_private;
8983
8984         /*
8985          * The relevant registers doen't exist on pre-ctg.
8986          * As the flip done interrupt doesn't trigger for mmio
8987          * flips on gmch platforms, a flip count check isn't
8988          * really needed there. But since ctg has the registers,
8989          * include it in the check anyway.
8990          */
8991         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
8992                 return true;
8993
8994         /*
8995          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
8996          * used the same base address. In that case the mmio flip might
8997          * have completed, but the CS hasn't even executed the flip yet.
8998          *
8999          * A flip count check isn't enough as the CS might have updated
9000          * the base address just after start of vblank, but before we
9001          * managed to process the interrupt. This means we'd complete the
9002          * CS flip too soon.
9003          *
9004          * Combining both checks should get us a good enough result. It may
9005          * still happen that the CS flip has been executed, but has not
9006          * yet actually completed. But in case the base address is the same
9007          * anyway, we don't really care.
9008          */
9009         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
9010                 crtc->unpin_work->gtt_offset &&
9011                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
9012                                     crtc->unpin_work->flip_count);
9013 }
9014
9015 void intel_prepare_page_flip(struct drm_device *dev, int plane)
9016 {
9017         struct drm_i915_private *dev_priv = dev->dev_private;
9018         struct intel_crtc *intel_crtc =
9019                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
9020         unsigned long flags;
9021
9022
9023         /*
9024          * This is called both by irq handlers and the reset code (to complete
9025          * lost pageflips) so needs the full irqsave spinlocks.
9026          *
9027          * NB: An MMIO update of the plane base pointer will also
9028          * generate a page-flip completion irq, i.e. every modeset
9029          * is also accompanied by a spurious intel_prepare_page_flip().
9030          */
9031         spin_lock_irqsave(&dev->event_lock, flags);
9032         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
9033                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
9034         spin_unlock_irqrestore(&dev->event_lock, flags);
9035 }
9036
9037 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
9038 {
9039         /* Ensure that the work item is consistent when activating it ... */
9040         smp_wmb();
9041         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
9042         /* and that it is marked active as soon as the irq could fire. */
9043         smp_wmb();
9044 }
9045
9046 static int intel_gen2_queue_flip(struct drm_device *dev,
9047                                  struct drm_crtc *crtc,
9048                                  struct drm_framebuffer *fb,
9049                                  struct drm_i915_gem_object *obj,
9050                                  struct intel_engine_cs *ring,
9051                                  uint32_t flags)
9052 {
9053         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9054         u32 flip_mask;
9055         int ret;
9056
9057         ret = intel_ring_begin(ring, 6);
9058         if (ret)
9059                 return ret;
9060
9061         /* Can't queue multiple flips, so wait for the previous
9062          * one to finish before executing the next.
9063          */
9064         if (intel_crtc->plane)
9065                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9066         else
9067                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9068         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9069         intel_ring_emit(ring, MI_NOOP);
9070         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9071                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9072         intel_ring_emit(ring, fb->pitches[0]);
9073         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9074         intel_ring_emit(ring, 0); /* aux display base address, unused */
9075
9076         intel_mark_page_flip_active(intel_crtc);
9077         __intel_ring_advance(ring);
9078         return 0;
9079 }
9080
9081 static int intel_gen3_queue_flip(struct drm_device *dev,
9082                                  struct drm_crtc *crtc,
9083                                  struct drm_framebuffer *fb,
9084                                  struct drm_i915_gem_object *obj,
9085                                  struct intel_engine_cs *ring,
9086                                  uint32_t flags)
9087 {
9088         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9089         u32 flip_mask;
9090         int ret;
9091
9092         ret = intel_ring_begin(ring, 6);
9093         if (ret)
9094                 return ret;
9095
9096         if (intel_crtc->plane)
9097                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9098         else
9099                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9100         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9101         intel_ring_emit(ring, MI_NOOP);
9102         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
9103                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9104         intel_ring_emit(ring, fb->pitches[0]);
9105         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9106         intel_ring_emit(ring, MI_NOOP);
9107
9108         intel_mark_page_flip_active(intel_crtc);
9109         __intel_ring_advance(ring);
9110         return 0;
9111 }
9112
9113 static int intel_gen4_queue_flip(struct drm_device *dev,
9114                                  struct drm_crtc *crtc,
9115                                  struct drm_framebuffer *fb,
9116                                  struct drm_i915_gem_object *obj,
9117                                  struct intel_engine_cs *ring,
9118                                  uint32_t flags)
9119 {
9120         struct drm_i915_private *dev_priv = dev->dev_private;
9121         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9122         uint32_t pf, pipesrc;
9123         int ret;
9124
9125         ret = intel_ring_begin(ring, 4);
9126         if (ret)
9127                 return ret;
9128
9129         /* i965+ uses the linear or tiled offsets from the
9130          * Display Registers (which do not change across a page-flip)
9131          * so we need only reprogram the base address.
9132          */
9133         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9134                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9135         intel_ring_emit(ring, fb->pitches[0]);
9136         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
9137                         obj->tiling_mode);
9138
9139         /* XXX Enabling the panel-fitter across page-flip is so far
9140          * untested on non-native modes, so ignore it for now.
9141          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
9142          */
9143         pf = 0;
9144         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9145         intel_ring_emit(ring, pf | pipesrc);
9146
9147         intel_mark_page_flip_active(intel_crtc);
9148         __intel_ring_advance(ring);
9149         return 0;
9150 }
9151
9152 static int intel_gen6_queue_flip(struct drm_device *dev,
9153                                  struct drm_crtc *crtc,
9154                                  struct drm_framebuffer *fb,
9155                                  struct drm_i915_gem_object *obj,
9156                                  struct intel_engine_cs *ring,
9157                                  uint32_t flags)
9158 {
9159         struct drm_i915_private *dev_priv = dev->dev_private;
9160         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9161         uint32_t pf, pipesrc;
9162         int ret;
9163
9164         ret = intel_ring_begin(ring, 4);
9165         if (ret)
9166                 return ret;
9167
9168         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9169                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9170         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
9171         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9172
9173         /* Contrary to the suggestions in the documentation,
9174          * "Enable Panel Fitter" does not seem to be required when page
9175          * flipping with a non-native mode, and worse causes a normal
9176          * modeset to fail.
9177          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
9178          */
9179         pf = 0;
9180         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9181         intel_ring_emit(ring, pf | pipesrc);
9182
9183         intel_mark_page_flip_active(intel_crtc);
9184         __intel_ring_advance(ring);
9185         return 0;
9186 }
9187
9188 static int intel_gen7_queue_flip(struct drm_device *dev,
9189                                  struct drm_crtc *crtc,
9190                                  struct drm_framebuffer *fb,
9191                                  struct drm_i915_gem_object *obj,
9192                                  struct intel_engine_cs *ring,
9193                                  uint32_t flags)
9194 {
9195         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9196         uint32_t plane_bit = 0;
9197         int len, ret;
9198
9199         switch (intel_crtc->plane) {
9200         case PLANE_A:
9201                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
9202                 break;
9203         case PLANE_B:
9204                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
9205                 break;
9206         case PLANE_C:
9207                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
9208                 break;
9209         default:
9210                 WARN_ONCE(1, "unknown plane in flip command\n");
9211                 return -ENODEV;
9212         }
9213
9214         len = 4;
9215         if (ring->id == RCS) {
9216                 len += 6;
9217                 /*
9218                  * On Gen 8, SRM is now taking an extra dword to accommodate
9219                  * 48bits addresses, and we need a NOOP for the batch size to
9220                  * stay even.
9221                  */
9222                 if (IS_GEN8(dev))
9223                         len += 2;
9224         }
9225
9226         /*
9227          * BSpec MI_DISPLAY_FLIP for IVB:
9228          * "The full packet must be contained within the same cache line."
9229          *
9230          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
9231          * cacheline, if we ever start emitting more commands before
9232          * the MI_DISPLAY_FLIP we may need to first emit everything else,
9233          * then do the cacheline alignment, and finally emit the
9234          * MI_DISPLAY_FLIP.
9235          */
9236         ret = intel_ring_cacheline_align(ring);
9237         if (ret)
9238                 return ret;
9239
9240         ret = intel_ring_begin(ring, len);
9241         if (ret)
9242                 return ret;
9243
9244         /* Unmask the flip-done completion message. Note that the bspec says that
9245          * we should do this for both the BCS and RCS, and that we must not unmask
9246          * more than one flip event at any time (or ensure that one flip message
9247          * can be sent by waiting for flip-done prior to queueing new flips).
9248          * Experimentation says that BCS works despite DERRMR masking all
9249          * flip-done completion events and that unmasking all planes at once
9250          * for the RCS also doesn't appear to drop events. Setting the DERRMR
9251          * to zero does lead to lockups within MI_DISPLAY_FLIP.
9252          */
9253         if (ring->id == RCS) {
9254                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9255                 intel_ring_emit(ring, DERRMR);
9256                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9257                                         DERRMR_PIPEB_PRI_FLIP_DONE |
9258                                         DERRMR_PIPEC_PRI_FLIP_DONE));
9259                 if (IS_GEN8(dev))
9260                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9261                                               MI_SRM_LRM_GLOBAL_GTT);
9262                 else
9263                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
9264                                               MI_SRM_LRM_GLOBAL_GTT);
9265                 intel_ring_emit(ring, DERRMR);
9266                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9267                 if (IS_GEN8(dev)) {
9268                         intel_ring_emit(ring, 0);
9269                         intel_ring_emit(ring, MI_NOOP);
9270                 }
9271         }
9272
9273         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
9274         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
9275         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9276         intel_ring_emit(ring, (MI_NOOP));
9277
9278         intel_mark_page_flip_active(intel_crtc);
9279         __intel_ring_advance(ring);
9280         return 0;
9281 }
9282
9283 static bool use_mmio_flip(struct intel_engine_cs *ring,
9284                           struct drm_i915_gem_object *obj)
9285 {
9286         /*
9287          * This is not being used for older platforms, because
9288          * non-availability of flip done interrupt forces us to use
9289          * CS flips. Older platforms derive flip done using some clever
9290          * tricks involving the flip_pending status bits and vblank irqs.
9291          * So using MMIO flips there would disrupt this mechanism.
9292          */
9293
9294         if (ring == NULL)
9295                 return true;
9296
9297         if (INTEL_INFO(ring->dev)->gen < 5)
9298                 return false;
9299
9300         if (i915.use_mmio_flip < 0)
9301                 return false;
9302         else if (i915.use_mmio_flip > 0)
9303                 return true;
9304         else if (i915.enable_execlists)
9305                 return true;
9306         else
9307                 return ring != obj->ring;
9308 }
9309
9310 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
9311 {
9312         struct drm_device *dev = intel_crtc->base.dev;
9313         struct drm_i915_private *dev_priv = dev->dev_private;
9314         struct intel_framebuffer *intel_fb =
9315                 to_intel_framebuffer(intel_crtc->base.primary->fb);
9316         struct drm_i915_gem_object *obj = intel_fb->obj;
9317         u32 dspcntr;
9318         u32 reg;
9319
9320         intel_mark_page_flip_active(intel_crtc);
9321
9322         reg = DSPCNTR(intel_crtc->plane);
9323         dspcntr = I915_READ(reg);
9324
9325         if (obj->tiling_mode != I915_TILING_NONE)
9326                 dspcntr |= DISPPLANE_TILED;
9327         else
9328                 dspcntr &= ~DISPPLANE_TILED;
9329
9330         I915_WRITE(reg, dspcntr);
9331
9332         I915_WRITE(DSPSURF(intel_crtc->plane),
9333                    intel_crtc->unpin_work->gtt_offset);
9334         POSTING_READ(DSPSURF(intel_crtc->plane));
9335 }
9336
9337 static int intel_postpone_flip(struct drm_i915_gem_object *obj)
9338 {
9339         struct intel_engine_cs *ring;
9340         int ret;
9341
9342         lockdep_assert_held(&obj->base.dev->struct_mutex);
9343
9344         if (!obj->last_write_seqno)
9345                 return 0;
9346
9347         ring = obj->ring;
9348
9349         if (i915_seqno_passed(ring->get_seqno(ring, true),
9350                               obj->last_write_seqno))
9351                 return 0;
9352
9353         ret = i915_gem_check_olr(ring, obj->last_write_seqno);
9354         if (ret)
9355                 return ret;
9356
9357         if (WARN_ON(!ring->irq_get(ring)))
9358                 return 0;
9359
9360         return 1;
9361 }
9362
9363 void intel_notify_mmio_flip(struct intel_engine_cs *ring)
9364 {
9365         struct drm_i915_private *dev_priv = to_i915(ring->dev);
9366         struct intel_crtc *intel_crtc;
9367         unsigned long irq_flags;
9368         u32 seqno;
9369
9370         seqno = ring->get_seqno(ring, false);
9371
9372         spin_lock_irqsave(&dev_priv->mmio_flip_lock, irq_flags);
9373         for_each_intel_crtc(ring->dev, intel_crtc) {
9374                 struct intel_mmio_flip *mmio_flip;
9375
9376                 mmio_flip = &intel_crtc->mmio_flip;
9377                 if (mmio_flip->seqno == 0)
9378                         continue;
9379
9380                 if (ring->id != mmio_flip->ring_id)
9381                         continue;
9382
9383                 if (i915_seqno_passed(seqno, mmio_flip->seqno)) {
9384                         intel_do_mmio_flip(intel_crtc);
9385                         mmio_flip->seqno = 0;
9386                         ring->irq_put(ring);
9387                 }
9388         }
9389         spin_unlock_irqrestore(&dev_priv->mmio_flip_lock, irq_flags);
9390 }
9391
9392 static int intel_queue_mmio_flip(struct drm_device *dev,
9393                                  struct drm_crtc *crtc,
9394                                  struct drm_framebuffer *fb,
9395                                  struct drm_i915_gem_object *obj,
9396                                  struct intel_engine_cs *ring,
9397                                  uint32_t flags)
9398 {
9399         struct drm_i915_private *dev_priv = dev->dev_private;
9400         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9401         int ret;
9402
9403         if (WARN_ON(intel_crtc->mmio_flip.seqno))
9404                 return -EBUSY;
9405
9406         ret = intel_postpone_flip(obj);
9407         if (ret < 0)
9408                 return ret;
9409         if (ret == 0) {
9410                 intel_do_mmio_flip(intel_crtc);
9411                 return 0;
9412         }
9413
9414         spin_lock_irq(&dev_priv->mmio_flip_lock);
9415         intel_crtc->mmio_flip.seqno = obj->last_write_seqno;
9416         intel_crtc->mmio_flip.ring_id = obj->ring->id;
9417         spin_unlock_irq(&dev_priv->mmio_flip_lock);
9418
9419         /*
9420          * Double check to catch cases where irq fired before
9421          * mmio flip data was ready
9422          */
9423         intel_notify_mmio_flip(obj->ring);
9424         return 0;
9425 }
9426
9427 static int intel_default_queue_flip(struct drm_device *dev,
9428                                     struct drm_crtc *crtc,
9429                                     struct drm_framebuffer *fb,
9430                                     struct drm_i915_gem_object *obj,
9431                                     struct intel_engine_cs *ring,
9432                                     uint32_t flags)
9433 {
9434         return -ENODEV;
9435 }
9436
9437 static bool __intel_pageflip_stall_check(struct drm_device *dev,
9438                                          struct drm_crtc *crtc)
9439 {
9440         struct drm_i915_private *dev_priv = dev->dev_private;
9441         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9442         struct intel_unpin_work *work = intel_crtc->unpin_work;
9443         u32 addr;
9444
9445         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
9446                 return true;
9447
9448         if (!work->enable_stall_check)
9449                 return false;
9450
9451         if (work->flip_ready_vblank == 0) {
9452                 if (work->flip_queued_ring &&
9453                     !i915_seqno_passed(work->flip_queued_ring->get_seqno(work->flip_queued_ring, true),
9454                                        work->flip_queued_seqno))
9455                         return false;
9456
9457                 work->flip_ready_vblank = drm_vblank_count(dev, intel_crtc->pipe);
9458         }
9459
9460         if (drm_vblank_count(dev, intel_crtc->pipe) - work->flip_ready_vblank < 3)
9461                 return false;
9462
9463         /* Potential stall - if we see that the flip has happened,
9464          * assume a missed interrupt. */
9465         if (INTEL_INFO(dev)->gen >= 4)
9466                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
9467         else
9468                 addr = I915_READ(DSPADDR(intel_crtc->plane));
9469
9470         /* There is a potential issue here with a false positive after a flip
9471          * to the same address. We could address this by checking for a
9472          * non-incrementing frame counter.
9473          */
9474         return addr == work->gtt_offset;
9475 }
9476
9477 void intel_check_page_flip(struct drm_device *dev, int pipe)
9478 {
9479         struct drm_i915_private *dev_priv = dev->dev_private;
9480         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9481         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9482
9483         WARN_ON(!in_irq());
9484
9485         if (crtc == NULL)
9486                 return;
9487
9488         spin_lock(&dev->event_lock);
9489         if (intel_crtc->unpin_work && __intel_pageflip_stall_check(dev, crtc)) {
9490                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
9491                          intel_crtc->unpin_work->flip_queued_vblank, drm_vblank_count(dev, pipe));
9492                 page_flip_completed(intel_crtc);
9493         }
9494         spin_unlock(&dev->event_lock);
9495 }
9496
9497 static int intel_crtc_page_flip(struct drm_crtc *crtc,
9498                                 struct drm_framebuffer *fb,
9499                                 struct drm_pending_vblank_event *event,
9500                                 uint32_t page_flip_flags)
9501 {
9502         struct drm_device *dev = crtc->dev;
9503         struct drm_i915_private *dev_priv = dev->dev_private;
9504         struct drm_framebuffer *old_fb = crtc->primary->fb;
9505         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9506         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9507         enum pipe pipe = intel_crtc->pipe;
9508         struct intel_unpin_work *work;
9509         struct intel_engine_cs *ring;
9510         int ret;
9511
9512         /*
9513          * drm_mode_page_flip_ioctl() should already catch this, but double
9514          * check to be safe.  In the future we may enable pageflipping from
9515          * a disabled primary plane.
9516          */
9517         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
9518                 return -EBUSY;
9519
9520         /* Can't change pixel format via MI display flips. */
9521         if (fb->pixel_format != crtc->primary->fb->pixel_format)
9522                 return -EINVAL;
9523
9524         /*
9525          * TILEOFF/LINOFF registers can't be changed via MI display flips.
9526          * Note that pitch changes could also affect these register.
9527          */
9528         if (INTEL_INFO(dev)->gen > 3 &&
9529             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
9530              fb->pitches[0] != crtc->primary->fb->pitches[0]))
9531                 return -EINVAL;
9532
9533         if (i915_terminally_wedged(&dev_priv->gpu_error))
9534                 goto out_hang;
9535
9536         work = kzalloc(sizeof(*work), GFP_KERNEL);
9537         if (work == NULL)
9538                 return -ENOMEM;
9539
9540         work->event = event;
9541         work->crtc = crtc;
9542         work->old_fb_obj = intel_fb_obj(old_fb);
9543         INIT_WORK(&work->work, intel_unpin_work_fn);
9544
9545         ret = drm_crtc_vblank_get(crtc);
9546         if (ret)
9547                 goto free_work;
9548
9549         /* We borrow the event spin lock for protecting unpin_work */
9550         spin_lock_irq(&dev->event_lock);
9551         if (intel_crtc->unpin_work) {
9552                 /* Before declaring the flip queue wedged, check if
9553                  * the hardware completed the operation behind our backs.
9554                  */
9555                 if (__intel_pageflip_stall_check(dev, crtc)) {
9556                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
9557                         page_flip_completed(intel_crtc);
9558                 } else {
9559                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
9560                         spin_unlock_irq(&dev->event_lock);
9561
9562                         drm_crtc_vblank_put(crtc);
9563                         kfree(work);
9564                         return -EBUSY;
9565                 }
9566         }
9567         intel_crtc->unpin_work = work;
9568         spin_unlock_irq(&dev->event_lock);
9569
9570         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
9571                 flush_workqueue(dev_priv->wq);
9572
9573         ret = i915_mutex_lock_interruptible(dev);
9574         if (ret)
9575                 goto cleanup;
9576
9577         /* Reference the objects for the scheduled work. */
9578         drm_gem_object_reference(&work->old_fb_obj->base);
9579         drm_gem_object_reference(&obj->base);
9580
9581         crtc->primary->fb = fb;
9582
9583         work->pending_flip_obj = obj;
9584
9585         atomic_inc(&intel_crtc->unpin_work_count);
9586         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
9587
9588         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
9589                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
9590
9591         if (IS_VALLEYVIEW(dev)) {
9592                 ring = &dev_priv->ring[BCS];
9593                 if (obj->tiling_mode != work->old_fb_obj->tiling_mode)
9594                         /* vlv: DISPLAY_FLIP fails to change tiling */
9595                         ring = NULL;
9596         } else if (IS_IVYBRIDGE(dev)) {
9597                 ring = &dev_priv->ring[BCS];
9598         } else if (INTEL_INFO(dev)->gen >= 7) {
9599                 ring = obj->ring;
9600                 if (ring == NULL || ring->id != RCS)
9601                         ring = &dev_priv->ring[BCS];
9602         } else {
9603                 ring = &dev_priv->ring[RCS];
9604         }
9605
9606         ret = intel_pin_and_fence_fb_obj(dev, obj, ring);
9607         if (ret)
9608                 goto cleanup_pending;
9609
9610         work->gtt_offset =
9611                 i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset;
9612
9613         if (use_mmio_flip(ring, obj)) {
9614                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
9615                                             page_flip_flags);
9616                 if (ret)
9617                         goto cleanup_unpin;
9618
9619                 work->flip_queued_seqno = obj->last_write_seqno;
9620                 work->flip_queued_ring = obj->ring;
9621         } else {
9622                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
9623                                                    page_flip_flags);
9624                 if (ret)
9625                         goto cleanup_unpin;
9626
9627                 work->flip_queued_seqno = intel_ring_get_seqno(ring);
9628                 work->flip_queued_ring = ring;
9629         }
9630
9631         work->flip_queued_vblank = drm_vblank_count(dev, intel_crtc->pipe);
9632         work->enable_stall_check = true;
9633
9634         i915_gem_track_fb(work->old_fb_obj, obj,
9635                           INTEL_FRONTBUFFER_PRIMARY(pipe));
9636
9637         intel_disable_fbc(dev);
9638         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9639         mutex_unlock(&dev->struct_mutex);
9640
9641         trace_i915_flip_request(intel_crtc->plane, obj);
9642
9643         return 0;
9644
9645 cleanup_unpin:
9646         intel_unpin_fb_obj(obj);
9647 cleanup_pending:
9648         atomic_dec(&intel_crtc->unpin_work_count);
9649         crtc->primary->fb = old_fb;
9650         drm_gem_object_unreference(&work->old_fb_obj->base);
9651         drm_gem_object_unreference(&obj->base);
9652         mutex_unlock(&dev->struct_mutex);
9653
9654 cleanup:
9655         spin_lock_irq(&dev->event_lock);
9656         intel_crtc->unpin_work = NULL;
9657         spin_unlock_irq(&dev->event_lock);
9658
9659         drm_crtc_vblank_put(crtc);
9660 free_work:
9661         kfree(work);
9662
9663         if (ret == -EIO) {
9664 out_hang:
9665                 intel_crtc_wait_for_pending_flips(crtc);
9666                 ret = intel_pipe_set_base(crtc, crtc->x, crtc->y, fb);
9667                 if (ret == 0 && event) {
9668                         spin_lock_irq(&dev->event_lock);
9669                         drm_send_vblank_event(dev, pipe, event);
9670                         spin_unlock_irq(&dev->event_lock);
9671                 }
9672         }
9673         return ret;
9674 }
9675
9676 static struct drm_crtc_helper_funcs intel_helper_funcs = {
9677         .mode_set_base_atomic = intel_pipe_set_base_atomic,
9678         .load_lut = intel_crtc_load_lut,
9679 };
9680
9681 /**
9682  * intel_modeset_update_staged_output_state
9683  *
9684  * Updates the staged output configuration state, e.g. after we've read out the
9685  * current hw state.
9686  */
9687 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
9688 {
9689         struct intel_crtc *crtc;
9690         struct intel_encoder *encoder;
9691         struct intel_connector *connector;
9692
9693         list_for_each_entry(connector, &dev->mode_config.connector_list,
9694                             base.head) {
9695                 connector->new_encoder =
9696                         to_intel_encoder(connector->base.encoder);
9697         }
9698
9699         for_each_intel_encoder(dev, encoder) {
9700                 encoder->new_crtc =
9701                         to_intel_crtc(encoder->base.crtc);
9702         }
9703
9704         for_each_intel_crtc(dev, crtc) {
9705                 crtc->new_enabled = crtc->base.enabled;
9706
9707                 if (crtc->new_enabled)
9708                         crtc->new_config = &crtc->config;
9709                 else
9710                         crtc->new_config = NULL;
9711         }
9712 }
9713
9714 /**
9715  * intel_modeset_commit_output_state
9716  *
9717  * This function copies the stage display pipe configuration to the real one.
9718  */
9719 static void intel_modeset_commit_output_state(struct drm_device *dev)
9720 {
9721         struct intel_crtc *crtc;
9722         struct intel_encoder *encoder;
9723         struct intel_connector *connector;
9724
9725         list_for_each_entry(connector, &dev->mode_config.connector_list,
9726                             base.head) {
9727                 connector->base.encoder = &connector->new_encoder->base;
9728         }
9729
9730         for_each_intel_encoder(dev, encoder) {
9731                 encoder->base.crtc = &encoder->new_crtc->base;
9732         }
9733
9734         for_each_intel_crtc(dev, crtc) {
9735                 crtc->base.enabled = crtc->new_enabled;
9736         }
9737 }
9738
9739 static void
9740 connected_sink_compute_bpp(struct intel_connector *connector,
9741                            struct intel_crtc_config *pipe_config)
9742 {
9743         int bpp = pipe_config->pipe_bpp;
9744
9745         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
9746                 connector->base.base.id,
9747                 connector->base.name);
9748
9749         /* Don't use an invalid EDID bpc value */
9750         if (connector->base.display_info.bpc &&
9751             connector->base.display_info.bpc * 3 < bpp) {
9752                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
9753                               bpp, connector->base.display_info.bpc*3);
9754                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
9755         }
9756
9757         /* Clamp bpp to 8 on screens without EDID 1.4 */
9758         if (connector->base.display_info.bpc == 0 && bpp > 24) {
9759                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
9760                               bpp);
9761                 pipe_config->pipe_bpp = 24;
9762         }
9763 }
9764
9765 static int
9766 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
9767                           struct drm_framebuffer *fb,
9768                           struct intel_crtc_config *pipe_config)
9769 {
9770         struct drm_device *dev = crtc->base.dev;
9771         struct intel_connector *connector;
9772         int bpp;
9773
9774         switch (fb->pixel_format) {
9775         case DRM_FORMAT_C8:
9776                 bpp = 8*3; /* since we go through a colormap */
9777                 break;
9778         case DRM_FORMAT_XRGB1555:
9779         case DRM_FORMAT_ARGB1555:
9780                 /* checked in intel_framebuffer_init already */
9781                 if (WARN_ON(INTEL_INFO(dev)->gen > 3))
9782                         return -EINVAL;
9783         case DRM_FORMAT_RGB565:
9784                 bpp = 6*3; /* min is 18bpp */
9785                 break;
9786         case DRM_FORMAT_XBGR8888:
9787         case DRM_FORMAT_ABGR8888:
9788                 /* checked in intel_framebuffer_init already */
9789                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
9790                         return -EINVAL;
9791         case DRM_FORMAT_XRGB8888:
9792         case DRM_FORMAT_ARGB8888:
9793                 bpp = 8*3;
9794                 break;
9795         case DRM_FORMAT_XRGB2101010:
9796         case DRM_FORMAT_ARGB2101010:
9797         case DRM_FORMAT_XBGR2101010:
9798         case DRM_FORMAT_ABGR2101010:
9799                 /* checked in intel_framebuffer_init already */
9800                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
9801                         return -EINVAL;
9802                 bpp = 10*3;
9803                 break;
9804         /* TODO: gen4+ supports 16 bpc floating point, too. */
9805         default:
9806                 DRM_DEBUG_KMS("unsupported depth\n");
9807                 return -EINVAL;
9808         }
9809
9810         pipe_config->pipe_bpp = bpp;
9811
9812         /* Clamp display bpp to EDID value */
9813         list_for_each_entry(connector, &dev->mode_config.connector_list,
9814                             base.head) {
9815                 if (!connector->new_encoder ||
9816                     connector->new_encoder->new_crtc != crtc)
9817                         continue;
9818
9819                 connected_sink_compute_bpp(connector, pipe_config);
9820         }
9821
9822         return bpp;
9823 }
9824
9825 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
9826 {
9827         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
9828                         "type: 0x%x flags: 0x%x\n",
9829                 mode->crtc_clock,
9830                 mode->crtc_hdisplay, mode->crtc_hsync_start,
9831                 mode->crtc_hsync_end, mode->crtc_htotal,
9832                 mode->crtc_vdisplay, mode->crtc_vsync_start,
9833                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
9834 }
9835
9836 static void intel_dump_pipe_config(struct intel_crtc *crtc,
9837                                    struct intel_crtc_config *pipe_config,
9838                                    const char *context)
9839 {
9840         DRM_DEBUG_KMS("[CRTC:%d]%s config for pipe %c\n", crtc->base.base.id,
9841                       context, pipe_name(crtc->pipe));
9842
9843         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
9844         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
9845                       pipe_config->pipe_bpp, pipe_config->dither);
9846         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
9847                       pipe_config->has_pch_encoder,
9848                       pipe_config->fdi_lanes,
9849                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
9850                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
9851                       pipe_config->fdi_m_n.tu);
9852         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
9853                       pipe_config->has_dp_encoder,
9854                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
9855                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
9856                       pipe_config->dp_m_n.tu);
9857
9858         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
9859                       pipe_config->has_dp_encoder,
9860                       pipe_config->dp_m2_n2.gmch_m,
9861                       pipe_config->dp_m2_n2.gmch_n,
9862                       pipe_config->dp_m2_n2.link_m,
9863                       pipe_config->dp_m2_n2.link_n,
9864                       pipe_config->dp_m2_n2.tu);
9865
9866         DRM_DEBUG_KMS("requested mode:\n");
9867         drm_mode_debug_printmodeline(&pipe_config->requested_mode);
9868         DRM_DEBUG_KMS("adjusted mode:\n");
9869         drm_mode_debug_printmodeline(&pipe_config->adjusted_mode);
9870         intel_dump_crtc_timings(&pipe_config->adjusted_mode);
9871         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
9872         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
9873                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
9874         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
9875                       pipe_config->gmch_pfit.control,
9876                       pipe_config->gmch_pfit.pgm_ratios,
9877                       pipe_config->gmch_pfit.lvds_border_bits);
9878         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
9879                       pipe_config->pch_pfit.pos,
9880                       pipe_config->pch_pfit.size,
9881                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
9882         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
9883         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
9884 }
9885
9886 static bool encoders_cloneable(const struct intel_encoder *a,
9887                                const struct intel_encoder *b)
9888 {
9889         /* masks could be asymmetric, so check both ways */
9890         return a == b || (a->cloneable & (1 << b->type) &&
9891                           b->cloneable & (1 << a->type));
9892 }
9893
9894 static bool check_single_encoder_cloning(struct intel_crtc *crtc,
9895                                          struct intel_encoder *encoder)
9896 {
9897         struct drm_device *dev = crtc->base.dev;
9898         struct intel_encoder *source_encoder;
9899
9900         for_each_intel_encoder(dev, source_encoder) {
9901                 if (source_encoder->new_crtc != crtc)
9902                         continue;
9903
9904                 if (!encoders_cloneable(encoder, source_encoder))
9905                         return false;
9906         }
9907
9908         return true;
9909 }
9910
9911 static bool check_encoder_cloning(struct intel_crtc *crtc)
9912 {
9913         struct drm_device *dev = crtc->base.dev;
9914         struct intel_encoder *encoder;
9915
9916         for_each_intel_encoder(dev, encoder) {
9917                 if (encoder->new_crtc != crtc)
9918                         continue;
9919
9920                 if (!check_single_encoder_cloning(crtc, encoder))
9921                         return false;
9922         }
9923
9924         return true;
9925 }
9926
9927 static struct intel_crtc_config *
9928 intel_modeset_pipe_config(struct drm_crtc *crtc,
9929                           struct drm_framebuffer *fb,
9930                           struct drm_display_mode *mode)
9931 {
9932         struct drm_device *dev = crtc->dev;
9933         struct intel_encoder *encoder;
9934         struct intel_crtc_config *pipe_config;
9935         int plane_bpp, ret = -EINVAL;
9936         bool retry = true;
9937
9938         if (!check_encoder_cloning(to_intel_crtc(crtc))) {
9939                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
9940                 return ERR_PTR(-EINVAL);
9941         }
9942
9943         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
9944         if (!pipe_config)
9945                 return ERR_PTR(-ENOMEM);
9946
9947         drm_mode_copy(&pipe_config->adjusted_mode, mode);
9948         drm_mode_copy(&pipe_config->requested_mode, mode);
9949
9950         pipe_config->cpu_transcoder =
9951                 (enum transcoder) to_intel_crtc(crtc)->pipe;
9952         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9953
9954         /*
9955          * Sanitize sync polarity flags based on requested ones. If neither
9956          * positive or negative polarity is requested, treat this as meaning
9957          * negative polarity.
9958          */
9959         if (!(pipe_config->adjusted_mode.flags &
9960               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
9961                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
9962
9963         if (!(pipe_config->adjusted_mode.flags &
9964               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
9965                 pipe_config->adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
9966
9967         /* Compute a starting value for pipe_config->pipe_bpp taking the source
9968          * plane pixel format and any sink constraints into account. Returns the
9969          * source plane bpp so that dithering can be selected on mismatches
9970          * after encoders and crtc also have had their say. */
9971         plane_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
9972                                               fb, pipe_config);
9973         if (plane_bpp < 0)
9974                 goto fail;
9975
9976         /*
9977          * Determine the real pipe dimensions. Note that stereo modes can
9978          * increase the actual pipe size due to the frame doubling and
9979          * insertion of additional space for blanks between the frame. This
9980          * is stored in the crtc timings. We use the requested mode to do this
9981          * computation to clearly distinguish it from the adjusted mode, which
9982          * can be changed by the connectors in the below retry loop.
9983          */
9984         drm_mode_set_crtcinfo(&pipe_config->requested_mode, CRTC_STEREO_DOUBLE);
9985         pipe_config->pipe_src_w = pipe_config->requested_mode.crtc_hdisplay;
9986         pipe_config->pipe_src_h = pipe_config->requested_mode.crtc_vdisplay;
9987
9988 encoder_retry:
9989         /* Ensure the port clock defaults are reset when retrying. */
9990         pipe_config->port_clock = 0;
9991         pipe_config->pixel_multiplier = 1;
9992
9993         /* Fill in default crtc timings, allow encoders to overwrite them. */
9994         drm_mode_set_crtcinfo(&pipe_config->adjusted_mode, CRTC_STEREO_DOUBLE);
9995
9996         /* Pass our mode to the connectors and the CRTC to give them a chance to
9997          * adjust it according to limitations or connector properties, and also
9998          * a chance to reject the mode entirely.
9999          */
10000         for_each_intel_encoder(dev, encoder) {
10001
10002                 if (&encoder->new_crtc->base != crtc)
10003                         continue;
10004
10005                 if (!(encoder->compute_config(encoder, pipe_config))) {
10006                         DRM_DEBUG_KMS("Encoder config failure\n");
10007                         goto fail;
10008                 }
10009         }
10010
10011         /* Set default port clock if not overwritten by the encoder. Needs to be
10012          * done afterwards in case the encoder adjusts the mode. */
10013         if (!pipe_config->port_clock)
10014                 pipe_config->port_clock = pipe_config->adjusted_mode.crtc_clock
10015                         * pipe_config->pixel_multiplier;
10016
10017         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10018         if (ret < 0) {
10019                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10020                 goto fail;
10021         }
10022
10023         if (ret == RETRY) {
10024                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10025                         ret = -EINVAL;
10026                         goto fail;
10027                 }
10028
10029                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10030                 retry = false;
10031                 goto encoder_retry;
10032         }
10033
10034         pipe_config->dither = pipe_config->pipe_bpp != plane_bpp;
10035         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
10036                       plane_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10037
10038         return pipe_config;
10039 fail:
10040         kfree(pipe_config);
10041         return ERR_PTR(ret);
10042 }
10043
10044 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
10045  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
10046 static void
10047 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
10048                              unsigned *prepare_pipes, unsigned *disable_pipes)
10049 {
10050         struct intel_crtc *intel_crtc;
10051         struct drm_device *dev = crtc->dev;
10052         struct intel_encoder *encoder;
10053         struct intel_connector *connector;
10054         struct drm_crtc *tmp_crtc;
10055
10056         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
10057
10058         /* Check which crtcs have changed outputs connected to them, these need
10059          * to be part of the prepare_pipes mask. We don't (yet) support global
10060          * modeset across multiple crtcs, so modeset_pipes will only have one
10061          * bit set at most. */
10062         list_for_each_entry(connector, &dev->mode_config.connector_list,
10063                             base.head) {
10064                 if (connector->base.encoder == &connector->new_encoder->base)
10065                         continue;
10066
10067                 if (connector->base.encoder) {
10068                         tmp_crtc = connector->base.encoder->crtc;
10069
10070                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10071                 }
10072
10073                 if (connector->new_encoder)
10074                         *prepare_pipes |=
10075                                 1 << connector->new_encoder->new_crtc->pipe;
10076         }
10077
10078         for_each_intel_encoder(dev, encoder) {
10079                 if (encoder->base.crtc == &encoder->new_crtc->base)
10080                         continue;
10081
10082                 if (encoder->base.crtc) {
10083                         tmp_crtc = encoder->base.crtc;
10084
10085                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10086                 }
10087
10088                 if (encoder->new_crtc)
10089                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
10090         }
10091
10092         /* Check for pipes that will be enabled/disabled ... */
10093         for_each_intel_crtc(dev, intel_crtc) {
10094                 if (intel_crtc->base.enabled == intel_crtc->new_enabled)
10095                         continue;
10096
10097                 if (!intel_crtc->new_enabled)
10098                         *disable_pipes |= 1 << intel_crtc->pipe;
10099                 else
10100                         *prepare_pipes |= 1 << intel_crtc->pipe;
10101         }
10102
10103
10104         /* set_mode is also used to update properties on life display pipes. */
10105         intel_crtc = to_intel_crtc(crtc);
10106         if (intel_crtc->new_enabled)
10107                 *prepare_pipes |= 1 << intel_crtc->pipe;
10108
10109         /*
10110          * For simplicity do a full modeset on any pipe where the output routing
10111          * changed. We could be more clever, but that would require us to be
10112          * more careful with calling the relevant encoder->mode_set functions.
10113          */
10114         if (*prepare_pipes)
10115                 *modeset_pipes = *prepare_pipes;
10116
10117         /* ... and mask these out. */
10118         *modeset_pipes &= ~(*disable_pipes);
10119         *prepare_pipes &= ~(*disable_pipes);
10120
10121         /*
10122          * HACK: We don't (yet) fully support global modesets. intel_set_config
10123          * obies this rule, but the modeset restore mode of
10124          * intel_modeset_setup_hw_state does not.
10125          */
10126         *modeset_pipes &= 1 << intel_crtc->pipe;
10127         *prepare_pipes &= 1 << intel_crtc->pipe;
10128
10129         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
10130                       *modeset_pipes, *prepare_pipes, *disable_pipes);
10131 }
10132
10133 static bool intel_crtc_in_use(struct drm_crtc *crtc)
10134 {
10135         struct drm_encoder *encoder;
10136         struct drm_device *dev = crtc->dev;
10137
10138         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
10139                 if (encoder->crtc == crtc)
10140                         return true;
10141
10142         return false;
10143 }
10144
10145 static void
10146 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
10147 {
10148         struct intel_encoder *intel_encoder;
10149         struct intel_crtc *intel_crtc;
10150         struct drm_connector *connector;
10151
10152         for_each_intel_encoder(dev, intel_encoder) {
10153                 if (!intel_encoder->base.crtc)
10154                         continue;
10155
10156                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
10157
10158                 if (prepare_pipes & (1 << intel_crtc->pipe))
10159                         intel_encoder->connectors_active = false;
10160         }
10161
10162         intel_modeset_commit_output_state(dev);
10163
10164         /* Double check state. */
10165         for_each_intel_crtc(dev, intel_crtc) {
10166                 WARN_ON(intel_crtc->base.enabled != intel_crtc_in_use(&intel_crtc->base));
10167                 WARN_ON(intel_crtc->new_config &&
10168                         intel_crtc->new_config != &intel_crtc->config);
10169                 WARN_ON(intel_crtc->base.enabled != !!intel_crtc->new_config);
10170         }
10171
10172         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10173                 if (!connector->encoder || !connector->encoder->crtc)
10174                         continue;
10175
10176                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
10177
10178                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
10179                         struct drm_property *dpms_property =
10180                                 dev->mode_config.dpms_property;
10181
10182                         connector->dpms = DRM_MODE_DPMS_ON;
10183                         drm_object_property_set_value(&connector->base,
10184                                                          dpms_property,
10185                                                          DRM_MODE_DPMS_ON);
10186
10187                         intel_encoder = to_intel_encoder(connector->encoder);
10188                         intel_encoder->connectors_active = true;
10189                 }
10190         }
10191
10192 }
10193
10194 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10195 {
10196         int diff;
10197
10198         if (clock1 == clock2)
10199                 return true;
10200
10201         if (!clock1 || !clock2)
10202                 return false;
10203
10204         diff = abs(clock1 - clock2);
10205
10206         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10207                 return true;
10208
10209         return false;
10210 }
10211
10212 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
10213         list_for_each_entry((intel_crtc), \
10214                             &(dev)->mode_config.crtc_list, \
10215                             base.head) \
10216                 if (mask & (1 <<(intel_crtc)->pipe))
10217
10218 static bool
10219 intel_pipe_config_compare(struct drm_device *dev,
10220                           struct intel_crtc_config *current_config,
10221                           struct intel_crtc_config *pipe_config)
10222 {
10223 #define PIPE_CONF_CHECK_X(name) \
10224         if (current_config->name != pipe_config->name) { \
10225                 DRM_ERROR("mismatch in " #name " " \
10226                           "(expected 0x%08x, found 0x%08x)\n", \
10227                           current_config->name, \
10228                           pipe_config->name); \
10229                 return false; \
10230         }
10231
10232 #define PIPE_CONF_CHECK_I(name) \
10233         if (current_config->name != pipe_config->name) { \
10234                 DRM_ERROR("mismatch in " #name " " \
10235                           "(expected %i, found %i)\n", \
10236                           current_config->name, \
10237                           pipe_config->name); \
10238                 return false; \
10239         }
10240
10241 /* This is required for BDW+ where there is only one set of registers for
10242  * switching between high and low RR.
10243  * This macro can be used whenever a comparison has to be made between one
10244  * hw state and multiple sw state variables.
10245  */
10246 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
10247         if ((current_config->name != pipe_config->name) && \
10248                 (current_config->alt_name != pipe_config->name)) { \
10249                         DRM_ERROR("mismatch in " #name " " \
10250                                   "(expected %i or %i, found %i)\n", \
10251                                   current_config->name, \
10252                                   current_config->alt_name, \
10253                                   pipe_config->name); \
10254                         return false; \
10255         }
10256
10257 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
10258         if ((current_config->name ^ pipe_config->name) & (mask)) { \
10259                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
10260                           "(expected %i, found %i)\n", \
10261                           current_config->name & (mask), \
10262                           pipe_config->name & (mask)); \
10263                 return false; \
10264         }
10265
10266 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
10267         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
10268                 DRM_ERROR("mismatch in " #name " " \
10269                           "(expected %i, found %i)\n", \
10270                           current_config->name, \
10271                           pipe_config->name); \
10272                 return false; \
10273         }
10274
10275 #define PIPE_CONF_QUIRK(quirk)  \
10276         ((current_config->quirks | pipe_config->quirks) & (quirk))
10277
10278         PIPE_CONF_CHECK_I(cpu_transcoder);
10279
10280         PIPE_CONF_CHECK_I(has_pch_encoder);
10281         PIPE_CONF_CHECK_I(fdi_lanes);
10282         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
10283         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
10284         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
10285         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
10286         PIPE_CONF_CHECK_I(fdi_m_n.tu);
10287
10288         PIPE_CONF_CHECK_I(has_dp_encoder);
10289
10290         if (INTEL_INFO(dev)->gen < 8) {
10291                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
10292                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
10293                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
10294                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
10295                 PIPE_CONF_CHECK_I(dp_m_n.tu);
10296
10297                 if (current_config->has_drrs) {
10298                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
10299                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
10300                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
10301                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
10302                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
10303                 }
10304         } else {
10305                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
10306                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
10307                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
10308                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
10309                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
10310         }
10311
10312         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hdisplay);
10313         PIPE_CONF_CHECK_I(adjusted_mode.crtc_htotal);
10314         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hblank_start);
10315         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hblank_end);
10316         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hsync_start);
10317         PIPE_CONF_CHECK_I(adjusted_mode.crtc_hsync_end);
10318
10319         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vdisplay);
10320         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vtotal);
10321         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vblank_start);
10322         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vblank_end);
10323         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vsync_start);
10324         PIPE_CONF_CHECK_I(adjusted_mode.crtc_vsync_end);
10325
10326         PIPE_CONF_CHECK_I(pixel_multiplier);
10327         PIPE_CONF_CHECK_I(has_hdmi_sink);
10328         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
10329             IS_VALLEYVIEW(dev))
10330                 PIPE_CONF_CHECK_I(limited_color_range);
10331
10332         PIPE_CONF_CHECK_I(has_audio);
10333
10334         PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
10335                               DRM_MODE_FLAG_INTERLACE);
10336
10337         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
10338                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
10339                                       DRM_MODE_FLAG_PHSYNC);
10340                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
10341                                       DRM_MODE_FLAG_NHSYNC);
10342                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
10343                                       DRM_MODE_FLAG_PVSYNC);
10344                 PIPE_CONF_CHECK_FLAGS(adjusted_mode.flags,
10345                                       DRM_MODE_FLAG_NVSYNC);
10346         }
10347
10348         PIPE_CONF_CHECK_I(pipe_src_w);
10349         PIPE_CONF_CHECK_I(pipe_src_h);
10350
10351         /*
10352          * FIXME: BIOS likes to set up a cloned config with lvds+external
10353          * screen. Since we don't yet re-compute the pipe config when moving
10354          * just the lvds port away to another pipe the sw tracking won't match.
10355          *
10356          * Proper atomic modesets with recomputed global state will fix this.
10357          * Until then just don't check gmch state for inherited modes.
10358          */
10359         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
10360                 PIPE_CONF_CHECK_I(gmch_pfit.control);
10361                 /* pfit ratios are autocomputed by the hw on gen4+ */
10362                 if (INTEL_INFO(dev)->gen < 4)
10363                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
10364                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
10365         }
10366
10367         PIPE_CONF_CHECK_I(pch_pfit.enabled);
10368         if (current_config->pch_pfit.enabled) {
10369                 PIPE_CONF_CHECK_I(pch_pfit.pos);
10370                 PIPE_CONF_CHECK_I(pch_pfit.size);
10371         }
10372
10373         /* BDW+ don't expose a synchronous way to read the state */
10374         if (IS_HASWELL(dev))
10375                 PIPE_CONF_CHECK_I(ips_enabled);
10376
10377         PIPE_CONF_CHECK_I(double_wide);
10378
10379         PIPE_CONF_CHECK_X(ddi_pll_sel);
10380
10381         PIPE_CONF_CHECK_I(shared_dpll);
10382         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
10383         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
10384         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
10385         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
10386         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
10387
10388         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
10389                 PIPE_CONF_CHECK_I(pipe_bpp);
10390
10391         PIPE_CONF_CHECK_CLOCK_FUZZY(adjusted_mode.crtc_clock);
10392         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
10393
10394 #undef PIPE_CONF_CHECK_X
10395 #undef PIPE_CONF_CHECK_I
10396 #undef PIPE_CONF_CHECK_I_ALT
10397 #undef PIPE_CONF_CHECK_FLAGS
10398 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
10399 #undef PIPE_CONF_QUIRK
10400
10401         return true;
10402 }
10403
10404 static void
10405 check_connector_state(struct drm_device *dev)
10406 {
10407         struct intel_connector *connector;
10408
10409         list_for_each_entry(connector, &dev->mode_config.connector_list,
10410                             base.head) {
10411                 /* This also checks the encoder/connector hw state with the
10412                  * ->get_hw_state callbacks. */
10413                 intel_connector_check_state(connector);
10414
10415                 WARN(&connector->new_encoder->base != connector->base.encoder,
10416                      "connector's staged encoder doesn't match current encoder\n");
10417         }
10418 }
10419
10420 static void
10421 check_encoder_state(struct drm_device *dev)
10422 {
10423         struct intel_encoder *encoder;
10424         struct intel_connector *connector;
10425
10426         for_each_intel_encoder(dev, encoder) {
10427                 bool enabled = false;
10428                 bool active = false;
10429                 enum pipe pipe, tracked_pipe;
10430
10431                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
10432                               encoder->base.base.id,
10433                               encoder->base.name);
10434
10435                 WARN(&encoder->new_crtc->base != encoder->base.crtc,
10436                      "encoder's stage crtc doesn't match current crtc\n");
10437                 WARN(encoder->connectors_active && !encoder->base.crtc,
10438                      "encoder's active_connectors set, but no crtc\n");
10439
10440                 list_for_each_entry(connector, &dev->mode_config.connector_list,
10441                                     base.head) {
10442                         if (connector->base.encoder != &encoder->base)
10443                                 continue;
10444                         enabled = true;
10445                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
10446                                 active = true;
10447                 }
10448                 /*
10449                  * for MST connectors if we unplug the connector is gone
10450                  * away but the encoder is still connected to a crtc
10451                  * until a modeset happens in response to the hotplug.
10452                  */
10453                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
10454                         continue;
10455
10456                 WARN(!!encoder->base.crtc != enabled,
10457                      "encoder's enabled state mismatch "
10458                      "(expected %i, found %i)\n",
10459                      !!encoder->base.crtc, enabled);
10460                 WARN(active && !encoder->base.crtc,
10461                      "active encoder with no crtc\n");
10462
10463                 WARN(encoder->connectors_active != active,
10464                      "encoder's computed active state doesn't match tracked active state "
10465                      "(expected %i, found %i)\n", active, encoder->connectors_active);
10466
10467                 active = encoder->get_hw_state(encoder, &pipe);
10468                 WARN(active != encoder->connectors_active,
10469                      "encoder's hw state doesn't match sw tracking "
10470                      "(expected %i, found %i)\n",
10471                      encoder->connectors_active, active);
10472
10473                 if (!encoder->base.crtc)
10474                         continue;
10475
10476                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
10477                 WARN(active && pipe != tracked_pipe,
10478                      "active encoder's pipe doesn't match"
10479                      "(expected %i, found %i)\n",
10480                      tracked_pipe, pipe);
10481
10482         }
10483 }
10484
10485 static void
10486 check_crtc_state(struct drm_device *dev)
10487 {
10488         struct drm_i915_private *dev_priv = dev->dev_private;
10489         struct intel_crtc *crtc;
10490         struct intel_encoder *encoder;
10491         struct intel_crtc_config pipe_config;
10492
10493         for_each_intel_crtc(dev, crtc) {
10494                 bool enabled = false;
10495                 bool active = false;
10496
10497                 memset(&pipe_config, 0, sizeof(pipe_config));
10498
10499                 DRM_DEBUG_KMS("[CRTC:%d]\n",
10500                               crtc->base.base.id);
10501
10502                 WARN(crtc->active && !crtc->base.enabled,
10503                      "active crtc, but not enabled in sw tracking\n");
10504
10505                 for_each_intel_encoder(dev, encoder) {
10506                         if (encoder->base.crtc != &crtc->base)
10507                                 continue;
10508                         enabled = true;
10509                         if (encoder->connectors_active)
10510                                 active = true;
10511                 }
10512
10513                 WARN(active != crtc->active,
10514                      "crtc's computed active state doesn't match tracked active state "
10515                      "(expected %i, found %i)\n", active, crtc->active);
10516                 WARN(enabled != crtc->base.enabled,
10517                      "crtc's computed enabled state doesn't match tracked enabled state "
10518                      "(expected %i, found %i)\n", enabled, crtc->base.enabled);
10519
10520                 active = dev_priv->display.get_pipe_config(crtc,
10521                                                            &pipe_config);
10522
10523                 /* hw state is inconsistent with the pipe quirk */
10524                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
10525                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
10526                         active = crtc->active;
10527
10528                 for_each_intel_encoder(dev, encoder) {
10529                         enum pipe pipe;
10530                         if (encoder->base.crtc != &crtc->base)
10531                                 continue;
10532                         if (encoder->get_hw_state(encoder, &pipe))
10533                                 encoder->get_config(encoder, &pipe_config);
10534                 }
10535
10536                 WARN(crtc->active != active,
10537                      "crtc active state doesn't match with hw state "
10538                      "(expected %i, found %i)\n", crtc->active, active);
10539
10540                 if (active &&
10541                     !intel_pipe_config_compare(dev, &crtc->config, &pipe_config)) {
10542                         WARN(1, "pipe state doesn't match!\n");
10543                         intel_dump_pipe_config(crtc, &pipe_config,
10544                                                "[hw state]");
10545                         intel_dump_pipe_config(crtc, &crtc->config,
10546                                                "[sw state]");
10547                 }
10548         }
10549 }
10550
10551 static void
10552 check_shared_dpll_state(struct drm_device *dev)
10553 {
10554         struct drm_i915_private *dev_priv = dev->dev_private;
10555         struct intel_crtc *crtc;
10556         struct intel_dpll_hw_state dpll_hw_state;
10557         int i;
10558
10559         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
10560                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
10561                 int enabled_crtcs = 0, active_crtcs = 0;
10562                 bool active;
10563
10564                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
10565
10566                 DRM_DEBUG_KMS("%s\n", pll->name);
10567
10568                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
10569
10570                 WARN(pll->active > pll->refcount,
10571                      "more active pll users than references: %i vs %i\n",
10572                      pll->active, pll->refcount);
10573                 WARN(pll->active && !pll->on,
10574                      "pll in active use but not on in sw tracking\n");
10575                 WARN(pll->on && !pll->active,
10576                      "pll in on but not on in use in sw tracking\n");
10577                 WARN(pll->on != active,
10578                      "pll on state mismatch (expected %i, found %i)\n",
10579                      pll->on, active);
10580
10581                 for_each_intel_crtc(dev, crtc) {
10582                         if (crtc->base.enabled && intel_crtc_to_shared_dpll(crtc) == pll)
10583                                 enabled_crtcs++;
10584                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
10585                                 active_crtcs++;
10586                 }
10587                 WARN(pll->active != active_crtcs,
10588                      "pll active crtcs mismatch (expected %i, found %i)\n",
10589                      pll->active, active_crtcs);
10590                 WARN(pll->refcount != enabled_crtcs,
10591                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
10592                      pll->refcount, enabled_crtcs);
10593
10594                 WARN(pll->on && memcmp(&pll->hw_state, &dpll_hw_state,
10595                                        sizeof(dpll_hw_state)),
10596                      "pll hw state mismatch\n");
10597         }
10598 }
10599
10600 void
10601 intel_modeset_check_state(struct drm_device *dev)
10602 {
10603         check_connector_state(dev);
10604         check_encoder_state(dev);
10605         check_crtc_state(dev);
10606         check_shared_dpll_state(dev);
10607 }
10608
10609 void ironlake_check_encoder_dotclock(const struct intel_crtc_config *pipe_config,
10610                                      int dotclock)
10611 {
10612         /*
10613          * FDI already provided one idea for the dotclock.
10614          * Yell if the encoder disagrees.
10615          */
10616         WARN(!intel_fuzzy_clock_check(pipe_config->adjusted_mode.crtc_clock, dotclock),
10617              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
10618              pipe_config->adjusted_mode.crtc_clock, dotclock);
10619 }
10620
10621 static void update_scanline_offset(struct intel_crtc *crtc)
10622 {
10623         struct drm_device *dev = crtc->base.dev;
10624
10625         /*
10626          * The scanline counter increments at the leading edge of hsync.
10627          *
10628          * On most platforms it starts counting from vtotal-1 on the
10629          * first active line. That means the scanline counter value is
10630          * always one less than what we would expect. Ie. just after
10631          * start of vblank, which also occurs at start of hsync (on the
10632          * last active line), the scanline counter will read vblank_start-1.
10633          *
10634          * On gen2 the scanline counter starts counting from 1 instead
10635          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
10636          * to keep the value positive), instead of adding one.
10637          *
10638          * On HSW+ the behaviour of the scanline counter depends on the output
10639          * type. For DP ports it behaves like most other platforms, but on HDMI
10640          * there's an extra 1 line difference. So we need to add two instead of
10641          * one to the value.
10642          */
10643         if (IS_GEN2(dev)) {
10644                 const struct drm_display_mode *mode = &crtc->config.adjusted_mode;
10645                 int vtotal;
10646
10647                 vtotal = mode->crtc_vtotal;
10648                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
10649                         vtotal /= 2;
10650
10651                 crtc->scanline_offset = vtotal - 1;
10652         } else if (HAS_DDI(dev) &&
10653                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
10654                 crtc->scanline_offset = 2;
10655         } else
10656                 crtc->scanline_offset = 1;
10657 }
10658
10659 static int __intel_set_mode(struct drm_crtc *crtc,
10660                             struct drm_display_mode *mode,
10661                             int x, int y, struct drm_framebuffer *fb)
10662 {
10663         struct drm_device *dev = crtc->dev;
10664         struct drm_i915_private *dev_priv = dev->dev_private;
10665         struct drm_display_mode *saved_mode;
10666         struct intel_crtc_config *pipe_config = NULL;
10667         struct intel_crtc *intel_crtc;
10668         unsigned disable_pipes, prepare_pipes, modeset_pipes;
10669         int ret = 0;
10670
10671         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
10672         if (!saved_mode)
10673                 return -ENOMEM;
10674
10675         intel_modeset_affected_pipes(crtc, &modeset_pipes,
10676                                      &prepare_pipes, &disable_pipes);
10677
10678         *saved_mode = crtc->mode;
10679
10680         /* Hack: Because we don't (yet) support global modeset on multiple
10681          * crtcs, we don't keep track of the new mode for more than one crtc.
10682          * Hence simply check whether any bit is set in modeset_pipes in all the
10683          * pieces of code that are not yet converted to deal with mutliple crtcs
10684          * changing their mode at the same time. */
10685         if (modeset_pipes) {
10686                 pipe_config = intel_modeset_pipe_config(crtc, fb, mode);
10687                 if (IS_ERR(pipe_config)) {
10688                         ret = PTR_ERR(pipe_config);
10689                         pipe_config = NULL;
10690
10691                         goto out;
10692                 }
10693                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
10694                                        "[modeset]");
10695                 to_intel_crtc(crtc)->new_config = pipe_config;
10696         }
10697
10698         /*
10699          * See if the config requires any additional preparation, e.g.
10700          * to adjust global state with pipes off.  We need to do this
10701          * here so we can get the modeset_pipe updated config for the new
10702          * mode set on this crtc.  For other crtcs we need to use the
10703          * adjusted_mode bits in the crtc directly.
10704          */
10705         if (IS_VALLEYVIEW(dev)) {
10706                 valleyview_modeset_global_pipes(dev, &prepare_pipes);
10707
10708                 /* may have added more to prepare_pipes than we should */
10709                 prepare_pipes &= ~disable_pipes;
10710         }
10711
10712         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
10713                 intel_crtc_disable(&intel_crtc->base);
10714
10715         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
10716                 if (intel_crtc->base.enabled)
10717                         dev_priv->display.crtc_disable(&intel_crtc->base);
10718         }
10719
10720         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
10721          * to set it here already despite that we pass it down the callchain.
10722          */
10723         if (modeset_pipes) {
10724                 crtc->mode = *mode;
10725                 /* mode_set/enable/disable functions rely on a correct pipe
10726                  * config. */
10727                 to_intel_crtc(crtc)->config = *pipe_config;
10728                 to_intel_crtc(crtc)->new_config = &to_intel_crtc(crtc)->config;
10729
10730                 /*
10731                  * Calculate and store various constants which
10732                  * are later needed by vblank and swap-completion
10733                  * timestamping. They are derived from true hwmode.
10734                  */
10735                 drm_calc_timestamping_constants(crtc,
10736                                                 &pipe_config->adjusted_mode);
10737         }
10738
10739         /* Only after disabling all output pipelines that will be changed can we
10740          * update the the output configuration. */
10741         intel_modeset_update_state(dev, prepare_pipes);
10742
10743         if (dev_priv->display.modeset_global_resources)
10744                 dev_priv->display.modeset_global_resources(dev);
10745
10746         /* Set up the DPLL and any encoders state that needs to adjust or depend
10747          * on the DPLL.
10748          */
10749         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
10750                 struct drm_framebuffer *old_fb = crtc->primary->fb;
10751                 struct drm_i915_gem_object *old_obj = intel_fb_obj(old_fb);
10752                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10753
10754                 mutex_lock(&dev->struct_mutex);
10755                 ret = intel_pin_and_fence_fb_obj(dev,
10756                                                  obj,
10757                                                  NULL);
10758                 if (ret != 0) {
10759                         DRM_ERROR("pin & fence failed\n");
10760                         mutex_unlock(&dev->struct_mutex);
10761                         goto done;
10762                 }
10763                 if (old_fb)
10764                         intel_unpin_fb_obj(old_obj);
10765                 i915_gem_track_fb(old_obj, obj,
10766                                   INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe));
10767                 mutex_unlock(&dev->struct_mutex);
10768
10769                 crtc->primary->fb = fb;
10770                 crtc->x = x;
10771                 crtc->y = y;
10772
10773                 ret = dev_priv->display.crtc_mode_set(intel_crtc, x, y, fb);
10774                 if (ret)
10775                         goto done;
10776         }
10777
10778         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
10779         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
10780                 update_scanline_offset(intel_crtc);
10781
10782                 dev_priv->display.crtc_enable(&intel_crtc->base);
10783         }
10784
10785         /* FIXME: add subpixel order */
10786 done:
10787         if (ret && crtc->enabled)
10788                 crtc->mode = *saved_mode;
10789
10790 out:
10791         kfree(pipe_config);
10792         kfree(saved_mode);
10793         return ret;
10794 }
10795
10796 static int intel_set_mode(struct drm_crtc *crtc,
10797                           struct drm_display_mode *mode,
10798                           int x, int y, struct drm_framebuffer *fb)
10799 {
10800         int ret;
10801
10802         ret = __intel_set_mode(crtc, mode, x, y, fb);
10803
10804         if (ret == 0)
10805                 intel_modeset_check_state(crtc->dev);
10806
10807         return ret;
10808 }
10809
10810 void intel_crtc_restore_mode(struct drm_crtc *crtc)
10811 {
10812         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb);
10813 }
10814
10815 #undef for_each_intel_crtc_masked
10816
10817 static void intel_set_config_free(struct intel_set_config *config)
10818 {
10819         if (!config)
10820                 return;
10821
10822         kfree(config->save_connector_encoders);
10823         kfree(config->save_encoder_crtcs);
10824         kfree(config->save_crtc_enabled);
10825         kfree(config);
10826 }
10827
10828 static int intel_set_config_save_state(struct drm_device *dev,
10829                                        struct intel_set_config *config)
10830 {
10831         struct drm_crtc *crtc;
10832         struct drm_encoder *encoder;
10833         struct drm_connector *connector;
10834         int count;
10835
10836         config->save_crtc_enabled =
10837                 kcalloc(dev->mode_config.num_crtc,
10838                         sizeof(bool), GFP_KERNEL);
10839         if (!config->save_crtc_enabled)
10840                 return -ENOMEM;
10841
10842         config->save_encoder_crtcs =
10843                 kcalloc(dev->mode_config.num_encoder,
10844                         sizeof(struct drm_crtc *), GFP_KERNEL);
10845         if (!config->save_encoder_crtcs)
10846                 return -ENOMEM;
10847
10848         config->save_connector_encoders =
10849                 kcalloc(dev->mode_config.num_connector,
10850                         sizeof(struct drm_encoder *), GFP_KERNEL);
10851         if (!config->save_connector_encoders)
10852                 return -ENOMEM;
10853
10854         /* Copy data. Note that driver private data is not affected.
10855          * Should anything bad happen only the expected state is
10856          * restored, not the drivers personal bookkeeping.
10857          */
10858         count = 0;
10859         for_each_crtc(dev, crtc) {
10860                 config->save_crtc_enabled[count++] = crtc->enabled;
10861         }
10862
10863         count = 0;
10864         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
10865                 config->save_encoder_crtcs[count++] = encoder->crtc;
10866         }
10867
10868         count = 0;
10869         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10870                 config->save_connector_encoders[count++] = connector->encoder;
10871         }
10872
10873         return 0;
10874 }
10875
10876 static void intel_set_config_restore_state(struct drm_device *dev,
10877                                            struct intel_set_config *config)
10878 {
10879         struct intel_crtc *crtc;
10880         struct intel_encoder *encoder;
10881         struct intel_connector *connector;
10882         int count;
10883
10884         count = 0;
10885         for_each_intel_crtc(dev, crtc) {
10886                 crtc->new_enabled = config->save_crtc_enabled[count++];
10887
10888                 if (crtc->new_enabled)
10889                         crtc->new_config = &crtc->config;
10890                 else
10891                         crtc->new_config = NULL;
10892         }
10893
10894         count = 0;
10895         for_each_intel_encoder(dev, encoder) {
10896                 encoder->new_crtc =
10897                         to_intel_crtc(config->save_encoder_crtcs[count++]);
10898         }
10899
10900         count = 0;
10901         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
10902                 connector->new_encoder =
10903                         to_intel_encoder(config->save_connector_encoders[count++]);
10904         }
10905 }
10906
10907 static bool
10908 is_crtc_connector_off(struct drm_mode_set *set)
10909 {
10910         int i;
10911
10912         if (set->num_connectors == 0)
10913                 return false;
10914
10915         if (WARN_ON(set->connectors == NULL))
10916                 return false;
10917
10918         for (i = 0; i < set->num_connectors; i++)
10919                 if (set->connectors[i]->encoder &&
10920                     set->connectors[i]->encoder->crtc == set->crtc &&
10921                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
10922                         return true;
10923
10924         return false;
10925 }
10926
10927 static void
10928 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
10929                                       struct intel_set_config *config)
10930 {
10931
10932         /* We should be able to check here if the fb has the same properties
10933          * and then just flip_or_move it */
10934         if (is_crtc_connector_off(set)) {
10935                 config->mode_changed = true;
10936         } else if (set->crtc->primary->fb != set->fb) {
10937                 /*
10938                  * If we have no fb, we can only flip as long as the crtc is
10939                  * active, otherwise we need a full mode set.  The crtc may
10940                  * be active if we've only disabled the primary plane, or
10941                  * in fastboot situations.
10942                  */
10943                 if (set->crtc->primary->fb == NULL) {
10944                         struct intel_crtc *intel_crtc =
10945                                 to_intel_crtc(set->crtc);
10946
10947                         if (intel_crtc->active) {
10948                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
10949                                 config->fb_changed = true;
10950                         } else {
10951                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
10952                                 config->mode_changed = true;
10953                         }
10954                 } else if (set->fb == NULL) {
10955                         config->mode_changed = true;
10956                 } else if (set->fb->pixel_format !=
10957                            set->crtc->primary->fb->pixel_format) {
10958                         config->mode_changed = true;
10959                 } else {
10960                         config->fb_changed = true;
10961                 }
10962         }
10963
10964         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
10965                 config->fb_changed = true;
10966
10967         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
10968                 DRM_DEBUG_KMS("modes are different, full mode set\n");
10969                 drm_mode_debug_printmodeline(&set->crtc->mode);
10970                 drm_mode_debug_printmodeline(set->mode);
10971                 config->mode_changed = true;
10972         }
10973
10974         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
10975                         set->crtc->base.id, config->mode_changed, config->fb_changed);
10976 }
10977
10978 static int
10979 intel_modeset_stage_output_state(struct drm_device *dev,
10980                                  struct drm_mode_set *set,
10981                                  struct intel_set_config *config)
10982 {
10983         struct intel_connector *connector;
10984         struct intel_encoder *encoder;
10985         struct intel_crtc *crtc;
10986         int ro;
10987
10988         /* The upper layers ensure that we either disable a crtc or have a list
10989          * of connectors. For paranoia, double-check this. */
10990         WARN_ON(!set->fb && (set->num_connectors != 0));
10991         WARN_ON(set->fb && (set->num_connectors == 0));
10992
10993         list_for_each_entry(connector, &dev->mode_config.connector_list,
10994                             base.head) {
10995                 /* Otherwise traverse passed in connector list and get encoders
10996                  * for them. */
10997                 for (ro = 0; ro < set->num_connectors; ro++) {
10998                         if (set->connectors[ro] == &connector->base) {
10999                                 connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
11000                                 break;
11001                         }
11002                 }
11003
11004                 /* If we disable the crtc, disable all its connectors. Also, if
11005                  * the connector is on the changing crtc but not on the new
11006                  * connector list, disable it. */
11007                 if ((!set->fb || ro == set->num_connectors) &&
11008                     connector->base.encoder &&
11009                     connector->base.encoder->crtc == set->crtc) {
11010                         connector->new_encoder = NULL;
11011
11012                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
11013                                 connector->base.base.id,
11014                                 connector->base.name);
11015                 }
11016
11017
11018                 if (&connector->new_encoder->base != connector->base.encoder) {
11019                         DRM_DEBUG_KMS("encoder changed, full mode switch\n");
11020                         config->mode_changed = true;
11021                 }
11022         }
11023         /* connector->new_encoder is now updated for all connectors. */
11024
11025         /* Update crtc of enabled connectors. */
11026         list_for_each_entry(connector, &dev->mode_config.connector_list,
11027                             base.head) {
11028                 struct drm_crtc *new_crtc;
11029
11030                 if (!connector->new_encoder)
11031                         continue;
11032
11033                 new_crtc = connector->new_encoder->base.crtc;
11034
11035                 for (ro = 0; ro < set->num_connectors; ro++) {
11036                         if (set->connectors[ro] == &connector->base)
11037                                 new_crtc = set->crtc;
11038                 }
11039
11040                 /* Make sure the new CRTC will work with the encoder */
11041                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
11042                                          new_crtc)) {
11043                         return -EINVAL;
11044                 }
11045                 connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
11046
11047                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
11048                         connector->base.base.id,
11049                         connector->base.name,
11050                         new_crtc->base.id);
11051         }
11052
11053         /* Check for any encoders that needs to be disabled. */
11054         for_each_intel_encoder(dev, encoder) {
11055                 int num_connectors = 0;
11056                 list_for_each_entry(connector,
11057                                     &dev->mode_config.connector_list,
11058                                     base.head) {
11059                         if (connector->new_encoder == encoder) {
11060                                 WARN_ON(!connector->new_encoder->new_crtc);
11061                                 num_connectors++;
11062                         }
11063                 }
11064
11065                 if (num_connectors == 0)
11066                         encoder->new_crtc = NULL;
11067                 else if (num_connectors > 1)
11068                         return -EINVAL;
11069
11070                 /* Only now check for crtc changes so we don't miss encoders
11071                  * that will be disabled. */
11072                 if (&encoder->new_crtc->base != encoder->base.crtc) {
11073                         DRM_DEBUG_KMS("crtc changed, full mode switch\n");
11074                         config->mode_changed = true;
11075                 }
11076         }
11077         /* Now we've also updated encoder->new_crtc for all encoders. */
11078         list_for_each_entry(connector, &dev->mode_config.connector_list,
11079                             base.head) {
11080                 if (connector->new_encoder)
11081                         if (connector->new_encoder != connector->encoder)
11082                                 connector->encoder = connector->new_encoder;
11083         }
11084         for_each_intel_crtc(dev, crtc) {
11085                 crtc->new_enabled = false;
11086
11087                 for_each_intel_encoder(dev, encoder) {
11088                         if (encoder->new_crtc == crtc) {
11089                                 crtc->new_enabled = true;
11090                                 break;
11091                         }
11092                 }
11093
11094                 if (crtc->new_enabled != crtc->base.enabled) {
11095                         DRM_DEBUG_KMS("crtc %sabled, full mode switch\n",
11096                                       crtc->new_enabled ? "en" : "dis");
11097                         config->mode_changed = true;
11098                 }
11099
11100                 if (crtc->new_enabled)
11101                         crtc->new_config = &crtc->config;
11102                 else
11103                         crtc->new_config = NULL;
11104         }
11105
11106         return 0;
11107 }
11108
11109 static void disable_crtc_nofb(struct intel_crtc *crtc)
11110 {
11111         struct drm_device *dev = crtc->base.dev;
11112         struct intel_encoder *encoder;
11113         struct intel_connector *connector;
11114
11115         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
11116                       pipe_name(crtc->pipe));
11117
11118         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
11119                 if (connector->new_encoder &&
11120                     connector->new_encoder->new_crtc == crtc)
11121                         connector->new_encoder = NULL;
11122         }
11123
11124         for_each_intel_encoder(dev, encoder) {
11125                 if (encoder->new_crtc == crtc)
11126                         encoder->new_crtc = NULL;
11127         }
11128
11129         crtc->new_enabled = false;
11130         crtc->new_config = NULL;
11131 }
11132
11133 static int intel_crtc_set_config(struct drm_mode_set *set)
11134 {
11135         struct drm_device *dev;
11136         struct drm_mode_set save_set;
11137         struct intel_set_config *config;
11138         int ret;
11139
11140         BUG_ON(!set);
11141         BUG_ON(!set->crtc);
11142         BUG_ON(!set->crtc->helper_private);
11143
11144         /* Enforce sane interface api - has been abused by the fb helper. */
11145         BUG_ON(!set->mode && set->fb);
11146         BUG_ON(set->fb && set->num_connectors == 0);
11147
11148         if (set->fb) {
11149                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
11150                                 set->crtc->base.id, set->fb->base.id,
11151                                 (int)set->num_connectors, set->x, set->y);
11152         } else {
11153                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
11154         }
11155
11156         dev = set->crtc->dev;
11157
11158         ret = -ENOMEM;
11159         config = kzalloc(sizeof(*config), GFP_KERNEL);
11160         if (!config)
11161                 goto out_config;
11162
11163         ret = intel_set_config_save_state(dev, config);
11164         if (ret)
11165                 goto out_config;
11166
11167         save_set.crtc = set->crtc;
11168         save_set.mode = &set->crtc->mode;
11169         save_set.x = set->crtc->x;
11170         save_set.y = set->crtc->y;
11171         save_set.fb = set->crtc->primary->fb;
11172
11173         /* Compute whether we need a full modeset, only an fb base update or no
11174          * change at all. In the future we might also check whether only the
11175          * mode changed, e.g. for LVDS where we only change the panel fitter in
11176          * such cases. */
11177         intel_set_config_compute_mode_changes(set, config);
11178
11179         ret = intel_modeset_stage_output_state(dev, set, config);
11180         if (ret)
11181                 goto fail;
11182
11183         if (config->mode_changed) {
11184                 ret = intel_set_mode(set->crtc, set->mode,
11185                                      set->x, set->y, set->fb);
11186         } else if (config->fb_changed) {
11187                 struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
11188
11189                 intel_crtc_wait_for_pending_flips(set->crtc);
11190
11191                 ret = intel_pipe_set_base(set->crtc,
11192                                           set->x, set->y, set->fb);
11193
11194                 /*
11195                  * We need to make sure the primary plane is re-enabled if it
11196                  * has previously been turned off.
11197                  */
11198                 if (!intel_crtc->primary_enabled && ret == 0) {
11199                         WARN_ON(!intel_crtc->active);
11200                         intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
11201                 }
11202
11203                 /*
11204                  * In the fastboot case this may be our only check of the
11205                  * state after boot.  It would be better to only do it on
11206                  * the first update, but we don't have a nice way of doing that
11207                  * (and really, set_config isn't used much for high freq page
11208                  * flipping, so increasing its cost here shouldn't be a big
11209                  * deal).
11210                  */
11211                 if (i915.fastboot && ret == 0)
11212                         intel_modeset_check_state(set->crtc->dev);
11213         }
11214
11215         if (ret) {
11216                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
11217                               set->crtc->base.id, ret);
11218 fail:
11219                 intel_set_config_restore_state(dev, config);
11220
11221                 /*
11222                  * HACK: if the pipe was on, but we didn't have a framebuffer,
11223                  * force the pipe off to avoid oopsing in the modeset code
11224                  * due to fb==NULL. This should only happen during boot since
11225                  * we don't yet reconstruct the FB from the hardware state.
11226                  */
11227                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
11228                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
11229
11230                 /* Try to restore the config */
11231                 if (config->mode_changed &&
11232                     intel_set_mode(save_set.crtc, save_set.mode,
11233                                    save_set.x, save_set.y, save_set.fb))
11234                         DRM_ERROR("failed to restore config after modeset failure\n");
11235         }
11236
11237 out_config:
11238         intel_set_config_free(config);
11239         return ret;
11240 }
11241
11242 static const struct drm_crtc_funcs intel_crtc_funcs = {
11243         .gamma_set = intel_crtc_gamma_set,
11244         .set_config = intel_crtc_set_config,
11245         .destroy = intel_crtc_destroy,
11246         .page_flip = intel_crtc_page_flip,
11247 };
11248
11249 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
11250                                       struct intel_shared_dpll *pll,
11251                                       struct intel_dpll_hw_state *hw_state)
11252 {
11253         uint32_t val;
11254
11255         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
11256                 return false;
11257
11258         val = I915_READ(PCH_DPLL(pll->id));
11259         hw_state->dpll = val;
11260         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
11261         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
11262
11263         return val & DPLL_VCO_ENABLE;
11264 }
11265
11266 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
11267                                   struct intel_shared_dpll *pll)
11268 {
11269         I915_WRITE(PCH_FP0(pll->id), pll->hw_state.fp0);
11270         I915_WRITE(PCH_FP1(pll->id), pll->hw_state.fp1);
11271 }
11272
11273 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
11274                                 struct intel_shared_dpll *pll)
11275 {
11276         /* PCH refclock must be enabled first */
11277         ibx_assert_pch_refclk_enabled(dev_priv);
11278
11279         I915_WRITE(PCH_DPLL(pll->id), pll->hw_state.dpll);
11280
11281         /* Wait for the clocks to stabilize. */
11282         POSTING_READ(PCH_DPLL(pll->id));
11283         udelay(150);
11284
11285         /* The pixel multiplier can only be updated once the
11286          * DPLL is enabled and the clocks are stable.
11287          *
11288          * So write it again.
11289          */
11290         I915_WRITE(PCH_DPLL(pll->id), pll->hw_state.dpll);
11291         POSTING_READ(PCH_DPLL(pll->id));
11292         udelay(200);
11293 }
11294
11295 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
11296                                  struct intel_shared_dpll *pll)
11297 {
11298         struct drm_device *dev = dev_priv->dev;
11299         struct intel_crtc *crtc;
11300
11301         /* Make sure no transcoder isn't still depending on us. */
11302         for_each_intel_crtc(dev, crtc) {
11303                 if (intel_crtc_to_shared_dpll(crtc) == pll)
11304                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
11305         }
11306
11307         I915_WRITE(PCH_DPLL(pll->id), 0);
11308         POSTING_READ(PCH_DPLL(pll->id));
11309         udelay(200);
11310 }
11311
11312 static char *ibx_pch_dpll_names[] = {
11313         "PCH DPLL A",
11314         "PCH DPLL B",
11315 };
11316
11317 static void ibx_pch_dpll_init(struct drm_device *dev)
11318 {
11319         struct drm_i915_private *dev_priv = dev->dev_private;
11320         int i;
11321
11322         dev_priv->num_shared_dpll = 2;
11323
11324         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11325                 dev_priv->shared_dplls[i].id = i;
11326                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
11327                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
11328                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
11329                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
11330                 dev_priv->shared_dplls[i].get_hw_state =
11331                         ibx_pch_dpll_get_hw_state;
11332         }
11333 }
11334
11335 static void intel_shared_dpll_init(struct drm_device *dev)
11336 {
11337         struct drm_i915_private *dev_priv = dev->dev_private;
11338
11339         if (HAS_DDI(dev))
11340                 intel_ddi_pll_init(dev);
11341         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
11342                 ibx_pch_dpll_init(dev);
11343         else
11344                 dev_priv->num_shared_dpll = 0;
11345
11346         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
11347 }
11348
11349 static int
11350 intel_primary_plane_disable(struct drm_plane *plane)
11351 {
11352         struct drm_device *dev = plane->dev;
11353         struct intel_crtc *intel_crtc;
11354
11355         if (!plane->fb)
11356                 return 0;
11357
11358         BUG_ON(!plane->crtc);
11359
11360         intel_crtc = to_intel_crtc(plane->crtc);
11361
11362         /*
11363          * Even though we checked plane->fb above, it's still possible that
11364          * the primary plane has been implicitly disabled because the crtc
11365          * coordinates given weren't visible, or because we detected
11366          * that it was 100% covered by a sprite plane.  Or, the CRTC may be
11367          * off and we've set a fb, but haven't actually turned on the CRTC yet.
11368          * In either case, we need to unpin the FB and let the fb pointer get
11369          * updated, but otherwise we don't need to touch the hardware.
11370          */
11371         if (!intel_crtc->primary_enabled)
11372                 goto disable_unpin;
11373
11374         intel_crtc_wait_for_pending_flips(plane->crtc);
11375         intel_disable_primary_hw_plane(plane, plane->crtc);
11376
11377 disable_unpin:
11378         mutex_lock(&dev->struct_mutex);
11379         i915_gem_track_fb(intel_fb_obj(plane->fb), NULL,
11380                           INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe));
11381         intel_unpin_fb_obj(intel_fb_obj(plane->fb));
11382         mutex_unlock(&dev->struct_mutex);
11383         plane->fb = NULL;
11384
11385         return 0;
11386 }
11387
11388 static int
11389 intel_check_primary_plane(struct drm_plane *plane,
11390                           struct intel_plane_state *state)
11391 {
11392         struct drm_crtc *crtc = state->crtc;
11393         struct drm_framebuffer *fb = state->fb;
11394         struct drm_rect *dest = &state->dst;
11395         struct drm_rect *src = &state->src;
11396         const struct drm_rect *clip = &state->clip;
11397
11398         return drm_plane_helper_check_update(plane, crtc, fb,
11399                                              src, dest, clip,
11400                                              DRM_PLANE_HELPER_NO_SCALING,
11401                                              DRM_PLANE_HELPER_NO_SCALING,
11402                                              false, true, &state->visible);
11403 }
11404
11405 static int
11406 intel_commit_primary_plane(struct drm_plane *plane,
11407                            struct intel_plane_state *state)
11408 {
11409         struct drm_crtc *crtc = state->crtc;
11410         struct drm_framebuffer *fb = state->fb;
11411         struct drm_device *dev = crtc->dev;
11412         struct drm_i915_private *dev_priv = dev->dev_private;
11413         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11414         enum pipe pipe = intel_crtc->pipe;
11415         struct drm_framebuffer *old_fb = plane->fb;
11416         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11417         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
11418         struct intel_plane *intel_plane = to_intel_plane(plane);
11419         struct drm_rect *src = &state->src;
11420         int ret;
11421
11422         intel_crtc_wait_for_pending_flips(crtc);
11423
11424         if (intel_crtc_has_pending_flip(crtc)) {
11425                 DRM_ERROR("pipe is still busy with an old pageflip\n");
11426                 return -EBUSY;
11427         }
11428
11429         if (plane->fb != fb) {
11430                 mutex_lock(&dev->struct_mutex);
11431                 ret = intel_pin_and_fence_fb_obj(dev, obj, NULL);
11432                 if (ret == 0)
11433                         i915_gem_track_fb(old_obj, obj,
11434                                           INTEL_FRONTBUFFER_PRIMARY(pipe));
11435                 mutex_unlock(&dev->struct_mutex);
11436                 if (ret != 0) {
11437                         DRM_DEBUG_KMS("pin & fence failed\n");
11438                         return ret;
11439                 }
11440         }
11441
11442         crtc->primary->fb = fb;
11443         crtc->x = src->x1;
11444         crtc->y = src->y1;
11445
11446         intel_plane->crtc_x = state->orig_dst.x1;
11447         intel_plane->crtc_y = state->orig_dst.y1;
11448         intel_plane->crtc_w = drm_rect_width(&state->orig_dst);
11449         intel_plane->crtc_h = drm_rect_height(&state->orig_dst);
11450         intel_plane->src_x = state->orig_src.x1;
11451         intel_plane->src_y = state->orig_src.y1;
11452         intel_plane->src_w = drm_rect_width(&state->orig_src);
11453         intel_plane->src_h = drm_rect_height(&state->orig_src);
11454         intel_plane->obj = obj;
11455
11456         if (intel_crtc->active) {
11457                 /*
11458                  * FBC does not work on some platforms for rotated
11459                  * planes, so disable it when rotation is not 0 and
11460                  * update it when rotation is set back to 0.
11461                  *
11462                  * FIXME: This is redundant with the fbc update done in
11463                  * the primary plane enable function except that that
11464                  * one is done too late. We eventually need to unify
11465                  * this.
11466                  */
11467                 if (intel_crtc->primary_enabled &&
11468                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11469                     dev_priv->fbc.plane == intel_crtc->plane &&
11470                     intel_plane->rotation != BIT(DRM_ROTATE_0)) {
11471                         intel_disable_fbc(dev);
11472                 }
11473
11474                 if (state->visible) {
11475                         bool was_enabled = intel_crtc->primary_enabled;
11476
11477                         /* FIXME: kill this fastboot hack */
11478                         intel_update_pipe_size(intel_crtc);
11479
11480                         intel_crtc->primary_enabled = true;
11481
11482                         dev_priv->display.update_primary_plane(crtc, plane->fb,
11483                                         crtc->x, crtc->y);
11484
11485                         /*
11486                          * BDW signals flip done immediately if the plane
11487                          * is disabled, even if the plane enable is already
11488                          * armed to occur at the next vblank :(
11489                          */
11490                         if (IS_BROADWELL(dev) && !was_enabled)
11491                                 intel_wait_for_vblank(dev, intel_crtc->pipe);
11492                 } else {
11493                         /*
11494                          * If clipping results in a non-visible primary plane,
11495                          * we'll disable the primary plane.  Note that this is
11496                          * a bit different than what happens if userspace
11497                          * explicitly disables the plane by passing fb=0
11498                          * because plane->fb still gets set and pinned.
11499                          */
11500                         intel_disable_primary_hw_plane(plane, crtc);
11501                 }
11502
11503                 intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
11504
11505                 mutex_lock(&dev->struct_mutex);
11506                 intel_update_fbc(dev);
11507                 mutex_unlock(&dev->struct_mutex);
11508         }
11509
11510         if (old_fb && old_fb != fb) {
11511                 if (intel_crtc->active)
11512                         intel_wait_for_vblank(dev, intel_crtc->pipe);
11513
11514                 mutex_lock(&dev->struct_mutex);
11515                 intel_unpin_fb_obj(old_obj);
11516                 mutex_unlock(&dev->struct_mutex);
11517         }
11518
11519         return 0;
11520 }
11521
11522 static int
11523 intel_primary_plane_setplane(struct drm_plane *plane, struct drm_crtc *crtc,
11524                              struct drm_framebuffer *fb, int crtc_x, int crtc_y,
11525                              unsigned int crtc_w, unsigned int crtc_h,
11526                              uint32_t src_x, uint32_t src_y,
11527                              uint32_t src_w, uint32_t src_h)
11528 {
11529         struct intel_plane_state state;
11530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11531         int ret;
11532
11533         state.crtc = crtc;
11534         state.fb = fb;
11535
11536         /* sample coordinates in 16.16 fixed point */
11537         state.src.x1 = src_x;
11538         state.src.x2 = src_x + src_w;
11539         state.src.y1 = src_y;
11540         state.src.y2 = src_y + src_h;
11541
11542         /* integer pixels */
11543         state.dst.x1 = crtc_x;
11544         state.dst.x2 = crtc_x + crtc_w;
11545         state.dst.y1 = crtc_y;
11546         state.dst.y2 = crtc_y + crtc_h;
11547
11548         state.clip.x1 = 0;
11549         state.clip.y1 = 0;
11550         state.clip.x2 = intel_crtc->active ? intel_crtc->config.pipe_src_w : 0;
11551         state.clip.y2 = intel_crtc->active ? intel_crtc->config.pipe_src_h : 0;
11552
11553         state.orig_src = state.src;
11554         state.orig_dst = state.dst;
11555
11556         ret = intel_check_primary_plane(plane, &state);
11557         if (ret)
11558                 return ret;
11559
11560         intel_commit_primary_plane(plane, &state);
11561
11562         return 0;
11563 }
11564
11565 /* Common destruction function for both primary and cursor planes */
11566 static void intel_plane_destroy(struct drm_plane *plane)
11567 {
11568         struct intel_plane *intel_plane = to_intel_plane(plane);
11569         drm_plane_cleanup(plane);
11570         kfree(intel_plane);
11571 }
11572
11573 static const struct drm_plane_funcs intel_primary_plane_funcs = {
11574         .update_plane = intel_primary_plane_setplane,
11575         .disable_plane = intel_primary_plane_disable,
11576         .destroy = intel_plane_destroy,
11577         .set_property = intel_plane_set_property
11578 };
11579
11580 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
11581                                                     int pipe)
11582 {
11583         struct intel_plane *primary;
11584         const uint32_t *intel_primary_formats;
11585         int num_formats;
11586
11587         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
11588         if (primary == NULL)
11589                 return NULL;
11590
11591         primary->can_scale = false;
11592         primary->max_downscale = 1;
11593         primary->pipe = pipe;
11594         primary->plane = pipe;
11595         primary->rotation = BIT(DRM_ROTATE_0);
11596         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
11597                 primary->plane = !pipe;
11598
11599         if (INTEL_INFO(dev)->gen <= 3) {
11600                 intel_primary_formats = intel_primary_formats_gen2;
11601                 num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
11602         } else {
11603                 intel_primary_formats = intel_primary_formats_gen4;
11604                 num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
11605         }
11606
11607         drm_universal_plane_init(dev, &primary->base, 0,
11608                                  &intel_primary_plane_funcs,
11609                                  intel_primary_formats, num_formats,
11610                                  DRM_PLANE_TYPE_PRIMARY);
11611
11612         if (INTEL_INFO(dev)->gen >= 4) {
11613                 if (!dev->mode_config.rotation_property)
11614                         dev->mode_config.rotation_property =
11615                                 drm_mode_create_rotation_property(dev,
11616                                                         BIT(DRM_ROTATE_0) |
11617                                                         BIT(DRM_ROTATE_180));
11618                 if (dev->mode_config.rotation_property)
11619                         drm_object_attach_property(&primary->base.base,
11620                                 dev->mode_config.rotation_property,
11621                                 primary->rotation);
11622         }
11623
11624         return &primary->base;
11625 }
11626
11627 static int
11628 intel_cursor_plane_disable(struct drm_plane *plane)
11629 {
11630         if (!plane->fb)
11631                 return 0;
11632
11633         BUG_ON(!plane->crtc);
11634
11635         return intel_crtc_cursor_set_obj(plane->crtc, NULL, 0, 0);
11636 }
11637
11638 static int
11639 intel_check_cursor_plane(struct drm_plane *plane,
11640                          struct intel_plane_state *state)
11641 {
11642         struct drm_crtc *crtc = state->crtc;
11643         struct drm_device *dev = crtc->dev;
11644         struct drm_framebuffer *fb = state->fb;
11645         struct drm_rect *dest = &state->dst;
11646         struct drm_rect *src = &state->src;
11647         const struct drm_rect *clip = &state->clip;
11648         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11649         int crtc_w, crtc_h;
11650         unsigned stride;
11651         int ret;
11652
11653         ret = drm_plane_helper_check_update(plane, crtc, fb,
11654                                             src, dest, clip,
11655                                             DRM_PLANE_HELPER_NO_SCALING,
11656                                             DRM_PLANE_HELPER_NO_SCALING,
11657                                             true, true, &state->visible);
11658         if (ret)
11659                 return ret;
11660
11661
11662         /* if we want to turn off the cursor ignore width and height */
11663         if (!obj)
11664                 return 0;
11665
11666         /* Check for which cursor types we support */
11667         crtc_w = drm_rect_width(&state->orig_dst);
11668         crtc_h = drm_rect_height(&state->orig_dst);
11669         if (!cursor_size_ok(dev, crtc_w, crtc_h)) {
11670                 DRM_DEBUG("Cursor dimension not supported\n");
11671                 return -EINVAL;
11672         }
11673
11674         stride = roundup_pow_of_two(crtc_w) * 4;
11675         if (obj->base.size < stride * crtc_h) {
11676                 DRM_DEBUG_KMS("buffer is too small\n");
11677                 return -ENOMEM;
11678         }
11679
11680         if (fb == crtc->cursor->fb)
11681                 return 0;
11682
11683         /* we only need to pin inside GTT if cursor is non-phy */
11684         mutex_lock(&dev->struct_mutex);
11685         if (!INTEL_INFO(dev)->cursor_needs_physical && obj->tiling_mode) {
11686                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
11687                 ret = -EINVAL;
11688         }
11689         mutex_unlock(&dev->struct_mutex);
11690
11691         return ret;
11692 }
11693
11694 static int
11695 intel_commit_cursor_plane(struct drm_plane *plane,
11696                           struct intel_plane_state *state)
11697 {
11698         struct drm_crtc *crtc = state->crtc;
11699         struct drm_framebuffer *fb = state->fb;
11700         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11701         struct intel_plane *intel_plane = to_intel_plane(plane);
11702         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
11703         struct drm_i915_gem_object *obj = intel_fb->obj;
11704         int crtc_w, crtc_h;
11705
11706         crtc->cursor_x = state->orig_dst.x1;
11707         crtc->cursor_y = state->orig_dst.y1;
11708
11709         intel_plane->crtc_x = state->orig_dst.x1;
11710         intel_plane->crtc_y = state->orig_dst.y1;
11711         intel_plane->crtc_w = drm_rect_width(&state->orig_dst);
11712         intel_plane->crtc_h = drm_rect_height(&state->orig_dst);
11713         intel_plane->src_x = state->orig_src.x1;
11714         intel_plane->src_y = state->orig_src.y1;
11715         intel_plane->src_w = drm_rect_width(&state->orig_src);
11716         intel_plane->src_h = drm_rect_height(&state->orig_src);
11717         intel_plane->obj = obj;
11718
11719         if (fb != crtc->cursor->fb) {
11720                 crtc_w = drm_rect_width(&state->orig_dst);
11721                 crtc_h = drm_rect_height(&state->orig_dst);
11722                 return intel_crtc_cursor_set_obj(crtc, obj, crtc_w, crtc_h);
11723         } else {
11724                 intel_crtc_update_cursor(crtc, state->visible);
11725
11726                 intel_frontbuffer_flip(crtc->dev,
11727                                        INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe));
11728
11729                 return 0;
11730         }
11731 }
11732
11733 static int
11734 intel_cursor_plane_update(struct drm_plane *plane, struct drm_crtc *crtc,
11735                           struct drm_framebuffer *fb, int crtc_x, int crtc_y,
11736                           unsigned int crtc_w, unsigned int crtc_h,
11737                           uint32_t src_x, uint32_t src_y,
11738                           uint32_t src_w, uint32_t src_h)
11739 {
11740         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11741         struct intel_plane_state state;
11742         int ret;
11743
11744         state.crtc = crtc;
11745         state.fb = fb;
11746
11747         /* sample coordinates in 16.16 fixed point */
11748         state.src.x1 = src_x;
11749         state.src.x2 = src_x + src_w;
11750         state.src.y1 = src_y;
11751         state.src.y2 = src_y + src_h;
11752
11753         /* integer pixels */
11754         state.dst.x1 = crtc_x;
11755         state.dst.x2 = crtc_x + crtc_w;
11756         state.dst.y1 = crtc_y;
11757         state.dst.y2 = crtc_y + crtc_h;
11758
11759         state.clip.x1 = 0;
11760         state.clip.y1 = 0;
11761         state.clip.x2 = intel_crtc->active ? intel_crtc->config.pipe_src_w : 0;
11762         state.clip.y2 = intel_crtc->active ? intel_crtc->config.pipe_src_h : 0;
11763
11764         state.orig_src = state.src;
11765         state.orig_dst = state.dst;
11766
11767         ret = intel_check_cursor_plane(plane, &state);
11768         if (ret)
11769                 return ret;
11770
11771         return intel_commit_cursor_plane(plane, &state);
11772 }
11773
11774 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
11775         .update_plane = intel_cursor_plane_update,
11776         .disable_plane = intel_cursor_plane_disable,
11777         .destroy = intel_plane_destroy,
11778         .set_property = intel_plane_set_property,
11779 };
11780
11781 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
11782                                                    int pipe)
11783 {
11784         struct intel_plane *cursor;
11785
11786         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
11787         if (cursor == NULL)
11788                 return NULL;
11789
11790         cursor->can_scale = false;
11791         cursor->max_downscale = 1;
11792         cursor->pipe = pipe;
11793         cursor->plane = pipe;
11794         cursor->rotation = BIT(DRM_ROTATE_0);
11795
11796         drm_universal_plane_init(dev, &cursor->base, 0,
11797                                  &intel_cursor_plane_funcs,
11798                                  intel_cursor_formats,
11799                                  ARRAY_SIZE(intel_cursor_formats),
11800                                  DRM_PLANE_TYPE_CURSOR);
11801
11802         if (INTEL_INFO(dev)->gen >= 4) {
11803                 if (!dev->mode_config.rotation_property)
11804                         dev->mode_config.rotation_property =
11805                                 drm_mode_create_rotation_property(dev,
11806                                                         BIT(DRM_ROTATE_0) |
11807                                                         BIT(DRM_ROTATE_180));
11808                 if (dev->mode_config.rotation_property)
11809                         drm_object_attach_property(&cursor->base.base,
11810                                 dev->mode_config.rotation_property,
11811                                 cursor->rotation);
11812         }
11813
11814         return &cursor->base;
11815 }
11816
11817 static void intel_crtc_init(struct drm_device *dev, int pipe)
11818 {
11819         struct drm_i915_private *dev_priv = dev->dev_private;
11820         struct intel_crtc *intel_crtc;
11821         struct drm_plane *primary = NULL;
11822         struct drm_plane *cursor = NULL;
11823         int i, ret;
11824
11825         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
11826         if (intel_crtc == NULL)
11827                 return;
11828
11829         primary = intel_primary_plane_create(dev, pipe);
11830         if (!primary)
11831                 goto fail;
11832
11833         cursor = intel_cursor_plane_create(dev, pipe);
11834         if (!cursor)
11835                 goto fail;
11836
11837         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
11838                                         cursor, &intel_crtc_funcs);
11839         if (ret)
11840                 goto fail;
11841
11842         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
11843         for (i = 0; i < 256; i++) {
11844                 intel_crtc->lut_r[i] = i;
11845                 intel_crtc->lut_g[i] = i;
11846                 intel_crtc->lut_b[i] = i;
11847         }
11848
11849         /*
11850          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
11851          * is hooked to pipe B. Hence we want plane A feeding pipe B.
11852          */
11853         intel_crtc->pipe = pipe;
11854         intel_crtc->plane = pipe;
11855         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
11856                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
11857                 intel_crtc->plane = !pipe;
11858         }
11859
11860         intel_crtc->cursor_base = ~0;
11861         intel_crtc->cursor_cntl = ~0;
11862         intel_crtc->cursor_size = ~0;
11863
11864         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
11865                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
11866         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
11867         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
11868
11869         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
11870
11871         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
11872         return;
11873
11874 fail:
11875         if (primary)
11876                 drm_plane_cleanup(primary);
11877         if (cursor)
11878                 drm_plane_cleanup(cursor);
11879         kfree(intel_crtc);
11880 }
11881
11882 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
11883 {
11884         struct drm_encoder *encoder = connector->base.encoder;
11885         struct drm_device *dev = connector->base.dev;
11886
11887         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
11888
11889         if (!encoder)
11890                 return INVALID_PIPE;
11891
11892         return to_intel_crtc(encoder->crtc)->pipe;
11893 }
11894
11895 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
11896                                 struct drm_file *file)
11897 {
11898         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
11899         struct drm_crtc *drmmode_crtc;
11900         struct intel_crtc *crtc;
11901
11902         if (!drm_core_check_feature(dev, DRIVER_MODESET))
11903                 return -ENODEV;
11904
11905         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
11906
11907         if (!drmmode_crtc) {
11908                 DRM_ERROR("no such CRTC id\n");
11909                 return -ENOENT;
11910         }
11911
11912         crtc = to_intel_crtc(drmmode_crtc);
11913         pipe_from_crtc_id->pipe = crtc->pipe;
11914
11915         return 0;
11916 }
11917
11918 static int intel_encoder_clones(struct intel_encoder *encoder)
11919 {
11920         struct drm_device *dev = encoder->base.dev;
11921         struct intel_encoder *source_encoder;
11922         int index_mask = 0;
11923         int entry = 0;
11924
11925         for_each_intel_encoder(dev, source_encoder) {
11926                 if (encoders_cloneable(encoder, source_encoder))
11927                         index_mask |= (1 << entry);
11928
11929                 entry++;
11930         }
11931
11932         return index_mask;
11933 }
11934
11935 static bool has_edp_a(struct drm_device *dev)
11936 {
11937         struct drm_i915_private *dev_priv = dev->dev_private;
11938
11939         if (!IS_MOBILE(dev))
11940                 return false;
11941
11942         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
11943                 return false;
11944
11945         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
11946                 return false;
11947
11948         return true;
11949 }
11950
11951 const char *intel_output_name(int output)
11952 {
11953         static const char *names[] = {
11954                 [INTEL_OUTPUT_UNUSED] = "Unused",
11955                 [INTEL_OUTPUT_ANALOG] = "Analog",
11956                 [INTEL_OUTPUT_DVO] = "DVO",
11957                 [INTEL_OUTPUT_SDVO] = "SDVO",
11958                 [INTEL_OUTPUT_LVDS] = "LVDS",
11959                 [INTEL_OUTPUT_TVOUT] = "TV",
11960                 [INTEL_OUTPUT_HDMI] = "HDMI",
11961                 [INTEL_OUTPUT_DISPLAYPORT] = "DisplayPort",
11962                 [INTEL_OUTPUT_EDP] = "eDP",
11963                 [INTEL_OUTPUT_DSI] = "DSI",
11964                 [INTEL_OUTPUT_UNKNOWN] = "Unknown",
11965         };
11966
11967         if (output < 0 || output >= ARRAY_SIZE(names) || !names[output])
11968                 return "Invalid";
11969
11970         return names[output];
11971 }
11972
11973 static bool intel_crt_present(struct drm_device *dev)
11974 {
11975         struct drm_i915_private *dev_priv = dev->dev_private;
11976
11977         if (INTEL_INFO(dev)->gen >= 9)
11978                 return false;
11979
11980         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
11981                 return false;
11982
11983         if (IS_CHERRYVIEW(dev))
11984                 return false;
11985
11986         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
11987                 return false;
11988
11989         return true;
11990 }
11991
11992 static void intel_setup_outputs(struct drm_device *dev)
11993 {
11994         struct drm_i915_private *dev_priv = dev->dev_private;
11995         struct intel_encoder *encoder;
11996         bool dpd_is_edp = false;
11997
11998         intel_lvds_init(dev);
11999
12000         if (intel_crt_present(dev))
12001                 intel_crt_init(dev);
12002
12003         if (HAS_DDI(dev)) {
12004                 int found;
12005
12006                 /* Haswell uses DDI functions to detect digital outputs */
12007                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
12008                 /* DDI A only supports eDP */
12009                 if (found)
12010                         intel_ddi_init(dev, PORT_A);
12011
12012                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
12013                  * register */
12014                 found = I915_READ(SFUSE_STRAP);
12015
12016                 if (found & SFUSE_STRAP_DDIB_DETECTED)
12017                         intel_ddi_init(dev, PORT_B);
12018                 if (found & SFUSE_STRAP_DDIC_DETECTED)
12019                         intel_ddi_init(dev, PORT_C);
12020                 if (found & SFUSE_STRAP_DDID_DETECTED)
12021                         intel_ddi_init(dev, PORT_D);
12022         } else if (HAS_PCH_SPLIT(dev)) {
12023                 int found;
12024                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
12025
12026                 if (has_edp_a(dev))
12027                         intel_dp_init(dev, DP_A, PORT_A);
12028
12029                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
12030                         /* PCH SDVOB multiplex with HDMIB */
12031                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
12032                         if (!found)
12033                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
12034                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
12035                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
12036                 }
12037
12038                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
12039                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
12040
12041                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
12042                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
12043
12044                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
12045                         intel_dp_init(dev, PCH_DP_C, PORT_C);
12046
12047                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
12048                         intel_dp_init(dev, PCH_DP_D, PORT_D);
12049         } else if (IS_VALLEYVIEW(dev)) {
12050                 /*
12051                  * The DP_DETECTED bit is the latched state of the DDC
12052                  * SDA pin at boot. However since eDP doesn't require DDC
12053                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
12054                  * eDP ports may have been muxed to an alternate function.
12055                  * Thus we can't rely on the DP_DETECTED bit alone to detect
12056                  * eDP ports. Consult the VBT as well as DP_DETECTED to
12057                  * detect eDP ports.
12058                  */
12059                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED)
12060                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
12061                                         PORT_B);
12062                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
12063                     intel_dp_is_edp(dev, PORT_B))
12064                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
12065
12066                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED)
12067                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
12068                                         PORT_C);
12069                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
12070                     intel_dp_is_edp(dev, PORT_C))
12071                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
12072
12073                 if (IS_CHERRYVIEW(dev)) {
12074                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
12075                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
12076                                                 PORT_D);
12077                         /* eDP not supported on port D, so don't check VBT */
12078                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
12079                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
12080                 }
12081
12082                 intel_dsi_init(dev);
12083         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
12084                 bool found = false;
12085
12086                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12087                         DRM_DEBUG_KMS("probing SDVOB\n");
12088                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
12089                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
12090                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
12091                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
12092                         }
12093
12094                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
12095                                 intel_dp_init(dev, DP_B, PORT_B);
12096                 }
12097
12098                 /* Before G4X SDVOC doesn't have its own detect register */
12099
12100                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12101                         DRM_DEBUG_KMS("probing SDVOC\n");
12102                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
12103                 }
12104
12105                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
12106
12107                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
12108                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
12109                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
12110                         }
12111                         if (SUPPORTS_INTEGRATED_DP(dev))
12112                                 intel_dp_init(dev, DP_C, PORT_C);
12113                 }
12114
12115                 if (SUPPORTS_INTEGRATED_DP(dev) &&
12116                     (I915_READ(DP_D) & DP_DETECTED))
12117                         intel_dp_init(dev, DP_D, PORT_D);
12118         } else if (IS_GEN2(dev))
12119                 intel_dvo_init(dev);
12120
12121         if (SUPPORTS_TV(dev))
12122                 intel_tv_init(dev);
12123
12124         intel_edp_psr_init(dev);
12125
12126         for_each_intel_encoder(dev, encoder) {
12127                 encoder->base.possible_crtcs = encoder->crtc_mask;
12128                 encoder->base.possible_clones =
12129                         intel_encoder_clones(encoder);
12130         }
12131
12132         intel_init_pch_refclk(dev);
12133
12134         drm_helper_move_panel_connectors_to_head(dev);
12135 }
12136
12137 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
12138 {
12139         struct drm_device *dev = fb->dev;
12140         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12141
12142         drm_framebuffer_cleanup(fb);
12143         mutex_lock(&dev->struct_mutex);
12144         WARN_ON(!intel_fb->obj->framebuffer_references--);
12145         drm_gem_object_unreference(&intel_fb->obj->base);
12146         mutex_unlock(&dev->struct_mutex);
12147         kfree(intel_fb);
12148 }
12149
12150 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
12151                                                 struct drm_file *file,
12152                                                 unsigned int *handle)
12153 {
12154         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12155         struct drm_i915_gem_object *obj = intel_fb->obj;
12156
12157         return drm_gem_handle_create(file, &obj->base, handle);
12158 }
12159
12160 static const struct drm_framebuffer_funcs intel_fb_funcs = {
12161         .destroy = intel_user_framebuffer_destroy,
12162         .create_handle = intel_user_framebuffer_create_handle,
12163 };
12164
12165 static int intel_framebuffer_init(struct drm_device *dev,
12166                                   struct intel_framebuffer *intel_fb,
12167                                   struct drm_mode_fb_cmd2 *mode_cmd,
12168                                   struct drm_i915_gem_object *obj)
12169 {
12170         int aligned_height;
12171         int pitch_limit;
12172         int ret;
12173
12174         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
12175
12176         if (obj->tiling_mode == I915_TILING_Y) {
12177                 DRM_DEBUG("hardware does not support tiling Y\n");
12178                 return -EINVAL;
12179         }
12180
12181         if (mode_cmd->pitches[0] & 63) {
12182                 DRM_DEBUG("pitch (%d) must be at least 64 byte aligned\n",
12183                           mode_cmd->pitches[0]);
12184                 return -EINVAL;
12185         }
12186
12187         if (INTEL_INFO(dev)->gen >= 5 && !IS_VALLEYVIEW(dev)) {
12188                 pitch_limit = 32*1024;
12189         } else if (INTEL_INFO(dev)->gen >= 4) {
12190                 if (obj->tiling_mode)
12191                         pitch_limit = 16*1024;
12192                 else
12193                         pitch_limit = 32*1024;
12194         } else if (INTEL_INFO(dev)->gen >= 3) {
12195                 if (obj->tiling_mode)
12196                         pitch_limit = 8*1024;
12197                 else
12198                         pitch_limit = 16*1024;
12199         } else
12200                 /* XXX DSPC is limited to 4k tiled */
12201                 pitch_limit = 8*1024;
12202
12203         if (mode_cmd->pitches[0] > pitch_limit) {
12204                 DRM_DEBUG("%s pitch (%d) must be at less than %d\n",
12205                           obj->tiling_mode ? "tiled" : "linear",
12206                           mode_cmd->pitches[0], pitch_limit);
12207                 return -EINVAL;
12208         }
12209
12210         if (obj->tiling_mode != I915_TILING_NONE &&
12211             mode_cmd->pitches[0] != obj->stride) {
12212                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
12213                           mode_cmd->pitches[0], obj->stride);
12214                 return -EINVAL;
12215         }
12216
12217         /* Reject formats not supported by any plane early. */
12218         switch (mode_cmd->pixel_format) {
12219         case DRM_FORMAT_C8:
12220         case DRM_FORMAT_RGB565:
12221         case DRM_FORMAT_XRGB8888:
12222         case DRM_FORMAT_ARGB8888:
12223                 break;
12224         case DRM_FORMAT_XRGB1555:
12225         case DRM_FORMAT_ARGB1555:
12226                 if (INTEL_INFO(dev)->gen > 3) {
12227                         DRM_DEBUG("unsupported pixel format: %s\n",
12228                                   drm_get_format_name(mode_cmd->pixel_format));
12229                         return -EINVAL;
12230                 }
12231                 break;
12232         case DRM_FORMAT_XBGR8888:
12233         case DRM_FORMAT_ABGR8888:
12234         case DRM_FORMAT_XRGB2101010:
12235         case DRM_FORMAT_ARGB2101010:
12236         case DRM_FORMAT_XBGR2101010:
12237         case DRM_FORMAT_ABGR2101010:
12238                 if (INTEL_INFO(dev)->gen < 4) {
12239                         DRM_DEBUG("unsupported pixel format: %s\n",
12240                                   drm_get_format_name(mode_cmd->pixel_format));
12241                         return -EINVAL;
12242                 }
12243                 break;
12244         case DRM_FORMAT_YUYV:
12245         case DRM_FORMAT_UYVY:
12246         case DRM_FORMAT_YVYU:
12247         case DRM_FORMAT_VYUY:
12248                 if (INTEL_INFO(dev)->gen < 5) {
12249                         DRM_DEBUG("unsupported pixel format: %s\n",
12250                                   drm_get_format_name(mode_cmd->pixel_format));
12251                         return -EINVAL;
12252                 }
12253                 break;
12254         default:
12255                 DRM_DEBUG("unsupported pixel format: %s\n",
12256                           drm_get_format_name(mode_cmd->pixel_format));
12257                 return -EINVAL;
12258         }
12259
12260         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
12261         if (mode_cmd->offsets[0] != 0)
12262                 return -EINVAL;
12263
12264         aligned_height = intel_align_height(dev, mode_cmd->height,
12265                                             obj->tiling_mode);
12266         /* FIXME drm helper for size checks (especially planar formats)? */
12267         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
12268                 return -EINVAL;
12269
12270         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
12271         intel_fb->obj = obj;
12272         intel_fb->obj->framebuffer_references++;
12273
12274         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
12275         if (ret) {
12276                 DRM_ERROR("framebuffer init failed %d\n", ret);
12277                 return ret;
12278         }
12279
12280         return 0;
12281 }
12282
12283 static struct drm_framebuffer *
12284 intel_user_framebuffer_create(struct drm_device *dev,
12285                               struct drm_file *filp,
12286                               struct drm_mode_fb_cmd2 *mode_cmd)
12287 {
12288         struct drm_i915_gem_object *obj;
12289
12290         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
12291                                                 mode_cmd->handles[0]));
12292         if (&obj->base == NULL)
12293                 return ERR_PTR(-ENOENT);
12294
12295         return intel_framebuffer_create(dev, mode_cmd, obj);
12296 }
12297
12298 #ifndef CONFIG_DRM_I915_FBDEV
12299 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
12300 {
12301 }
12302 #endif
12303
12304 static const struct drm_mode_config_funcs intel_mode_funcs = {
12305         .fb_create = intel_user_framebuffer_create,
12306         .output_poll_changed = intel_fbdev_output_poll_changed,
12307 };
12308
12309 /* Set up chip specific display functions */
12310 static void intel_init_display(struct drm_device *dev)
12311 {
12312         struct drm_i915_private *dev_priv = dev->dev_private;
12313
12314         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
12315                 dev_priv->display.find_dpll = g4x_find_best_dpll;
12316         else if (IS_CHERRYVIEW(dev))
12317                 dev_priv->display.find_dpll = chv_find_best_dpll;
12318         else if (IS_VALLEYVIEW(dev))
12319                 dev_priv->display.find_dpll = vlv_find_best_dpll;
12320         else if (IS_PINEVIEW(dev))
12321                 dev_priv->display.find_dpll = pnv_find_best_dpll;
12322         else
12323                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
12324
12325         if (HAS_DDI(dev)) {
12326                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
12327                 dev_priv->display.get_plane_config = ironlake_get_plane_config;
12328                 dev_priv->display.crtc_mode_set = haswell_crtc_mode_set;
12329                 dev_priv->display.crtc_enable = haswell_crtc_enable;
12330                 dev_priv->display.crtc_disable = haswell_crtc_disable;
12331                 dev_priv->display.off = ironlake_crtc_off;
12332                 if (INTEL_INFO(dev)->gen >= 9)
12333                         dev_priv->display.update_primary_plane =
12334                                 skylake_update_primary_plane;
12335                 else
12336                         dev_priv->display.update_primary_plane =
12337                                 ironlake_update_primary_plane;
12338         } else if (HAS_PCH_SPLIT(dev)) {
12339                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
12340                 dev_priv->display.get_plane_config = ironlake_get_plane_config;
12341                 dev_priv->display.crtc_mode_set = ironlake_crtc_mode_set;
12342                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
12343                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
12344                 dev_priv->display.off = ironlake_crtc_off;
12345                 dev_priv->display.update_primary_plane =
12346                         ironlake_update_primary_plane;
12347         } else if (IS_VALLEYVIEW(dev)) {
12348                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12349                 dev_priv->display.get_plane_config = i9xx_get_plane_config;
12350                 dev_priv->display.crtc_mode_set = i9xx_crtc_mode_set;
12351                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
12352                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12353                 dev_priv->display.off = i9xx_crtc_off;
12354                 dev_priv->display.update_primary_plane =
12355                         i9xx_update_primary_plane;
12356         } else {
12357                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12358                 dev_priv->display.get_plane_config = i9xx_get_plane_config;
12359                 dev_priv->display.crtc_mode_set = i9xx_crtc_mode_set;
12360                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
12361                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12362                 dev_priv->display.off = i9xx_crtc_off;
12363                 dev_priv->display.update_primary_plane =
12364                         i9xx_update_primary_plane;
12365         }
12366
12367         /* Returns the core display clock speed */
12368         if (IS_VALLEYVIEW(dev))
12369                 dev_priv->display.get_display_clock_speed =
12370                         valleyview_get_display_clock_speed;
12371         else if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
12372                 dev_priv->display.get_display_clock_speed =
12373                         i945_get_display_clock_speed;
12374         else if (IS_I915G(dev))
12375                 dev_priv->display.get_display_clock_speed =
12376                         i915_get_display_clock_speed;
12377         else if (IS_I945GM(dev) || IS_845G(dev))
12378                 dev_priv->display.get_display_clock_speed =
12379                         i9xx_misc_get_display_clock_speed;
12380         else if (IS_PINEVIEW(dev))
12381                 dev_priv->display.get_display_clock_speed =
12382                         pnv_get_display_clock_speed;
12383         else if (IS_I915GM(dev))
12384                 dev_priv->display.get_display_clock_speed =
12385                         i915gm_get_display_clock_speed;
12386         else if (IS_I865G(dev))
12387                 dev_priv->display.get_display_clock_speed =
12388                         i865_get_display_clock_speed;
12389         else if (IS_I85X(dev))
12390                 dev_priv->display.get_display_clock_speed =
12391                         i855_get_display_clock_speed;
12392         else /* 852, 830 */
12393                 dev_priv->display.get_display_clock_speed =
12394                         i830_get_display_clock_speed;
12395
12396         if (IS_GEN5(dev)) {
12397                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
12398         } else if (IS_GEN6(dev)) {
12399                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
12400                 dev_priv->display.modeset_global_resources =
12401                         snb_modeset_global_resources;
12402         } else if (IS_IVYBRIDGE(dev)) {
12403                 /* FIXME: detect B0+ stepping and use auto training */
12404                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
12405                 dev_priv->display.modeset_global_resources =
12406                         ivb_modeset_global_resources;
12407         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
12408                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
12409                 dev_priv->display.modeset_global_resources =
12410                         haswell_modeset_global_resources;
12411         } else if (IS_VALLEYVIEW(dev)) {
12412                 dev_priv->display.modeset_global_resources =
12413                         valleyview_modeset_global_resources;
12414         } else if (INTEL_INFO(dev)->gen >= 9) {
12415                 dev_priv->display.modeset_global_resources =
12416                         haswell_modeset_global_resources;
12417         }
12418
12419         /* Default just returns -ENODEV to indicate unsupported */
12420         dev_priv->display.queue_flip = intel_default_queue_flip;
12421
12422         switch (INTEL_INFO(dev)->gen) {
12423         case 2:
12424                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
12425                 break;
12426
12427         case 3:
12428                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
12429                 break;
12430
12431         case 4:
12432         case 5:
12433                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
12434                 break;
12435
12436         case 6:
12437                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
12438                 break;
12439         case 7:
12440         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
12441                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
12442                 break;
12443         }
12444
12445         intel_panel_init_backlight_funcs(dev);
12446
12447         mutex_init(&dev_priv->pps_mutex);
12448 }
12449
12450 /*
12451  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
12452  * resume, or other times.  This quirk makes sure that's the case for
12453  * affected systems.
12454  */
12455 static void quirk_pipea_force(struct drm_device *dev)
12456 {
12457         struct drm_i915_private *dev_priv = dev->dev_private;
12458
12459         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
12460         DRM_INFO("applying pipe a force quirk\n");
12461 }
12462
12463 static void quirk_pipeb_force(struct drm_device *dev)
12464 {
12465         struct drm_i915_private *dev_priv = dev->dev_private;
12466
12467         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
12468         DRM_INFO("applying pipe b force quirk\n");
12469 }
12470
12471 /*
12472  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
12473  */
12474 static void quirk_ssc_force_disable(struct drm_device *dev)
12475 {
12476         struct drm_i915_private *dev_priv = dev->dev_private;
12477         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
12478         DRM_INFO("applying lvds SSC disable quirk\n");
12479 }
12480
12481 /*
12482  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
12483  * brightness value
12484  */
12485 static void quirk_invert_brightness(struct drm_device *dev)
12486 {
12487         struct drm_i915_private *dev_priv = dev->dev_private;
12488         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
12489         DRM_INFO("applying inverted panel brightness quirk\n");
12490 }
12491
12492 /* Some VBT's incorrectly indicate no backlight is present */
12493 static void quirk_backlight_present(struct drm_device *dev)
12494 {
12495         struct drm_i915_private *dev_priv = dev->dev_private;
12496         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
12497         DRM_INFO("applying backlight present quirk\n");
12498 }
12499
12500 struct intel_quirk {
12501         int device;
12502         int subsystem_vendor;
12503         int subsystem_device;
12504         void (*hook)(struct drm_device *dev);
12505 };
12506
12507 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
12508 struct intel_dmi_quirk {
12509         void (*hook)(struct drm_device *dev);
12510         const struct dmi_system_id (*dmi_id_list)[];
12511 };
12512
12513 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
12514 {
12515         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
12516         return 1;
12517 }
12518
12519 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
12520         {
12521                 .dmi_id_list = &(const struct dmi_system_id[]) {
12522                         {
12523                                 .callback = intel_dmi_reverse_brightness,
12524                                 .ident = "NCR Corporation",
12525                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
12526                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
12527                                 },
12528                         },
12529                         { }  /* terminating entry */
12530                 },
12531                 .hook = quirk_invert_brightness,
12532         },
12533 };
12534
12535 static struct intel_quirk intel_quirks[] = {
12536         /* HP Mini needs pipe A force quirk (LP: #322104) */
12537         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
12538
12539         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
12540         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
12541
12542         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
12543         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
12544
12545         /* 830 needs to leave pipe A & dpll A up */
12546         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
12547
12548         /* 830 needs to leave pipe B & dpll B up */
12549         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
12550
12551         /* Lenovo U160 cannot use SSC on LVDS */
12552         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
12553
12554         /* Sony Vaio Y cannot use SSC on LVDS */
12555         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
12556
12557         /* Acer Aspire 5734Z must invert backlight brightness */
12558         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
12559
12560         /* Acer/eMachines G725 */
12561         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
12562
12563         /* Acer/eMachines e725 */
12564         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
12565
12566         /* Acer/Packard Bell NCL20 */
12567         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
12568
12569         /* Acer Aspire 4736Z */
12570         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
12571
12572         /* Acer Aspire 5336 */
12573         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
12574
12575         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
12576         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
12577
12578         /* Acer C720 Chromebook (Core i3 4005U) */
12579         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
12580
12581         /* Toshiba CB35 Chromebook (Celeron 2955U) */
12582         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
12583
12584         /* HP Chromebook 14 (Celeron 2955U) */
12585         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
12586 };
12587
12588 static void intel_init_quirks(struct drm_device *dev)
12589 {
12590         struct pci_dev *d = dev->pdev;
12591         int i;
12592
12593         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
12594                 struct intel_quirk *q = &intel_quirks[i];
12595
12596                 if (d->device == q->device &&
12597                     (d->subsystem_vendor == q->subsystem_vendor ||
12598                      q->subsystem_vendor == PCI_ANY_ID) &&
12599                     (d->subsystem_device == q->subsystem_device ||
12600                      q->subsystem_device == PCI_ANY_ID))
12601                         q->hook(dev);
12602         }
12603         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
12604                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
12605                         intel_dmi_quirks[i].hook(dev);
12606         }
12607 }
12608
12609 /* Disable the VGA plane that we never use */
12610 static void i915_disable_vga(struct drm_device *dev)
12611 {
12612         struct drm_i915_private *dev_priv = dev->dev_private;
12613         u8 sr1;
12614         u32 vga_reg = i915_vgacntrl_reg(dev);
12615
12616         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
12617         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
12618         outb(SR01, VGA_SR_INDEX);
12619         sr1 = inb(VGA_SR_DATA);
12620         outb(sr1 | 1<<5, VGA_SR_DATA);
12621         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
12622         udelay(300);
12623
12624         /*
12625          * Fujitsu-Siemens Lifebook S6010 (830) has problems resuming
12626          * from S3 without preserving (some of?) the other bits.
12627          */
12628         I915_WRITE(vga_reg, dev_priv->bios_vgacntr | VGA_DISP_DISABLE);
12629         POSTING_READ(vga_reg);
12630 }
12631
12632 void intel_modeset_init_hw(struct drm_device *dev)
12633 {
12634         intel_prepare_ddi(dev);
12635
12636         if (IS_VALLEYVIEW(dev))
12637                 vlv_update_cdclk(dev);
12638
12639         intel_init_clock_gating(dev);
12640
12641         intel_enable_gt_powersave(dev);
12642 }
12643
12644 void intel_modeset_init(struct drm_device *dev)
12645 {
12646         struct drm_i915_private *dev_priv = dev->dev_private;
12647         int sprite, ret;
12648         enum pipe pipe;
12649         struct intel_crtc *crtc;
12650
12651         drm_mode_config_init(dev);
12652
12653         dev->mode_config.min_width = 0;
12654         dev->mode_config.min_height = 0;
12655
12656         dev->mode_config.preferred_depth = 24;
12657         dev->mode_config.prefer_shadow = 1;
12658
12659         dev->mode_config.funcs = &intel_mode_funcs;
12660
12661         intel_init_quirks(dev);
12662
12663         intel_init_pm(dev);
12664
12665         if (INTEL_INFO(dev)->num_pipes == 0)
12666                 return;
12667
12668         intel_init_display(dev);
12669         intel_init_audio(dev);
12670
12671         if (IS_GEN2(dev)) {
12672                 dev->mode_config.max_width = 2048;
12673                 dev->mode_config.max_height = 2048;
12674         } else if (IS_GEN3(dev)) {
12675                 dev->mode_config.max_width = 4096;
12676                 dev->mode_config.max_height = 4096;
12677         } else {
12678                 dev->mode_config.max_width = 8192;
12679                 dev->mode_config.max_height = 8192;
12680         }
12681
12682         if (IS_845G(dev) || IS_I865G(dev)) {
12683                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
12684                 dev->mode_config.cursor_height = 1023;
12685         } else if (IS_GEN2(dev)) {
12686                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
12687                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
12688         } else {
12689                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
12690                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
12691         }
12692
12693         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
12694
12695         DRM_DEBUG_KMS("%d display pipe%s available.\n",
12696                       INTEL_INFO(dev)->num_pipes,
12697                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
12698
12699         for_each_pipe(dev_priv, pipe) {
12700                 intel_crtc_init(dev, pipe);
12701                 for_each_sprite(pipe, sprite) {
12702                         ret = intel_plane_init(dev, pipe, sprite);
12703                         if (ret)
12704                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
12705                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
12706                 }
12707         }
12708
12709         intel_init_dpio(dev);
12710
12711         intel_shared_dpll_init(dev);
12712
12713         /* save the BIOS value before clobbering it */
12714         dev_priv->bios_vgacntr = I915_READ(i915_vgacntrl_reg(dev));
12715         /* Just disable it once at startup */
12716         i915_disable_vga(dev);
12717         intel_setup_outputs(dev);
12718
12719         /* Just in case the BIOS is doing something questionable. */
12720         intel_disable_fbc(dev);
12721
12722         drm_modeset_lock_all(dev);
12723         intel_modeset_setup_hw_state(dev, false);
12724         drm_modeset_unlock_all(dev);
12725
12726         for_each_intel_crtc(dev, crtc) {
12727                 if (!crtc->active)
12728                         continue;
12729
12730                 /*
12731                  * Note that reserving the BIOS fb up front prevents us
12732                  * from stuffing other stolen allocations like the ring
12733                  * on top.  This prevents some ugliness at boot time, and
12734                  * can even allow for smooth boot transitions if the BIOS
12735                  * fb is large enough for the active pipe configuration.
12736                  */
12737                 if (dev_priv->display.get_plane_config) {
12738                         dev_priv->display.get_plane_config(crtc,
12739                                                            &crtc->plane_config);
12740                         /*
12741                          * If the fb is shared between multiple heads, we'll
12742                          * just get the first one.
12743                          */
12744                         intel_find_plane_obj(crtc, &crtc->plane_config);
12745                 }
12746         }
12747 }
12748
12749 static void intel_enable_pipe_a(struct drm_device *dev)
12750 {
12751         struct intel_connector *connector;
12752         struct drm_connector *crt = NULL;
12753         struct intel_load_detect_pipe load_detect_temp;
12754         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
12755
12756         /* We can't just switch on the pipe A, we need to set things up with a
12757          * proper mode and output configuration. As a gross hack, enable pipe A
12758          * by enabling the load detect pipe once. */
12759         list_for_each_entry(connector,
12760                             &dev->mode_config.connector_list,
12761                             base.head) {
12762                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
12763                         crt = &connector->base;
12764                         break;
12765                 }
12766         }
12767
12768         if (!crt)
12769                 return;
12770
12771         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
12772                 intel_release_load_detect_pipe(crt, &load_detect_temp);
12773 }
12774
12775 static bool
12776 intel_check_plane_mapping(struct intel_crtc *crtc)
12777 {
12778         struct drm_device *dev = crtc->base.dev;
12779         struct drm_i915_private *dev_priv = dev->dev_private;
12780         u32 reg, val;
12781
12782         if (INTEL_INFO(dev)->num_pipes == 1)
12783                 return true;
12784
12785         reg = DSPCNTR(!crtc->plane);
12786         val = I915_READ(reg);
12787
12788         if ((val & DISPLAY_PLANE_ENABLE) &&
12789             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
12790                 return false;
12791
12792         return true;
12793 }
12794
12795 static void intel_sanitize_crtc(struct intel_crtc *crtc)
12796 {
12797         struct drm_device *dev = crtc->base.dev;
12798         struct drm_i915_private *dev_priv = dev->dev_private;
12799         u32 reg;
12800
12801         /* Clear any frame start delays used for debugging left by the BIOS */
12802         reg = PIPECONF(crtc->config.cpu_transcoder);
12803         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
12804
12805         /* restore vblank interrupts to correct state */
12806         if (crtc->active) {
12807                 update_scanline_offset(crtc);
12808                 drm_vblank_on(dev, crtc->pipe);
12809         } else
12810                 drm_vblank_off(dev, crtc->pipe);
12811
12812         /* We need to sanitize the plane -> pipe mapping first because this will
12813          * disable the crtc (and hence change the state) if it is wrong. Note
12814          * that gen4+ has a fixed plane -> pipe mapping.  */
12815         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
12816                 struct intel_connector *connector;
12817                 bool plane;
12818
12819                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
12820                               crtc->base.base.id);
12821
12822                 /* Pipe has the wrong plane attached and the plane is active.
12823                  * Temporarily change the plane mapping and disable everything
12824                  * ...  */
12825                 plane = crtc->plane;
12826                 crtc->plane = !plane;
12827                 crtc->primary_enabled = true;
12828                 dev_priv->display.crtc_disable(&crtc->base);
12829                 crtc->plane = plane;
12830
12831                 /* ... and break all links. */
12832                 list_for_each_entry(connector, &dev->mode_config.connector_list,
12833                                     base.head) {
12834                         if (connector->encoder->base.crtc != &crtc->base)
12835                                 continue;
12836
12837                         connector->base.dpms = DRM_MODE_DPMS_OFF;
12838                         connector->base.encoder = NULL;
12839                 }
12840                 /* multiple connectors may have the same encoder:
12841                  *  handle them and break crtc link separately */
12842                 list_for_each_entry(connector, &dev->mode_config.connector_list,
12843                                     base.head)
12844                         if (connector->encoder->base.crtc == &crtc->base) {
12845                                 connector->encoder->base.crtc = NULL;
12846                                 connector->encoder->connectors_active = false;
12847                         }
12848
12849                 WARN_ON(crtc->active);
12850                 crtc->base.enabled = false;
12851         }
12852
12853         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
12854             crtc->pipe == PIPE_A && !crtc->active) {
12855                 /* BIOS forgot to enable pipe A, this mostly happens after
12856                  * resume. Force-enable the pipe to fix this, the update_dpms
12857                  * call below we restore the pipe to the right state, but leave
12858                  * the required bits on. */
12859                 intel_enable_pipe_a(dev);
12860         }
12861
12862         /* Adjust the state of the output pipe according to whether we
12863          * have active connectors/encoders. */
12864         intel_crtc_update_dpms(&crtc->base);
12865
12866         if (crtc->active != crtc->base.enabled) {
12867                 struct intel_encoder *encoder;
12868
12869                 /* This can happen either due to bugs in the get_hw_state
12870                  * functions or because the pipe is force-enabled due to the
12871                  * pipe A quirk. */
12872                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
12873                               crtc->base.base.id,
12874                               crtc->base.enabled ? "enabled" : "disabled",
12875                               crtc->active ? "enabled" : "disabled");
12876
12877                 crtc->base.enabled = crtc->active;
12878
12879                 /* Because we only establish the connector -> encoder ->
12880                  * crtc links if something is active, this means the
12881                  * crtc is now deactivated. Break the links. connector
12882                  * -> encoder links are only establish when things are
12883                  *  actually up, hence no need to break them. */
12884                 WARN_ON(crtc->active);
12885
12886                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
12887                         WARN_ON(encoder->connectors_active);
12888                         encoder->base.crtc = NULL;
12889                 }
12890         }
12891
12892         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
12893                 /*
12894                  * We start out with underrun reporting disabled to avoid races.
12895                  * For correct bookkeeping mark this on active crtcs.
12896                  *
12897                  * Also on gmch platforms we dont have any hardware bits to
12898                  * disable the underrun reporting. Which means we need to start
12899                  * out with underrun reporting disabled also on inactive pipes,
12900                  * since otherwise we'll complain about the garbage we read when
12901                  * e.g. coming up after runtime pm.
12902                  *
12903                  * No protection against concurrent access is required - at
12904                  * worst a fifo underrun happens which also sets this to false.
12905                  */
12906                 crtc->cpu_fifo_underrun_disabled = true;
12907                 crtc->pch_fifo_underrun_disabled = true;
12908         }
12909 }
12910
12911 static void intel_sanitize_encoder(struct intel_encoder *encoder)
12912 {
12913         struct intel_connector *connector;
12914         struct drm_device *dev = encoder->base.dev;
12915
12916         /* We need to check both for a crtc link (meaning that the
12917          * encoder is active and trying to read from a pipe) and the
12918          * pipe itself being active. */
12919         bool has_active_crtc = encoder->base.crtc &&
12920                 to_intel_crtc(encoder->base.crtc)->active;
12921
12922         if (encoder->connectors_active && !has_active_crtc) {
12923                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
12924                               encoder->base.base.id,
12925                               encoder->base.name);
12926
12927                 /* Connector is active, but has no active pipe. This is
12928                  * fallout from our resume register restoring. Disable
12929                  * the encoder manually again. */
12930                 if (encoder->base.crtc) {
12931                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
12932                                       encoder->base.base.id,
12933                                       encoder->base.name);
12934                         encoder->disable(encoder);
12935                         if (encoder->post_disable)
12936                                 encoder->post_disable(encoder);
12937                 }
12938                 encoder->base.crtc = NULL;
12939                 encoder->connectors_active = false;
12940
12941                 /* Inconsistent output/port/pipe state happens presumably due to
12942                  * a bug in one of the get_hw_state functions. Or someplace else
12943                  * in our code, like the register restore mess on resume. Clamp
12944                  * things to off as a safer default. */
12945                 list_for_each_entry(connector,
12946                                     &dev->mode_config.connector_list,
12947                                     base.head) {
12948                         if (connector->encoder != encoder)
12949                                 continue;
12950                         connector->base.dpms = DRM_MODE_DPMS_OFF;
12951                         connector->base.encoder = NULL;
12952                 }
12953         }
12954         /* Enabled encoders without active connectors will be fixed in
12955          * the crtc fixup. */
12956 }
12957
12958 void i915_redisable_vga_power_on(struct drm_device *dev)
12959 {
12960         struct drm_i915_private *dev_priv = dev->dev_private;
12961         u32 vga_reg = i915_vgacntrl_reg(dev);
12962
12963         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
12964                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
12965                 i915_disable_vga(dev);
12966         }
12967 }
12968
12969 void i915_redisable_vga(struct drm_device *dev)
12970 {
12971         struct drm_i915_private *dev_priv = dev->dev_private;
12972
12973         /* This function can be called both from intel_modeset_setup_hw_state or
12974          * at a very early point in our resume sequence, where the power well
12975          * structures are not yet restored. Since this function is at a very
12976          * paranoid "someone might have enabled VGA while we were not looking"
12977          * level, just check if the power well is enabled instead of trying to
12978          * follow the "don't touch the power well if we don't need it" policy
12979          * the rest of the driver uses. */
12980         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
12981                 return;
12982
12983         i915_redisable_vga_power_on(dev);
12984 }
12985
12986 static bool primary_get_hw_state(struct intel_crtc *crtc)
12987 {
12988         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
12989
12990         if (!crtc->active)
12991                 return false;
12992
12993         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
12994 }
12995
12996 static void intel_modeset_readout_hw_state(struct drm_device *dev)
12997 {
12998         struct drm_i915_private *dev_priv = dev->dev_private;
12999         enum pipe pipe;
13000         struct intel_crtc *crtc;
13001         struct intel_encoder *encoder;
13002         struct intel_connector *connector;
13003         int i;
13004
13005         for_each_intel_crtc(dev, crtc) {
13006                 memset(&crtc->config, 0, sizeof(crtc->config));
13007
13008                 crtc->config.quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
13009
13010                 crtc->active = dev_priv->display.get_pipe_config(crtc,
13011                                                                  &crtc->config);
13012
13013                 crtc->base.enabled = crtc->active;
13014                 crtc->primary_enabled = primary_get_hw_state(crtc);
13015
13016                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
13017                               crtc->base.base.id,
13018                               crtc->active ? "enabled" : "disabled");
13019         }
13020
13021         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13022                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13023
13024                 pll->on = pll->get_hw_state(dev_priv, pll, &pll->hw_state);
13025                 pll->active = 0;
13026                 for_each_intel_crtc(dev, crtc) {
13027                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
13028                                 pll->active++;
13029                 }
13030                 pll->refcount = pll->active;
13031
13032                 DRM_DEBUG_KMS("%s hw state readout: refcount %i, on %i\n",
13033                               pll->name, pll->refcount, pll->on);
13034
13035                 if (pll->refcount)
13036                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
13037         }
13038
13039         for_each_intel_encoder(dev, encoder) {
13040                 pipe = 0;
13041
13042                 if (encoder->get_hw_state(encoder, &pipe)) {
13043                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13044                         encoder->base.crtc = &crtc->base;
13045                         encoder->get_config(encoder, &crtc->config);
13046                 } else {
13047                         encoder->base.crtc = NULL;
13048                 }
13049
13050                 encoder->connectors_active = false;
13051                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
13052                               encoder->base.base.id,
13053                               encoder->base.name,
13054                               encoder->base.crtc ? "enabled" : "disabled",
13055                               pipe_name(pipe));
13056         }
13057
13058         list_for_each_entry(connector, &dev->mode_config.connector_list,
13059                             base.head) {
13060                 if (connector->get_hw_state(connector)) {
13061                         connector->base.dpms = DRM_MODE_DPMS_ON;
13062                         connector->encoder->connectors_active = true;
13063                         connector->base.encoder = &connector->encoder->base;
13064                 } else {
13065                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13066                         connector->base.encoder = NULL;
13067                 }
13068                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
13069                               connector->base.base.id,
13070                               connector->base.name,
13071                               connector->base.encoder ? "enabled" : "disabled");
13072         }
13073 }
13074
13075 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
13076  * and i915 state tracking structures. */
13077 void intel_modeset_setup_hw_state(struct drm_device *dev,
13078                                   bool force_restore)
13079 {
13080         struct drm_i915_private *dev_priv = dev->dev_private;
13081         enum pipe pipe;
13082         struct intel_crtc *crtc;
13083         struct intel_encoder *encoder;
13084         int i;
13085
13086         intel_modeset_readout_hw_state(dev);
13087
13088         /*
13089          * Now that we have the config, copy it to each CRTC struct
13090          * Note that this could go away if we move to using crtc_config
13091          * checking everywhere.
13092          */
13093         for_each_intel_crtc(dev, crtc) {
13094                 if (crtc->active && i915.fastboot) {
13095                         intel_mode_from_pipe_config(&crtc->base.mode, &crtc->config);
13096                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
13097                                       crtc->base.base.id);
13098                         drm_mode_debug_printmodeline(&crtc->base.mode);
13099                 }
13100         }
13101
13102         /* HW state is read out, now we need to sanitize this mess. */
13103         for_each_intel_encoder(dev, encoder) {
13104                 intel_sanitize_encoder(encoder);
13105         }
13106
13107         for_each_pipe(dev_priv, pipe) {
13108                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13109                 intel_sanitize_crtc(crtc);
13110                 intel_dump_pipe_config(crtc, &crtc->config, "[setup_hw_state]");
13111         }
13112
13113         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13114                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13115
13116                 if (!pll->on || pll->active)
13117                         continue;
13118
13119                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
13120
13121                 pll->disable(dev_priv, pll);
13122                 pll->on = false;
13123         }
13124
13125         if (HAS_PCH_SPLIT(dev))
13126                 ilk_wm_get_hw_state(dev);
13127
13128         if (force_restore) {
13129                 i915_redisable_vga(dev);
13130
13131                 /*
13132                  * We need to use raw interfaces for restoring state to avoid
13133                  * checking (bogus) intermediate states.
13134                  */
13135                 for_each_pipe(dev_priv, pipe) {
13136                         struct drm_crtc *crtc =
13137                                 dev_priv->pipe_to_crtc_mapping[pipe];
13138
13139                         __intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y,
13140                                          crtc->primary->fb);
13141                 }
13142         } else {
13143                 intel_modeset_update_staged_output_state(dev);
13144         }
13145
13146         intel_modeset_check_state(dev);
13147 }
13148
13149 void intel_modeset_gem_init(struct drm_device *dev)
13150 {
13151         struct drm_crtc *c;
13152         struct drm_i915_gem_object *obj;
13153
13154         mutex_lock(&dev->struct_mutex);
13155         intel_init_gt_powersave(dev);
13156         mutex_unlock(&dev->struct_mutex);
13157
13158         intel_modeset_init_hw(dev);
13159
13160         intel_setup_overlay(dev);
13161
13162         /*
13163          * Make sure any fbs we allocated at startup are properly
13164          * pinned & fenced.  When we do the allocation it's too early
13165          * for this.
13166          */
13167         mutex_lock(&dev->struct_mutex);
13168         for_each_crtc(dev, c) {
13169                 obj = intel_fb_obj(c->primary->fb);
13170                 if (obj == NULL)
13171                         continue;
13172
13173                 if (intel_pin_and_fence_fb_obj(dev, obj, NULL)) {
13174                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
13175                                   to_intel_crtc(c)->pipe);
13176                         drm_framebuffer_unreference(c->primary->fb);
13177                         c->primary->fb = NULL;
13178                 }
13179         }
13180         mutex_unlock(&dev->struct_mutex);
13181 }
13182
13183 void intel_connector_unregister(struct intel_connector *intel_connector)
13184 {
13185         struct drm_connector *connector = &intel_connector->base;
13186
13187         intel_panel_destroy_backlight(connector);
13188         drm_connector_unregister(connector);
13189 }
13190
13191 void intel_modeset_cleanup(struct drm_device *dev)
13192 {
13193         struct drm_i915_private *dev_priv = dev->dev_private;
13194         struct drm_connector *connector;
13195
13196         /*
13197          * Interrupts and polling as the first thing to avoid creating havoc.
13198          * Too much stuff here (turning of rps, connectors, ...) would
13199          * experience fancy races otherwise.
13200          */
13201         intel_irq_uninstall(dev_priv);
13202
13203         /*
13204          * Due to the hpd irq storm handling the hotplug work can re-arm the
13205          * poll handlers. Hence disable polling after hpd handling is shut down.
13206          */
13207         drm_kms_helper_poll_fini(dev);
13208
13209         mutex_lock(&dev->struct_mutex);
13210
13211         intel_unregister_dsm_handler();
13212
13213         intel_disable_fbc(dev);
13214
13215         intel_disable_gt_powersave(dev);
13216
13217         ironlake_teardown_rc6(dev);
13218
13219         mutex_unlock(&dev->struct_mutex);
13220
13221         /* flush any delayed tasks or pending work */
13222         flush_scheduled_work();
13223
13224         /* destroy the backlight and sysfs files before encoders/connectors */
13225         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
13226                 struct intel_connector *intel_connector;
13227
13228                 intel_connector = to_intel_connector(connector);
13229                 intel_connector->unregister(intel_connector);
13230         }
13231
13232         drm_mode_config_cleanup(dev);
13233
13234         intel_cleanup_overlay(dev);
13235
13236         mutex_lock(&dev->struct_mutex);
13237         intel_cleanup_gt_powersave(dev);
13238         mutex_unlock(&dev->struct_mutex);
13239 }
13240
13241 /*
13242  * Return which encoder is currently attached for connector.
13243  */
13244 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
13245 {
13246         return &intel_attached_encoder(connector)->base;
13247 }
13248
13249 void intel_connector_attach_encoder(struct intel_connector *connector,
13250                                     struct intel_encoder *encoder)
13251 {
13252         connector->encoder = encoder;
13253         drm_mode_connector_attach_encoder(&connector->base,
13254                                           &encoder->base);
13255 }
13256
13257 /*
13258  * set vga decode state - true == enable VGA decode
13259  */
13260 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
13261 {
13262         struct drm_i915_private *dev_priv = dev->dev_private;
13263         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
13264         u16 gmch_ctrl;
13265
13266         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
13267                 DRM_ERROR("failed to read control word\n");
13268                 return -EIO;
13269         }
13270
13271         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
13272                 return 0;
13273
13274         if (state)
13275                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
13276         else
13277                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
13278
13279         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
13280                 DRM_ERROR("failed to write control word\n");
13281                 return -EIO;
13282         }
13283
13284         return 0;
13285 }
13286
13287 struct intel_display_error_state {
13288
13289         u32 power_well_driver;
13290
13291         int num_transcoders;
13292
13293         struct intel_cursor_error_state {
13294                 u32 control;
13295                 u32 position;
13296                 u32 base;
13297                 u32 size;
13298         } cursor[I915_MAX_PIPES];
13299
13300         struct intel_pipe_error_state {
13301                 bool power_domain_on;
13302                 u32 source;
13303                 u32 stat;
13304         } pipe[I915_MAX_PIPES];
13305
13306         struct intel_plane_error_state {
13307                 u32 control;
13308                 u32 stride;
13309                 u32 size;
13310                 u32 pos;
13311                 u32 addr;
13312                 u32 surface;
13313                 u32 tile_offset;
13314         } plane[I915_MAX_PIPES];
13315
13316         struct intel_transcoder_error_state {
13317                 bool power_domain_on;
13318                 enum transcoder cpu_transcoder;
13319
13320                 u32 conf;
13321
13322                 u32 htotal;
13323                 u32 hblank;
13324                 u32 hsync;
13325                 u32 vtotal;
13326                 u32 vblank;
13327                 u32 vsync;
13328         } transcoder[4];
13329 };
13330
13331 struct intel_display_error_state *
13332 intel_display_capture_error_state(struct drm_device *dev)
13333 {
13334         struct drm_i915_private *dev_priv = dev->dev_private;
13335         struct intel_display_error_state *error;
13336         int transcoders[] = {
13337                 TRANSCODER_A,
13338                 TRANSCODER_B,
13339                 TRANSCODER_C,
13340                 TRANSCODER_EDP,
13341         };
13342         int i;
13343
13344         if (INTEL_INFO(dev)->num_pipes == 0)
13345                 return NULL;
13346
13347         error = kzalloc(sizeof(*error), GFP_ATOMIC);
13348         if (error == NULL)
13349                 return NULL;
13350
13351         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
13352                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
13353
13354         for_each_pipe(dev_priv, i) {
13355                 error->pipe[i].power_domain_on =
13356                         __intel_display_power_is_enabled(dev_priv,
13357                                                          POWER_DOMAIN_PIPE(i));
13358                 if (!error->pipe[i].power_domain_on)
13359                         continue;
13360
13361                 error->cursor[i].control = I915_READ(CURCNTR(i));
13362                 error->cursor[i].position = I915_READ(CURPOS(i));
13363                 error->cursor[i].base = I915_READ(CURBASE(i));
13364
13365                 error->plane[i].control = I915_READ(DSPCNTR(i));
13366                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
13367                 if (INTEL_INFO(dev)->gen <= 3) {
13368                         error->plane[i].size = I915_READ(DSPSIZE(i));
13369                         error->plane[i].pos = I915_READ(DSPPOS(i));
13370                 }
13371                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
13372                         error->plane[i].addr = I915_READ(DSPADDR(i));
13373                 if (INTEL_INFO(dev)->gen >= 4) {
13374                         error->plane[i].surface = I915_READ(DSPSURF(i));
13375                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
13376                 }
13377
13378                 error->pipe[i].source = I915_READ(PIPESRC(i));
13379
13380                 if (HAS_GMCH_DISPLAY(dev))
13381                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
13382         }
13383
13384         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
13385         if (HAS_DDI(dev_priv->dev))
13386                 error->num_transcoders++; /* Account for eDP. */
13387
13388         for (i = 0; i < error->num_transcoders; i++) {
13389                 enum transcoder cpu_transcoder = transcoders[i];
13390
13391                 error->transcoder[i].power_domain_on =
13392                         __intel_display_power_is_enabled(dev_priv,
13393                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
13394                 if (!error->transcoder[i].power_domain_on)
13395                         continue;
13396
13397                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
13398
13399                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
13400                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
13401                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
13402                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
13403                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
13404                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
13405                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
13406         }
13407
13408         return error;
13409 }
13410
13411 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
13412
13413 void
13414 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
13415                                 struct drm_device *dev,
13416                                 struct intel_display_error_state *error)
13417 {
13418         struct drm_i915_private *dev_priv = dev->dev_private;
13419         int i;
13420
13421         if (!error)
13422                 return;
13423
13424         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
13425         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
13426                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
13427                            error->power_well_driver);
13428         for_each_pipe(dev_priv, i) {
13429                 err_printf(m, "Pipe [%d]:\n", i);
13430                 err_printf(m, "  Power: %s\n",
13431                            error->pipe[i].power_domain_on ? "on" : "off");
13432                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
13433                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
13434
13435                 err_printf(m, "Plane [%d]:\n", i);
13436                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
13437                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
13438                 if (INTEL_INFO(dev)->gen <= 3) {
13439                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
13440                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
13441                 }
13442                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
13443                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
13444                 if (INTEL_INFO(dev)->gen >= 4) {
13445                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
13446                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
13447                 }
13448
13449                 err_printf(m, "Cursor [%d]:\n", i);
13450                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
13451                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
13452                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
13453         }
13454
13455         for (i = 0; i < error->num_transcoders; i++) {
13456                 err_printf(m, "CPU transcoder: %c\n",
13457                            transcoder_name(error->transcoder[i].cpu_transcoder));
13458                 err_printf(m, "  Power: %s\n",
13459                            error->transcoder[i].power_domain_on ? "on" : "off");
13460                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
13461                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
13462                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
13463                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
13464                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
13465                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
13466                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
13467         }
13468 }
13469
13470 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
13471 {
13472         struct intel_crtc *crtc;
13473
13474         for_each_intel_crtc(dev, crtc) {
13475                 struct intel_unpin_work *work;
13476
13477                 spin_lock_irq(&dev->event_lock);
13478
13479                 work = crtc->unpin_work;
13480
13481                 if (work && work->event &&
13482                     work->event->base.file_priv == file) {
13483                         kfree(work->event);
13484                         work->event = NULL;
13485                 }
13486
13487                 spin_unlock_irq(&dev->event_lock);
13488         }
13489 }