164d54689efe18020b0630ee1fd37b25ba31868a
[cascardo/linux.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_atomic_helper.h>
41 #include <drm/drm_dp_helper.h>
42 #include <drm/drm_crtc_helper.h>
43 #include <drm/drm_plane_helper.h>
44 #include <drm/drm_rect.h>
45 #include <linux/dma_remapping.h>
46
47 /* Primary plane formats supported by all gen */
48 #define COMMON_PRIMARY_FORMATS \
49         DRM_FORMAT_C8, \
50         DRM_FORMAT_RGB565, \
51         DRM_FORMAT_XRGB8888, \
52         DRM_FORMAT_ARGB8888
53
54 /* Primary plane formats for gen <= 3 */
55 static const uint32_t intel_primary_formats_gen2[] = {
56         COMMON_PRIMARY_FORMATS,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_ARGB1555,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t intel_primary_formats_gen4[] = {
63         COMMON_PRIMARY_FORMATS, \
64         DRM_FORMAT_XBGR8888,
65         DRM_FORMAT_ABGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_ARGB2101010,
68         DRM_FORMAT_XBGR2101010,
69         DRM_FORMAT_ABGR2101010,
70 };
71
72 /* Cursor formats */
73 static const uint32_t intel_cursor_formats[] = {
74         DRM_FORMAT_ARGB8888,
75 };
76
77 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
78
79 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
80                                 struct intel_crtc_state *pipe_config);
81 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
82                                    struct intel_crtc_state *pipe_config);
83
84 static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
85                           int x, int y, struct drm_framebuffer *old_fb);
86 static int intel_framebuffer_init(struct drm_device *dev,
87                                   struct intel_framebuffer *ifb,
88                                   struct drm_mode_fb_cmd2 *mode_cmd,
89                                   struct drm_i915_gem_object *obj);
90 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
91 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
92 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
93                                          struct intel_link_m_n *m_n,
94                                          struct intel_link_m_n *m2_n2);
95 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
96 static void haswell_set_pipeconf(struct drm_crtc *crtc);
97 static void intel_set_pipe_csc(struct drm_crtc *crtc);
98 static void vlv_prepare_pll(struct intel_crtc *crtc,
99                             const struct intel_crtc_state *pipe_config);
100 static void chv_prepare_pll(struct intel_crtc *crtc,
101                             const struct intel_crtc_state *pipe_config);
102 static void intel_begin_crtc_commit(struct drm_crtc *crtc);
103 static void intel_finish_crtc_commit(struct drm_crtc *crtc);
104
105 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
106 {
107         if (!connector->mst_port)
108                 return connector->encoder;
109         else
110                 return &connector->mst_port->mst_encoders[pipe]->base;
111 }
112
113 typedef struct {
114         int     min, max;
115 } intel_range_t;
116
117 typedef struct {
118         int     dot_limit;
119         int     p2_slow, p2_fast;
120 } intel_p2_t;
121
122 typedef struct intel_limit intel_limit_t;
123 struct intel_limit {
124         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
125         intel_p2_t          p2;
126 };
127
128 int
129 intel_pch_rawclk(struct drm_device *dev)
130 {
131         struct drm_i915_private *dev_priv = dev->dev_private;
132
133         WARN_ON(!HAS_PCH_SPLIT(dev));
134
135         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
136 }
137
138 static inline u32 /* units of 100MHz */
139 intel_fdi_link_freq(struct drm_device *dev)
140 {
141         if (IS_GEN5(dev)) {
142                 struct drm_i915_private *dev_priv = dev->dev_private;
143                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
144         } else
145                 return 27;
146 }
147
148 static const intel_limit_t intel_limits_i8xx_dac = {
149         .dot = { .min = 25000, .max = 350000 },
150         .vco = { .min = 908000, .max = 1512000 },
151         .n = { .min = 2, .max = 16 },
152         .m = { .min = 96, .max = 140 },
153         .m1 = { .min = 18, .max = 26 },
154         .m2 = { .min = 6, .max = 16 },
155         .p = { .min = 4, .max = 128 },
156         .p1 = { .min = 2, .max = 33 },
157         .p2 = { .dot_limit = 165000,
158                 .p2_slow = 4, .p2_fast = 2 },
159 };
160
161 static const intel_limit_t intel_limits_i8xx_dvo = {
162         .dot = { .min = 25000, .max = 350000 },
163         .vco = { .min = 908000, .max = 1512000 },
164         .n = { .min = 2, .max = 16 },
165         .m = { .min = 96, .max = 140 },
166         .m1 = { .min = 18, .max = 26 },
167         .m2 = { .min = 6, .max = 16 },
168         .p = { .min = 4, .max = 128 },
169         .p1 = { .min = 2, .max = 33 },
170         .p2 = { .dot_limit = 165000,
171                 .p2_slow = 4, .p2_fast = 4 },
172 };
173
174 static const intel_limit_t intel_limits_i8xx_lvds = {
175         .dot = { .min = 25000, .max = 350000 },
176         .vco = { .min = 908000, .max = 1512000 },
177         .n = { .min = 2, .max = 16 },
178         .m = { .min = 96, .max = 140 },
179         .m1 = { .min = 18, .max = 26 },
180         .m2 = { .min = 6, .max = 16 },
181         .p = { .min = 4, .max = 128 },
182         .p1 = { .min = 1, .max = 6 },
183         .p2 = { .dot_limit = 165000,
184                 .p2_slow = 14, .p2_fast = 7 },
185 };
186
187 static const intel_limit_t intel_limits_i9xx_sdvo = {
188         .dot = { .min = 20000, .max = 400000 },
189         .vco = { .min = 1400000, .max = 2800000 },
190         .n = { .min = 1, .max = 6 },
191         .m = { .min = 70, .max = 120 },
192         .m1 = { .min = 8, .max = 18 },
193         .m2 = { .min = 3, .max = 7 },
194         .p = { .min = 5, .max = 80 },
195         .p1 = { .min = 1, .max = 8 },
196         .p2 = { .dot_limit = 200000,
197                 .p2_slow = 10, .p2_fast = 5 },
198 };
199
200 static const intel_limit_t intel_limits_i9xx_lvds = {
201         .dot = { .min = 20000, .max = 400000 },
202         .vco = { .min = 1400000, .max = 2800000 },
203         .n = { .min = 1, .max = 6 },
204         .m = { .min = 70, .max = 120 },
205         .m1 = { .min = 8, .max = 18 },
206         .m2 = { .min = 3, .max = 7 },
207         .p = { .min = 7, .max = 98 },
208         .p1 = { .min = 1, .max = 8 },
209         .p2 = { .dot_limit = 112000,
210                 .p2_slow = 14, .p2_fast = 7 },
211 };
212
213
214 static const intel_limit_t intel_limits_g4x_sdvo = {
215         .dot = { .min = 25000, .max = 270000 },
216         .vco = { .min = 1750000, .max = 3500000},
217         .n = { .min = 1, .max = 4 },
218         .m = { .min = 104, .max = 138 },
219         .m1 = { .min = 17, .max = 23 },
220         .m2 = { .min = 5, .max = 11 },
221         .p = { .min = 10, .max = 30 },
222         .p1 = { .min = 1, .max = 3},
223         .p2 = { .dot_limit = 270000,
224                 .p2_slow = 10,
225                 .p2_fast = 10
226         },
227 };
228
229 static const intel_limit_t intel_limits_g4x_hdmi = {
230         .dot = { .min = 22000, .max = 400000 },
231         .vco = { .min = 1750000, .max = 3500000},
232         .n = { .min = 1, .max = 4 },
233         .m = { .min = 104, .max = 138 },
234         .m1 = { .min = 16, .max = 23 },
235         .m2 = { .min = 5, .max = 11 },
236         .p = { .min = 5, .max = 80 },
237         .p1 = { .min = 1, .max = 8},
238         .p2 = { .dot_limit = 165000,
239                 .p2_slow = 10, .p2_fast = 5 },
240 };
241
242 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
243         .dot = { .min = 20000, .max = 115000 },
244         .vco = { .min = 1750000, .max = 3500000 },
245         .n = { .min = 1, .max = 3 },
246         .m = { .min = 104, .max = 138 },
247         .m1 = { .min = 17, .max = 23 },
248         .m2 = { .min = 5, .max = 11 },
249         .p = { .min = 28, .max = 112 },
250         .p1 = { .min = 2, .max = 8 },
251         .p2 = { .dot_limit = 0,
252                 .p2_slow = 14, .p2_fast = 14
253         },
254 };
255
256 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
257         .dot = { .min = 80000, .max = 224000 },
258         .vco = { .min = 1750000, .max = 3500000 },
259         .n = { .min = 1, .max = 3 },
260         .m = { .min = 104, .max = 138 },
261         .m1 = { .min = 17, .max = 23 },
262         .m2 = { .min = 5, .max = 11 },
263         .p = { .min = 14, .max = 42 },
264         .p1 = { .min = 2, .max = 6 },
265         .p2 = { .dot_limit = 0,
266                 .p2_slow = 7, .p2_fast = 7
267         },
268 };
269
270 static const intel_limit_t intel_limits_pineview_sdvo = {
271         .dot = { .min = 20000, .max = 400000},
272         .vco = { .min = 1700000, .max = 3500000 },
273         /* Pineview's Ncounter is a ring counter */
274         .n = { .min = 3, .max = 6 },
275         .m = { .min = 2, .max = 256 },
276         /* Pineview only has one combined m divider, which we treat as m2. */
277         .m1 = { .min = 0, .max = 0 },
278         .m2 = { .min = 0, .max = 254 },
279         .p = { .min = 5, .max = 80 },
280         .p1 = { .min = 1, .max = 8 },
281         .p2 = { .dot_limit = 200000,
282                 .p2_slow = 10, .p2_fast = 5 },
283 };
284
285 static const intel_limit_t intel_limits_pineview_lvds = {
286         .dot = { .min = 20000, .max = 400000 },
287         .vco = { .min = 1700000, .max = 3500000 },
288         .n = { .min = 3, .max = 6 },
289         .m = { .min = 2, .max = 256 },
290         .m1 = { .min = 0, .max = 0 },
291         .m2 = { .min = 0, .max = 254 },
292         .p = { .min = 7, .max = 112 },
293         .p1 = { .min = 1, .max = 8 },
294         .p2 = { .dot_limit = 112000,
295                 .p2_slow = 14, .p2_fast = 14 },
296 };
297
298 /* Ironlake / Sandybridge
299  *
300  * We calculate clock using (register_value + 2) for N/M1/M2, so here
301  * the range value for them is (actual_value - 2).
302  */
303 static const intel_limit_t intel_limits_ironlake_dac = {
304         .dot = { .min = 25000, .max = 350000 },
305         .vco = { .min = 1760000, .max = 3510000 },
306         .n = { .min = 1, .max = 5 },
307         .m = { .min = 79, .max = 127 },
308         .m1 = { .min = 12, .max = 22 },
309         .m2 = { .min = 5, .max = 9 },
310         .p = { .min = 5, .max = 80 },
311         .p1 = { .min = 1, .max = 8 },
312         .p2 = { .dot_limit = 225000,
313                 .p2_slow = 10, .p2_fast = 5 },
314 };
315
316 static const intel_limit_t intel_limits_ironlake_single_lvds = {
317         .dot = { .min = 25000, .max = 350000 },
318         .vco = { .min = 1760000, .max = 3510000 },
319         .n = { .min = 1, .max = 3 },
320         .m = { .min = 79, .max = 118 },
321         .m1 = { .min = 12, .max = 22 },
322         .m2 = { .min = 5, .max = 9 },
323         .p = { .min = 28, .max = 112 },
324         .p1 = { .min = 2, .max = 8 },
325         .p2 = { .dot_limit = 225000,
326                 .p2_slow = 14, .p2_fast = 14 },
327 };
328
329 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
330         .dot = { .min = 25000, .max = 350000 },
331         .vco = { .min = 1760000, .max = 3510000 },
332         .n = { .min = 1, .max = 3 },
333         .m = { .min = 79, .max = 127 },
334         .m1 = { .min = 12, .max = 22 },
335         .m2 = { .min = 5, .max = 9 },
336         .p = { .min = 14, .max = 56 },
337         .p1 = { .min = 2, .max = 8 },
338         .p2 = { .dot_limit = 225000,
339                 .p2_slow = 7, .p2_fast = 7 },
340 };
341
342 /* LVDS 100mhz refclk limits. */
343 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
344         .dot = { .min = 25000, .max = 350000 },
345         .vco = { .min = 1760000, .max = 3510000 },
346         .n = { .min = 1, .max = 2 },
347         .m = { .min = 79, .max = 126 },
348         .m1 = { .min = 12, .max = 22 },
349         .m2 = { .min = 5, .max = 9 },
350         .p = { .min = 28, .max = 112 },
351         .p1 = { .min = 2, .max = 8 },
352         .p2 = { .dot_limit = 225000,
353                 .p2_slow = 14, .p2_fast = 14 },
354 };
355
356 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
357         .dot = { .min = 25000, .max = 350000 },
358         .vco = { .min = 1760000, .max = 3510000 },
359         .n = { .min = 1, .max = 3 },
360         .m = { .min = 79, .max = 126 },
361         .m1 = { .min = 12, .max = 22 },
362         .m2 = { .min = 5, .max = 9 },
363         .p = { .min = 14, .max = 42 },
364         .p1 = { .min = 2, .max = 6 },
365         .p2 = { .dot_limit = 225000,
366                 .p2_slow = 7, .p2_fast = 7 },
367 };
368
369 static const intel_limit_t intel_limits_vlv = {
370          /*
371           * These are the data rate limits (measured in fast clocks)
372           * since those are the strictest limits we have. The fast
373           * clock and actual rate limits are more relaxed, so checking
374           * them would make no difference.
375           */
376         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
377         .vco = { .min = 4000000, .max = 6000000 },
378         .n = { .min = 1, .max = 7 },
379         .m1 = { .min = 2, .max = 3 },
380         .m2 = { .min = 11, .max = 156 },
381         .p1 = { .min = 2, .max = 3 },
382         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
383 };
384
385 static const intel_limit_t intel_limits_chv = {
386         /*
387          * These are the data rate limits (measured in fast clocks)
388          * since those are the strictest limits we have.  The fast
389          * clock and actual rate limits are more relaxed, so checking
390          * them would make no difference.
391          */
392         .dot = { .min = 25000 * 5, .max = 540000 * 5},
393         .vco = { .min = 4860000, .max = 6480000 },
394         .n = { .min = 1, .max = 1 },
395         .m1 = { .min = 2, .max = 2 },
396         .m2 = { .min = 24 << 22, .max = 175 << 22 },
397         .p1 = { .min = 2, .max = 4 },
398         .p2 = { .p2_slow = 1, .p2_fast = 14 },
399 };
400
401 static void vlv_clock(int refclk, intel_clock_t *clock)
402 {
403         clock->m = clock->m1 * clock->m2;
404         clock->p = clock->p1 * clock->p2;
405         if (WARN_ON(clock->n == 0 || clock->p == 0))
406                 return;
407         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
408         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
409 }
410
411 /**
412  * Returns whether any output on the specified pipe is of the specified type
413  */
414 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
415 {
416         struct drm_device *dev = crtc->base.dev;
417         struct intel_encoder *encoder;
418
419         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
420                 if (encoder->type == type)
421                         return true;
422
423         return false;
424 }
425
426 /**
427  * Returns whether any output on the specified pipe will have the specified
428  * type after a staged modeset is complete, i.e., the same as
429  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
430  * encoder->crtc.
431  */
432 static bool intel_pipe_will_have_type(struct intel_crtc *crtc, int type)
433 {
434         struct drm_device *dev = crtc->base.dev;
435         struct intel_encoder *encoder;
436
437         for_each_intel_encoder(dev, encoder)
438                 if (encoder->new_crtc == crtc && encoder->type == type)
439                         return true;
440
441         return false;
442 }
443
444 static const intel_limit_t *intel_ironlake_limit(struct intel_crtc *crtc,
445                                                 int refclk)
446 {
447         struct drm_device *dev = crtc->base.dev;
448         const intel_limit_t *limit;
449
450         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
451                 if (intel_is_dual_link_lvds(dev)) {
452                         if (refclk == 100000)
453                                 limit = &intel_limits_ironlake_dual_lvds_100m;
454                         else
455                                 limit = &intel_limits_ironlake_dual_lvds;
456                 } else {
457                         if (refclk == 100000)
458                                 limit = &intel_limits_ironlake_single_lvds_100m;
459                         else
460                                 limit = &intel_limits_ironlake_single_lvds;
461                 }
462         } else
463                 limit = &intel_limits_ironlake_dac;
464
465         return limit;
466 }
467
468 static const intel_limit_t *intel_g4x_limit(struct intel_crtc *crtc)
469 {
470         struct drm_device *dev = crtc->base.dev;
471         const intel_limit_t *limit;
472
473         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
474                 if (intel_is_dual_link_lvds(dev))
475                         limit = &intel_limits_g4x_dual_channel_lvds;
476                 else
477                         limit = &intel_limits_g4x_single_channel_lvds;
478         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_HDMI) ||
479                    intel_pipe_will_have_type(crtc, INTEL_OUTPUT_ANALOG)) {
480                 limit = &intel_limits_g4x_hdmi;
481         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_SDVO)) {
482                 limit = &intel_limits_g4x_sdvo;
483         } else /* The option is for other outputs */
484                 limit = &intel_limits_i9xx_sdvo;
485
486         return limit;
487 }
488
489 static const intel_limit_t *intel_limit(struct intel_crtc *crtc, int refclk)
490 {
491         struct drm_device *dev = crtc->base.dev;
492         const intel_limit_t *limit;
493
494         if (HAS_PCH_SPLIT(dev))
495                 limit = intel_ironlake_limit(crtc, refclk);
496         else if (IS_G4X(dev)) {
497                 limit = intel_g4x_limit(crtc);
498         } else if (IS_PINEVIEW(dev)) {
499                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
500                         limit = &intel_limits_pineview_lvds;
501                 else
502                         limit = &intel_limits_pineview_sdvo;
503         } else if (IS_CHERRYVIEW(dev)) {
504                 limit = &intel_limits_chv;
505         } else if (IS_VALLEYVIEW(dev)) {
506                 limit = &intel_limits_vlv;
507         } else if (!IS_GEN2(dev)) {
508                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
509                         limit = &intel_limits_i9xx_lvds;
510                 else
511                         limit = &intel_limits_i9xx_sdvo;
512         } else {
513                 if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
514                         limit = &intel_limits_i8xx_lvds;
515                 else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_DVO))
516                         limit = &intel_limits_i8xx_dvo;
517                 else
518                         limit = &intel_limits_i8xx_dac;
519         }
520         return limit;
521 }
522
523 /* m1 is reserved as 0 in Pineview, n is a ring counter */
524 static void pineview_clock(int refclk, intel_clock_t *clock)
525 {
526         clock->m = clock->m2 + 2;
527         clock->p = clock->p1 * clock->p2;
528         if (WARN_ON(clock->n == 0 || clock->p == 0))
529                 return;
530         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
531         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
532 }
533
534 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
535 {
536         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
537 }
538
539 static void i9xx_clock(int refclk, intel_clock_t *clock)
540 {
541         clock->m = i9xx_dpll_compute_m(clock);
542         clock->p = clock->p1 * clock->p2;
543         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
544                 return;
545         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
546         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
547 }
548
549 static void chv_clock(int refclk, intel_clock_t *clock)
550 {
551         clock->m = clock->m1 * clock->m2;
552         clock->p = clock->p1 * clock->p2;
553         if (WARN_ON(clock->n == 0 || clock->p == 0))
554                 return;
555         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
556                         clock->n << 22);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558 }
559
560 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
561 /**
562  * Returns whether the given set of divisors are valid for a given refclk with
563  * the given connectors.
564  */
565
566 static bool intel_PLL_is_valid(struct drm_device *dev,
567                                const intel_limit_t *limit,
568                                const intel_clock_t *clock)
569 {
570         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
571                 INTELPllInvalid("n out of range\n");
572         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
573                 INTELPllInvalid("p1 out of range\n");
574         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
575                 INTELPllInvalid("m2 out of range\n");
576         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
577                 INTELPllInvalid("m1 out of range\n");
578
579         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
580                 if (clock->m1 <= clock->m2)
581                         INTELPllInvalid("m1 <= m2\n");
582
583         if (!IS_VALLEYVIEW(dev)) {
584                 if (clock->p < limit->p.min || limit->p.max < clock->p)
585                         INTELPllInvalid("p out of range\n");
586                 if (clock->m < limit->m.min || limit->m.max < clock->m)
587                         INTELPllInvalid("m out of range\n");
588         }
589
590         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
591                 INTELPllInvalid("vco out of range\n");
592         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
593          * connector, etc., rather than just a single range.
594          */
595         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
596                 INTELPllInvalid("dot out of range\n");
597
598         return true;
599 }
600
601 static bool
602 i9xx_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
603                     int target, int refclk, intel_clock_t *match_clock,
604                     intel_clock_t *best_clock)
605 {
606         struct drm_device *dev = crtc->base.dev;
607         intel_clock_t clock;
608         int err = target;
609
610         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
611                 /*
612                  * For LVDS just rely on its current settings for dual-channel.
613                  * We haven't figured out how to reliably set up different
614                  * single/dual channel state, if we even can.
615                  */
616                 if (intel_is_dual_link_lvds(dev))
617                         clock.p2 = limit->p2.p2_fast;
618                 else
619                         clock.p2 = limit->p2.p2_slow;
620         } else {
621                 if (target < limit->p2.dot_limit)
622                         clock.p2 = limit->p2.p2_slow;
623                 else
624                         clock.p2 = limit->p2.p2_fast;
625         }
626
627         memset(best_clock, 0, sizeof(*best_clock));
628
629         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
630              clock.m1++) {
631                 for (clock.m2 = limit->m2.min;
632                      clock.m2 <= limit->m2.max; clock.m2++) {
633                         if (clock.m2 >= clock.m1)
634                                 break;
635                         for (clock.n = limit->n.min;
636                              clock.n <= limit->n.max; clock.n++) {
637                                 for (clock.p1 = limit->p1.min;
638                                         clock.p1 <= limit->p1.max; clock.p1++) {
639                                         int this_err;
640
641                                         i9xx_clock(refclk, &clock);
642                                         if (!intel_PLL_is_valid(dev, limit,
643                                                                 &clock))
644                                                 continue;
645                                         if (match_clock &&
646                                             clock.p != match_clock->p)
647                                                 continue;
648
649                                         this_err = abs(clock.dot - target);
650                                         if (this_err < err) {
651                                                 *best_clock = clock;
652                                                 err = this_err;
653                                         }
654                                 }
655                         }
656                 }
657         }
658
659         return (err != target);
660 }
661
662 static bool
663 pnv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
664                    int target, int refclk, intel_clock_t *match_clock,
665                    intel_clock_t *best_clock)
666 {
667         struct drm_device *dev = crtc->base.dev;
668         intel_clock_t clock;
669         int err = target;
670
671         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
672                 /*
673                  * For LVDS just rely on its current settings for dual-channel.
674                  * We haven't figured out how to reliably set up different
675                  * single/dual channel state, if we even can.
676                  */
677                 if (intel_is_dual_link_lvds(dev))
678                         clock.p2 = limit->p2.p2_fast;
679                 else
680                         clock.p2 = limit->p2.p2_slow;
681         } else {
682                 if (target < limit->p2.dot_limit)
683                         clock.p2 = limit->p2.p2_slow;
684                 else
685                         clock.p2 = limit->p2.p2_fast;
686         }
687
688         memset(best_clock, 0, sizeof(*best_clock));
689
690         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
691              clock.m1++) {
692                 for (clock.m2 = limit->m2.min;
693                      clock.m2 <= limit->m2.max; clock.m2++) {
694                         for (clock.n = limit->n.min;
695                              clock.n <= limit->n.max; clock.n++) {
696                                 for (clock.p1 = limit->p1.min;
697                                         clock.p1 <= limit->p1.max; clock.p1++) {
698                                         int this_err;
699
700                                         pineview_clock(refclk, &clock);
701                                         if (!intel_PLL_is_valid(dev, limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 static bool
722 g4x_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
723                    int target, int refclk, intel_clock_t *match_clock,
724                    intel_clock_t *best_clock)
725 {
726         struct drm_device *dev = crtc->base.dev;
727         intel_clock_t clock;
728         int max_n;
729         bool found;
730         /* approximately equals target * 0.00585 */
731         int err_most = (target >> 8) + (target >> 9);
732         found = false;
733
734         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
735                 if (intel_is_dual_link_lvds(dev))
736                         clock.p2 = limit->p2.p2_fast;
737                 else
738                         clock.p2 = limit->p2.p2_slow;
739         } else {
740                 if (target < limit->p2.dot_limit)
741                         clock.p2 = limit->p2.p2_slow;
742                 else
743                         clock.p2 = limit->p2.p2_fast;
744         }
745
746         memset(best_clock, 0, sizeof(*best_clock));
747         max_n = limit->n.max;
748         /* based on hardware requirement, prefer smaller n to precision */
749         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
750                 /* based on hardware requirement, prefere larger m1,m2 */
751                 for (clock.m1 = limit->m1.max;
752                      clock.m1 >= limit->m1.min; clock.m1--) {
753                         for (clock.m2 = limit->m2.max;
754                              clock.m2 >= limit->m2.min; clock.m2--) {
755                                 for (clock.p1 = limit->p1.max;
756                                      clock.p1 >= limit->p1.min; clock.p1--) {
757                                         int this_err;
758
759                                         i9xx_clock(refclk, &clock);
760                                         if (!intel_PLL_is_valid(dev, limit,
761                                                                 &clock))
762                                                 continue;
763
764                                         this_err = abs(clock.dot - target);
765                                         if (this_err < err_most) {
766                                                 *best_clock = clock;
767                                                 err_most = this_err;
768                                                 max_n = clock.n;
769                                                 found = true;
770                                         }
771                                 }
772                         }
773                 }
774         }
775         return found;
776 }
777
778 static bool
779 vlv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
780                    int target, int refclk, intel_clock_t *match_clock,
781                    intel_clock_t *best_clock)
782 {
783         struct drm_device *dev = crtc->base.dev;
784         intel_clock_t clock;
785         unsigned int bestppm = 1000000;
786         /* min update 19.2 MHz */
787         int max_n = min(limit->n.max, refclk / 19200);
788         bool found = false;
789
790         target *= 5; /* fast clock */
791
792         memset(best_clock, 0, sizeof(*best_clock));
793
794         /* based on hardware requirement, prefer smaller n to precision */
795         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
796                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
797                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
798                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
799                                 clock.p = clock.p1 * clock.p2;
800                                 /* based on hardware requirement, prefer bigger m1,m2 values */
801                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
802                                         unsigned int ppm, diff;
803
804                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
805                                                                      refclk * clock.m1);
806
807                                         vlv_clock(refclk, &clock);
808
809                                         if (!intel_PLL_is_valid(dev, limit,
810                                                                 &clock))
811                                                 continue;
812
813                                         diff = abs(clock.dot - target);
814                                         ppm = div_u64(1000000ULL * diff, target);
815
816                                         if (ppm < 100 && clock.p > best_clock->p) {
817                                                 bestppm = 0;
818                                                 *best_clock = clock;
819                                                 found = true;
820                                         }
821
822                                         if (bestppm >= 10 && ppm < bestppm - 10) {
823                                                 bestppm = ppm;
824                                                 *best_clock = clock;
825                                                 found = true;
826                                         }
827                                 }
828                         }
829                 }
830         }
831
832         return found;
833 }
834
835 static bool
836 chv_find_best_dpll(const intel_limit_t *limit, struct intel_crtc *crtc,
837                    int target, int refclk, intel_clock_t *match_clock,
838                    intel_clock_t *best_clock)
839 {
840         struct drm_device *dev = crtc->base.dev;
841         intel_clock_t clock;
842         uint64_t m2;
843         int found = false;
844
845         memset(best_clock, 0, sizeof(*best_clock));
846
847         /*
848          * Based on hardware doc, the n always set to 1, and m1 always
849          * set to 2.  If requires to support 200Mhz refclk, we need to
850          * revisit this because n may not 1 anymore.
851          */
852         clock.n = 1, clock.m1 = 2;
853         target *= 5;    /* fast clock */
854
855         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
856                 for (clock.p2 = limit->p2.p2_fast;
857                                 clock.p2 >= limit->p2.p2_slow;
858                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
859
860                         clock.p = clock.p1 * clock.p2;
861
862                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
863                                         clock.n) << 22, refclk * clock.m1);
864
865                         if (m2 > INT_MAX/clock.m1)
866                                 continue;
867
868                         clock.m2 = m2;
869
870                         chv_clock(refclk, &clock);
871
872                         if (!intel_PLL_is_valid(dev, limit, &clock))
873                                 continue;
874
875                         /* based on hardware requirement, prefer bigger p
876                          */
877                         if (clock.p > best_clock->p) {
878                                 *best_clock = clock;
879                                 found = true;
880                         }
881                 }
882         }
883
884         return found;
885 }
886
887 bool intel_crtc_active(struct drm_crtc *crtc)
888 {
889         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
890
891         /* Be paranoid as we can arrive here with only partial
892          * state retrieved from the hardware during setup.
893          *
894          * We can ditch the adjusted_mode.crtc_clock check as soon
895          * as Haswell has gained clock readout/fastboot support.
896          *
897          * We can ditch the crtc->primary->fb check as soon as we can
898          * properly reconstruct framebuffers.
899          */
900         return intel_crtc->active && crtc->primary->fb &&
901                 intel_crtc->config->base.adjusted_mode.crtc_clock;
902 }
903
904 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
905                                              enum pipe pipe)
906 {
907         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
908         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
909
910         return intel_crtc->config->cpu_transcoder;
911 }
912
913 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
914 {
915         struct drm_i915_private *dev_priv = dev->dev_private;
916         u32 reg = PIPEDSL(pipe);
917         u32 line1, line2;
918         u32 line_mask;
919
920         if (IS_GEN2(dev))
921                 line_mask = DSL_LINEMASK_GEN2;
922         else
923                 line_mask = DSL_LINEMASK_GEN3;
924
925         line1 = I915_READ(reg) & line_mask;
926         mdelay(5);
927         line2 = I915_READ(reg) & line_mask;
928
929         return line1 == line2;
930 }
931
932 /*
933  * intel_wait_for_pipe_off - wait for pipe to turn off
934  * @crtc: crtc whose pipe to wait for
935  *
936  * After disabling a pipe, we can't wait for vblank in the usual way,
937  * spinning on the vblank interrupt status bit, since we won't actually
938  * see an interrupt when the pipe is disabled.
939  *
940  * On Gen4 and above:
941  *   wait for the pipe register state bit to turn off
942  *
943  * Otherwise:
944  *   wait for the display line value to settle (it usually
945  *   ends up stopping at the start of the next frame).
946  *
947  */
948 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
949 {
950         struct drm_device *dev = crtc->base.dev;
951         struct drm_i915_private *dev_priv = dev->dev_private;
952         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
953         enum pipe pipe = crtc->pipe;
954
955         if (INTEL_INFO(dev)->gen >= 4) {
956                 int reg = PIPECONF(cpu_transcoder);
957
958                 /* Wait for the Pipe State to go off */
959                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
960                              100))
961                         WARN(1, "pipe_off wait timed out\n");
962         } else {
963                 /* Wait for the display line to settle */
964                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
965                         WARN(1, "pipe_off wait timed out\n");
966         }
967 }
968
969 /*
970  * ibx_digital_port_connected - is the specified port connected?
971  * @dev_priv: i915 private structure
972  * @port: the port to test
973  *
974  * Returns true if @port is connected, false otherwise.
975  */
976 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
977                                 struct intel_digital_port *port)
978 {
979         u32 bit;
980
981         if (HAS_PCH_IBX(dev_priv->dev)) {
982                 switch (port->port) {
983                 case PORT_B:
984                         bit = SDE_PORTB_HOTPLUG;
985                         break;
986                 case PORT_C:
987                         bit = SDE_PORTC_HOTPLUG;
988                         break;
989                 case PORT_D:
990                         bit = SDE_PORTD_HOTPLUG;
991                         break;
992                 default:
993                         return true;
994                 }
995         } else {
996                 switch (port->port) {
997                 case PORT_B:
998                         bit = SDE_PORTB_HOTPLUG_CPT;
999                         break;
1000                 case PORT_C:
1001                         bit = SDE_PORTC_HOTPLUG_CPT;
1002                         break;
1003                 case PORT_D:
1004                         bit = SDE_PORTD_HOTPLUG_CPT;
1005                         break;
1006                 default:
1007                         return true;
1008                 }
1009         }
1010
1011         return I915_READ(SDEISR) & bit;
1012 }
1013
1014 static const char *state_string(bool enabled)
1015 {
1016         return enabled ? "on" : "off";
1017 }
1018
1019 /* Only for pre-ILK configs */
1020 void assert_pll(struct drm_i915_private *dev_priv,
1021                 enum pipe pipe, bool state)
1022 {
1023         int reg;
1024         u32 val;
1025         bool cur_state;
1026
1027         reg = DPLL(pipe);
1028         val = I915_READ(reg);
1029         cur_state = !!(val & DPLL_VCO_ENABLE);
1030         I915_STATE_WARN(cur_state != state,
1031              "PLL state assertion failure (expected %s, current %s)\n",
1032              state_string(state), state_string(cur_state));
1033 }
1034
1035 /* XXX: the dsi pll is shared between MIPI DSI ports */
1036 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1037 {
1038         u32 val;
1039         bool cur_state;
1040
1041         mutex_lock(&dev_priv->dpio_lock);
1042         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1043         mutex_unlock(&dev_priv->dpio_lock);
1044
1045         cur_state = val & DSI_PLL_VCO_EN;
1046         I915_STATE_WARN(cur_state != state,
1047              "DSI PLL state assertion failure (expected %s, current %s)\n",
1048              state_string(state), state_string(cur_state));
1049 }
1050 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1051 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1052
1053 struct intel_shared_dpll *
1054 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1055 {
1056         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1057
1058         if (crtc->config->shared_dpll < 0)
1059                 return NULL;
1060
1061         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1062 }
1063
1064 /* For ILK+ */
1065 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1066                         struct intel_shared_dpll *pll,
1067                         bool state)
1068 {
1069         bool cur_state;
1070         struct intel_dpll_hw_state hw_state;
1071
1072         if (WARN (!pll,
1073                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1074                 return;
1075
1076         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1077         I915_STATE_WARN(cur_state != state,
1078              "%s assertion failure (expected %s, current %s)\n",
1079              pll->name, state_string(state), state_string(cur_state));
1080 }
1081
1082 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1083                           enum pipe pipe, bool state)
1084 {
1085         int reg;
1086         u32 val;
1087         bool cur_state;
1088         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1089                                                                       pipe);
1090
1091         if (HAS_DDI(dev_priv->dev)) {
1092                 /* DDI does not have a specific FDI_TX register */
1093                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1094                 val = I915_READ(reg);
1095                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1096         } else {
1097                 reg = FDI_TX_CTL(pipe);
1098                 val = I915_READ(reg);
1099                 cur_state = !!(val & FDI_TX_ENABLE);
1100         }
1101         I915_STATE_WARN(cur_state != state,
1102              "FDI TX state assertion failure (expected %s, current %s)\n",
1103              state_string(state), state_string(cur_state));
1104 }
1105 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1106 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1107
1108 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1109                           enum pipe pipe, bool state)
1110 {
1111         int reg;
1112         u32 val;
1113         bool cur_state;
1114
1115         reg = FDI_RX_CTL(pipe);
1116         val = I915_READ(reg);
1117         cur_state = !!(val & FDI_RX_ENABLE);
1118         I915_STATE_WARN(cur_state != state,
1119              "FDI RX state assertion failure (expected %s, current %s)\n",
1120              state_string(state), state_string(cur_state));
1121 }
1122 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1123 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1124
1125 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1126                                       enum pipe pipe)
1127 {
1128         int reg;
1129         u32 val;
1130
1131         /* ILK FDI PLL is always enabled */
1132         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1133                 return;
1134
1135         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1136         if (HAS_DDI(dev_priv->dev))
1137                 return;
1138
1139         reg = FDI_TX_CTL(pipe);
1140         val = I915_READ(reg);
1141         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1142 }
1143
1144 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1145                        enum pipe pipe, bool state)
1146 {
1147         int reg;
1148         u32 val;
1149         bool cur_state;
1150
1151         reg = FDI_RX_CTL(pipe);
1152         val = I915_READ(reg);
1153         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1154         I915_STATE_WARN(cur_state != state,
1155              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1156              state_string(state), state_string(cur_state));
1157 }
1158
1159 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1160                            enum pipe pipe)
1161 {
1162         struct drm_device *dev = dev_priv->dev;
1163         int pp_reg;
1164         u32 val;
1165         enum pipe panel_pipe = PIPE_A;
1166         bool locked = true;
1167
1168         if (WARN_ON(HAS_DDI(dev)))
1169                 return;
1170
1171         if (HAS_PCH_SPLIT(dev)) {
1172                 u32 port_sel;
1173
1174                 pp_reg = PCH_PP_CONTROL;
1175                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1176
1177                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1178                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1179                         panel_pipe = PIPE_B;
1180                 /* XXX: else fix for eDP */
1181         } else if (IS_VALLEYVIEW(dev)) {
1182                 /* presumably write lock depends on pipe, not port select */
1183                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1184                 panel_pipe = pipe;
1185         } else {
1186                 pp_reg = PP_CONTROL;
1187                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1188                         panel_pipe = PIPE_B;
1189         }
1190
1191         val = I915_READ(pp_reg);
1192         if (!(val & PANEL_POWER_ON) ||
1193             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1194                 locked = false;
1195
1196         I915_STATE_WARN(panel_pipe == pipe && locked,
1197              "panel assertion failure, pipe %c regs locked\n",
1198              pipe_name(pipe));
1199 }
1200
1201 static void assert_cursor(struct drm_i915_private *dev_priv,
1202                           enum pipe pipe, bool state)
1203 {
1204         struct drm_device *dev = dev_priv->dev;
1205         bool cur_state;
1206
1207         if (IS_845G(dev) || IS_I865G(dev))
1208                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1209         else
1210                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1211
1212         I915_STATE_WARN(cur_state != state,
1213              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1214              pipe_name(pipe), state_string(state), state_string(cur_state));
1215 }
1216 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1217 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1218
1219 void assert_pipe(struct drm_i915_private *dev_priv,
1220                  enum pipe pipe, bool state)
1221 {
1222         int reg;
1223         u32 val;
1224         bool cur_state;
1225         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1226                                                                       pipe);
1227
1228         /* if we need the pipe quirk it must be always on */
1229         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1230             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1231                 state = true;
1232
1233         if (!intel_display_power_is_enabled(dev_priv,
1234                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1235                 cur_state = false;
1236         } else {
1237                 reg = PIPECONF(cpu_transcoder);
1238                 val = I915_READ(reg);
1239                 cur_state = !!(val & PIPECONF_ENABLE);
1240         }
1241
1242         I915_STATE_WARN(cur_state != state,
1243              "pipe %c assertion failure (expected %s, current %s)\n",
1244              pipe_name(pipe), state_string(state), state_string(cur_state));
1245 }
1246
1247 static void assert_plane(struct drm_i915_private *dev_priv,
1248                          enum plane plane, bool state)
1249 {
1250         int reg;
1251         u32 val;
1252         bool cur_state;
1253
1254         reg = DSPCNTR(plane);
1255         val = I915_READ(reg);
1256         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1257         I915_STATE_WARN(cur_state != state,
1258              "plane %c assertion failure (expected %s, current %s)\n",
1259              plane_name(plane), state_string(state), state_string(cur_state));
1260 }
1261
1262 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1263 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1264
1265 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1266                                    enum pipe pipe)
1267 {
1268         struct drm_device *dev = dev_priv->dev;
1269         int reg, i;
1270         u32 val;
1271         int cur_pipe;
1272
1273         /* Primary planes are fixed to pipes on gen4+ */
1274         if (INTEL_INFO(dev)->gen >= 4) {
1275                 reg = DSPCNTR(pipe);
1276                 val = I915_READ(reg);
1277                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1278                      "plane %c assertion failure, should be disabled but not\n",
1279                      plane_name(pipe));
1280                 return;
1281         }
1282
1283         /* Need to check both planes against the pipe */
1284         for_each_pipe(dev_priv, i) {
1285                 reg = DSPCNTR(i);
1286                 val = I915_READ(reg);
1287                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1288                         DISPPLANE_SEL_PIPE_SHIFT;
1289                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1290                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1291                      plane_name(i), pipe_name(pipe));
1292         }
1293 }
1294
1295 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1296                                     enum pipe pipe)
1297 {
1298         struct drm_device *dev = dev_priv->dev;
1299         int reg, sprite;
1300         u32 val;
1301
1302         if (INTEL_INFO(dev)->gen >= 9) {
1303                 for_each_sprite(pipe, sprite) {
1304                         val = I915_READ(PLANE_CTL(pipe, sprite));
1305                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1306                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1307                              sprite, pipe_name(pipe));
1308                 }
1309         } else if (IS_VALLEYVIEW(dev)) {
1310                 for_each_sprite(pipe, sprite) {
1311                         reg = SPCNTR(pipe, sprite);
1312                         val = I915_READ(reg);
1313                         I915_STATE_WARN(val & SP_ENABLE,
1314                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1315                              sprite_name(pipe, sprite), pipe_name(pipe));
1316                 }
1317         } else if (INTEL_INFO(dev)->gen >= 7) {
1318                 reg = SPRCTL(pipe);
1319                 val = I915_READ(reg);
1320                 I915_STATE_WARN(val & SPRITE_ENABLE,
1321                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1322                      plane_name(pipe), pipe_name(pipe));
1323         } else if (INTEL_INFO(dev)->gen >= 5) {
1324                 reg = DVSCNTR(pipe);
1325                 val = I915_READ(reg);
1326                 I915_STATE_WARN(val & DVS_ENABLE,
1327                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1328                      plane_name(pipe), pipe_name(pipe));
1329         }
1330 }
1331
1332 static void assert_vblank_disabled(struct drm_crtc *crtc)
1333 {
1334         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1335                 drm_crtc_vblank_put(crtc);
1336 }
1337
1338 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1339 {
1340         u32 val;
1341         bool enabled;
1342
1343         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1344
1345         val = I915_READ(PCH_DREF_CONTROL);
1346         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1347                             DREF_SUPERSPREAD_SOURCE_MASK));
1348         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1349 }
1350
1351 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1352                                            enum pipe pipe)
1353 {
1354         int reg;
1355         u32 val;
1356         bool enabled;
1357
1358         reg = PCH_TRANSCONF(pipe);
1359         val = I915_READ(reg);
1360         enabled = !!(val & TRANS_ENABLE);
1361         I915_STATE_WARN(enabled,
1362              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1363              pipe_name(pipe));
1364 }
1365
1366 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1367                             enum pipe pipe, u32 port_sel, u32 val)
1368 {
1369         if ((val & DP_PORT_EN) == 0)
1370                 return false;
1371
1372         if (HAS_PCH_CPT(dev_priv->dev)) {
1373                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1374                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1375                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1376                         return false;
1377         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1378                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1379                         return false;
1380         } else {
1381                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1382                         return false;
1383         }
1384         return true;
1385 }
1386
1387 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1388                               enum pipe pipe, u32 val)
1389 {
1390         if ((val & SDVO_ENABLE) == 0)
1391                 return false;
1392
1393         if (HAS_PCH_CPT(dev_priv->dev)) {
1394                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1395                         return false;
1396         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1397                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1398                         return false;
1399         } else {
1400                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1401                         return false;
1402         }
1403         return true;
1404 }
1405
1406 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1407                               enum pipe pipe, u32 val)
1408 {
1409         if ((val & LVDS_PORT_EN) == 0)
1410                 return false;
1411
1412         if (HAS_PCH_CPT(dev_priv->dev)) {
1413                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1414                         return false;
1415         } else {
1416                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1417                         return false;
1418         }
1419         return true;
1420 }
1421
1422 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1423                               enum pipe pipe, u32 val)
1424 {
1425         if ((val & ADPA_DAC_ENABLE) == 0)
1426                 return false;
1427         if (HAS_PCH_CPT(dev_priv->dev)) {
1428                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1429                         return false;
1430         } else {
1431                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1432                         return false;
1433         }
1434         return true;
1435 }
1436
1437 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1438                                    enum pipe pipe, int reg, u32 port_sel)
1439 {
1440         u32 val = I915_READ(reg);
1441         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1442              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1443              reg, pipe_name(pipe));
1444
1445         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1446              && (val & DP_PIPEB_SELECT),
1447              "IBX PCH dp port still using transcoder B\n");
1448 }
1449
1450 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1451                                      enum pipe pipe, int reg)
1452 {
1453         u32 val = I915_READ(reg);
1454         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1455              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1456              reg, pipe_name(pipe));
1457
1458         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1459              && (val & SDVO_PIPE_B_SELECT),
1460              "IBX PCH hdmi port still using transcoder B\n");
1461 }
1462
1463 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1464                                       enum pipe pipe)
1465 {
1466         int reg;
1467         u32 val;
1468
1469         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1470         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1471         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1472
1473         reg = PCH_ADPA;
1474         val = I915_READ(reg);
1475         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1476              "PCH VGA enabled on transcoder %c, should be disabled\n",
1477              pipe_name(pipe));
1478
1479         reg = PCH_LVDS;
1480         val = I915_READ(reg);
1481         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1482              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1483              pipe_name(pipe));
1484
1485         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1486         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1487         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1488 }
1489
1490 static void intel_init_dpio(struct drm_device *dev)
1491 {
1492         struct drm_i915_private *dev_priv = dev->dev_private;
1493
1494         if (!IS_VALLEYVIEW(dev))
1495                 return;
1496
1497         /*
1498          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1499          * CHV x1 PHY (DP/HDMI D)
1500          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1501          */
1502         if (IS_CHERRYVIEW(dev)) {
1503                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1504                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1505         } else {
1506                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1507         }
1508 }
1509
1510 static void vlv_enable_pll(struct intel_crtc *crtc,
1511                            const struct intel_crtc_state *pipe_config)
1512 {
1513         struct drm_device *dev = crtc->base.dev;
1514         struct drm_i915_private *dev_priv = dev->dev_private;
1515         int reg = DPLL(crtc->pipe);
1516         u32 dpll = pipe_config->dpll_hw_state.dpll;
1517
1518         assert_pipe_disabled(dev_priv, crtc->pipe);
1519
1520         /* No really, not for ILK+ */
1521         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1522
1523         /* PLL is protected by panel, make sure we can write it */
1524         if (IS_MOBILE(dev_priv->dev))
1525                 assert_panel_unlocked(dev_priv, crtc->pipe);
1526
1527         I915_WRITE(reg, dpll);
1528         POSTING_READ(reg);
1529         udelay(150);
1530
1531         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1532                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1533
1534         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1535         POSTING_READ(DPLL_MD(crtc->pipe));
1536
1537         /* We do this three times for luck */
1538         I915_WRITE(reg, dpll);
1539         POSTING_READ(reg);
1540         udelay(150); /* wait for warmup */
1541         I915_WRITE(reg, dpll);
1542         POSTING_READ(reg);
1543         udelay(150); /* wait for warmup */
1544         I915_WRITE(reg, dpll);
1545         POSTING_READ(reg);
1546         udelay(150); /* wait for warmup */
1547 }
1548
1549 static void chv_enable_pll(struct intel_crtc *crtc,
1550                            const struct intel_crtc_state *pipe_config)
1551 {
1552         struct drm_device *dev = crtc->base.dev;
1553         struct drm_i915_private *dev_priv = dev->dev_private;
1554         int pipe = crtc->pipe;
1555         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1556         u32 tmp;
1557
1558         assert_pipe_disabled(dev_priv, crtc->pipe);
1559
1560         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1561
1562         mutex_lock(&dev_priv->dpio_lock);
1563
1564         /* Enable back the 10bit clock to display controller */
1565         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1566         tmp |= DPIO_DCLKP_EN;
1567         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1568
1569         /*
1570          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1571          */
1572         udelay(1);
1573
1574         /* Enable PLL */
1575         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1576
1577         /* Check PLL is locked */
1578         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1579                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1580
1581         /* not sure when this should be written */
1582         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1583         POSTING_READ(DPLL_MD(pipe));
1584
1585         mutex_unlock(&dev_priv->dpio_lock);
1586 }
1587
1588 static int intel_num_dvo_pipes(struct drm_device *dev)
1589 {
1590         struct intel_crtc *crtc;
1591         int count = 0;
1592
1593         for_each_intel_crtc(dev, crtc)
1594                 count += crtc->active &&
1595                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1596
1597         return count;
1598 }
1599
1600 static void i9xx_enable_pll(struct intel_crtc *crtc)
1601 {
1602         struct drm_device *dev = crtc->base.dev;
1603         struct drm_i915_private *dev_priv = dev->dev_private;
1604         int reg = DPLL(crtc->pipe);
1605         u32 dpll = crtc->config->dpll_hw_state.dpll;
1606
1607         assert_pipe_disabled(dev_priv, crtc->pipe);
1608
1609         /* No really, not for ILK+ */
1610         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1611
1612         /* PLL is protected by panel, make sure we can write it */
1613         if (IS_MOBILE(dev) && !IS_I830(dev))
1614                 assert_panel_unlocked(dev_priv, crtc->pipe);
1615
1616         /* Enable DVO 2x clock on both PLLs if necessary */
1617         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1618                 /*
1619                  * It appears to be important that we don't enable this
1620                  * for the current pipe before otherwise configuring the
1621                  * PLL. No idea how this should be handled if multiple
1622                  * DVO outputs are enabled simultaneosly.
1623                  */
1624                 dpll |= DPLL_DVO_2X_MODE;
1625                 I915_WRITE(DPLL(!crtc->pipe),
1626                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1627         }
1628
1629         /* Wait for the clocks to stabilize. */
1630         POSTING_READ(reg);
1631         udelay(150);
1632
1633         if (INTEL_INFO(dev)->gen >= 4) {
1634                 I915_WRITE(DPLL_MD(crtc->pipe),
1635                            crtc->config->dpll_hw_state.dpll_md);
1636         } else {
1637                 /* The pixel multiplier can only be updated once the
1638                  * DPLL is enabled and the clocks are stable.
1639                  *
1640                  * So write it again.
1641                  */
1642                 I915_WRITE(reg, dpll);
1643         }
1644
1645         /* We do this three times for luck */
1646         I915_WRITE(reg, dpll);
1647         POSTING_READ(reg);
1648         udelay(150); /* wait for warmup */
1649         I915_WRITE(reg, dpll);
1650         POSTING_READ(reg);
1651         udelay(150); /* wait for warmup */
1652         I915_WRITE(reg, dpll);
1653         POSTING_READ(reg);
1654         udelay(150); /* wait for warmup */
1655 }
1656
1657 /**
1658  * i9xx_disable_pll - disable a PLL
1659  * @dev_priv: i915 private structure
1660  * @pipe: pipe PLL to disable
1661  *
1662  * Disable the PLL for @pipe, making sure the pipe is off first.
1663  *
1664  * Note!  This is for pre-ILK only.
1665  */
1666 static void i9xx_disable_pll(struct intel_crtc *crtc)
1667 {
1668         struct drm_device *dev = crtc->base.dev;
1669         struct drm_i915_private *dev_priv = dev->dev_private;
1670         enum pipe pipe = crtc->pipe;
1671
1672         /* Disable DVO 2x clock on both PLLs if necessary */
1673         if (IS_I830(dev) &&
1674             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1675             intel_num_dvo_pipes(dev) == 1) {
1676                 I915_WRITE(DPLL(PIPE_B),
1677                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1678                 I915_WRITE(DPLL(PIPE_A),
1679                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1680         }
1681
1682         /* Don't disable pipe or pipe PLLs if needed */
1683         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1684             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1685                 return;
1686
1687         /* Make sure the pipe isn't still relying on us */
1688         assert_pipe_disabled(dev_priv, pipe);
1689
1690         I915_WRITE(DPLL(pipe), 0);
1691         POSTING_READ(DPLL(pipe));
1692 }
1693
1694 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1695 {
1696         u32 val = 0;
1697
1698         /* Make sure the pipe isn't still relying on us */
1699         assert_pipe_disabled(dev_priv, pipe);
1700
1701         /*
1702          * Leave integrated clock source and reference clock enabled for pipe B.
1703          * The latter is needed for VGA hotplug / manual detection.
1704          */
1705         if (pipe == PIPE_B)
1706                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1707         I915_WRITE(DPLL(pipe), val);
1708         POSTING_READ(DPLL(pipe));
1709
1710 }
1711
1712 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1715         u32 val;
1716
1717         /* Make sure the pipe isn't still relying on us */
1718         assert_pipe_disabled(dev_priv, pipe);
1719
1720         /* Set PLL en = 0 */
1721         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1722         if (pipe != PIPE_A)
1723                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726
1727         mutex_lock(&dev_priv->dpio_lock);
1728
1729         /* Disable 10bit clock to display controller */
1730         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1731         val &= ~DPIO_DCLKP_EN;
1732         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1733
1734         /* disable left/right clock distribution */
1735         if (pipe != PIPE_B) {
1736                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1737                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1738                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1739         } else {
1740                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1741                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1742                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1743         }
1744
1745         mutex_unlock(&dev_priv->dpio_lock);
1746 }
1747
1748 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1749                 struct intel_digital_port *dport)
1750 {
1751         u32 port_mask;
1752         int dpll_reg;
1753
1754         switch (dport->port) {
1755         case PORT_B:
1756                 port_mask = DPLL_PORTB_READY_MASK;
1757                 dpll_reg = DPLL(0);
1758                 break;
1759         case PORT_C:
1760                 port_mask = DPLL_PORTC_READY_MASK;
1761                 dpll_reg = DPLL(0);
1762                 break;
1763         case PORT_D:
1764                 port_mask = DPLL_PORTD_READY_MASK;
1765                 dpll_reg = DPIO_PHY_STATUS;
1766                 break;
1767         default:
1768                 BUG();
1769         }
1770
1771         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1772                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1773                      port_name(dport->port), I915_READ(dpll_reg));
1774 }
1775
1776 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1777 {
1778         struct drm_device *dev = crtc->base.dev;
1779         struct drm_i915_private *dev_priv = dev->dev_private;
1780         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1781
1782         if (WARN_ON(pll == NULL))
1783                 return;
1784
1785         WARN_ON(!pll->config.crtc_mask);
1786         if (pll->active == 0) {
1787                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1788                 WARN_ON(pll->on);
1789                 assert_shared_dpll_disabled(dev_priv, pll);
1790
1791                 pll->mode_set(dev_priv, pll);
1792         }
1793 }
1794
1795 /**
1796  * intel_enable_shared_dpll - enable PCH PLL
1797  * @dev_priv: i915 private structure
1798  * @pipe: pipe PLL to enable
1799  *
1800  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1801  * drives the transcoder clock.
1802  */
1803 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1804 {
1805         struct drm_device *dev = crtc->base.dev;
1806         struct drm_i915_private *dev_priv = dev->dev_private;
1807         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1808
1809         if (WARN_ON(pll == NULL))
1810                 return;
1811
1812         if (WARN_ON(pll->config.crtc_mask == 0))
1813                 return;
1814
1815         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1816                       pll->name, pll->active, pll->on,
1817                       crtc->base.base.id);
1818
1819         if (pll->active++) {
1820                 WARN_ON(!pll->on);
1821                 assert_shared_dpll_enabled(dev_priv, pll);
1822                 return;
1823         }
1824         WARN_ON(pll->on);
1825
1826         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1827
1828         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1829         pll->enable(dev_priv, pll);
1830         pll->on = true;
1831 }
1832
1833 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1834 {
1835         struct drm_device *dev = crtc->base.dev;
1836         struct drm_i915_private *dev_priv = dev->dev_private;
1837         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1838
1839         /* PCH only available on ILK+ */
1840         BUG_ON(INTEL_INFO(dev)->gen < 5);
1841         if (WARN_ON(pll == NULL))
1842                return;
1843
1844         if (WARN_ON(pll->config.crtc_mask == 0))
1845                 return;
1846
1847         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1848                       pll->name, pll->active, pll->on,
1849                       crtc->base.base.id);
1850
1851         if (WARN_ON(pll->active == 0)) {
1852                 assert_shared_dpll_disabled(dev_priv, pll);
1853                 return;
1854         }
1855
1856         assert_shared_dpll_enabled(dev_priv, pll);
1857         WARN_ON(!pll->on);
1858         if (--pll->active)
1859                 return;
1860
1861         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1862         pll->disable(dev_priv, pll);
1863         pll->on = false;
1864
1865         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1866 }
1867
1868 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1869                                            enum pipe pipe)
1870 {
1871         struct drm_device *dev = dev_priv->dev;
1872         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1874         uint32_t reg, val, pipeconf_val;
1875
1876         /* PCH only available on ILK+ */
1877         BUG_ON(!HAS_PCH_SPLIT(dev));
1878
1879         /* Make sure PCH DPLL is enabled */
1880         assert_shared_dpll_enabled(dev_priv,
1881                                    intel_crtc_to_shared_dpll(intel_crtc));
1882
1883         /* FDI must be feeding us bits for PCH ports */
1884         assert_fdi_tx_enabled(dev_priv, pipe);
1885         assert_fdi_rx_enabled(dev_priv, pipe);
1886
1887         if (HAS_PCH_CPT(dev)) {
1888                 /* Workaround: Set the timing override bit before enabling the
1889                  * pch transcoder. */
1890                 reg = TRANS_CHICKEN2(pipe);
1891                 val = I915_READ(reg);
1892                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1893                 I915_WRITE(reg, val);
1894         }
1895
1896         reg = PCH_TRANSCONF(pipe);
1897         val = I915_READ(reg);
1898         pipeconf_val = I915_READ(PIPECONF(pipe));
1899
1900         if (HAS_PCH_IBX(dev_priv->dev)) {
1901                 /*
1902                  * make the BPC in transcoder be consistent with
1903                  * that in pipeconf reg.
1904                  */
1905                 val &= ~PIPECONF_BPC_MASK;
1906                 val |= pipeconf_val & PIPECONF_BPC_MASK;
1907         }
1908
1909         val &= ~TRANS_INTERLACE_MASK;
1910         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1911                 if (HAS_PCH_IBX(dev_priv->dev) &&
1912                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1913                         val |= TRANS_LEGACY_INTERLACED_ILK;
1914                 else
1915                         val |= TRANS_INTERLACED;
1916         else
1917                 val |= TRANS_PROGRESSIVE;
1918
1919         I915_WRITE(reg, val | TRANS_ENABLE);
1920         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1921                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1922 }
1923
1924 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1925                                       enum transcoder cpu_transcoder)
1926 {
1927         u32 val, pipeconf_val;
1928
1929         /* PCH only available on ILK+ */
1930         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1931
1932         /* FDI must be feeding us bits for PCH ports */
1933         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1934         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1935
1936         /* Workaround: set timing override bit. */
1937         val = I915_READ(_TRANSA_CHICKEN2);
1938         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1939         I915_WRITE(_TRANSA_CHICKEN2, val);
1940
1941         val = TRANS_ENABLE;
1942         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1943
1944         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1945             PIPECONF_INTERLACED_ILK)
1946                 val |= TRANS_INTERLACED;
1947         else
1948                 val |= TRANS_PROGRESSIVE;
1949
1950         I915_WRITE(LPT_TRANSCONF, val);
1951         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1952                 DRM_ERROR("Failed to enable PCH transcoder\n");
1953 }
1954
1955 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1956                                             enum pipe pipe)
1957 {
1958         struct drm_device *dev = dev_priv->dev;
1959         uint32_t reg, val;
1960
1961         /* FDI relies on the transcoder */
1962         assert_fdi_tx_disabled(dev_priv, pipe);
1963         assert_fdi_rx_disabled(dev_priv, pipe);
1964
1965         /* Ports must be off as well */
1966         assert_pch_ports_disabled(dev_priv, pipe);
1967
1968         reg = PCH_TRANSCONF(pipe);
1969         val = I915_READ(reg);
1970         val &= ~TRANS_ENABLE;
1971         I915_WRITE(reg, val);
1972         /* wait for PCH transcoder off, transcoder state */
1973         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1974                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1975
1976         if (!HAS_PCH_IBX(dev)) {
1977                 /* Workaround: Clear the timing override chicken bit again. */
1978                 reg = TRANS_CHICKEN2(pipe);
1979                 val = I915_READ(reg);
1980                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1981                 I915_WRITE(reg, val);
1982         }
1983 }
1984
1985 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1986 {
1987         u32 val;
1988
1989         val = I915_READ(LPT_TRANSCONF);
1990         val &= ~TRANS_ENABLE;
1991         I915_WRITE(LPT_TRANSCONF, val);
1992         /* wait for PCH transcoder off, transcoder state */
1993         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1994                 DRM_ERROR("Failed to disable PCH transcoder\n");
1995
1996         /* Workaround: clear timing override bit. */
1997         val = I915_READ(_TRANSA_CHICKEN2);
1998         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1999         I915_WRITE(_TRANSA_CHICKEN2, val);
2000 }
2001
2002 /**
2003  * intel_enable_pipe - enable a pipe, asserting requirements
2004  * @crtc: crtc responsible for the pipe
2005  *
2006  * Enable @crtc's pipe, making sure that various hardware specific requirements
2007  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2008  */
2009 static void intel_enable_pipe(struct intel_crtc *crtc)
2010 {
2011         struct drm_device *dev = crtc->base.dev;
2012         struct drm_i915_private *dev_priv = dev->dev_private;
2013         enum pipe pipe = crtc->pipe;
2014         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2015                                                                       pipe);
2016         enum pipe pch_transcoder;
2017         int reg;
2018         u32 val;
2019
2020         assert_planes_disabled(dev_priv, pipe);
2021         assert_cursor_disabled(dev_priv, pipe);
2022         assert_sprites_disabled(dev_priv, pipe);
2023
2024         if (HAS_PCH_LPT(dev_priv->dev))
2025                 pch_transcoder = TRANSCODER_A;
2026         else
2027                 pch_transcoder = pipe;
2028
2029         /*
2030          * A pipe without a PLL won't actually be able to drive bits from
2031          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2032          * need the check.
2033          */
2034         if (!HAS_PCH_SPLIT(dev_priv->dev))
2035                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2036                         assert_dsi_pll_enabled(dev_priv);
2037                 else
2038                         assert_pll_enabled(dev_priv, pipe);
2039         else {
2040                 if (crtc->config->has_pch_encoder) {
2041                         /* if driving the PCH, we need FDI enabled */
2042                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2043                         assert_fdi_tx_pll_enabled(dev_priv,
2044                                                   (enum pipe) cpu_transcoder);
2045                 }
2046                 /* FIXME: assert CPU port conditions for SNB+ */
2047         }
2048
2049         reg = PIPECONF(cpu_transcoder);
2050         val = I915_READ(reg);
2051         if (val & PIPECONF_ENABLE) {
2052                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2053                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2054                 return;
2055         }
2056
2057         I915_WRITE(reg, val | PIPECONF_ENABLE);
2058         POSTING_READ(reg);
2059 }
2060
2061 /**
2062  * intel_disable_pipe - disable a pipe, asserting requirements
2063  * @crtc: crtc whose pipes is to be disabled
2064  *
2065  * Disable the pipe of @crtc, making sure that various hardware
2066  * specific requirements are met, if applicable, e.g. plane
2067  * disabled, panel fitter off, etc.
2068  *
2069  * Will wait until the pipe has shut down before returning.
2070  */
2071 static void intel_disable_pipe(struct intel_crtc *crtc)
2072 {
2073         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2074         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2075         enum pipe pipe = crtc->pipe;
2076         int reg;
2077         u32 val;
2078
2079         /*
2080          * Make sure planes won't keep trying to pump pixels to us,
2081          * or we might hang the display.
2082          */
2083         assert_planes_disabled(dev_priv, pipe);
2084         assert_cursor_disabled(dev_priv, pipe);
2085         assert_sprites_disabled(dev_priv, pipe);
2086
2087         reg = PIPECONF(cpu_transcoder);
2088         val = I915_READ(reg);
2089         if ((val & PIPECONF_ENABLE) == 0)
2090                 return;
2091
2092         /*
2093          * Double wide has implications for planes
2094          * so best keep it disabled when not needed.
2095          */
2096         if (crtc->config->double_wide)
2097                 val &= ~PIPECONF_DOUBLE_WIDE;
2098
2099         /* Don't disable pipe or pipe PLLs if needed */
2100         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2101             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2102                 val &= ~PIPECONF_ENABLE;
2103
2104         I915_WRITE(reg, val);
2105         if ((val & PIPECONF_ENABLE) == 0)
2106                 intel_wait_for_pipe_off(crtc);
2107 }
2108
2109 /*
2110  * Plane regs are double buffered, going from enabled->disabled needs a
2111  * trigger in order to latch.  The display address reg provides this.
2112  */
2113 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2114                                enum plane plane)
2115 {
2116         struct drm_device *dev = dev_priv->dev;
2117         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2118
2119         I915_WRITE(reg, I915_READ(reg));
2120         POSTING_READ(reg);
2121 }
2122
2123 /**
2124  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2125  * @plane:  plane to be enabled
2126  * @crtc: crtc for the plane
2127  *
2128  * Enable @plane on @crtc, making sure that the pipe is running first.
2129  */
2130 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2131                                           struct drm_crtc *crtc)
2132 {
2133         struct drm_device *dev = plane->dev;
2134         struct drm_i915_private *dev_priv = dev->dev_private;
2135         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2136
2137         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2138         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2139
2140         if (intel_crtc->primary_enabled)
2141                 return;
2142
2143         intel_crtc->primary_enabled = true;
2144
2145         dev_priv->display.update_primary_plane(crtc, plane->fb,
2146                                                crtc->x, crtc->y);
2147
2148         /*
2149          * BDW signals flip done immediately if the plane
2150          * is disabled, even if the plane enable is already
2151          * armed to occur at the next vblank :(
2152          */
2153         if (IS_BROADWELL(dev))
2154                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2155 }
2156
2157 /**
2158  * intel_disable_primary_hw_plane - disable the primary hardware plane
2159  * @plane: plane to be disabled
2160  * @crtc: crtc for the plane
2161  *
2162  * Disable @plane on @crtc, making sure that the pipe is running first.
2163  */
2164 static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2165                                            struct drm_crtc *crtc)
2166 {
2167         struct drm_device *dev = plane->dev;
2168         struct drm_i915_private *dev_priv = dev->dev_private;
2169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2170
2171         if (WARN_ON(!intel_crtc->active))
2172                 return;
2173
2174         if (!intel_crtc->primary_enabled)
2175                 return;
2176
2177         intel_crtc->primary_enabled = false;
2178
2179         dev_priv->display.update_primary_plane(crtc, plane->fb,
2180                                                crtc->x, crtc->y);
2181 }
2182
2183 static bool need_vtd_wa(struct drm_device *dev)
2184 {
2185 #ifdef CONFIG_INTEL_IOMMU
2186         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2187                 return true;
2188 #endif
2189         return false;
2190 }
2191
2192 int
2193 intel_fb_align_height(struct drm_device *dev, int height,
2194                       uint32_t pixel_format,
2195                       uint64_t fb_format_modifier)
2196 {
2197         int tile_height;
2198         uint32_t bits_per_pixel;
2199
2200         switch (fb_format_modifier) {
2201         case DRM_FORMAT_MOD_NONE:
2202                 tile_height = 1;
2203                 break;
2204         case I915_FORMAT_MOD_X_TILED:
2205                 tile_height = IS_GEN2(dev) ? 16 : 8;
2206                 break;
2207         case I915_FORMAT_MOD_Y_TILED:
2208                 tile_height = 32;
2209                 break;
2210         case I915_FORMAT_MOD_Yf_TILED:
2211                 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2212                 switch (bits_per_pixel) {
2213                 default:
2214                 case 8:
2215                         tile_height = 64;
2216                         break;
2217                 case 16:
2218                 case 32:
2219                         tile_height = 32;
2220                         break;
2221                 case 64:
2222                         tile_height = 16;
2223                         break;
2224                 case 128:
2225                         WARN_ONCE(1,
2226                                   "128-bit pixels are not supported for display!");
2227                         tile_height = 16;
2228                         break;
2229                 }
2230                 break;
2231         default:
2232                 MISSING_CASE(fb_format_modifier);
2233                 tile_height = 1;
2234                 break;
2235         }
2236
2237         return ALIGN(height, tile_height);
2238 }
2239
2240 int
2241 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2242                            struct drm_framebuffer *fb,
2243                            struct intel_engine_cs *pipelined)
2244 {
2245         struct drm_device *dev = fb->dev;
2246         struct drm_i915_private *dev_priv = dev->dev_private;
2247         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2248         u32 alignment;
2249         int ret;
2250
2251         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2252
2253         switch (fb->modifier[0]) {
2254         case DRM_FORMAT_MOD_NONE:
2255                 if (INTEL_INFO(dev)->gen >= 9)
2256                         alignment = 256 * 1024;
2257                 else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2258                         alignment = 128 * 1024;
2259                 else if (INTEL_INFO(dev)->gen >= 4)
2260                         alignment = 4 * 1024;
2261                 else
2262                         alignment = 64 * 1024;
2263                 break;
2264         case I915_FORMAT_MOD_X_TILED:
2265                 if (INTEL_INFO(dev)->gen >= 9)
2266                         alignment = 256 * 1024;
2267                 else {
2268                         /* pin() will align the object as required by fence */
2269                         alignment = 0;
2270                 }
2271                 break;
2272         case I915_FORMAT_MOD_Y_TILED:
2273         case I915_FORMAT_MOD_Yf_TILED:
2274                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2275                           "Y tiling bo slipped through, driver bug!\n"))
2276                         return -EINVAL;
2277                 alignment = 1 * 1024 * 1024;
2278                 break;
2279         default:
2280                 MISSING_CASE(fb->modifier[0]);
2281                 return -EINVAL;
2282         }
2283
2284         /* Note that the w/a also requires 64 PTE of padding following the
2285          * bo. We currently fill all unused PTE with the shadow page and so
2286          * we should always have valid PTE following the scanout preventing
2287          * the VT-d warning.
2288          */
2289         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2290                 alignment = 256 * 1024;
2291
2292         /*
2293          * Global gtt pte registers are special registers which actually forward
2294          * writes to a chunk of system memory. Which means that there is no risk
2295          * that the register values disappear as soon as we call
2296          * intel_runtime_pm_put(), so it is correct to wrap only the
2297          * pin/unpin/fence and not more.
2298          */
2299         intel_runtime_pm_get(dev_priv);
2300
2301         dev_priv->mm.interruptible = false;
2302         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined);
2303         if (ret)
2304                 goto err_interruptible;
2305
2306         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2307          * fence, whereas 965+ only requires a fence if using
2308          * framebuffer compression.  For simplicity, we always install
2309          * a fence as the cost is not that onerous.
2310          */
2311         ret = i915_gem_object_get_fence(obj);
2312         if (ret)
2313                 goto err_unpin;
2314
2315         i915_gem_object_pin_fence(obj);
2316
2317         dev_priv->mm.interruptible = true;
2318         intel_runtime_pm_put(dev_priv);
2319         return 0;
2320
2321 err_unpin:
2322         i915_gem_object_unpin_from_display_plane(obj);
2323 err_interruptible:
2324         dev_priv->mm.interruptible = true;
2325         intel_runtime_pm_put(dev_priv);
2326         return ret;
2327 }
2328
2329 static void intel_unpin_fb_obj(struct drm_i915_gem_object *obj)
2330 {
2331         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2332
2333         i915_gem_object_unpin_fence(obj);
2334         i915_gem_object_unpin_from_display_plane(obj);
2335 }
2336
2337 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2338  * is assumed to be a power-of-two. */
2339 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2340                                              unsigned int tiling_mode,
2341                                              unsigned int cpp,
2342                                              unsigned int pitch)
2343 {
2344         if (tiling_mode != I915_TILING_NONE) {
2345                 unsigned int tile_rows, tiles;
2346
2347                 tile_rows = *y / 8;
2348                 *y %= 8;
2349
2350                 tiles = *x / (512/cpp);
2351                 *x %= 512/cpp;
2352
2353                 return tile_rows * pitch * 8 + tiles * 4096;
2354         } else {
2355                 unsigned int offset;
2356
2357                 offset = *y * pitch + *x * cpp;
2358                 *y = 0;
2359                 *x = (offset & 4095) / cpp;
2360                 return offset & -4096;
2361         }
2362 }
2363
2364 static int i9xx_format_to_fourcc(int format)
2365 {
2366         switch (format) {
2367         case DISPPLANE_8BPP:
2368                 return DRM_FORMAT_C8;
2369         case DISPPLANE_BGRX555:
2370                 return DRM_FORMAT_XRGB1555;
2371         case DISPPLANE_BGRX565:
2372                 return DRM_FORMAT_RGB565;
2373         default:
2374         case DISPPLANE_BGRX888:
2375                 return DRM_FORMAT_XRGB8888;
2376         case DISPPLANE_RGBX888:
2377                 return DRM_FORMAT_XBGR8888;
2378         case DISPPLANE_BGRX101010:
2379                 return DRM_FORMAT_XRGB2101010;
2380         case DISPPLANE_RGBX101010:
2381                 return DRM_FORMAT_XBGR2101010;
2382         }
2383 }
2384
2385 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2386 {
2387         switch (format) {
2388         case PLANE_CTL_FORMAT_RGB_565:
2389                 return DRM_FORMAT_RGB565;
2390         default:
2391         case PLANE_CTL_FORMAT_XRGB_8888:
2392                 if (rgb_order) {
2393                         if (alpha)
2394                                 return DRM_FORMAT_ABGR8888;
2395                         else
2396                                 return DRM_FORMAT_XBGR8888;
2397                 } else {
2398                         if (alpha)
2399                                 return DRM_FORMAT_ARGB8888;
2400                         else
2401                                 return DRM_FORMAT_XRGB8888;
2402                 }
2403         case PLANE_CTL_FORMAT_XRGB_2101010:
2404                 if (rgb_order)
2405                         return DRM_FORMAT_XBGR2101010;
2406                 else
2407                         return DRM_FORMAT_XRGB2101010;
2408         }
2409 }
2410
2411 static bool
2412 intel_alloc_plane_obj(struct intel_crtc *crtc,
2413                       struct intel_initial_plane_config *plane_config)
2414 {
2415         struct drm_device *dev = crtc->base.dev;
2416         struct drm_i915_gem_object *obj = NULL;
2417         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2418         struct drm_framebuffer *fb = &plane_config->fb->base;
2419         u32 base = plane_config->base;
2420
2421         if (plane_config->size == 0)
2422                 return false;
2423
2424         obj = i915_gem_object_create_stolen_for_preallocated(dev, base, base,
2425                                                              plane_config->size);
2426         if (!obj)
2427                 return false;
2428
2429         obj->tiling_mode = plane_config->tiling;
2430         if (obj->tiling_mode == I915_TILING_X)
2431                 obj->stride = fb->pitches[0];
2432
2433         mode_cmd.pixel_format = fb->pixel_format;
2434         mode_cmd.width = fb->width;
2435         mode_cmd.height = fb->height;
2436         mode_cmd.pitches[0] = fb->pitches[0];
2437         mode_cmd.modifier[0] = fb->modifier[0];
2438         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2439
2440         mutex_lock(&dev->struct_mutex);
2441
2442         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2443                                    &mode_cmd, obj)) {
2444                 DRM_DEBUG_KMS("intel fb init failed\n");
2445                 goto out_unref_obj;
2446         }
2447
2448         obj->frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(crtc->pipe);
2449         mutex_unlock(&dev->struct_mutex);
2450
2451         DRM_DEBUG_KMS("plane fb obj %p\n", obj);
2452         return true;
2453
2454 out_unref_obj:
2455         drm_gem_object_unreference(&obj->base);
2456         mutex_unlock(&dev->struct_mutex);
2457         return false;
2458 }
2459
2460 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2461 static void
2462 update_state_fb(struct drm_plane *plane)
2463 {
2464         if (plane->fb == plane->state->fb)
2465                 return;
2466
2467         if (plane->state->fb)
2468                 drm_framebuffer_unreference(plane->state->fb);
2469         plane->state->fb = plane->fb;
2470         if (plane->state->fb)
2471                 drm_framebuffer_reference(plane->state->fb);
2472 }
2473
2474 static void
2475 intel_find_plane_obj(struct intel_crtc *intel_crtc,
2476                      struct intel_initial_plane_config *plane_config)
2477 {
2478         struct drm_device *dev = intel_crtc->base.dev;
2479         struct drm_i915_private *dev_priv = dev->dev_private;
2480         struct drm_crtc *c;
2481         struct intel_crtc *i;
2482         struct drm_i915_gem_object *obj;
2483
2484         if (!plane_config->fb)
2485                 return;
2486
2487         if (intel_alloc_plane_obj(intel_crtc, plane_config)) {
2488                 struct drm_plane *primary = intel_crtc->base.primary;
2489
2490                 primary->fb = &plane_config->fb->base;
2491                 primary->state->crtc = &intel_crtc->base;
2492                 update_state_fb(primary);
2493
2494                 return;
2495         }
2496
2497         kfree(plane_config->fb);
2498
2499         /*
2500          * Failed to alloc the obj, check to see if we should share
2501          * an fb with another CRTC instead
2502          */
2503         for_each_crtc(dev, c) {
2504                 i = to_intel_crtc(c);
2505
2506                 if (c == &intel_crtc->base)
2507                         continue;
2508
2509                 if (!i->active)
2510                         continue;
2511
2512                 obj = intel_fb_obj(c->primary->fb);
2513                 if (obj == NULL)
2514                         continue;
2515
2516                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2517                         struct drm_plane *primary = intel_crtc->base.primary;
2518
2519                         if (obj->tiling_mode != I915_TILING_NONE)
2520                                 dev_priv->preserve_bios_swizzle = true;
2521
2522                         drm_framebuffer_reference(c->primary->fb);
2523                         primary->fb = c->primary->fb;
2524                         primary->state->crtc = &intel_crtc->base;
2525                         update_state_fb(intel_crtc->base.primary);
2526                         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2527                         break;
2528                 }
2529         }
2530
2531 }
2532
2533 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2534                                       struct drm_framebuffer *fb,
2535                                       int x, int y)
2536 {
2537         struct drm_device *dev = crtc->dev;
2538         struct drm_i915_private *dev_priv = dev->dev_private;
2539         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2540         struct drm_i915_gem_object *obj;
2541         int plane = intel_crtc->plane;
2542         unsigned long linear_offset;
2543         u32 dspcntr;
2544         u32 reg = DSPCNTR(plane);
2545         int pixel_size;
2546
2547         if (!intel_crtc->primary_enabled) {
2548                 I915_WRITE(reg, 0);
2549                 if (INTEL_INFO(dev)->gen >= 4)
2550                         I915_WRITE(DSPSURF(plane), 0);
2551                 else
2552                         I915_WRITE(DSPADDR(plane), 0);
2553                 POSTING_READ(reg);
2554                 return;
2555         }
2556
2557         obj = intel_fb_obj(fb);
2558         if (WARN_ON(obj == NULL))
2559                 return;
2560
2561         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2562
2563         dspcntr = DISPPLANE_GAMMA_ENABLE;
2564
2565         dspcntr |= DISPLAY_PLANE_ENABLE;
2566
2567         if (INTEL_INFO(dev)->gen < 4) {
2568                 if (intel_crtc->pipe == PIPE_B)
2569                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2570
2571                 /* pipesrc and dspsize control the size that is scaled from,
2572                  * which should always be the user's requested size.
2573                  */
2574                 I915_WRITE(DSPSIZE(plane),
2575                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2576                            (intel_crtc->config->pipe_src_w - 1));
2577                 I915_WRITE(DSPPOS(plane), 0);
2578         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2579                 I915_WRITE(PRIMSIZE(plane),
2580                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2581                            (intel_crtc->config->pipe_src_w - 1));
2582                 I915_WRITE(PRIMPOS(plane), 0);
2583                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2584         }
2585
2586         switch (fb->pixel_format) {
2587         case DRM_FORMAT_C8:
2588                 dspcntr |= DISPPLANE_8BPP;
2589                 break;
2590         case DRM_FORMAT_XRGB1555:
2591         case DRM_FORMAT_ARGB1555:
2592                 dspcntr |= DISPPLANE_BGRX555;
2593                 break;
2594         case DRM_FORMAT_RGB565:
2595                 dspcntr |= DISPPLANE_BGRX565;
2596                 break;
2597         case DRM_FORMAT_XRGB8888:
2598         case DRM_FORMAT_ARGB8888:
2599                 dspcntr |= DISPPLANE_BGRX888;
2600                 break;
2601         case DRM_FORMAT_XBGR8888:
2602         case DRM_FORMAT_ABGR8888:
2603                 dspcntr |= DISPPLANE_RGBX888;
2604                 break;
2605         case DRM_FORMAT_XRGB2101010:
2606         case DRM_FORMAT_ARGB2101010:
2607                 dspcntr |= DISPPLANE_BGRX101010;
2608                 break;
2609         case DRM_FORMAT_XBGR2101010:
2610         case DRM_FORMAT_ABGR2101010:
2611                 dspcntr |= DISPPLANE_RGBX101010;
2612                 break;
2613         default:
2614                 BUG();
2615         }
2616
2617         if (INTEL_INFO(dev)->gen >= 4 &&
2618             obj->tiling_mode != I915_TILING_NONE)
2619                 dspcntr |= DISPPLANE_TILED;
2620
2621         if (IS_G4X(dev))
2622                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2623
2624         linear_offset = y * fb->pitches[0] + x * pixel_size;
2625
2626         if (INTEL_INFO(dev)->gen >= 4) {
2627                 intel_crtc->dspaddr_offset =
2628                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2629                                                        pixel_size,
2630                                                        fb->pitches[0]);
2631                 linear_offset -= intel_crtc->dspaddr_offset;
2632         } else {
2633                 intel_crtc->dspaddr_offset = linear_offset;
2634         }
2635
2636         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2637                 dspcntr |= DISPPLANE_ROTATE_180;
2638
2639                 x += (intel_crtc->config->pipe_src_w - 1);
2640                 y += (intel_crtc->config->pipe_src_h - 1);
2641
2642                 /* Finding the last pixel of the last line of the display
2643                 data and adding to linear_offset*/
2644                 linear_offset +=
2645                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2646                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2647         }
2648
2649         I915_WRITE(reg, dspcntr);
2650
2651         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2652                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2653                       fb->pitches[0]);
2654         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2655         if (INTEL_INFO(dev)->gen >= 4) {
2656                 I915_WRITE(DSPSURF(plane),
2657                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2658                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2659                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2660         } else
2661                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2662         POSTING_READ(reg);
2663 }
2664
2665 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2666                                           struct drm_framebuffer *fb,
2667                                           int x, int y)
2668 {
2669         struct drm_device *dev = crtc->dev;
2670         struct drm_i915_private *dev_priv = dev->dev_private;
2671         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2672         struct drm_i915_gem_object *obj;
2673         int plane = intel_crtc->plane;
2674         unsigned long linear_offset;
2675         u32 dspcntr;
2676         u32 reg = DSPCNTR(plane);
2677         int pixel_size;
2678
2679         if (!intel_crtc->primary_enabled) {
2680                 I915_WRITE(reg, 0);
2681                 I915_WRITE(DSPSURF(plane), 0);
2682                 POSTING_READ(reg);
2683                 return;
2684         }
2685
2686         obj = intel_fb_obj(fb);
2687         if (WARN_ON(obj == NULL))
2688                 return;
2689
2690         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2691
2692         dspcntr = DISPPLANE_GAMMA_ENABLE;
2693
2694         dspcntr |= DISPLAY_PLANE_ENABLE;
2695
2696         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2697                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2698
2699         switch (fb->pixel_format) {
2700         case DRM_FORMAT_C8:
2701                 dspcntr |= DISPPLANE_8BPP;
2702                 break;
2703         case DRM_FORMAT_RGB565:
2704                 dspcntr |= DISPPLANE_BGRX565;
2705                 break;
2706         case DRM_FORMAT_XRGB8888:
2707         case DRM_FORMAT_ARGB8888:
2708                 dspcntr |= DISPPLANE_BGRX888;
2709                 break;
2710         case DRM_FORMAT_XBGR8888:
2711         case DRM_FORMAT_ABGR8888:
2712                 dspcntr |= DISPPLANE_RGBX888;
2713                 break;
2714         case DRM_FORMAT_XRGB2101010:
2715         case DRM_FORMAT_ARGB2101010:
2716                 dspcntr |= DISPPLANE_BGRX101010;
2717                 break;
2718         case DRM_FORMAT_XBGR2101010:
2719         case DRM_FORMAT_ABGR2101010:
2720                 dspcntr |= DISPPLANE_RGBX101010;
2721                 break;
2722         default:
2723                 BUG();
2724         }
2725
2726         if (obj->tiling_mode != I915_TILING_NONE)
2727                 dspcntr |= DISPPLANE_TILED;
2728
2729         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2730                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2731
2732         linear_offset = y * fb->pitches[0] + x * pixel_size;
2733         intel_crtc->dspaddr_offset =
2734                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2735                                                pixel_size,
2736                                                fb->pitches[0]);
2737         linear_offset -= intel_crtc->dspaddr_offset;
2738         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2739                 dspcntr |= DISPPLANE_ROTATE_180;
2740
2741                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2742                         x += (intel_crtc->config->pipe_src_w - 1);
2743                         y += (intel_crtc->config->pipe_src_h - 1);
2744
2745                         /* Finding the last pixel of the last line of the display
2746                         data and adding to linear_offset*/
2747                         linear_offset +=
2748                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2749                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2750                 }
2751         }
2752
2753         I915_WRITE(reg, dspcntr);
2754
2755         DRM_DEBUG_KMS("Writing base %08lX %08lX %d %d %d\n",
2756                       i915_gem_obj_ggtt_offset(obj), linear_offset, x, y,
2757                       fb->pitches[0]);
2758         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2759         I915_WRITE(DSPSURF(plane),
2760                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2761         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2762                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2763         } else {
2764                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2765                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2766         }
2767         POSTING_READ(reg);
2768 }
2769
2770 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2771                               uint32_t pixel_format)
2772 {
2773         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2774
2775         /*
2776          * The stride is either expressed as a multiple of 64 bytes
2777          * chunks for linear buffers or in number of tiles for tiled
2778          * buffers.
2779          */
2780         switch (fb_modifier) {
2781         case DRM_FORMAT_MOD_NONE:
2782                 return 64;
2783         case I915_FORMAT_MOD_X_TILED:
2784                 if (INTEL_INFO(dev)->gen == 2)
2785                         return 128;
2786                 return 512;
2787         case I915_FORMAT_MOD_Y_TILED:
2788                 /* No need to check for old gens and Y tiling since this is
2789                  * about the display engine and those will be blocked before
2790                  * we get here.
2791                  */
2792                 return 128;
2793         case I915_FORMAT_MOD_Yf_TILED:
2794                 if (bits_per_pixel == 8)
2795                         return 64;
2796                 else
2797                         return 128;
2798         default:
2799                 MISSING_CASE(fb_modifier);
2800                 return 64;
2801         }
2802 }
2803
2804 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2805                                          struct drm_framebuffer *fb,
2806                                          int x, int y)
2807 {
2808         struct drm_device *dev = crtc->dev;
2809         struct drm_i915_private *dev_priv = dev->dev_private;
2810         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2811         struct drm_i915_gem_object *obj;
2812         int pipe = intel_crtc->pipe;
2813         u32 plane_ctl, stride_div;
2814
2815         if (!intel_crtc->primary_enabled) {
2816                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
2817                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
2818                 POSTING_READ(PLANE_CTL(pipe, 0));
2819                 return;
2820         }
2821
2822         plane_ctl = PLANE_CTL_ENABLE |
2823                     PLANE_CTL_PIPE_GAMMA_ENABLE |
2824                     PLANE_CTL_PIPE_CSC_ENABLE;
2825
2826         switch (fb->pixel_format) {
2827         case DRM_FORMAT_RGB565:
2828                 plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
2829                 break;
2830         case DRM_FORMAT_XRGB8888:
2831                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2832                 break;
2833         case DRM_FORMAT_XBGR8888:
2834                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2835                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2836                 break;
2837         case DRM_FORMAT_XRGB2101010:
2838                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2839                 break;
2840         case DRM_FORMAT_XBGR2101010:
2841                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
2842                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
2843                 break;
2844         default:
2845                 BUG();
2846         }
2847
2848         switch (fb->modifier[0]) {
2849         case DRM_FORMAT_MOD_NONE:
2850                 break;
2851         case I915_FORMAT_MOD_X_TILED:
2852                 plane_ctl |= PLANE_CTL_TILED_X;
2853                 break;
2854         case I915_FORMAT_MOD_Y_TILED:
2855                 plane_ctl |= PLANE_CTL_TILED_Y;
2856                 break;
2857         case I915_FORMAT_MOD_Yf_TILED:
2858                 plane_ctl |= PLANE_CTL_TILED_YF;
2859                 break;
2860         default:
2861                 MISSING_CASE(fb->modifier[0]);
2862         }
2863
2864         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
2865         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180))
2866                 plane_ctl |= PLANE_CTL_ROTATE_180;
2867
2868         obj = intel_fb_obj(fb);
2869         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
2870                                                fb->pixel_format);
2871
2872         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
2873
2874         DRM_DEBUG_KMS("Writing base %08lX %d,%d,%d,%d pitch=%d\n",
2875                       i915_gem_obj_ggtt_offset(obj),
2876                       x, y, fb->width, fb->height,
2877                       fb->pitches[0]);
2878
2879         I915_WRITE(PLANE_POS(pipe, 0), 0);
2880         I915_WRITE(PLANE_OFFSET(pipe, 0), (y << 16) | x);
2881         I915_WRITE(PLANE_SIZE(pipe, 0),
2882                    (intel_crtc->config->pipe_src_h - 1) << 16 |
2883                    (intel_crtc->config->pipe_src_w - 1));
2884         I915_WRITE(PLANE_STRIDE(pipe, 0), fb->pitches[0] / stride_div);
2885         I915_WRITE(PLANE_SURF(pipe, 0), i915_gem_obj_ggtt_offset(obj));
2886
2887         POSTING_READ(PLANE_SURF(pipe, 0));
2888 }
2889
2890 /* Assume fb object is pinned & idle & fenced and just update base pointers */
2891 static int
2892 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
2893                            int x, int y, enum mode_set_atomic state)
2894 {
2895         struct drm_device *dev = crtc->dev;
2896         struct drm_i915_private *dev_priv = dev->dev_private;
2897
2898         if (dev_priv->display.disable_fbc)
2899                 dev_priv->display.disable_fbc(dev);
2900
2901         dev_priv->display.update_primary_plane(crtc, fb, x, y);
2902
2903         return 0;
2904 }
2905
2906 static void intel_complete_page_flips(struct drm_device *dev)
2907 {
2908         struct drm_crtc *crtc;
2909
2910         for_each_crtc(dev, crtc) {
2911                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2912                 enum plane plane = intel_crtc->plane;
2913
2914                 intel_prepare_page_flip(dev, plane);
2915                 intel_finish_page_flip_plane(dev, plane);
2916         }
2917 }
2918
2919 static void intel_update_primary_planes(struct drm_device *dev)
2920 {
2921         struct drm_i915_private *dev_priv = dev->dev_private;
2922         struct drm_crtc *crtc;
2923
2924         for_each_crtc(dev, crtc) {
2925                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2926
2927                 drm_modeset_lock(&crtc->mutex, NULL);
2928                 /*
2929                  * FIXME: Once we have proper support for primary planes (and
2930                  * disabling them without disabling the entire crtc) allow again
2931                  * a NULL crtc->primary->fb.
2932                  */
2933                 if (intel_crtc->active && crtc->primary->fb)
2934                         dev_priv->display.update_primary_plane(crtc,
2935                                                                crtc->primary->fb,
2936                                                                crtc->x,
2937                                                                crtc->y);
2938                 drm_modeset_unlock(&crtc->mutex);
2939         }
2940 }
2941
2942 void intel_prepare_reset(struct drm_device *dev)
2943 {
2944         struct drm_i915_private *dev_priv = to_i915(dev);
2945         struct intel_crtc *crtc;
2946
2947         /* no reset support for gen2 */
2948         if (IS_GEN2(dev))
2949                 return;
2950
2951         /* reset doesn't touch the display */
2952         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
2953                 return;
2954
2955         drm_modeset_lock_all(dev);
2956
2957         /*
2958          * Disabling the crtcs gracefully seems nicer. Also the
2959          * g33 docs say we should at least disable all the planes.
2960          */
2961         for_each_intel_crtc(dev, crtc) {
2962                 if (crtc->active)
2963                         dev_priv->display.crtc_disable(&crtc->base);
2964         }
2965 }
2966
2967 void intel_finish_reset(struct drm_device *dev)
2968 {
2969         struct drm_i915_private *dev_priv = to_i915(dev);
2970
2971         /*
2972          * Flips in the rings will be nuked by the reset,
2973          * so complete all pending flips so that user space
2974          * will get its events and not get stuck.
2975          */
2976         intel_complete_page_flips(dev);
2977
2978         /* no reset support for gen2 */
2979         if (IS_GEN2(dev))
2980                 return;
2981
2982         /* reset doesn't touch the display */
2983         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
2984                 /*
2985                  * Flips in the rings have been nuked by the reset,
2986                  * so update the base address of all primary
2987                  * planes to the the last fb to make sure we're
2988                  * showing the correct fb after a reset.
2989                  */
2990                 intel_update_primary_planes(dev);
2991                 return;
2992         }
2993
2994         /*
2995          * The display has been reset as well,
2996          * so need a full re-initialization.
2997          */
2998         intel_runtime_pm_disable_interrupts(dev_priv);
2999         intel_runtime_pm_enable_interrupts(dev_priv);
3000
3001         intel_modeset_init_hw(dev);
3002
3003         spin_lock_irq(&dev_priv->irq_lock);
3004         if (dev_priv->display.hpd_irq_setup)
3005                 dev_priv->display.hpd_irq_setup(dev);
3006         spin_unlock_irq(&dev_priv->irq_lock);
3007
3008         intel_modeset_setup_hw_state(dev, true);
3009
3010         intel_hpd_init(dev_priv);
3011
3012         drm_modeset_unlock_all(dev);
3013 }
3014
3015 static int
3016 intel_finish_fb(struct drm_framebuffer *old_fb)
3017 {
3018         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3019         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3020         bool was_interruptible = dev_priv->mm.interruptible;
3021         int ret;
3022
3023         /* Big Hammer, we also need to ensure that any pending
3024          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3025          * current scanout is retired before unpinning the old
3026          * framebuffer.
3027          *
3028          * This should only fail upon a hung GPU, in which case we
3029          * can safely continue.
3030          */
3031         dev_priv->mm.interruptible = false;
3032         ret = i915_gem_object_finish_gpu(obj);
3033         dev_priv->mm.interruptible = was_interruptible;
3034
3035         return ret;
3036 }
3037
3038 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3039 {
3040         struct drm_device *dev = crtc->dev;
3041         struct drm_i915_private *dev_priv = dev->dev_private;
3042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3043         bool pending;
3044
3045         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3046             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3047                 return false;
3048
3049         spin_lock_irq(&dev->event_lock);
3050         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3051         spin_unlock_irq(&dev->event_lock);
3052
3053         return pending;
3054 }
3055
3056 static void intel_update_pipe_size(struct intel_crtc *crtc)
3057 {
3058         struct drm_device *dev = crtc->base.dev;
3059         struct drm_i915_private *dev_priv = dev->dev_private;
3060         const struct drm_display_mode *adjusted_mode;
3061
3062         if (!i915.fastboot)
3063                 return;
3064
3065         /*
3066          * Update pipe size and adjust fitter if needed: the reason for this is
3067          * that in compute_mode_changes we check the native mode (not the pfit
3068          * mode) to see if we can flip rather than do a full mode set. In the
3069          * fastboot case, we'll flip, but if we don't update the pipesrc and
3070          * pfit state, we'll end up with a big fb scanned out into the wrong
3071          * sized surface.
3072          *
3073          * To fix this properly, we need to hoist the checks up into
3074          * compute_mode_changes (or above), check the actual pfit state and
3075          * whether the platform allows pfit disable with pipe active, and only
3076          * then update the pipesrc and pfit state, even on the flip path.
3077          */
3078
3079         adjusted_mode = &crtc->config->base.adjusted_mode;
3080
3081         I915_WRITE(PIPESRC(crtc->pipe),
3082                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3083                    (adjusted_mode->crtc_vdisplay - 1));
3084         if (!crtc->config->pch_pfit.enabled &&
3085             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3086              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3087                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3088                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3089                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3090         }
3091         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3092         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3093 }
3094
3095 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3096 {
3097         struct drm_device *dev = crtc->dev;
3098         struct drm_i915_private *dev_priv = dev->dev_private;
3099         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3100         int pipe = intel_crtc->pipe;
3101         u32 reg, temp;
3102
3103         /* enable normal train */
3104         reg = FDI_TX_CTL(pipe);
3105         temp = I915_READ(reg);
3106         if (IS_IVYBRIDGE(dev)) {
3107                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3108                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3109         } else {
3110                 temp &= ~FDI_LINK_TRAIN_NONE;
3111                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3112         }
3113         I915_WRITE(reg, temp);
3114
3115         reg = FDI_RX_CTL(pipe);
3116         temp = I915_READ(reg);
3117         if (HAS_PCH_CPT(dev)) {
3118                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3119                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3120         } else {
3121                 temp &= ~FDI_LINK_TRAIN_NONE;
3122                 temp |= FDI_LINK_TRAIN_NONE;
3123         }
3124         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3125
3126         /* wait one idle pattern time */
3127         POSTING_READ(reg);
3128         udelay(1000);
3129
3130         /* IVB wants error correction enabled */
3131         if (IS_IVYBRIDGE(dev))
3132                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3133                            FDI_FE_ERRC_ENABLE);
3134 }
3135
3136 static bool pipe_has_enabled_pch(struct intel_crtc *crtc)
3137 {
3138         return crtc->base.state->enable && crtc->active &&
3139                 crtc->config->has_pch_encoder;
3140 }
3141
3142 static void ivb_modeset_global_resources(struct drm_device *dev)
3143 {
3144         struct drm_i915_private *dev_priv = dev->dev_private;
3145         struct intel_crtc *pipe_B_crtc =
3146                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
3147         struct intel_crtc *pipe_C_crtc =
3148                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_C]);
3149         uint32_t temp;
3150
3151         /*
3152          * When everything is off disable fdi C so that we could enable fdi B
3153          * with all lanes. Note that we don't care about enabled pipes without
3154          * an enabled pch encoder.
3155          */
3156         if (!pipe_has_enabled_pch(pipe_B_crtc) &&
3157             !pipe_has_enabled_pch(pipe_C_crtc)) {
3158                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3159                 WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3160
3161                 temp = I915_READ(SOUTH_CHICKEN1);
3162                 temp &= ~FDI_BC_BIFURCATION_SELECT;
3163                 DRM_DEBUG_KMS("disabling fdi C rx\n");
3164                 I915_WRITE(SOUTH_CHICKEN1, temp);
3165         }
3166 }
3167
3168 /* The FDI link training functions for ILK/Ibexpeak. */
3169 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3170 {
3171         struct drm_device *dev = crtc->dev;
3172         struct drm_i915_private *dev_priv = dev->dev_private;
3173         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3174         int pipe = intel_crtc->pipe;
3175         u32 reg, temp, tries;
3176
3177         /* FDI needs bits from pipe first */
3178         assert_pipe_enabled(dev_priv, pipe);
3179
3180         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3181            for train result */
3182         reg = FDI_RX_IMR(pipe);
3183         temp = I915_READ(reg);
3184         temp &= ~FDI_RX_SYMBOL_LOCK;
3185         temp &= ~FDI_RX_BIT_LOCK;
3186         I915_WRITE(reg, temp);
3187         I915_READ(reg);
3188         udelay(150);
3189
3190         /* enable CPU FDI TX and PCH FDI RX */
3191         reg = FDI_TX_CTL(pipe);
3192         temp = I915_READ(reg);
3193         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3194         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3195         temp &= ~FDI_LINK_TRAIN_NONE;
3196         temp |= FDI_LINK_TRAIN_PATTERN_1;
3197         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3198
3199         reg = FDI_RX_CTL(pipe);
3200         temp = I915_READ(reg);
3201         temp &= ~FDI_LINK_TRAIN_NONE;
3202         temp |= FDI_LINK_TRAIN_PATTERN_1;
3203         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3204
3205         POSTING_READ(reg);
3206         udelay(150);
3207
3208         /* Ironlake workaround, enable clock pointer after FDI enable*/
3209         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3210         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3211                    FDI_RX_PHASE_SYNC_POINTER_EN);
3212
3213         reg = FDI_RX_IIR(pipe);
3214         for (tries = 0; tries < 5; tries++) {
3215                 temp = I915_READ(reg);
3216                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3217
3218                 if ((temp & FDI_RX_BIT_LOCK)) {
3219                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3220                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3221                         break;
3222                 }
3223         }
3224         if (tries == 5)
3225                 DRM_ERROR("FDI train 1 fail!\n");
3226
3227         /* Train 2 */
3228         reg = FDI_TX_CTL(pipe);
3229         temp = I915_READ(reg);
3230         temp &= ~FDI_LINK_TRAIN_NONE;
3231         temp |= FDI_LINK_TRAIN_PATTERN_2;
3232         I915_WRITE(reg, temp);
3233
3234         reg = FDI_RX_CTL(pipe);
3235         temp = I915_READ(reg);
3236         temp &= ~FDI_LINK_TRAIN_NONE;
3237         temp |= FDI_LINK_TRAIN_PATTERN_2;
3238         I915_WRITE(reg, temp);
3239
3240         POSTING_READ(reg);
3241         udelay(150);
3242
3243         reg = FDI_RX_IIR(pipe);
3244         for (tries = 0; tries < 5; tries++) {
3245                 temp = I915_READ(reg);
3246                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3247
3248                 if (temp & FDI_RX_SYMBOL_LOCK) {
3249                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3250                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3251                         break;
3252                 }
3253         }
3254         if (tries == 5)
3255                 DRM_ERROR("FDI train 2 fail!\n");
3256
3257         DRM_DEBUG_KMS("FDI train done\n");
3258
3259 }
3260
3261 static const int snb_b_fdi_train_param[] = {
3262         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3263         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3264         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3265         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3266 };
3267
3268 /* The FDI link training functions for SNB/Cougarpoint. */
3269 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3270 {
3271         struct drm_device *dev = crtc->dev;
3272         struct drm_i915_private *dev_priv = dev->dev_private;
3273         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3274         int pipe = intel_crtc->pipe;
3275         u32 reg, temp, i, retry;
3276
3277         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3278            for train result */
3279         reg = FDI_RX_IMR(pipe);
3280         temp = I915_READ(reg);
3281         temp &= ~FDI_RX_SYMBOL_LOCK;
3282         temp &= ~FDI_RX_BIT_LOCK;
3283         I915_WRITE(reg, temp);
3284
3285         POSTING_READ(reg);
3286         udelay(150);
3287
3288         /* enable CPU FDI TX and PCH FDI RX */
3289         reg = FDI_TX_CTL(pipe);
3290         temp = I915_READ(reg);
3291         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3292         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3293         temp &= ~FDI_LINK_TRAIN_NONE;
3294         temp |= FDI_LINK_TRAIN_PATTERN_1;
3295         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3296         /* SNB-B */
3297         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3298         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3299
3300         I915_WRITE(FDI_RX_MISC(pipe),
3301                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3302
3303         reg = FDI_RX_CTL(pipe);
3304         temp = I915_READ(reg);
3305         if (HAS_PCH_CPT(dev)) {
3306                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3307                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3308         } else {
3309                 temp &= ~FDI_LINK_TRAIN_NONE;
3310                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3311         }
3312         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3313
3314         POSTING_READ(reg);
3315         udelay(150);
3316
3317         for (i = 0; i < 4; i++) {
3318                 reg = FDI_TX_CTL(pipe);
3319                 temp = I915_READ(reg);
3320                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3321                 temp |= snb_b_fdi_train_param[i];
3322                 I915_WRITE(reg, temp);
3323
3324                 POSTING_READ(reg);
3325                 udelay(500);
3326
3327                 for (retry = 0; retry < 5; retry++) {
3328                         reg = FDI_RX_IIR(pipe);
3329                         temp = I915_READ(reg);
3330                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3331                         if (temp & FDI_RX_BIT_LOCK) {
3332                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3333                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3334                                 break;
3335                         }
3336                         udelay(50);
3337                 }
3338                 if (retry < 5)
3339                         break;
3340         }
3341         if (i == 4)
3342                 DRM_ERROR("FDI train 1 fail!\n");
3343
3344         /* Train 2 */
3345         reg = FDI_TX_CTL(pipe);
3346         temp = I915_READ(reg);
3347         temp &= ~FDI_LINK_TRAIN_NONE;
3348         temp |= FDI_LINK_TRAIN_PATTERN_2;
3349         if (IS_GEN6(dev)) {
3350                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3351                 /* SNB-B */
3352                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3353         }
3354         I915_WRITE(reg, temp);
3355
3356         reg = FDI_RX_CTL(pipe);
3357         temp = I915_READ(reg);
3358         if (HAS_PCH_CPT(dev)) {
3359                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3360                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3361         } else {
3362                 temp &= ~FDI_LINK_TRAIN_NONE;
3363                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3364         }
3365         I915_WRITE(reg, temp);
3366
3367         POSTING_READ(reg);
3368         udelay(150);
3369
3370         for (i = 0; i < 4; i++) {
3371                 reg = FDI_TX_CTL(pipe);
3372                 temp = I915_READ(reg);
3373                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3374                 temp |= snb_b_fdi_train_param[i];
3375                 I915_WRITE(reg, temp);
3376
3377                 POSTING_READ(reg);
3378                 udelay(500);
3379
3380                 for (retry = 0; retry < 5; retry++) {
3381                         reg = FDI_RX_IIR(pipe);
3382                         temp = I915_READ(reg);
3383                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3384                         if (temp & FDI_RX_SYMBOL_LOCK) {
3385                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3386                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3387                                 break;
3388                         }
3389                         udelay(50);
3390                 }
3391                 if (retry < 5)
3392                         break;
3393         }
3394         if (i == 4)
3395                 DRM_ERROR("FDI train 2 fail!\n");
3396
3397         DRM_DEBUG_KMS("FDI train done.\n");
3398 }
3399
3400 /* Manual link training for Ivy Bridge A0 parts */
3401 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3402 {
3403         struct drm_device *dev = crtc->dev;
3404         struct drm_i915_private *dev_priv = dev->dev_private;
3405         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3406         int pipe = intel_crtc->pipe;
3407         u32 reg, temp, i, j;
3408
3409         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3410            for train result */
3411         reg = FDI_RX_IMR(pipe);
3412         temp = I915_READ(reg);
3413         temp &= ~FDI_RX_SYMBOL_LOCK;
3414         temp &= ~FDI_RX_BIT_LOCK;
3415         I915_WRITE(reg, temp);
3416
3417         POSTING_READ(reg);
3418         udelay(150);
3419
3420         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3421                       I915_READ(FDI_RX_IIR(pipe)));
3422
3423         /* Try each vswing and preemphasis setting twice before moving on */
3424         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3425                 /* disable first in case we need to retry */
3426                 reg = FDI_TX_CTL(pipe);
3427                 temp = I915_READ(reg);
3428                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3429                 temp &= ~FDI_TX_ENABLE;
3430                 I915_WRITE(reg, temp);
3431
3432                 reg = FDI_RX_CTL(pipe);
3433                 temp = I915_READ(reg);
3434                 temp &= ~FDI_LINK_TRAIN_AUTO;
3435                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3436                 temp &= ~FDI_RX_ENABLE;
3437                 I915_WRITE(reg, temp);
3438
3439                 /* enable CPU FDI TX and PCH FDI RX */
3440                 reg = FDI_TX_CTL(pipe);
3441                 temp = I915_READ(reg);
3442                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3443                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3444                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3445                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3446                 temp |= snb_b_fdi_train_param[j/2];
3447                 temp |= FDI_COMPOSITE_SYNC;
3448                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3449
3450                 I915_WRITE(FDI_RX_MISC(pipe),
3451                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3452
3453                 reg = FDI_RX_CTL(pipe);
3454                 temp = I915_READ(reg);
3455                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3456                 temp |= FDI_COMPOSITE_SYNC;
3457                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3458
3459                 POSTING_READ(reg);
3460                 udelay(1); /* should be 0.5us */
3461
3462                 for (i = 0; i < 4; i++) {
3463                         reg = FDI_RX_IIR(pipe);
3464                         temp = I915_READ(reg);
3465                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3466
3467                         if (temp & FDI_RX_BIT_LOCK ||
3468                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3469                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3470                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3471                                               i);
3472                                 break;
3473                         }
3474                         udelay(1); /* should be 0.5us */
3475                 }
3476                 if (i == 4) {
3477                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3478                         continue;
3479                 }
3480
3481                 /* Train 2 */
3482                 reg = FDI_TX_CTL(pipe);
3483                 temp = I915_READ(reg);
3484                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3485                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3486                 I915_WRITE(reg, temp);
3487
3488                 reg = FDI_RX_CTL(pipe);
3489                 temp = I915_READ(reg);
3490                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3491                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3492                 I915_WRITE(reg, temp);
3493
3494                 POSTING_READ(reg);
3495                 udelay(2); /* should be 1.5us */
3496
3497                 for (i = 0; i < 4; i++) {
3498                         reg = FDI_RX_IIR(pipe);
3499                         temp = I915_READ(reg);
3500                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3501
3502                         if (temp & FDI_RX_SYMBOL_LOCK ||
3503                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3504                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3505                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3506                                               i);
3507                                 goto train_done;
3508                         }
3509                         udelay(2); /* should be 1.5us */
3510                 }
3511                 if (i == 4)
3512                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3513         }
3514
3515 train_done:
3516         DRM_DEBUG_KMS("FDI train done.\n");
3517 }
3518
3519 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3520 {
3521         struct drm_device *dev = intel_crtc->base.dev;
3522         struct drm_i915_private *dev_priv = dev->dev_private;
3523         int pipe = intel_crtc->pipe;
3524         u32 reg, temp;
3525
3526
3527         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3528         reg = FDI_RX_CTL(pipe);
3529         temp = I915_READ(reg);
3530         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3531         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3532         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3533         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3534
3535         POSTING_READ(reg);
3536         udelay(200);
3537
3538         /* Switch from Rawclk to PCDclk */
3539         temp = I915_READ(reg);
3540         I915_WRITE(reg, temp | FDI_PCDCLK);
3541
3542         POSTING_READ(reg);
3543         udelay(200);
3544
3545         /* Enable CPU FDI TX PLL, always on for Ironlake */
3546         reg = FDI_TX_CTL(pipe);
3547         temp = I915_READ(reg);
3548         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3549                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3550
3551                 POSTING_READ(reg);
3552                 udelay(100);
3553         }
3554 }
3555
3556 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3557 {
3558         struct drm_device *dev = intel_crtc->base.dev;
3559         struct drm_i915_private *dev_priv = dev->dev_private;
3560         int pipe = intel_crtc->pipe;
3561         u32 reg, temp;
3562
3563         /* Switch from PCDclk to Rawclk */
3564         reg = FDI_RX_CTL(pipe);
3565         temp = I915_READ(reg);
3566         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3567
3568         /* Disable CPU FDI TX PLL */
3569         reg = FDI_TX_CTL(pipe);
3570         temp = I915_READ(reg);
3571         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3572
3573         POSTING_READ(reg);
3574         udelay(100);
3575
3576         reg = FDI_RX_CTL(pipe);
3577         temp = I915_READ(reg);
3578         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3579
3580         /* Wait for the clocks to turn off. */
3581         POSTING_READ(reg);
3582         udelay(100);
3583 }
3584
3585 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3586 {
3587         struct drm_device *dev = crtc->dev;
3588         struct drm_i915_private *dev_priv = dev->dev_private;
3589         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3590         int pipe = intel_crtc->pipe;
3591         u32 reg, temp;
3592
3593         /* disable CPU FDI tx and PCH FDI rx */
3594         reg = FDI_TX_CTL(pipe);
3595         temp = I915_READ(reg);
3596         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3597         POSTING_READ(reg);
3598
3599         reg = FDI_RX_CTL(pipe);
3600         temp = I915_READ(reg);
3601         temp &= ~(0x7 << 16);
3602         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3603         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3604
3605         POSTING_READ(reg);
3606         udelay(100);
3607
3608         /* Ironlake workaround, disable clock pointer after downing FDI */
3609         if (HAS_PCH_IBX(dev))
3610                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3611
3612         /* still set train pattern 1 */
3613         reg = FDI_TX_CTL(pipe);
3614         temp = I915_READ(reg);
3615         temp &= ~FDI_LINK_TRAIN_NONE;
3616         temp |= FDI_LINK_TRAIN_PATTERN_1;
3617         I915_WRITE(reg, temp);
3618
3619         reg = FDI_RX_CTL(pipe);
3620         temp = I915_READ(reg);
3621         if (HAS_PCH_CPT(dev)) {
3622                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3623                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3624         } else {
3625                 temp &= ~FDI_LINK_TRAIN_NONE;
3626                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3627         }
3628         /* BPC in FDI rx is consistent with that in PIPECONF */
3629         temp &= ~(0x07 << 16);
3630         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3631         I915_WRITE(reg, temp);
3632
3633         POSTING_READ(reg);
3634         udelay(100);
3635 }
3636
3637 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3638 {
3639         struct intel_crtc *crtc;
3640
3641         /* Note that we don't need to be called with mode_config.lock here
3642          * as our list of CRTC objects is static for the lifetime of the
3643          * device and so cannot disappear as we iterate. Similarly, we can
3644          * happily treat the predicates as racy, atomic checks as userspace
3645          * cannot claim and pin a new fb without at least acquring the
3646          * struct_mutex and so serialising with us.
3647          */
3648         for_each_intel_crtc(dev, crtc) {
3649                 if (atomic_read(&crtc->unpin_work_count) == 0)
3650                         continue;
3651
3652                 if (crtc->unpin_work)
3653                         intel_wait_for_vblank(dev, crtc->pipe);
3654
3655                 return true;
3656         }
3657
3658         return false;
3659 }
3660
3661 static void page_flip_completed(struct intel_crtc *intel_crtc)
3662 {
3663         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3664         struct intel_unpin_work *work = intel_crtc->unpin_work;
3665
3666         /* ensure that the unpin work is consistent wrt ->pending. */
3667         smp_rmb();
3668         intel_crtc->unpin_work = NULL;
3669
3670         if (work->event)
3671                 drm_send_vblank_event(intel_crtc->base.dev,
3672                                       intel_crtc->pipe,
3673                                       work->event);
3674
3675         drm_crtc_vblank_put(&intel_crtc->base);
3676
3677         wake_up_all(&dev_priv->pending_flip_queue);
3678         queue_work(dev_priv->wq, &work->work);
3679
3680         trace_i915_flip_complete(intel_crtc->plane,
3681                                  work->pending_flip_obj);
3682 }
3683
3684 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3685 {
3686         struct drm_device *dev = crtc->dev;
3687         struct drm_i915_private *dev_priv = dev->dev_private;
3688
3689         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3690         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3691                                        !intel_crtc_has_pending_flip(crtc),
3692                                        60*HZ) == 0)) {
3693                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3694
3695                 spin_lock_irq(&dev->event_lock);
3696                 if (intel_crtc->unpin_work) {
3697                         WARN_ONCE(1, "Removing stuck page flip\n");
3698                         page_flip_completed(intel_crtc);
3699                 }
3700                 spin_unlock_irq(&dev->event_lock);
3701         }
3702
3703         if (crtc->primary->fb) {
3704                 mutex_lock(&dev->struct_mutex);
3705                 intel_finish_fb(crtc->primary->fb);
3706                 mutex_unlock(&dev->struct_mutex);
3707         }
3708 }
3709
3710 /* Program iCLKIP clock to the desired frequency */
3711 static void lpt_program_iclkip(struct drm_crtc *crtc)
3712 {
3713         struct drm_device *dev = crtc->dev;
3714         struct drm_i915_private *dev_priv = dev->dev_private;
3715         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3716         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3717         u32 temp;
3718
3719         mutex_lock(&dev_priv->dpio_lock);
3720
3721         /* It is necessary to ungate the pixclk gate prior to programming
3722          * the divisors, and gate it back when it is done.
3723          */
3724         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3725
3726         /* Disable SSCCTL */
3727         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3728                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3729                                 SBI_SSCCTL_DISABLE,
3730                         SBI_ICLK);
3731
3732         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3733         if (clock == 20000) {
3734                 auxdiv = 1;
3735                 divsel = 0x41;
3736                 phaseinc = 0x20;
3737         } else {
3738                 /* The iCLK virtual clock root frequency is in MHz,
3739                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3740                  * divisors, it is necessary to divide one by another, so we
3741                  * convert the virtual clock precision to KHz here for higher
3742                  * precision.
3743                  */
3744                 u32 iclk_virtual_root_freq = 172800 * 1000;
3745                 u32 iclk_pi_range = 64;
3746                 u32 desired_divisor, msb_divisor_value, pi_value;
3747
3748                 desired_divisor = (iclk_virtual_root_freq / clock);
3749                 msb_divisor_value = desired_divisor / iclk_pi_range;
3750                 pi_value = desired_divisor % iclk_pi_range;
3751
3752                 auxdiv = 0;
3753                 divsel = msb_divisor_value - 2;
3754                 phaseinc = pi_value;
3755         }
3756
3757         /* This should not happen with any sane values */
3758         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3759                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3760         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3761                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3762
3763         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3764                         clock,
3765                         auxdiv,
3766                         divsel,
3767                         phasedir,
3768                         phaseinc);
3769
3770         /* Program SSCDIVINTPHASE6 */
3771         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3772         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3773         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3774         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3775         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3776         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3777         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3778         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3779
3780         /* Program SSCAUXDIV */
3781         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3782         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3783         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3784         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3785
3786         /* Enable modulator and associated divider */
3787         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3788         temp &= ~SBI_SSCCTL_DISABLE;
3789         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3790
3791         /* Wait for initialization time */
3792         udelay(24);
3793
3794         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3795
3796         mutex_unlock(&dev_priv->dpio_lock);
3797 }
3798
3799 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3800                                                 enum pipe pch_transcoder)
3801 {
3802         struct drm_device *dev = crtc->base.dev;
3803         struct drm_i915_private *dev_priv = dev->dev_private;
3804         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3805
3806         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3807                    I915_READ(HTOTAL(cpu_transcoder)));
3808         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3809                    I915_READ(HBLANK(cpu_transcoder)));
3810         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3811                    I915_READ(HSYNC(cpu_transcoder)));
3812
3813         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3814                    I915_READ(VTOTAL(cpu_transcoder)));
3815         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3816                    I915_READ(VBLANK(cpu_transcoder)));
3817         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3818                    I915_READ(VSYNC(cpu_transcoder)));
3819         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3820                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3821 }
3822
3823 static void cpt_enable_fdi_bc_bifurcation(struct drm_device *dev)
3824 {
3825         struct drm_i915_private *dev_priv = dev->dev_private;
3826         uint32_t temp;
3827
3828         temp = I915_READ(SOUTH_CHICKEN1);
3829         if (temp & FDI_BC_BIFURCATION_SELECT)
3830                 return;
3831
3832         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3833         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3834
3835         temp |= FDI_BC_BIFURCATION_SELECT;
3836         DRM_DEBUG_KMS("enabling fdi C rx\n");
3837         I915_WRITE(SOUTH_CHICKEN1, temp);
3838         POSTING_READ(SOUTH_CHICKEN1);
3839 }
3840
3841 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3842 {
3843         struct drm_device *dev = intel_crtc->base.dev;
3844         struct drm_i915_private *dev_priv = dev->dev_private;
3845
3846         switch (intel_crtc->pipe) {
3847         case PIPE_A:
3848                 break;
3849         case PIPE_B:
3850                 if (intel_crtc->config->fdi_lanes > 2)
3851                         WARN_ON(I915_READ(SOUTH_CHICKEN1) & FDI_BC_BIFURCATION_SELECT);
3852                 else
3853                         cpt_enable_fdi_bc_bifurcation(dev);
3854
3855                 break;
3856         case PIPE_C:
3857                 cpt_enable_fdi_bc_bifurcation(dev);
3858
3859                 break;
3860         default:
3861                 BUG();
3862         }
3863 }
3864
3865 /*
3866  * Enable PCH resources required for PCH ports:
3867  *   - PCH PLLs
3868  *   - FDI training & RX/TX
3869  *   - update transcoder timings
3870  *   - DP transcoding bits
3871  *   - transcoder
3872  */
3873 static void ironlake_pch_enable(struct drm_crtc *crtc)
3874 {
3875         struct drm_device *dev = crtc->dev;
3876         struct drm_i915_private *dev_priv = dev->dev_private;
3877         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3878         int pipe = intel_crtc->pipe;
3879         u32 reg, temp;
3880
3881         assert_pch_transcoder_disabled(dev_priv, pipe);
3882
3883         if (IS_IVYBRIDGE(dev))
3884                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
3885
3886         /* Write the TU size bits before fdi link training, so that error
3887          * detection works. */
3888         I915_WRITE(FDI_RX_TUSIZE1(pipe),
3889                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
3890
3891         /* For PCH output, training FDI link */
3892         dev_priv->display.fdi_link_train(crtc);
3893
3894         /* We need to program the right clock selection before writing the pixel
3895          * mutliplier into the DPLL. */
3896         if (HAS_PCH_CPT(dev)) {
3897                 u32 sel;
3898
3899                 temp = I915_READ(PCH_DPLL_SEL);
3900                 temp |= TRANS_DPLL_ENABLE(pipe);
3901                 sel = TRANS_DPLLB_SEL(pipe);
3902                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
3903                         temp |= sel;
3904                 else
3905                         temp &= ~sel;
3906                 I915_WRITE(PCH_DPLL_SEL, temp);
3907         }
3908
3909         /* XXX: pch pll's can be enabled any time before we enable the PCH
3910          * transcoder, and we actually should do this to not upset any PCH
3911          * transcoder that already use the clock when we share it.
3912          *
3913          * Note that enable_shared_dpll tries to do the right thing, but
3914          * get_shared_dpll unconditionally resets the pll - we need that to have
3915          * the right LVDS enable sequence. */
3916         intel_enable_shared_dpll(intel_crtc);
3917
3918         /* set transcoder timing, panel must allow it */
3919         assert_panel_unlocked(dev_priv, pipe);
3920         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
3921
3922         intel_fdi_normal_train(crtc);
3923
3924         /* For PCH DP, enable TRANS_DP_CTL */
3925         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
3926                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
3927                 reg = TRANS_DP_CTL(pipe);
3928                 temp = I915_READ(reg);
3929                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
3930                           TRANS_DP_SYNC_MASK |
3931                           TRANS_DP_BPC_MASK);
3932                 temp |= (TRANS_DP_OUTPUT_ENABLE |
3933                          TRANS_DP_ENH_FRAMING);
3934                 temp |= bpc << 9; /* same format but at 11:9 */
3935
3936                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
3937                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
3938                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
3939                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
3940
3941                 switch (intel_trans_dp_port_sel(crtc)) {
3942                 case PCH_DP_B:
3943                         temp |= TRANS_DP_PORT_SEL_B;
3944                         break;
3945                 case PCH_DP_C:
3946                         temp |= TRANS_DP_PORT_SEL_C;
3947                         break;
3948                 case PCH_DP_D:
3949                         temp |= TRANS_DP_PORT_SEL_D;
3950                         break;
3951                 default:
3952                         BUG();
3953                 }
3954
3955                 I915_WRITE(reg, temp);
3956         }
3957
3958         ironlake_enable_pch_transcoder(dev_priv, pipe);
3959 }
3960
3961 static void lpt_pch_enable(struct drm_crtc *crtc)
3962 {
3963         struct drm_device *dev = crtc->dev;
3964         struct drm_i915_private *dev_priv = dev->dev_private;
3965         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3966         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
3967
3968         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
3969
3970         lpt_program_iclkip(crtc);
3971
3972         /* Set transcoder timing. */
3973         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
3974
3975         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
3976 }
3977
3978 void intel_put_shared_dpll(struct intel_crtc *crtc)
3979 {
3980         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
3981
3982         if (pll == NULL)
3983                 return;
3984
3985         if (!(pll->config.crtc_mask & (1 << crtc->pipe))) {
3986                 WARN(1, "bad %s crtc mask\n", pll->name);
3987                 return;
3988         }
3989
3990         pll->config.crtc_mask &= ~(1 << crtc->pipe);
3991         if (pll->config.crtc_mask == 0) {
3992                 WARN_ON(pll->on);
3993                 WARN_ON(pll->active);
3994         }
3995
3996         crtc->config->shared_dpll = DPLL_ID_PRIVATE;
3997 }
3998
3999 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4000                                                 struct intel_crtc_state *crtc_state)
4001 {
4002         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4003         struct intel_shared_dpll *pll;
4004         enum intel_dpll_id i;
4005
4006         if (HAS_PCH_IBX(dev_priv->dev)) {
4007                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4008                 i = (enum intel_dpll_id) crtc->pipe;
4009                 pll = &dev_priv->shared_dplls[i];
4010
4011                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4012                               crtc->base.base.id, pll->name);
4013
4014                 WARN_ON(pll->new_config->crtc_mask);
4015
4016                 goto found;
4017         }
4018
4019         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4020                 pll = &dev_priv->shared_dplls[i];
4021
4022                 /* Only want to check enabled timings first */
4023                 if (pll->new_config->crtc_mask == 0)
4024                         continue;
4025
4026                 if (memcmp(&crtc_state->dpll_hw_state,
4027                            &pll->new_config->hw_state,
4028                            sizeof(pll->new_config->hw_state)) == 0) {
4029                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4030                                       crtc->base.base.id, pll->name,
4031                                       pll->new_config->crtc_mask,
4032                                       pll->active);
4033                         goto found;
4034                 }
4035         }
4036
4037         /* Ok no matching timings, maybe there's a free one? */
4038         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4039                 pll = &dev_priv->shared_dplls[i];
4040                 if (pll->new_config->crtc_mask == 0) {
4041                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4042                                       crtc->base.base.id, pll->name);
4043                         goto found;
4044                 }
4045         }
4046
4047         return NULL;
4048
4049 found:
4050         if (pll->new_config->crtc_mask == 0)
4051                 pll->new_config->hw_state = crtc_state->dpll_hw_state;
4052
4053         crtc_state->shared_dpll = i;
4054         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4055                          pipe_name(crtc->pipe));
4056
4057         pll->new_config->crtc_mask |= 1 << crtc->pipe;
4058
4059         return pll;
4060 }
4061
4062 /**
4063  * intel_shared_dpll_start_config - start a new PLL staged config
4064  * @dev_priv: DRM device
4065  * @clear_pipes: mask of pipes that will have their PLLs freed
4066  *
4067  * Starts a new PLL staged config, copying the current config but
4068  * releasing the references of pipes specified in clear_pipes.
4069  */
4070 static int intel_shared_dpll_start_config(struct drm_i915_private *dev_priv,
4071                                           unsigned clear_pipes)
4072 {
4073         struct intel_shared_dpll *pll;
4074         enum intel_dpll_id i;
4075
4076         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4077                 pll = &dev_priv->shared_dplls[i];
4078
4079                 pll->new_config = kmemdup(&pll->config, sizeof pll->config,
4080                                           GFP_KERNEL);
4081                 if (!pll->new_config)
4082                         goto cleanup;
4083
4084                 pll->new_config->crtc_mask &= ~clear_pipes;
4085         }
4086
4087         return 0;
4088
4089 cleanup:
4090         while (--i >= 0) {
4091                 pll = &dev_priv->shared_dplls[i];
4092                 kfree(pll->new_config);
4093                 pll->new_config = NULL;
4094         }
4095
4096         return -ENOMEM;
4097 }
4098
4099 static void intel_shared_dpll_commit(struct drm_i915_private *dev_priv)
4100 {
4101         struct intel_shared_dpll *pll;
4102         enum intel_dpll_id i;
4103
4104         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4105                 pll = &dev_priv->shared_dplls[i];
4106
4107                 WARN_ON(pll->new_config == &pll->config);
4108
4109                 pll->config = *pll->new_config;
4110                 kfree(pll->new_config);
4111                 pll->new_config = NULL;
4112         }
4113 }
4114
4115 static void intel_shared_dpll_abort_config(struct drm_i915_private *dev_priv)
4116 {
4117         struct intel_shared_dpll *pll;
4118         enum intel_dpll_id i;
4119
4120         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4121                 pll = &dev_priv->shared_dplls[i];
4122
4123                 WARN_ON(pll->new_config == &pll->config);
4124
4125                 kfree(pll->new_config);
4126                 pll->new_config = NULL;
4127         }
4128 }
4129
4130 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4131 {
4132         struct drm_i915_private *dev_priv = dev->dev_private;
4133         int dslreg = PIPEDSL(pipe);
4134         u32 temp;
4135
4136         temp = I915_READ(dslreg);
4137         udelay(500);
4138         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4139                 if (wait_for(I915_READ(dslreg) != temp, 5))
4140                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4141         }
4142 }
4143
4144 static void skylake_pfit_enable(struct intel_crtc *crtc)
4145 {
4146         struct drm_device *dev = crtc->base.dev;
4147         struct drm_i915_private *dev_priv = dev->dev_private;
4148         int pipe = crtc->pipe;
4149
4150         if (crtc->config->pch_pfit.enabled) {
4151                 I915_WRITE(PS_CTL(pipe), PS_ENABLE);
4152                 I915_WRITE(PS_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4153                 I915_WRITE(PS_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4154         }
4155 }
4156
4157 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4158 {
4159         struct drm_device *dev = crtc->base.dev;
4160         struct drm_i915_private *dev_priv = dev->dev_private;
4161         int pipe = crtc->pipe;
4162
4163         if (crtc->config->pch_pfit.enabled) {
4164                 /* Force use of hard-coded filter coefficients
4165                  * as some pre-programmed values are broken,
4166                  * e.g. x201.
4167                  */
4168                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4169                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4170                                                  PF_PIPE_SEL_IVB(pipe));
4171                 else
4172                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4173                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4174                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4175         }
4176 }
4177
4178 static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4179 {
4180         struct drm_device *dev = crtc->dev;
4181         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4182         struct drm_plane *plane;
4183         struct intel_plane *intel_plane;
4184
4185         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4186                 intel_plane = to_intel_plane(plane);
4187                 if (intel_plane->pipe == pipe)
4188                         intel_plane_restore(&intel_plane->base);
4189         }
4190 }
4191
4192 static void intel_disable_sprite_planes(struct drm_crtc *crtc)
4193 {
4194         struct drm_device *dev = crtc->dev;
4195         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4196         struct drm_plane *plane;
4197         struct intel_plane *intel_plane;
4198
4199         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4200                 intel_plane = to_intel_plane(plane);
4201                 if (intel_plane->pipe == pipe)
4202                         plane->funcs->disable_plane(plane);
4203         }
4204 }
4205
4206 void hsw_enable_ips(struct intel_crtc *crtc)
4207 {
4208         struct drm_device *dev = crtc->base.dev;
4209         struct drm_i915_private *dev_priv = dev->dev_private;
4210
4211         if (!crtc->config->ips_enabled)
4212                 return;
4213
4214         /* We can only enable IPS after we enable a plane and wait for a vblank */
4215         intel_wait_for_vblank(dev, crtc->pipe);
4216
4217         assert_plane_enabled(dev_priv, crtc->plane);
4218         if (IS_BROADWELL(dev)) {
4219                 mutex_lock(&dev_priv->rps.hw_lock);
4220                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4221                 mutex_unlock(&dev_priv->rps.hw_lock);
4222                 /* Quoting Art Runyan: "its not safe to expect any particular
4223                  * value in IPS_CTL bit 31 after enabling IPS through the
4224                  * mailbox." Moreover, the mailbox may return a bogus state,
4225                  * so we need to just enable it and continue on.
4226                  */
4227         } else {
4228                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4229                 /* The bit only becomes 1 in the next vblank, so this wait here
4230                  * is essentially intel_wait_for_vblank. If we don't have this
4231                  * and don't wait for vblanks until the end of crtc_enable, then
4232                  * the HW state readout code will complain that the expected
4233                  * IPS_CTL value is not the one we read. */
4234                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4235                         DRM_ERROR("Timed out waiting for IPS enable\n");
4236         }
4237 }
4238
4239 void hsw_disable_ips(struct intel_crtc *crtc)
4240 {
4241         struct drm_device *dev = crtc->base.dev;
4242         struct drm_i915_private *dev_priv = dev->dev_private;
4243
4244         if (!crtc->config->ips_enabled)
4245                 return;
4246
4247         assert_plane_enabled(dev_priv, crtc->plane);
4248         if (IS_BROADWELL(dev)) {
4249                 mutex_lock(&dev_priv->rps.hw_lock);
4250                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4251                 mutex_unlock(&dev_priv->rps.hw_lock);
4252                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4253                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4254                         DRM_ERROR("Timed out waiting for IPS disable\n");
4255         } else {
4256                 I915_WRITE(IPS_CTL, 0);
4257                 POSTING_READ(IPS_CTL);
4258         }
4259
4260         /* We need to wait for a vblank before we can disable the plane. */
4261         intel_wait_for_vblank(dev, crtc->pipe);
4262 }
4263
4264 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4265 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4266 {
4267         struct drm_device *dev = crtc->dev;
4268         struct drm_i915_private *dev_priv = dev->dev_private;
4269         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4270         enum pipe pipe = intel_crtc->pipe;
4271         int palreg = PALETTE(pipe);
4272         int i;
4273         bool reenable_ips = false;
4274
4275         /* The clocks have to be on to load the palette. */
4276         if (!crtc->state->enable || !intel_crtc->active)
4277                 return;
4278
4279         if (!HAS_PCH_SPLIT(dev_priv->dev)) {
4280                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4281                         assert_dsi_pll_enabled(dev_priv);
4282                 else
4283                         assert_pll_enabled(dev_priv, pipe);
4284         }
4285
4286         /* use legacy palette for Ironlake */
4287         if (!HAS_GMCH_DISPLAY(dev))
4288                 palreg = LGC_PALETTE(pipe);
4289
4290         /* Workaround : Do not read or write the pipe palette/gamma data while
4291          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4292          */
4293         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4294             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4295              GAMMA_MODE_MODE_SPLIT)) {
4296                 hsw_disable_ips(intel_crtc);
4297                 reenable_ips = true;
4298         }
4299
4300         for (i = 0; i < 256; i++) {
4301                 I915_WRITE(palreg + 4 * i,
4302                            (intel_crtc->lut_r[i] << 16) |
4303                            (intel_crtc->lut_g[i] << 8) |
4304                            intel_crtc->lut_b[i]);
4305         }
4306
4307         if (reenable_ips)
4308                 hsw_enable_ips(intel_crtc);
4309 }
4310
4311 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4312 {
4313         if (!enable && intel_crtc->overlay) {
4314                 struct drm_device *dev = intel_crtc->base.dev;
4315                 struct drm_i915_private *dev_priv = dev->dev_private;
4316
4317                 mutex_lock(&dev->struct_mutex);
4318                 dev_priv->mm.interruptible = false;
4319                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4320                 dev_priv->mm.interruptible = true;
4321                 mutex_unlock(&dev->struct_mutex);
4322         }
4323
4324         /* Let userspace switch the overlay on again. In most cases userspace
4325          * has to recompute where to put it anyway.
4326          */
4327 }
4328
4329 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4330 {
4331         struct drm_device *dev = crtc->dev;
4332         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4333         int pipe = intel_crtc->pipe;
4334
4335         intel_enable_primary_hw_plane(crtc->primary, crtc);
4336         intel_enable_sprite_planes(crtc);
4337         intel_crtc_update_cursor(crtc, true);
4338         intel_crtc_dpms_overlay(intel_crtc, true);
4339
4340         hsw_enable_ips(intel_crtc);
4341
4342         mutex_lock(&dev->struct_mutex);
4343         intel_fbc_update(dev);
4344         mutex_unlock(&dev->struct_mutex);
4345
4346         /*
4347          * FIXME: Once we grow proper nuclear flip support out of this we need
4348          * to compute the mask of flip planes precisely. For the time being
4349          * consider this a flip from a NULL plane.
4350          */
4351         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4352 }
4353
4354 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4355 {
4356         struct drm_device *dev = crtc->dev;
4357         struct drm_i915_private *dev_priv = dev->dev_private;
4358         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4359         int pipe = intel_crtc->pipe;
4360
4361         intel_crtc_wait_for_pending_flips(crtc);
4362
4363         if (dev_priv->fbc.crtc == intel_crtc)
4364                 intel_fbc_disable(dev);
4365
4366         hsw_disable_ips(intel_crtc);
4367
4368         intel_crtc_dpms_overlay(intel_crtc, false);
4369         intel_crtc_update_cursor(crtc, false);
4370         intel_disable_sprite_planes(crtc);
4371         intel_disable_primary_hw_plane(crtc->primary, crtc);
4372
4373         /*
4374          * FIXME: Once we grow proper nuclear flip support out of this we need
4375          * to compute the mask of flip planes precisely. For the time being
4376          * consider this a flip to a NULL plane.
4377          */
4378         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4379 }
4380
4381 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4382 {
4383         struct drm_device *dev = crtc->dev;
4384         struct drm_i915_private *dev_priv = dev->dev_private;
4385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4386         struct intel_encoder *encoder;
4387         int pipe = intel_crtc->pipe;
4388
4389         WARN_ON(!crtc->state->enable);
4390
4391         if (intel_crtc->active)
4392                 return;
4393
4394         if (intel_crtc->config->has_pch_encoder)
4395                 intel_prepare_shared_dpll(intel_crtc);
4396
4397         if (intel_crtc->config->has_dp_encoder)
4398                 intel_dp_set_m_n(intel_crtc, M1_N1);
4399
4400         intel_set_pipe_timings(intel_crtc);
4401
4402         if (intel_crtc->config->has_pch_encoder) {
4403                 intel_cpu_transcoder_set_m_n(intel_crtc,
4404                                      &intel_crtc->config->fdi_m_n, NULL);
4405         }
4406
4407         ironlake_set_pipeconf(crtc);
4408
4409         intel_crtc->active = true;
4410
4411         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4412         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4413
4414         for_each_encoder_on_crtc(dev, crtc, encoder)
4415                 if (encoder->pre_enable)
4416                         encoder->pre_enable(encoder);
4417
4418         if (intel_crtc->config->has_pch_encoder) {
4419                 /* Note: FDI PLL enabling _must_ be done before we enable the
4420                  * cpu pipes, hence this is separate from all the other fdi/pch
4421                  * enabling. */
4422                 ironlake_fdi_pll_enable(intel_crtc);
4423         } else {
4424                 assert_fdi_tx_disabled(dev_priv, pipe);
4425                 assert_fdi_rx_disabled(dev_priv, pipe);
4426         }
4427
4428         ironlake_pfit_enable(intel_crtc);
4429
4430         /*
4431          * On ILK+ LUT must be loaded before the pipe is running but with
4432          * clocks enabled
4433          */
4434         intel_crtc_load_lut(crtc);
4435
4436         intel_update_watermarks(crtc);
4437         intel_enable_pipe(intel_crtc);
4438
4439         if (intel_crtc->config->has_pch_encoder)
4440                 ironlake_pch_enable(crtc);
4441
4442         assert_vblank_disabled(crtc);
4443         drm_crtc_vblank_on(crtc);
4444
4445         for_each_encoder_on_crtc(dev, crtc, encoder)
4446                 encoder->enable(encoder);
4447
4448         if (HAS_PCH_CPT(dev))
4449                 cpt_verify_modeset(dev, intel_crtc->pipe);
4450
4451         intel_crtc_enable_planes(crtc);
4452 }
4453
4454 /* IPS only exists on ULT machines and is tied to pipe A. */
4455 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4456 {
4457         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4458 }
4459
4460 /*
4461  * This implements the workaround described in the "notes" section of the mode
4462  * set sequence documentation. When going from no pipes or single pipe to
4463  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4464  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4465  */
4466 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4467 {
4468         struct drm_device *dev = crtc->base.dev;
4469         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4470
4471         /* We want to get the other_active_crtc only if there's only 1 other
4472          * active crtc. */
4473         for_each_intel_crtc(dev, crtc_it) {
4474                 if (!crtc_it->active || crtc_it == crtc)
4475                         continue;
4476
4477                 if (other_active_crtc)
4478                         return;
4479
4480                 other_active_crtc = crtc_it;
4481         }
4482         if (!other_active_crtc)
4483                 return;
4484
4485         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4486         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4487 }
4488
4489 static void haswell_crtc_enable(struct drm_crtc *crtc)
4490 {
4491         struct drm_device *dev = crtc->dev;
4492         struct drm_i915_private *dev_priv = dev->dev_private;
4493         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4494         struct intel_encoder *encoder;
4495         int pipe = intel_crtc->pipe;
4496
4497         WARN_ON(!crtc->state->enable);
4498
4499         if (intel_crtc->active)
4500                 return;
4501
4502         if (intel_crtc_to_shared_dpll(intel_crtc))
4503                 intel_enable_shared_dpll(intel_crtc);
4504
4505         if (intel_crtc->config->has_dp_encoder)
4506                 intel_dp_set_m_n(intel_crtc, M1_N1);
4507
4508         intel_set_pipe_timings(intel_crtc);
4509
4510         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4511                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4512                            intel_crtc->config->pixel_multiplier - 1);
4513         }
4514
4515         if (intel_crtc->config->has_pch_encoder) {
4516                 intel_cpu_transcoder_set_m_n(intel_crtc,
4517                                      &intel_crtc->config->fdi_m_n, NULL);
4518         }
4519
4520         haswell_set_pipeconf(crtc);
4521
4522         intel_set_pipe_csc(crtc);
4523
4524         intel_crtc->active = true;
4525
4526         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4527         for_each_encoder_on_crtc(dev, crtc, encoder)
4528                 if (encoder->pre_enable)
4529                         encoder->pre_enable(encoder);
4530
4531         if (intel_crtc->config->has_pch_encoder) {
4532                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4533                                                       true);
4534                 dev_priv->display.fdi_link_train(crtc);
4535         }
4536
4537         intel_ddi_enable_pipe_clock(intel_crtc);
4538
4539         if (IS_SKYLAKE(dev))
4540                 skylake_pfit_enable(intel_crtc);
4541         else
4542                 ironlake_pfit_enable(intel_crtc);
4543
4544         /*
4545          * On ILK+ LUT must be loaded before the pipe is running but with
4546          * clocks enabled
4547          */
4548         intel_crtc_load_lut(crtc);
4549
4550         intel_ddi_set_pipe_settings(crtc);
4551         intel_ddi_enable_transcoder_func(crtc);
4552
4553         intel_update_watermarks(crtc);
4554         intel_enable_pipe(intel_crtc);
4555
4556         if (intel_crtc->config->has_pch_encoder)
4557                 lpt_pch_enable(crtc);
4558
4559         if (intel_crtc->config->dp_encoder_is_mst)
4560                 intel_ddi_set_vc_payload_alloc(crtc, true);
4561
4562         assert_vblank_disabled(crtc);
4563         drm_crtc_vblank_on(crtc);
4564
4565         for_each_encoder_on_crtc(dev, crtc, encoder) {
4566                 encoder->enable(encoder);
4567                 intel_opregion_notify_encoder(encoder, true);
4568         }
4569
4570         /* If we change the relative order between pipe/planes enabling, we need
4571          * to change the workaround. */
4572         haswell_mode_set_planes_workaround(intel_crtc);
4573         intel_crtc_enable_planes(crtc);
4574 }
4575
4576 static void skylake_pfit_disable(struct intel_crtc *crtc)
4577 {
4578         struct drm_device *dev = crtc->base.dev;
4579         struct drm_i915_private *dev_priv = dev->dev_private;
4580         int pipe = crtc->pipe;
4581
4582         /* To avoid upsetting the power well on haswell only disable the pfit if
4583          * it's in use. The hw state code will make sure we get this right. */
4584         if (crtc->config->pch_pfit.enabled) {
4585                 I915_WRITE(PS_CTL(pipe), 0);
4586                 I915_WRITE(PS_WIN_POS(pipe), 0);
4587                 I915_WRITE(PS_WIN_SZ(pipe), 0);
4588         }
4589 }
4590
4591 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4592 {
4593         struct drm_device *dev = crtc->base.dev;
4594         struct drm_i915_private *dev_priv = dev->dev_private;
4595         int pipe = crtc->pipe;
4596
4597         /* To avoid upsetting the power well on haswell only disable the pfit if
4598          * it's in use. The hw state code will make sure we get this right. */
4599         if (crtc->config->pch_pfit.enabled) {
4600                 I915_WRITE(PF_CTL(pipe), 0);
4601                 I915_WRITE(PF_WIN_POS(pipe), 0);
4602                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4603         }
4604 }
4605
4606 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4607 {
4608         struct drm_device *dev = crtc->dev;
4609         struct drm_i915_private *dev_priv = dev->dev_private;
4610         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4611         struct intel_encoder *encoder;
4612         int pipe = intel_crtc->pipe;
4613         u32 reg, temp;
4614
4615         if (!intel_crtc->active)
4616                 return;
4617
4618         intel_crtc_disable_planes(crtc);
4619
4620         for_each_encoder_on_crtc(dev, crtc, encoder)
4621                 encoder->disable(encoder);
4622
4623         drm_crtc_vblank_off(crtc);
4624         assert_vblank_disabled(crtc);
4625
4626         if (intel_crtc->config->has_pch_encoder)
4627                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4628
4629         intel_disable_pipe(intel_crtc);
4630
4631         ironlake_pfit_disable(intel_crtc);
4632
4633         for_each_encoder_on_crtc(dev, crtc, encoder)
4634                 if (encoder->post_disable)
4635                         encoder->post_disable(encoder);
4636
4637         if (intel_crtc->config->has_pch_encoder) {
4638                 ironlake_fdi_disable(crtc);
4639
4640                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4641
4642                 if (HAS_PCH_CPT(dev)) {
4643                         /* disable TRANS_DP_CTL */
4644                         reg = TRANS_DP_CTL(pipe);
4645                         temp = I915_READ(reg);
4646                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4647                                   TRANS_DP_PORT_SEL_MASK);
4648                         temp |= TRANS_DP_PORT_SEL_NONE;
4649                         I915_WRITE(reg, temp);
4650
4651                         /* disable DPLL_SEL */
4652                         temp = I915_READ(PCH_DPLL_SEL);
4653                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4654                         I915_WRITE(PCH_DPLL_SEL, temp);
4655                 }
4656
4657                 /* disable PCH DPLL */
4658                 intel_disable_shared_dpll(intel_crtc);
4659
4660                 ironlake_fdi_pll_disable(intel_crtc);
4661         }
4662
4663         intel_crtc->active = false;
4664         intel_update_watermarks(crtc);
4665
4666         mutex_lock(&dev->struct_mutex);
4667         intel_fbc_update(dev);
4668         mutex_unlock(&dev->struct_mutex);
4669 }
4670
4671 static void haswell_crtc_disable(struct drm_crtc *crtc)
4672 {
4673         struct drm_device *dev = crtc->dev;
4674         struct drm_i915_private *dev_priv = dev->dev_private;
4675         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4676         struct intel_encoder *encoder;
4677         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4678
4679         if (!intel_crtc->active)
4680                 return;
4681
4682         intel_crtc_disable_planes(crtc);
4683
4684         for_each_encoder_on_crtc(dev, crtc, encoder) {
4685                 intel_opregion_notify_encoder(encoder, false);
4686                 encoder->disable(encoder);
4687         }
4688
4689         drm_crtc_vblank_off(crtc);
4690         assert_vblank_disabled(crtc);
4691
4692         if (intel_crtc->config->has_pch_encoder)
4693                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4694                                                       false);
4695         intel_disable_pipe(intel_crtc);
4696
4697         if (intel_crtc->config->dp_encoder_is_mst)
4698                 intel_ddi_set_vc_payload_alloc(crtc, false);
4699
4700         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4701
4702         if (IS_SKYLAKE(dev))
4703                 skylake_pfit_disable(intel_crtc);
4704         else
4705                 ironlake_pfit_disable(intel_crtc);
4706
4707         intel_ddi_disable_pipe_clock(intel_crtc);
4708
4709         if (intel_crtc->config->has_pch_encoder) {
4710                 lpt_disable_pch_transcoder(dev_priv);
4711                 intel_ddi_fdi_disable(crtc);
4712         }
4713
4714         for_each_encoder_on_crtc(dev, crtc, encoder)
4715                 if (encoder->post_disable)
4716                         encoder->post_disable(encoder);
4717
4718         intel_crtc->active = false;
4719         intel_update_watermarks(crtc);
4720
4721         mutex_lock(&dev->struct_mutex);
4722         intel_fbc_update(dev);
4723         mutex_unlock(&dev->struct_mutex);
4724
4725         if (intel_crtc_to_shared_dpll(intel_crtc))
4726                 intel_disable_shared_dpll(intel_crtc);
4727 }
4728
4729 static void ironlake_crtc_off(struct drm_crtc *crtc)
4730 {
4731         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4732         intel_put_shared_dpll(intel_crtc);
4733 }
4734
4735
4736 static void i9xx_pfit_enable(struct intel_crtc *crtc)
4737 {
4738         struct drm_device *dev = crtc->base.dev;
4739         struct drm_i915_private *dev_priv = dev->dev_private;
4740         struct intel_crtc_state *pipe_config = crtc->config;
4741
4742         if (!pipe_config->gmch_pfit.control)
4743                 return;
4744
4745         /*
4746          * The panel fitter should only be adjusted whilst the pipe is disabled,
4747          * according to register description and PRM.
4748          */
4749         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
4750         assert_pipe_disabled(dev_priv, crtc->pipe);
4751
4752         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
4753         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
4754
4755         /* Border color in case we don't scale up to the full screen. Black by
4756          * default, change to something else for debugging. */
4757         I915_WRITE(BCLRPAT(crtc->pipe), 0);
4758 }
4759
4760 static enum intel_display_power_domain port_to_power_domain(enum port port)
4761 {
4762         switch (port) {
4763         case PORT_A:
4764                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
4765         case PORT_B:
4766                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
4767         case PORT_C:
4768                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
4769         case PORT_D:
4770                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
4771         default:
4772                 WARN_ON_ONCE(1);
4773                 return POWER_DOMAIN_PORT_OTHER;
4774         }
4775 }
4776
4777 #define for_each_power_domain(domain, mask)                             \
4778         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
4779                 if ((1 << (domain)) & (mask))
4780
4781 enum intel_display_power_domain
4782 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
4783 {
4784         struct drm_device *dev = intel_encoder->base.dev;
4785         struct intel_digital_port *intel_dig_port;
4786
4787         switch (intel_encoder->type) {
4788         case INTEL_OUTPUT_UNKNOWN:
4789                 /* Only DDI platforms should ever use this output type */
4790                 WARN_ON_ONCE(!HAS_DDI(dev));
4791         case INTEL_OUTPUT_DISPLAYPORT:
4792         case INTEL_OUTPUT_HDMI:
4793         case INTEL_OUTPUT_EDP:
4794                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
4795                 return port_to_power_domain(intel_dig_port->port);
4796         case INTEL_OUTPUT_DP_MST:
4797                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
4798                 return port_to_power_domain(intel_dig_port->port);
4799         case INTEL_OUTPUT_ANALOG:
4800                 return POWER_DOMAIN_PORT_CRT;
4801         case INTEL_OUTPUT_DSI:
4802                 return POWER_DOMAIN_PORT_DSI;
4803         default:
4804                 return POWER_DOMAIN_PORT_OTHER;
4805         }
4806 }
4807
4808 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
4809 {
4810         struct drm_device *dev = crtc->dev;
4811         struct intel_encoder *intel_encoder;
4812         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4813         enum pipe pipe = intel_crtc->pipe;
4814         unsigned long mask;
4815         enum transcoder transcoder;
4816
4817         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
4818
4819         mask = BIT(POWER_DOMAIN_PIPE(pipe));
4820         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
4821         if (intel_crtc->config->pch_pfit.enabled ||
4822             intel_crtc->config->pch_pfit.force_thru)
4823                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
4824
4825         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
4826                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
4827
4828         return mask;
4829 }
4830
4831 static void modeset_update_crtc_power_domains(struct drm_device *dev)
4832 {
4833         struct drm_i915_private *dev_priv = dev->dev_private;
4834         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
4835         struct intel_crtc *crtc;
4836
4837         /*
4838          * First get all needed power domains, then put all unneeded, to avoid
4839          * any unnecessary toggling of the power wells.
4840          */
4841         for_each_intel_crtc(dev, crtc) {
4842                 enum intel_display_power_domain domain;
4843
4844                 if (!crtc->base.state->enable)
4845                         continue;
4846
4847                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
4848
4849                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
4850                         intel_display_power_get(dev_priv, domain);
4851         }
4852
4853         if (dev_priv->display.modeset_global_resources)
4854                 dev_priv->display.modeset_global_resources(dev);
4855
4856         for_each_intel_crtc(dev, crtc) {
4857                 enum intel_display_power_domain domain;
4858
4859                 for_each_power_domain(domain, crtc->enabled_power_domains)
4860                         intel_display_power_put(dev_priv, domain);
4861
4862                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
4863         }
4864
4865         intel_display_set_init_power(dev_priv, false);
4866 }
4867
4868 /* returns HPLL frequency in kHz */
4869 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
4870 {
4871         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
4872
4873         /* Obtain SKU information */
4874         mutex_lock(&dev_priv->dpio_lock);
4875         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
4876                 CCK_FUSE_HPLL_FREQ_MASK;
4877         mutex_unlock(&dev_priv->dpio_lock);
4878
4879         return vco_freq[hpll_freq] * 1000;
4880 }
4881
4882 static void vlv_update_cdclk(struct drm_device *dev)
4883 {
4884         struct drm_i915_private *dev_priv = dev->dev_private;
4885
4886         dev_priv->vlv_cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
4887         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
4888                          dev_priv->vlv_cdclk_freq);
4889
4890         /*
4891          * Program the gmbus_freq based on the cdclk frequency.
4892          * BSpec erroneously claims we should aim for 4MHz, but
4893          * in fact 1MHz is the correct frequency.
4894          */
4895         I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->vlv_cdclk_freq, 1000));
4896 }
4897
4898 /* Adjust CDclk dividers to allow high res or save power if possible */
4899 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
4900 {
4901         struct drm_i915_private *dev_priv = dev->dev_private;
4902         u32 val, cmd;
4903
4904         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4905
4906         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
4907                 cmd = 2;
4908         else if (cdclk == 266667)
4909                 cmd = 1;
4910         else
4911                 cmd = 0;
4912
4913         mutex_lock(&dev_priv->rps.hw_lock);
4914         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4915         val &= ~DSPFREQGUAR_MASK;
4916         val |= (cmd << DSPFREQGUAR_SHIFT);
4917         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4918         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4919                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
4920                      50)) {
4921                 DRM_ERROR("timed out waiting for CDclk change\n");
4922         }
4923         mutex_unlock(&dev_priv->rps.hw_lock);
4924
4925         if (cdclk == 400000) {
4926                 u32 divider;
4927
4928                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
4929
4930                 mutex_lock(&dev_priv->dpio_lock);
4931                 /* adjust cdclk divider */
4932                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
4933                 val &= ~DISPLAY_FREQUENCY_VALUES;
4934                 val |= divider;
4935                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
4936
4937                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
4938                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
4939                              50))
4940                         DRM_ERROR("timed out waiting for CDclk change\n");
4941                 mutex_unlock(&dev_priv->dpio_lock);
4942         }
4943
4944         mutex_lock(&dev_priv->dpio_lock);
4945         /* adjust self-refresh exit latency value */
4946         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
4947         val &= ~0x7f;
4948
4949         /*
4950          * For high bandwidth configs, we set a higher latency in the bunit
4951          * so that the core display fetch happens in time to avoid underruns.
4952          */
4953         if (cdclk == 400000)
4954                 val |= 4500 / 250; /* 4.5 usec */
4955         else
4956                 val |= 3000 / 250; /* 3.0 usec */
4957         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
4958         mutex_unlock(&dev_priv->dpio_lock);
4959
4960         vlv_update_cdclk(dev);
4961 }
4962
4963 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
4964 {
4965         struct drm_i915_private *dev_priv = dev->dev_private;
4966         u32 val, cmd;
4967
4968         WARN_ON(dev_priv->display.get_display_clock_speed(dev) != dev_priv->vlv_cdclk_freq);
4969
4970         switch (cdclk) {
4971         case 400000:
4972                 cmd = 3;
4973                 break;
4974         case 333333:
4975         case 320000:
4976                 cmd = 2;
4977                 break;
4978         case 266667:
4979                 cmd = 1;
4980                 break;
4981         case 200000:
4982                 cmd = 0;
4983                 break;
4984         default:
4985                 MISSING_CASE(cdclk);
4986                 return;
4987         }
4988
4989         mutex_lock(&dev_priv->rps.hw_lock);
4990         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
4991         val &= ~DSPFREQGUAR_MASK_CHV;
4992         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
4993         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
4994         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
4995                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
4996                      50)) {
4997                 DRM_ERROR("timed out waiting for CDclk change\n");
4998         }
4999         mutex_unlock(&dev_priv->rps.hw_lock);
5000
5001         vlv_update_cdclk(dev);
5002 }
5003
5004 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5005                                  int max_pixclk)
5006 {
5007         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5008
5009         /* FIXME: Punit isn't quite ready yet */
5010         if (IS_CHERRYVIEW(dev_priv->dev))
5011                 return 400000;
5012
5013         /*
5014          * Really only a few cases to deal with, as only 4 CDclks are supported:
5015          *   200MHz
5016          *   267MHz
5017          *   320/333MHz (depends on HPLL freq)
5018          *   400MHz
5019          * So we check to see whether we're above 90% of the lower bin and
5020          * adjust if needed.
5021          *
5022          * We seem to get an unstable or solid color picture at 200MHz.
5023          * Not sure what's wrong. For now use 200MHz only when all pipes
5024          * are off.
5025          */
5026         if (max_pixclk > freq_320*9/10)
5027                 return 400000;
5028         else if (max_pixclk > 266667*9/10)
5029                 return freq_320;
5030         else if (max_pixclk > 0)
5031                 return 266667;
5032         else
5033                 return 200000;
5034 }
5035
5036 /* compute the max pixel clock for new configuration */
5037 static int intel_mode_max_pixclk(struct drm_i915_private *dev_priv)
5038 {
5039         struct drm_device *dev = dev_priv->dev;
5040         struct intel_crtc *intel_crtc;
5041         int max_pixclk = 0;
5042
5043         for_each_intel_crtc(dev, intel_crtc) {
5044                 if (intel_crtc->new_enabled)
5045                         max_pixclk = max(max_pixclk,
5046                                          intel_crtc->new_config->base.adjusted_mode.crtc_clock);
5047         }
5048
5049         return max_pixclk;
5050 }
5051
5052 static void valleyview_modeset_global_pipes(struct drm_device *dev,
5053                                             unsigned *prepare_pipes)
5054 {
5055         struct drm_i915_private *dev_priv = dev->dev_private;
5056         struct intel_crtc *intel_crtc;
5057         int max_pixclk = intel_mode_max_pixclk(dev_priv);
5058
5059         if (valleyview_calc_cdclk(dev_priv, max_pixclk) ==
5060             dev_priv->vlv_cdclk_freq)
5061                 return;
5062
5063         /* disable/enable all currently active pipes while we change cdclk */
5064         for_each_intel_crtc(dev, intel_crtc)
5065                 if (intel_crtc->base.state->enable)
5066                         *prepare_pipes |= (1 << intel_crtc->pipe);
5067 }
5068
5069 static void valleyview_modeset_global_resources(struct drm_device *dev)
5070 {
5071         struct drm_i915_private *dev_priv = dev->dev_private;
5072         int max_pixclk = intel_mode_max_pixclk(dev_priv);
5073         int req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5074
5075         if (req_cdclk != dev_priv->vlv_cdclk_freq) {
5076                 /*
5077                  * FIXME: We can end up here with all power domains off, yet
5078                  * with a CDCLK frequency other than the minimum. To account
5079                  * for this take the PIPE-A power domain, which covers the HW
5080                  * blocks needed for the following programming. This can be
5081                  * removed once it's guaranteed that we get here either with
5082                  * the minimum CDCLK set, or the required power domains
5083                  * enabled.
5084                  */
5085                 intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5086
5087                 if (IS_CHERRYVIEW(dev))
5088                         cherryview_set_cdclk(dev, req_cdclk);
5089                 else
5090                         valleyview_set_cdclk(dev, req_cdclk);
5091
5092                 intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5093         }
5094 }
5095
5096 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5097 {
5098         struct drm_device *dev = crtc->dev;
5099         struct drm_i915_private *dev_priv = to_i915(dev);
5100         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5101         struct intel_encoder *encoder;
5102         int pipe = intel_crtc->pipe;
5103         bool is_dsi;
5104
5105         WARN_ON(!crtc->state->enable);
5106
5107         if (intel_crtc->active)
5108                 return;
5109
5110         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
5111
5112         if (!is_dsi) {
5113                 if (IS_CHERRYVIEW(dev))
5114                         chv_prepare_pll(intel_crtc, intel_crtc->config);
5115                 else
5116                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
5117         }
5118
5119         if (intel_crtc->config->has_dp_encoder)
5120                 intel_dp_set_m_n(intel_crtc, M1_N1);
5121
5122         intel_set_pipe_timings(intel_crtc);
5123
5124         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
5125                 struct drm_i915_private *dev_priv = dev->dev_private;
5126
5127                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5128                 I915_WRITE(CHV_CANVAS(pipe), 0);
5129         }
5130
5131         i9xx_set_pipeconf(intel_crtc);
5132
5133         intel_crtc->active = true;
5134
5135         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5136
5137         for_each_encoder_on_crtc(dev, crtc, encoder)
5138                 if (encoder->pre_pll_enable)
5139                         encoder->pre_pll_enable(encoder);
5140
5141         if (!is_dsi) {
5142                 if (IS_CHERRYVIEW(dev))
5143                         chv_enable_pll(intel_crtc, intel_crtc->config);
5144                 else
5145                         vlv_enable_pll(intel_crtc, intel_crtc->config);
5146         }
5147
5148         for_each_encoder_on_crtc(dev, crtc, encoder)
5149                 if (encoder->pre_enable)
5150                         encoder->pre_enable(encoder);
5151
5152         i9xx_pfit_enable(intel_crtc);
5153
5154         intel_crtc_load_lut(crtc);
5155
5156         intel_update_watermarks(crtc);
5157         intel_enable_pipe(intel_crtc);
5158
5159         assert_vblank_disabled(crtc);
5160         drm_crtc_vblank_on(crtc);
5161
5162         for_each_encoder_on_crtc(dev, crtc, encoder)
5163                 encoder->enable(encoder);
5164
5165         intel_crtc_enable_planes(crtc);
5166
5167         /* Underruns don't raise interrupts, so check manually. */
5168         i9xx_check_fifo_underruns(dev_priv);
5169 }
5170
5171 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5172 {
5173         struct drm_device *dev = crtc->base.dev;
5174         struct drm_i915_private *dev_priv = dev->dev_private;
5175
5176         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5177         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5178 }
5179
5180 static void i9xx_crtc_enable(struct drm_crtc *crtc)
5181 {
5182         struct drm_device *dev = crtc->dev;
5183         struct drm_i915_private *dev_priv = to_i915(dev);
5184         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5185         struct intel_encoder *encoder;
5186         int pipe = intel_crtc->pipe;
5187
5188         WARN_ON(!crtc->state->enable);
5189
5190         if (intel_crtc->active)
5191                 return;
5192
5193         i9xx_set_pll_dividers(intel_crtc);
5194
5195         if (intel_crtc->config->has_dp_encoder)
5196                 intel_dp_set_m_n(intel_crtc, M1_N1);
5197
5198         intel_set_pipe_timings(intel_crtc);
5199
5200         i9xx_set_pipeconf(intel_crtc);
5201
5202         intel_crtc->active = true;
5203
5204         if (!IS_GEN2(dev))
5205                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5206
5207         for_each_encoder_on_crtc(dev, crtc, encoder)
5208                 if (encoder->pre_enable)
5209                         encoder->pre_enable(encoder);
5210
5211         i9xx_enable_pll(intel_crtc);
5212
5213         i9xx_pfit_enable(intel_crtc);
5214
5215         intel_crtc_load_lut(crtc);
5216
5217         intel_update_watermarks(crtc);
5218         intel_enable_pipe(intel_crtc);
5219
5220         assert_vblank_disabled(crtc);
5221         drm_crtc_vblank_on(crtc);
5222
5223         for_each_encoder_on_crtc(dev, crtc, encoder)
5224                 encoder->enable(encoder);
5225
5226         intel_crtc_enable_planes(crtc);
5227
5228         /*
5229          * Gen2 reports pipe underruns whenever all planes are disabled.
5230          * So don't enable underrun reporting before at least some planes
5231          * are enabled.
5232          * FIXME: Need to fix the logic to work when we turn off all planes
5233          * but leave the pipe running.
5234          */
5235         if (IS_GEN2(dev))
5236                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5237
5238         /* Underruns don't raise interrupts, so check manually. */
5239         i9xx_check_fifo_underruns(dev_priv);
5240 }
5241
5242 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5243 {
5244         struct drm_device *dev = crtc->base.dev;
5245         struct drm_i915_private *dev_priv = dev->dev_private;
5246
5247         if (!crtc->config->gmch_pfit.control)
5248                 return;
5249
5250         assert_pipe_disabled(dev_priv, crtc->pipe);
5251
5252         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5253                          I915_READ(PFIT_CONTROL));
5254         I915_WRITE(PFIT_CONTROL, 0);
5255 }
5256
5257 static void i9xx_crtc_disable(struct drm_crtc *crtc)
5258 {
5259         struct drm_device *dev = crtc->dev;
5260         struct drm_i915_private *dev_priv = dev->dev_private;
5261         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5262         struct intel_encoder *encoder;
5263         int pipe = intel_crtc->pipe;
5264
5265         if (!intel_crtc->active)
5266                 return;
5267
5268         /*
5269          * Gen2 reports pipe underruns whenever all planes are disabled.
5270          * So diasble underrun reporting before all the planes get disabled.
5271          * FIXME: Need to fix the logic to work when we turn off all planes
5272          * but leave the pipe running.
5273          */
5274         if (IS_GEN2(dev))
5275                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5276
5277         /*
5278          * Vblank time updates from the shadow to live plane control register
5279          * are blocked if the memory self-refresh mode is active at that
5280          * moment. So to make sure the plane gets truly disabled, disable
5281          * first the self-refresh mode. The self-refresh enable bit in turn
5282          * will be checked/applied by the HW only at the next frame start
5283          * event which is after the vblank start event, so we need to have a
5284          * wait-for-vblank between disabling the plane and the pipe.
5285          */
5286         intel_set_memory_cxsr(dev_priv, false);
5287         intel_crtc_disable_planes(crtc);
5288
5289         /*
5290          * On gen2 planes are double buffered but the pipe isn't, so we must
5291          * wait for planes to fully turn off before disabling the pipe.
5292          * We also need to wait on all gmch platforms because of the
5293          * self-refresh mode constraint explained above.
5294          */
5295         intel_wait_for_vblank(dev, pipe);
5296
5297         for_each_encoder_on_crtc(dev, crtc, encoder)
5298                 encoder->disable(encoder);
5299
5300         drm_crtc_vblank_off(crtc);
5301         assert_vblank_disabled(crtc);
5302
5303         intel_disable_pipe(intel_crtc);
5304
5305         i9xx_pfit_disable(intel_crtc);
5306
5307         for_each_encoder_on_crtc(dev, crtc, encoder)
5308                 if (encoder->post_disable)
5309                         encoder->post_disable(encoder);
5310
5311         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5312                 if (IS_CHERRYVIEW(dev))
5313                         chv_disable_pll(dev_priv, pipe);
5314                 else if (IS_VALLEYVIEW(dev))
5315                         vlv_disable_pll(dev_priv, pipe);
5316                 else
5317                         i9xx_disable_pll(intel_crtc);
5318         }
5319
5320         if (!IS_GEN2(dev))
5321                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5322
5323         intel_crtc->active = false;
5324         intel_update_watermarks(crtc);
5325
5326         mutex_lock(&dev->struct_mutex);
5327         intel_fbc_update(dev);
5328         mutex_unlock(&dev->struct_mutex);
5329 }
5330
5331 static void i9xx_crtc_off(struct drm_crtc *crtc)
5332 {
5333 }
5334
5335 /* Master function to enable/disable CRTC and corresponding power wells */
5336 void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5337 {
5338         struct drm_device *dev = crtc->dev;
5339         struct drm_i915_private *dev_priv = dev->dev_private;
5340         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5341         enum intel_display_power_domain domain;
5342         unsigned long domains;
5343
5344         if (enable) {
5345                 if (!intel_crtc->active) {
5346                         domains = get_crtc_power_domains(crtc);
5347                         for_each_power_domain(domain, domains)
5348                                 intel_display_power_get(dev_priv, domain);
5349                         intel_crtc->enabled_power_domains = domains;
5350
5351                         dev_priv->display.crtc_enable(crtc);
5352                 }
5353         } else {
5354                 if (intel_crtc->active) {
5355                         dev_priv->display.crtc_disable(crtc);
5356
5357                         domains = intel_crtc->enabled_power_domains;
5358                         for_each_power_domain(domain, domains)
5359                                 intel_display_power_put(dev_priv, domain);
5360                         intel_crtc->enabled_power_domains = 0;
5361                 }
5362         }
5363 }
5364
5365 /**
5366  * Sets the power management mode of the pipe and plane.
5367  */
5368 void intel_crtc_update_dpms(struct drm_crtc *crtc)
5369 {
5370         struct drm_device *dev = crtc->dev;
5371         struct intel_encoder *intel_encoder;
5372         bool enable = false;
5373
5374         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5375                 enable |= intel_encoder->connectors_active;
5376
5377         intel_crtc_control(crtc, enable);
5378 }
5379
5380 static void intel_crtc_disable(struct drm_crtc *crtc)
5381 {
5382         struct drm_device *dev = crtc->dev;
5383         struct drm_connector *connector;
5384         struct drm_i915_private *dev_priv = dev->dev_private;
5385
5386         /* crtc should still be enabled when we disable it. */
5387         WARN_ON(!crtc->state->enable);
5388
5389         dev_priv->display.crtc_disable(crtc);
5390         dev_priv->display.off(crtc);
5391
5392         crtc->primary->funcs->disable_plane(crtc->primary);
5393
5394         /* Update computed state. */
5395         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
5396                 if (!connector->encoder || !connector->encoder->crtc)
5397                         continue;
5398
5399                 if (connector->encoder->crtc != crtc)
5400                         continue;
5401
5402                 connector->dpms = DRM_MODE_DPMS_OFF;
5403                 to_intel_encoder(connector->encoder)->connectors_active = false;
5404         }
5405 }
5406
5407 void intel_encoder_destroy(struct drm_encoder *encoder)
5408 {
5409         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5410
5411         drm_encoder_cleanup(encoder);
5412         kfree(intel_encoder);
5413 }
5414
5415 /* Simple dpms helper for encoders with just one connector, no cloning and only
5416  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
5417  * state of the entire output pipe. */
5418 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
5419 {
5420         if (mode == DRM_MODE_DPMS_ON) {
5421                 encoder->connectors_active = true;
5422
5423                 intel_crtc_update_dpms(encoder->base.crtc);
5424         } else {
5425                 encoder->connectors_active = false;
5426
5427                 intel_crtc_update_dpms(encoder->base.crtc);
5428         }
5429 }
5430
5431 /* Cross check the actual hw state with our own modeset state tracking (and it's
5432  * internal consistency). */
5433 static void intel_connector_check_state(struct intel_connector *connector)
5434 {
5435         if (connector->get_hw_state(connector)) {
5436                 struct intel_encoder *encoder = connector->encoder;
5437                 struct drm_crtc *crtc;
5438                 bool encoder_enabled;
5439                 enum pipe pipe;
5440
5441                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5442                               connector->base.base.id,
5443                               connector->base.name);
5444
5445                 /* there is no real hw state for MST connectors */
5446                 if (connector->mst_port)
5447                         return;
5448
5449                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
5450                      "wrong connector dpms state\n");
5451                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
5452                      "active connector not linked to encoder\n");
5453
5454                 if (encoder) {
5455                         I915_STATE_WARN(!encoder->connectors_active,
5456                              "encoder->connectors_active not set\n");
5457
5458                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
5459                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
5460                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
5461                                 return;
5462
5463                         crtc = encoder->base.crtc;
5464
5465                         I915_STATE_WARN(!crtc->state->enable,
5466                                         "crtc not enabled\n");
5467                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
5468                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
5469                              "encoder active on the wrong pipe\n");
5470                 }
5471         }
5472 }
5473
5474 /* Even simpler default implementation, if there's really no special case to
5475  * consider. */
5476 void intel_connector_dpms(struct drm_connector *connector, int mode)
5477 {
5478         /* All the simple cases only support two dpms states. */
5479         if (mode != DRM_MODE_DPMS_ON)
5480                 mode = DRM_MODE_DPMS_OFF;
5481
5482         if (mode == connector->dpms)
5483                 return;
5484
5485         connector->dpms = mode;
5486
5487         /* Only need to change hw state when actually enabled */
5488         if (connector->encoder)
5489                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
5490
5491         intel_modeset_check_state(connector->dev);
5492 }
5493
5494 /* Simple connector->get_hw_state implementation for encoders that support only
5495  * one connector and no cloning and hence the encoder state determines the state
5496  * of the connector. */
5497 bool intel_connector_get_hw_state(struct intel_connector *connector)
5498 {
5499         enum pipe pipe = 0;
5500         struct intel_encoder *encoder = connector->encoder;
5501
5502         return encoder->get_hw_state(encoder, &pipe);
5503 }
5504
5505 static bool ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
5506                                      struct intel_crtc_state *pipe_config)
5507 {
5508         struct drm_i915_private *dev_priv = dev->dev_private;
5509         struct intel_crtc *pipe_B_crtc =
5510                 to_intel_crtc(dev_priv->pipe_to_crtc_mapping[PIPE_B]);
5511
5512         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
5513                       pipe_name(pipe), pipe_config->fdi_lanes);
5514         if (pipe_config->fdi_lanes > 4) {
5515                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
5516                               pipe_name(pipe), pipe_config->fdi_lanes);
5517                 return false;
5518         }
5519
5520         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
5521                 if (pipe_config->fdi_lanes > 2) {
5522                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
5523                                       pipe_config->fdi_lanes);
5524                         return false;
5525                 } else {
5526                         return true;
5527                 }
5528         }
5529
5530         if (INTEL_INFO(dev)->num_pipes == 2)
5531                 return true;
5532
5533         /* Ivybridge 3 pipe is really complicated */
5534         switch (pipe) {
5535         case PIPE_A:
5536                 return true;
5537         case PIPE_B:
5538                 if (dev_priv->pipe_to_crtc_mapping[PIPE_C]->enabled &&
5539                     pipe_config->fdi_lanes > 2) {
5540                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5541                                       pipe_name(pipe), pipe_config->fdi_lanes);
5542                         return false;
5543                 }
5544                 return true;
5545         case PIPE_C:
5546                 if (!pipe_has_enabled_pch(pipe_B_crtc) ||
5547                     pipe_B_crtc->config->fdi_lanes <= 2) {
5548                         if (pipe_config->fdi_lanes > 2) {
5549                                 DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
5550                                               pipe_name(pipe), pipe_config->fdi_lanes);
5551                                 return false;
5552                         }
5553                 } else {
5554                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
5555                         return false;
5556                 }
5557                 return true;
5558         default:
5559                 BUG();
5560         }
5561 }
5562
5563 #define RETRY 1
5564 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
5565                                        struct intel_crtc_state *pipe_config)
5566 {
5567         struct drm_device *dev = intel_crtc->base.dev;
5568         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5569         int lane, link_bw, fdi_dotclock;
5570         bool setup_ok, needs_recompute = false;
5571
5572 retry:
5573         /* FDI is a binary signal running at ~2.7GHz, encoding
5574          * each output octet as 10 bits. The actual frequency
5575          * is stored as a divider into a 100MHz clock, and the
5576          * mode pixel clock is stored in units of 1KHz.
5577          * Hence the bw of each lane in terms of the mode signal
5578          * is:
5579          */
5580         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
5581
5582         fdi_dotclock = adjusted_mode->crtc_clock;
5583
5584         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
5585                                            pipe_config->pipe_bpp);
5586
5587         pipe_config->fdi_lanes = lane;
5588
5589         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
5590                                link_bw, &pipe_config->fdi_m_n);
5591
5592         setup_ok = ironlake_check_fdi_lanes(intel_crtc->base.dev,
5593                                             intel_crtc->pipe, pipe_config);
5594         if (!setup_ok && pipe_config->pipe_bpp > 6*3) {
5595                 pipe_config->pipe_bpp -= 2*3;
5596                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
5597                               pipe_config->pipe_bpp);
5598                 needs_recompute = true;
5599                 pipe_config->bw_constrained = true;
5600
5601                 goto retry;
5602         }
5603
5604         if (needs_recompute)
5605                 return RETRY;
5606
5607         return setup_ok ? 0 : -EINVAL;
5608 }
5609
5610 static void hsw_compute_ips_config(struct intel_crtc *crtc,
5611                                    struct intel_crtc_state *pipe_config)
5612 {
5613         pipe_config->ips_enabled = i915.enable_ips &&
5614                                    hsw_crtc_supports_ips(crtc) &&
5615                                    pipe_config->pipe_bpp <= 24;
5616 }
5617
5618 static int intel_crtc_compute_config(struct intel_crtc *crtc,
5619                                      struct intel_crtc_state *pipe_config)
5620 {
5621         struct drm_device *dev = crtc->base.dev;
5622         struct drm_i915_private *dev_priv = dev->dev_private;
5623         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
5624
5625         /* FIXME should check pixel clock limits on all platforms */
5626         if (INTEL_INFO(dev)->gen < 4) {
5627                 int clock_limit =
5628                         dev_priv->display.get_display_clock_speed(dev);
5629
5630                 /*
5631                  * Enable pixel doubling when the dot clock
5632                  * is > 90% of the (display) core speed.
5633                  *
5634                  * GDG double wide on either pipe,
5635                  * otherwise pipe A only.
5636                  */
5637                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
5638                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
5639                         clock_limit *= 2;
5640                         pipe_config->double_wide = true;
5641                 }
5642
5643                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
5644                         return -EINVAL;
5645         }
5646
5647         /*
5648          * Pipe horizontal size must be even in:
5649          * - DVO ganged mode
5650          * - LVDS dual channel mode
5651          * - Double wide pipe
5652          */
5653         if ((intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
5654              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
5655                 pipe_config->pipe_src_w &= ~1;
5656
5657         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
5658          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
5659          */
5660         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
5661                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
5662                 return -EINVAL;
5663
5664         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)) && pipe_config->pipe_bpp > 10*3) {
5665                 pipe_config->pipe_bpp = 10*3; /* 12bpc is gen5+ */
5666         } else if (INTEL_INFO(dev)->gen <= 4 && pipe_config->pipe_bpp > 8*3) {
5667                 /* only a 8bpc pipe, with 6bpc dither through the panel fitter
5668                  * for lvds. */
5669                 pipe_config->pipe_bpp = 8*3;
5670         }
5671
5672         if (HAS_IPS(dev))
5673                 hsw_compute_ips_config(crtc, pipe_config);
5674
5675         if (pipe_config->has_pch_encoder)
5676                 return ironlake_fdi_compute_config(crtc, pipe_config);
5677
5678         return 0;
5679 }
5680
5681 static int valleyview_get_display_clock_speed(struct drm_device *dev)
5682 {
5683         struct drm_i915_private *dev_priv = dev->dev_private;
5684         u32 val;
5685         int divider;
5686
5687         /* FIXME: Punit isn't quite ready yet */
5688         if (IS_CHERRYVIEW(dev))
5689                 return 400000;
5690
5691         if (dev_priv->hpll_freq == 0)
5692                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
5693
5694         mutex_lock(&dev_priv->dpio_lock);
5695         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5696         mutex_unlock(&dev_priv->dpio_lock);
5697
5698         divider = val & DISPLAY_FREQUENCY_VALUES;
5699
5700         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
5701              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5702              "cdclk change in progress\n");
5703
5704         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
5705 }
5706
5707 static int i945_get_display_clock_speed(struct drm_device *dev)
5708 {
5709         return 400000;
5710 }
5711
5712 static int i915_get_display_clock_speed(struct drm_device *dev)
5713 {
5714         return 333000;
5715 }
5716
5717 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
5718 {
5719         return 200000;
5720 }
5721
5722 static int pnv_get_display_clock_speed(struct drm_device *dev)
5723 {
5724         u16 gcfgc = 0;
5725
5726         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5727
5728         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5729         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
5730                 return 267000;
5731         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
5732                 return 333000;
5733         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
5734                 return 444000;
5735         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
5736                 return 200000;
5737         default:
5738                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
5739         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
5740                 return 133000;
5741         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
5742                 return 167000;
5743         }
5744 }
5745
5746 static int i915gm_get_display_clock_speed(struct drm_device *dev)
5747 {
5748         u16 gcfgc = 0;
5749
5750         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
5751
5752         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
5753                 return 133000;
5754         else {
5755                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
5756                 case GC_DISPLAY_CLOCK_333_MHZ:
5757                         return 333000;
5758                 default:
5759                 case GC_DISPLAY_CLOCK_190_200_MHZ:
5760                         return 190000;
5761                 }
5762         }
5763 }
5764
5765 static int i865_get_display_clock_speed(struct drm_device *dev)
5766 {
5767         return 266000;
5768 }
5769
5770 static int i855_get_display_clock_speed(struct drm_device *dev)
5771 {
5772         u16 hpllcc = 0;
5773         /* Assume that the hardware is in the high speed state.  This
5774          * should be the default.
5775          */
5776         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
5777         case GC_CLOCK_133_200:
5778         case GC_CLOCK_100_200:
5779                 return 200000;
5780         case GC_CLOCK_166_250:
5781                 return 250000;
5782         case GC_CLOCK_100_133:
5783                 return 133000;
5784         }
5785
5786         /* Shouldn't happen */
5787         return 0;
5788 }
5789
5790 static int i830_get_display_clock_speed(struct drm_device *dev)
5791 {
5792         return 133000;
5793 }
5794
5795 static void
5796 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
5797 {
5798         while (*num > DATA_LINK_M_N_MASK ||
5799                *den > DATA_LINK_M_N_MASK) {
5800                 *num >>= 1;
5801                 *den >>= 1;
5802         }
5803 }
5804
5805 static void compute_m_n(unsigned int m, unsigned int n,
5806                         uint32_t *ret_m, uint32_t *ret_n)
5807 {
5808         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
5809         *ret_m = div_u64((uint64_t) m * *ret_n, n);
5810         intel_reduce_m_n_ratio(ret_m, ret_n);
5811 }
5812
5813 void
5814 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
5815                        int pixel_clock, int link_clock,
5816                        struct intel_link_m_n *m_n)
5817 {
5818         m_n->tu = 64;
5819
5820         compute_m_n(bits_per_pixel * pixel_clock,
5821                     link_clock * nlanes * 8,
5822                     &m_n->gmch_m, &m_n->gmch_n);
5823
5824         compute_m_n(pixel_clock, link_clock,
5825                     &m_n->link_m, &m_n->link_n);
5826 }
5827
5828 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
5829 {
5830         if (i915.panel_use_ssc >= 0)
5831                 return i915.panel_use_ssc != 0;
5832         return dev_priv->vbt.lvds_use_ssc
5833                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
5834 }
5835
5836 static int i9xx_get_refclk(struct intel_crtc *crtc, int num_connectors)
5837 {
5838         struct drm_device *dev = crtc->base.dev;
5839         struct drm_i915_private *dev_priv = dev->dev_private;
5840         int refclk;
5841
5842         if (IS_VALLEYVIEW(dev)) {
5843                 refclk = 100000;
5844         } else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
5845             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
5846                 refclk = dev_priv->vbt.lvds_ssc_freq;
5847                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
5848         } else if (!IS_GEN2(dev)) {
5849                 refclk = 96000;
5850         } else {
5851                 refclk = 48000;
5852         }
5853
5854         return refclk;
5855 }
5856
5857 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
5858 {
5859         return (1 << dpll->n) << 16 | dpll->m2;
5860 }
5861
5862 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
5863 {
5864         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
5865 }
5866
5867 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
5868                                      struct intel_crtc_state *crtc_state,
5869                                      intel_clock_t *reduced_clock)
5870 {
5871         struct drm_device *dev = crtc->base.dev;
5872         u32 fp, fp2 = 0;
5873
5874         if (IS_PINEVIEW(dev)) {
5875                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
5876                 if (reduced_clock)
5877                         fp2 = pnv_dpll_compute_fp(reduced_clock);
5878         } else {
5879                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
5880                 if (reduced_clock)
5881                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
5882         }
5883
5884         crtc_state->dpll_hw_state.fp0 = fp;
5885
5886         crtc->lowfreq_avail = false;
5887         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
5888             reduced_clock && i915.powersave) {
5889                 crtc_state->dpll_hw_state.fp1 = fp2;
5890                 crtc->lowfreq_avail = true;
5891         } else {
5892                 crtc_state->dpll_hw_state.fp1 = fp;
5893         }
5894 }
5895
5896 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
5897                 pipe)
5898 {
5899         u32 reg_val;
5900
5901         /*
5902          * PLLB opamp always calibrates to max value of 0x3f, force enable it
5903          * and set it to a reasonable value instead.
5904          */
5905         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5906         reg_val &= 0xffffff00;
5907         reg_val |= 0x00000030;
5908         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5909
5910         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5911         reg_val &= 0x8cffffff;
5912         reg_val = 0x8c000000;
5913         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5914
5915         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
5916         reg_val &= 0xffffff00;
5917         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
5918
5919         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
5920         reg_val &= 0x00ffffff;
5921         reg_val |= 0xb0000000;
5922         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
5923 }
5924
5925 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
5926                                          struct intel_link_m_n *m_n)
5927 {
5928         struct drm_device *dev = crtc->base.dev;
5929         struct drm_i915_private *dev_priv = dev->dev_private;
5930         int pipe = crtc->pipe;
5931
5932         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5933         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
5934         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
5935         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
5936 }
5937
5938 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
5939                                          struct intel_link_m_n *m_n,
5940                                          struct intel_link_m_n *m2_n2)
5941 {
5942         struct drm_device *dev = crtc->base.dev;
5943         struct drm_i915_private *dev_priv = dev->dev_private;
5944         int pipe = crtc->pipe;
5945         enum transcoder transcoder = crtc->config->cpu_transcoder;
5946
5947         if (INTEL_INFO(dev)->gen >= 5) {
5948                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
5949                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
5950                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
5951                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
5952                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
5953                  * for gen < 8) and if DRRS is supported (to make sure the
5954                  * registers are not unnecessarily accessed).
5955                  */
5956                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
5957                         crtc->config->has_drrs) {
5958                         I915_WRITE(PIPE_DATA_M2(transcoder),
5959                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
5960                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
5961                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
5962                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
5963                 }
5964         } else {
5965                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
5966                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
5967                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
5968                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
5969         }
5970 }
5971
5972 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
5973 {
5974         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
5975
5976         if (m_n == M1_N1) {
5977                 dp_m_n = &crtc->config->dp_m_n;
5978                 dp_m2_n2 = &crtc->config->dp_m2_n2;
5979         } else if (m_n == M2_N2) {
5980
5981                 /*
5982                  * M2_N2 registers are not supported. Hence m2_n2 divider value
5983                  * needs to be programmed into M1_N1.
5984                  */
5985                 dp_m_n = &crtc->config->dp_m2_n2;
5986         } else {
5987                 DRM_ERROR("Unsupported divider value\n");
5988                 return;
5989         }
5990
5991         if (crtc->config->has_pch_encoder)
5992                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
5993         else
5994                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
5995 }
5996
5997 static void vlv_update_pll(struct intel_crtc *crtc,
5998                            struct intel_crtc_state *pipe_config)
5999 {
6000         u32 dpll, dpll_md;
6001
6002         /*
6003          * Enable DPIO clock input. We should never disable the reference
6004          * clock for pipe B, since VGA hotplug / manual detection depends
6005          * on it.
6006          */
6007         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
6008                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
6009         /* We should never disable this, set it here for state tracking */
6010         if (crtc->pipe == PIPE_B)
6011                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6012         dpll |= DPLL_VCO_ENABLE;
6013         pipe_config->dpll_hw_state.dpll = dpll;
6014
6015         dpll_md = (pipe_config->pixel_multiplier - 1)
6016                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6017         pipe_config->dpll_hw_state.dpll_md = dpll_md;
6018 }
6019
6020 static void vlv_prepare_pll(struct intel_crtc *crtc,
6021                             const struct intel_crtc_state *pipe_config)
6022 {
6023         struct drm_device *dev = crtc->base.dev;
6024         struct drm_i915_private *dev_priv = dev->dev_private;
6025         int pipe = crtc->pipe;
6026         u32 mdiv;
6027         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6028         u32 coreclk, reg_val;
6029
6030         mutex_lock(&dev_priv->dpio_lock);
6031
6032         bestn = pipe_config->dpll.n;
6033         bestm1 = pipe_config->dpll.m1;
6034         bestm2 = pipe_config->dpll.m2;
6035         bestp1 = pipe_config->dpll.p1;
6036         bestp2 = pipe_config->dpll.p2;
6037
6038         /* See eDP HDMI DPIO driver vbios notes doc */
6039
6040         /* PLL B needs special handling */
6041         if (pipe == PIPE_B)
6042                 vlv_pllb_recal_opamp(dev_priv, pipe);
6043
6044         /* Set up Tx target for periodic Rcomp update */
6045         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6046
6047         /* Disable target IRef on PLL */
6048         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6049         reg_val &= 0x00ffffff;
6050         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6051
6052         /* Disable fast lock */
6053         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6054
6055         /* Set idtafcrecal before PLL is enabled */
6056         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6057         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6058         mdiv |= ((bestn << DPIO_N_SHIFT));
6059         mdiv |= (1 << DPIO_K_SHIFT);
6060
6061         /*
6062          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6063          * but we don't support that).
6064          * Note: don't use the DAC post divider as it seems unstable.
6065          */
6066         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6067         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6068
6069         mdiv |= DPIO_ENABLE_CALIBRATION;
6070         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6071
6072         /* Set HBR and RBR LPF coefficients */
6073         if (pipe_config->port_clock == 162000 ||
6074             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
6075             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
6076                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6077                                  0x009f0003);
6078         else
6079                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6080                                  0x00d0000f);
6081
6082         if (pipe_config->has_dp_encoder) {
6083                 /* Use SSC source */
6084                 if (pipe == PIPE_A)
6085                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6086                                          0x0df40000);
6087                 else
6088                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6089                                          0x0df70000);
6090         } else { /* HDMI or VGA */
6091                 /* Use bend source */
6092                 if (pipe == PIPE_A)
6093                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6094                                          0x0df70000);
6095                 else
6096                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6097                                          0x0df40000);
6098         }
6099
6100         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6101         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6102         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
6103             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
6104                 coreclk |= 0x01000000;
6105         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6106
6107         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6108         mutex_unlock(&dev_priv->dpio_lock);
6109 }
6110
6111 static void chv_update_pll(struct intel_crtc *crtc,
6112                            struct intel_crtc_state *pipe_config)
6113 {
6114         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
6115                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
6116                 DPLL_VCO_ENABLE;
6117         if (crtc->pipe != PIPE_A)
6118                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6119
6120         pipe_config->dpll_hw_state.dpll_md =
6121                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6122 }
6123
6124 static void chv_prepare_pll(struct intel_crtc *crtc,
6125                             const struct intel_crtc_state *pipe_config)
6126 {
6127         struct drm_device *dev = crtc->base.dev;
6128         struct drm_i915_private *dev_priv = dev->dev_private;
6129         int pipe = crtc->pipe;
6130         int dpll_reg = DPLL(crtc->pipe);
6131         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6132         u32 loopfilter, intcoeff;
6133         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6134         int refclk;
6135
6136         bestn = pipe_config->dpll.n;
6137         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6138         bestm1 = pipe_config->dpll.m1;
6139         bestm2 = pipe_config->dpll.m2 >> 22;
6140         bestp1 = pipe_config->dpll.p1;
6141         bestp2 = pipe_config->dpll.p2;
6142
6143         /*
6144          * Enable Refclk and SSC
6145          */
6146         I915_WRITE(dpll_reg,
6147                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6148
6149         mutex_lock(&dev_priv->dpio_lock);
6150
6151         /* p1 and p2 divider */
6152         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6153                         5 << DPIO_CHV_S1_DIV_SHIFT |
6154                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6155                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6156                         1 << DPIO_CHV_K_DIV_SHIFT);
6157
6158         /* Feedback post-divider - m2 */
6159         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6160
6161         /* Feedback refclk divider - n and m1 */
6162         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6163                         DPIO_CHV_M1_DIV_BY_2 |
6164                         1 << DPIO_CHV_N_DIV_SHIFT);
6165
6166         /* M2 fraction division */
6167         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6168
6169         /* M2 fraction division enable */
6170         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port),
6171                        DPIO_CHV_FRAC_DIV_EN |
6172                        (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT));
6173
6174         /* Loop filter */
6175         refclk = i9xx_get_refclk(crtc, 0);
6176         loopfilter = 5 << DPIO_CHV_PROP_COEFF_SHIFT |
6177                 2 << DPIO_CHV_GAIN_CTRL_SHIFT;
6178         if (refclk == 100000)
6179                 intcoeff = 11;
6180         else if (refclk == 38400)
6181                 intcoeff = 10;
6182         else
6183                 intcoeff = 9;
6184         loopfilter |= intcoeff << DPIO_CHV_INT_COEFF_SHIFT;
6185         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6186
6187         /* AFC Recal */
6188         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6189                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6190                         DPIO_AFC_RECAL);
6191
6192         mutex_unlock(&dev_priv->dpio_lock);
6193 }
6194
6195 /**
6196  * vlv_force_pll_on - forcibly enable just the PLL
6197  * @dev_priv: i915 private structure
6198  * @pipe: pipe PLL to enable
6199  * @dpll: PLL configuration
6200  *
6201  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6202  * in cases where we need the PLL enabled even when @pipe is not going to
6203  * be enabled.
6204  */
6205 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
6206                       const struct dpll *dpll)
6207 {
6208         struct intel_crtc *crtc =
6209                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
6210         struct intel_crtc_state pipe_config = {
6211                 .pixel_multiplier = 1,
6212                 .dpll = *dpll,
6213         };
6214
6215         if (IS_CHERRYVIEW(dev)) {
6216                 chv_update_pll(crtc, &pipe_config);
6217                 chv_prepare_pll(crtc, &pipe_config);
6218                 chv_enable_pll(crtc, &pipe_config);
6219         } else {
6220                 vlv_update_pll(crtc, &pipe_config);
6221                 vlv_prepare_pll(crtc, &pipe_config);
6222                 vlv_enable_pll(crtc, &pipe_config);
6223         }
6224 }
6225
6226 /**
6227  * vlv_force_pll_off - forcibly disable just the PLL
6228  * @dev_priv: i915 private structure
6229  * @pipe: pipe PLL to disable
6230  *
6231  * Disable the PLL for @pipe. To be used in cases where we need
6232  * the PLL enabled even when @pipe is not going to be enabled.
6233  */
6234 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
6235 {
6236         if (IS_CHERRYVIEW(dev))
6237                 chv_disable_pll(to_i915(dev), pipe);
6238         else
6239                 vlv_disable_pll(to_i915(dev), pipe);
6240 }
6241
6242 static void i9xx_update_pll(struct intel_crtc *crtc,
6243                             struct intel_crtc_state *crtc_state,
6244                             intel_clock_t *reduced_clock,
6245                             int num_connectors)
6246 {
6247         struct drm_device *dev = crtc->base.dev;
6248         struct drm_i915_private *dev_priv = dev->dev_private;
6249         u32 dpll;
6250         bool is_sdvo;
6251         struct dpll *clock = &crtc_state->dpll;
6252
6253         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6254
6255         is_sdvo = intel_pipe_will_have_type(crtc, INTEL_OUTPUT_SDVO) ||
6256                 intel_pipe_will_have_type(crtc, INTEL_OUTPUT_HDMI);
6257
6258         dpll = DPLL_VGA_MODE_DIS;
6259
6260         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS))
6261                 dpll |= DPLLB_MODE_LVDS;
6262         else
6263                 dpll |= DPLLB_MODE_DAC_SERIAL;
6264
6265         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6266                 dpll |= (crtc_state->pixel_multiplier - 1)
6267                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6268         }
6269
6270         if (is_sdvo)
6271                 dpll |= DPLL_SDVO_HIGH_SPEED;
6272
6273         if (crtc_state->has_dp_encoder)
6274                 dpll |= DPLL_SDVO_HIGH_SPEED;
6275
6276         /* compute bitmask from p1 value */
6277         if (IS_PINEVIEW(dev))
6278                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6279         else {
6280                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6281                 if (IS_G4X(dev) && reduced_clock)
6282                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6283         }
6284         switch (clock->p2) {
6285         case 5:
6286                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6287                 break;
6288         case 7:
6289                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6290                 break;
6291         case 10:
6292                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6293                 break;
6294         case 14:
6295                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6296                 break;
6297         }
6298         if (INTEL_INFO(dev)->gen >= 4)
6299                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6300
6301         if (crtc_state->sdvo_tv_clock)
6302                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6303         else if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
6304                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6305                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6306         else
6307                 dpll |= PLL_REF_INPUT_DREFCLK;
6308
6309         dpll |= DPLL_VCO_ENABLE;
6310         crtc_state->dpll_hw_state.dpll = dpll;
6311
6312         if (INTEL_INFO(dev)->gen >= 4) {
6313                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6314                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6315                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6316         }
6317 }
6318
6319 static void i8xx_update_pll(struct intel_crtc *crtc,
6320                             struct intel_crtc_state *crtc_state,
6321                             intel_clock_t *reduced_clock,
6322                             int num_connectors)
6323 {
6324         struct drm_device *dev = crtc->base.dev;
6325         struct drm_i915_private *dev_priv = dev->dev_private;
6326         u32 dpll;
6327         struct dpll *clock = &crtc_state->dpll;
6328
6329         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6330
6331         dpll = DPLL_VGA_MODE_DIS;
6332
6333         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS)) {
6334                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6335         } else {
6336                 if (clock->p1 == 2)
6337                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6338                 else
6339                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6340                 if (clock->p2 == 4)
6341                         dpll |= PLL_P2_DIVIDE_BY_4;
6342         }
6343
6344         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc, INTEL_OUTPUT_DVO))
6345                 dpll |= DPLL_DVO_2X_MODE;
6346
6347         if (intel_pipe_will_have_type(crtc, INTEL_OUTPUT_LVDS) &&
6348                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
6349                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6350         else
6351                 dpll |= PLL_REF_INPUT_DREFCLK;
6352
6353         dpll |= DPLL_VCO_ENABLE;
6354         crtc_state->dpll_hw_state.dpll = dpll;
6355 }
6356
6357 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6358 {
6359         struct drm_device *dev = intel_crtc->base.dev;
6360         struct drm_i915_private *dev_priv = dev->dev_private;
6361         enum pipe pipe = intel_crtc->pipe;
6362         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6363         struct drm_display_mode *adjusted_mode =
6364                 &intel_crtc->config->base.adjusted_mode;
6365         uint32_t crtc_vtotal, crtc_vblank_end;
6366         int vsyncshift = 0;
6367
6368         /* We need to be careful not to changed the adjusted mode, for otherwise
6369          * the hw state checker will get angry at the mismatch. */
6370         crtc_vtotal = adjusted_mode->crtc_vtotal;
6371         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6372
6373         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6374                 /* the chip adds 2 halflines automatically */
6375                 crtc_vtotal -= 1;
6376                 crtc_vblank_end -= 1;
6377
6378                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6379                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6380                 else
6381                         vsyncshift = adjusted_mode->crtc_hsync_start -
6382                                 adjusted_mode->crtc_htotal / 2;
6383                 if (vsyncshift < 0)
6384                         vsyncshift += adjusted_mode->crtc_htotal;
6385         }
6386
6387         if (INTEL_INFO(dev)->gen > 3)
6388                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6389
6390         I915_WRITE(HTOTAL(cpu_transcoder),
6391                    (adjusted_mode->crtc_hdisplay - 1) |
6392                    ((adjusted_mode->crtc_htotal - 1) << 16));
6393         I915_WRITE(HBLANK(cpu_transcoder),
6394                    (adjusted_mode->crtc_hblank_start - 1) |
6395                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6396         I915_WRITE(HSYNC(cpu_transcoder),
6397                    (adjusted_mode->crtc_hsync_start - 1) |
6398                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6399
6400         I915_WRITE(VTOTAL(cpu_transcoder),
6401                    (adjusted_mode->crtc_vdisplay - 1) |
6402                    ((crtc_vtotal - 1) << 16));
6403         I915_WRITE(VBLANK(cpu_transcoder),
6404                    (adjusted_mode->crtc_vblank_start - 1) |
6405                    ((crtc_vblank_end - 1) << 16));
6406         I915_WRITE(VSYNC(cpu_transcoder),
6407                    (adjusted_mode->crtc_vsync_start - 1) |
6408                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6409
6410         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6411          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6412          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6413          * bits. */
6414         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
6415             (pipe == PIPE_B || pipe == PIPE_C))
6416                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6417
6418         /* pipesrc controls the size that is scaled from, which should
6419          * always be the user's requested size.
6420          */
6421         I915_WRITE(PIPESRC(pipe),
6422                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
6423                    (intel_crtc->config->pipe_src_h - 1));
6424 }
6425
6426 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6427                                    struct intel_crtc_state *pipe_config)
6428 {
6429         struct drm_device *dev = crtc->base.dev;
6430         struct drm_i915_private *dev_priv = dev->dev_private;
6431         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6432         uint32_t tmp;
6433
6434         tmp = I915_READ(HTOTAL(cpu_transcoder));
6435         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6436         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6437         tmp = I915_READ(HBLANK(cpu_transcoder));
6438         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6439         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6440         tmp = I915_READ(HSYNC(cpu_transcoder));
6441         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6442         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6443
6444         tmp = I915_READ(VTOTAL(cpu_transcoder));
6445         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6446         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6447         tmp = I915_READ(VBLANK(cpu_transcoder));
6448         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6449         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6450         tmp = I915_READ(VSYNC(cpu_transcoder));
6451         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6452         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6453
6454         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6455                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6456                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6457                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6458         }
6459
6460         tmp = I915_READ(PIPESRC(crtc->pipe));
6461         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
6462         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
6463
6464         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
6465         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
6466 }
6467
6468 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
6469                                  struct intel_crtc_state *pipe_config)
6470 {
6471         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
6472         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
6473         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
6474         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
6475
6476         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
6477         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
6478         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
6479         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
6480
6481         mode->flags = pipe_config->base.adjusted_mode.flags;
6482
6483         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
6484         mode->flags |= pipe_config->base.adjusted_mode.flags;
6485 }
6486
6487 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
6488 {
6489         struct drm_device *dev = intel_crtc->base.dev;
6490         struct drm_i915_private *dev_priv = dev->dev_private;
6491         uint32_t pipeconf;
6492
6493         pipeconf = 0;
6494
6495         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
6496             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
6497                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
6498
6499         if (intel_crtc->config->double_wide)
6500                 pipeconf |= PIPECONF_DOUBLE_WIDE;
6501
6502         /* only g4x and later have fancy bpc/dither controls */
6503         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6504                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
6505                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
6506                         pipeconf |= PIPECONF_DITHER_EN |
6507                                     PIPECONF_DITHER_TYPE_SP;
6508
6509                 switch (intel_crtc->config->pipe_bpp) {
6510                 case 18:
6511                         pipeconf |= PIPECONF_6BPC;
6512                         break;
6513                 case 24:
6514                         pipeconf |= PIPECONF_8BPC;
6515                         break;
6516                 case 30:
6517                         pipeconf |= PIPECONF_10BPC;
6518                         break;
6519                 default:
6520                         /* Case prevented by intel_choose_pipe_bpp_dither. */
6521                         BUG();
6522                 }
6523         }
6524
6525         if (HAS_PIPE_CXSR(dev)) {
6526                 if (intel_crtc->lowfreq_avail) {
6527                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
6528                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
6529                 } else {
6530                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
6531                 }
6532         }
6533
6534         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
6535                 if (INTEL_INFO(dev)->gen < 4 ||
6536                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
6537                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
6538                 else
6539                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
6540         } else
6541                 pipeconf |= PIPECONF_PROGRESSIVE;
6542
6543         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
6544                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
6545
6546         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
6547         POSTING_READ(PIPECONF(intel_crtc->pipe));
6548 }
6549
6550 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
6551                                    struct intel_crtc_state *crtc_state)
6552 {
6553         struct drm_device *dev = crtc->base.dev;
6554         struct drm_i915_private *dev_priv = dev->dev_private;
6555         int refclk, num_connectors = 0;
6556         intel_clock_t clock, reduced_clock;
6557         bool ok, has_reduced_clock = false;
6558         bool is_lvds = false, is_dsi = false;
6559         struct intel_encoder *encoder;
6560         const intel_limit_t *limit;
6561
6562         for_each_intel_encoder(dev, encoder) {
6563                 if (encoder->new_crtc != crtc)
6564                         continue;
6565
6566                 switch (encoder->type) {
6567                 case INTEL_OUTPUT_LVDS:
6568                         is_lvds = true;
6569                         break;
6570                 case INTEL_OUTPUT_DSI:
6571                         is_dsi = true;
6572                         break;
6573                 default:
6574                         break;
6575                 }
6576
6577                 num_connectors++;
6578         }
6579
6580         if (is_dsi)
6581                 return 0;
6582
6583         if (!crtc_state->clock_set) {
6584                 refclk = i9xx_get_refclk(crtc, num_connectors);
6585
6586                 /*
6587                  * Returns a set of divisors for the desired target clock with
6588                  * the given refclk, or FALSE.  The returned values represent
6589                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
6590                  * 2) / p1 / p2.
6591                  */
6592                 limit = intel_limit(crtc, refclk);
6593                 ok = dev_priv->display.find_dpll(limit, crtc,
6594                                                  crtc_state->port_clock,
6595                                                  refclk, NULL, &clock);
6596                 if (!ok) {
6597                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
6598                         return -EINVAL;
6599                 }
6600
6601                 if (is_lvds && dev_priv->lvds_downclock_avail) {
6602                         /*
6603                          * Ensure we match the reduced clock's P to the target
6604                          * clock.  If the clocks don't match, we can't switch
6605                          * the display clock by using the FP0/FP1. In such case
6606                          * we will disable the LVDS downclock feature.
6607                          */
6608                         has_reduced_clock =
6609                                 dev_priv->display.find_dpll(limit, crtc,
6610                                                             dev_priv->lvds_downclock,
6611                                                             refclk, &clock,
6612                                                             &reduced_clock);
6613                 }
6614                 /* Compat-code for transition, will disappear. */
6615                 crtc_state->dpll.n = clock.n;
6616                 crtc_state->dpll.m1 = clock.m1;
6617                 crtc_state->dpll.m2 = clock.m2;
6618                 crtc_state->dpll.p1 = clock.p1;
6619                 crtc_state->dpll.p2 = clock.p2;
6620         }
6621
6622         if (IS_GEN2(dev)) {
6623                 i8xx_update_pll(crtc, crtc_state,
6624                                 has_reduced_clock ? &reduced_clock : NULL,
6625                                 num_connectors);
6626         } else if (IS_CHERRYVIEW(dev)) {
6627                 chv_update_pll(crtc, crtc_state);
6628         } else if (IS_VALLEYVIEW(dev)) {
6629                 vlv_update_pll(crtc, crtc_state);
6630         } else {
6631                 i9xx_update_pll(crtc, crtc_state,
6632                                 has_reduced_clock ? &reduced_clock : NULL,
6633                                 num_connectors);
6634         }
6635
6636         return 0;
6637 }
6638
6639 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
6640                                  struct intel_crtc_state *pipe_config)
6641 {
6642         struct drm_device *dev = crtc->base.dev;
6643         struct drm_i915_private *dev_priv = dev->dev_private;
6644         uint32_t tmp;
6645
6646         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
6647                 return;
6648
6649         tmp = I915_READ(PFIT_CONTROL);
6650         if (!(tmp & PFIT_ENABLE))
6651                 return;
6652
6653         /* Check whether the pfit is attached to our pipe. */
6654         if (INTEL_INFO(dev)->gen < 4) {
6655                 if (crtc->pipe != PIPE_B)
6656                         return;
6657         } else {
6658                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
6659                         return;
6660         }
6661
6662         pipe_config->gmch_pfit.control = tmp;
6663         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
6664         if (INTEL_INFO(dev)->gen < 5)
6665                 pipe_config->gmch_pfit.lvds_border_bits =
6666                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
6667 }
6668
6669 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
6670                                struct intel_crtc_state *pipe_config)
6671 {
6672         struct drm_device *dev = crtc->base.dev;
6673         struct drm_i915_private *dev_priv = dev->dev_private;
6674         int pipe = pipe_config->cpu_transcoder;
6675         intel_clock_t clock;
6676         u32 mdiv;
6677         int refclk = 100000;
6678
6679         /* In case of MIPI DPLL will not even be used */
6680         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
6681                 return;
6682
6683         mutex_lock(&dev_priv->dpio_lock);
6684         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
6685         mutex_unlock(&dev_priv->dpio_lock);
6686
6687         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
6688         clock.m2 = mdiv & DPIO_M2DIV_MASK;
6689         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
6690         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
6691         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
6692
6693         vlv_clock(refclk, &clock);
6694
6695         /* clock.dot is the fast clock */
6696         pipe_config->port_clock = clock.dot / 5;
6697 }
6698
6699 static void
6700 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
6701                               struct intel_initial_plane_config *plane_config)
6702 {
6703         struct drm_device *dev = crtc->base.dev;
6704         struct drm_i915_private *dev_priv = dev->dev_private;
6705         u32 val, base, offset;
6706         int pipe = crtc->pipe, plane = crtc->plane;
6707         int fourcc, pixel_format;
6708         int aligned_height;
6709         struct drm_framebuffer *fb;
6710         struct intel_framebuffer *intel_fb;
6711
6712         val = I915_READ(DSPCNTR(plane));
6713         if (!(val & DISPLAY_PLANE_ENABLE))
6714                 return;
6715
6716         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
6717         if (!intel_fb) {
6718                 DRM_DEBUG_KMS("failed to alloc fb\n");
6719                 return;
6720         }
6721
6722         fb = &intel_fb->base;
6723
6724         if (INTEL_INFO(dev)->gen >= 4) {
6725                 if (val & DISPPLANE_TILED) {
6726                         plane_config->tiling = I915_TILING_X;
6727                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
6728                 }
6729         }
6730
6731         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
6732         fourcc = i9xx_format_to_fourcc(pixel_format);
6733         fb->pixel_format = fourcc;
6734         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
6735
6736         if (INTEL_INFO(dev)->gen >= 4) {
6737                 if (plane_config->tiling)
6738                         offset = I915_READ(DSPTILEOFF(plane));
6739                 else
6740                         offset = I915_READ(DSPLINOFF(plane));
6741                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
6742         } else {
6743                 base = I915_READ(DSPADDR(plane));
6744         }
6745         plane_config->base = base;
6746
6747         val = I915_READ(PIPESRC(pipe));
6748         fb->width = ((val >> 16) & 0xfff) + 1;
6749         fb->height = ((val >> 0) & 0xfff) + 1;
6750
6751         val = I915_READ(DSPSTRIDE(pipe));
6752         fb->pitches[0] = val & 0xffffffc0;
6753
6754         aligned_height = intel_fb_align_height(dev, fb->height,
6755                                                fb->pixel_format,
6756                                                fb->modifier[0]);
6757
6758         plane_config->size = PAGE_ALIGN(fb->pitches[0] * aligned_height);
6759
6760         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
6761                       pipe_name(pipe), plane, fb->width, fb->height,
6762                       fb->bits_per_pixel, base, fb->pitches[0],
6763                       plane_config->size);
6764
6765         plane_config->fb = intel_fb;
6766 }
6767
6768 static void chv_crtc_clock_get(struct intel_crtc *crtc,
6769                                struct intel_crtc_state *pipe_config)
6770 {
6771         struct drm_device *dev = crtc->base.dev;
6772         struct drm_i915_private *dev_priv = dev->dev_private;
6773         int pipe = pipe_config->cpu_transcoder;
6774         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6775         intel_clock_t clock;
6776         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
6777         int refclk = 100000;
6778
6779         mutex_lock(&dev_priv->dpio_lock);
6780         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
6781         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
6782         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
6783         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
6784         mutex_unlock(&dev_priv->dpio_lock);
6785
6786         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
6787         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
6788         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
6789         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
6790         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
6791
6792         chv_clock(refclk, &clock);
6793
6794         /* clock.dot is the fast clock */
6795         pipe_config->port_clock = clock.dot / 5;
6796 }
6797
6798 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
6799                                  struct intel_crtc_state *pipe_config)
6800 {
6801         struct drm_device *dev = crtc->base.dev;
6802         struct drm_i915_private *dev_priv = dev->dev_private;
6803         uint32_t tmp;
6804
6805         if (!intel_display_power_is_enabled(dev_priv,
6806                                             POWER_DOMAIN_PIPE(crtc->pipe)))
6807                 return false;
6808
6809         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
6810         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
6811
6812         tmp = I915_READ(PIPECONF(crtc->pipe));
6813         if (!(tmp & PIPECONF_ENABLE))
6814                 return false;
6815
6816         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
6817                 switch (tmp & PIPECONF_BPC_MASK) {
6818                 case PIPECONF_6BPC:
6819                         pipe_config->pipe_bpp = 18;
6820                         break;
6821                 case PIPECONF_8BPC:
6822                         pipe_config->pipe_bpp = 24;
6823                         break;
6824                 case PIPECONF_10BPC:
6825                         pipe_config->pipe_bpp = 30;
6826                         break;
6827                 default:
6828                         break;
6829                 }
6830         }
6831
6832         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
6833                 pipe_config->limited_color_range = true;
6834
6835         if (INTEL_INFO(dev)->gen < 4)
6836                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
6837
6838         intel_get_pipe_timings(crtc, pipe_config);
6839
6840         i9xx_get_pfit_config(crtc, pipe_config);
6841
6842         if (INTEL_INFO(dev)->gen >= 4) {
6843                 tmp = I915_READ(DPLL_MD(crtc->pipe));
6844                 pipe_config->pixel_multiplier =
6845                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
6846                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
6847                 pipe_config->dpll_hw_state.dpll_md = tmp;
6848         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
6849                 tmp = I915_READ(DPLL(crtc->pipe));
6850                 pipe_config->pixel_multiplier =
6851                         ((tmp & SDVO_MULTIPLIER_MASK)
6852                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
6853         } else {
6854                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
6855                  * port and will be fixed up in the encoder->get_config
6856                  * function. */
6857                 pipe_config->pixel_multiplier = 1;
6858         }
6859         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
6860         if (!IS_VALLEYVIEW(dev)) {
6861                 /*
6862                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
6863                  * on 830. Filter it out here so that we don't
6864                  * report errors due to that.
6865                  */
6866                 if (IS_I830(dev))
6867                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
6868
6869                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
6870                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
6871         } else {
6872                 /* Mask out read-only status bits. */
6873                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
6874                                                      DPLL_PORTC_READY_MASK |
6875                                                      DPLL_PORTB_READY_MASK);
6876         }
6877
6878         if (IS_CHERRYVIEW(dev))
6879                 chv_crtc_clock_get(crtc, pipe_config);
6880         else if (IS_VALLEYVIEW(dev))
6881                 vlv_crtc_clock_get(crtc, pipe_config);
6882         else
6883                 i9xx_crtc_clock_get(crtc, pipe_config);
6884
6885         return true;
6886 }
6887
6888 static void ironlake_init_pch_refclk(struct drm_device *dev)
6889 {
6890         struct drm_i915_private *dev_priv = dev->dev_private;
6891         struct intel_encoder *encoder;
6892         u32 val, final;
6893         bool has_lvds = false;
6894         bool has_cpu_edp = false;
6895         bool has_panel = false;
6896         bool has_ck505 = false;
6897         bool can_ssc = false;
6898
6899         /* We need to take the global config into account */
6900         for_each_intel_encoder(dev, encoder) {
6901                 switch (encoder->type) {
6902                 case INTEL_OUTPUT_LVDS:
6903                         has_panel = true;
6904                         has_lvds = true;
6905                         break;
6906                 case INTEL_OUTPUT_EDP:
6907                         has_panel = true;
6908                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
6909                                 has_cpu_edp = true;
6910                         break;
6911                 default:
6912                         break;
6913                 }
6914         }
6915
6916         if (HAS_PCH_IBX(dev)) {
6917                 has_ck505 = dev_priv->vbt.display_clock_mode;
6918                 can_ssc = has_ck505;
6919         } else {
6920                 has_ck505 = false;
6921                 can_ssc = true;
6922         }
6923
6924         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
6925                       has_panel, has_lvds, has_ck505);
6926
6927         /* Ironlake: try to setup display ref clock before DPLL
6928          * enabling. This is only under driver's control after
6929          * PCH B stepping, previous chipset stepping should be
6930          * ignoring this setting.
6931          */
6932         val = I915_READ(PCH_DREF_CONTROL);
6933
6934         /* As we must carefully and slowly disable/enable each source in turn,
6935          * compute the final state we want first and check if we need to
6936          * make any changes at all.
6937          */
6938         final = val;
6939         final &= ~DREF_NONSPREAD_SOURCE_MASK;
6940         if (has_ck505)
6941                 final |= DREF_NONSPREAD_CK505_ENABLE;
6942         else
6943                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
6944
6945         final &= ~DREF_SSC_SOURCE_MASK;
6946         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6947         final &= ~DREF_SSC1_ENABLE;
6948
6949         if (has_panel) {
6950                 final |= DREF_SSC_SOURCE_ENABLE;
6951
6952                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
6953                         final |= DREF_SSC1_ENABLE;
6954
6955                 if (has_cpu_edp) {
6956                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
6957                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
6958                         else
6959                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
6960                 } else
6961                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6962         } else {
6963                 final |= DREF_SSC_SOURCE_DISABLE;
6964                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
6965         }
6966
6967         if (final == val)
6968                 return;
6969
6970         /* Always enable nonspread source */
6971         val &= ~DREF_NONSPREAD_SOURCE_MASK;
6972
6973         if (has_ck505)
6974                 val |= DREF_NONSPREAD_CK505_ENABLE;
6975         else
6976                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
6977
6978         if (has_panel) {
6979                 val &= ~DREF_SSC_SOURCE_MASK;
6980                 val |= DREF_SSC_SOURCE_ENABLE;
6981
6982                 /* SSC must be turned on before enabling the CPU output  */
6983                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6984                         DRM_DEBUG_KMS("Using SSC on panel\n");
6985                         val |= DREF_SSC1_ENABLE;
6986                 } else
6987                         val &= ~DREF_SSC1_ENABLE;
6988
6989                 /* Get SSC going before enabling the outputs */
6990                 I915_WRITE(PCH_DREF_CONTROL, val);
6991                 POSTING_READ(PCH_DREF_CONTROL);
6992                 udelay(200);
6993
6994                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
6995
6996                 /* Enable CPU source on CPU attached eDP */
6997                 if (has_cpu_edp) {
6998                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
6999                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7000                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7001                         } else
7002                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7003                 } else
7004                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7005
7006                 I915_WRITE(PCH_DREF_CONTROL, val);
7007                 POSTING_READ(PCH_DREF_CONTROL);
7008                 udelay(200);
7009         } else {
7010                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
7011
7012                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7013
7014                 /* Turn off CPU output */
7015                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7016
7017                 I915_WRITE(PCH_DREF_CONTROL, val);
7018                 POSTING_READ(PCH_DREF_CONTROL);
7019                 udelay(200);
7020
7021                 /* Turn off the SSC source */
7022                 val &= ~DREF_SSC_SOURCE_MASK;
7023                 val |= DREF_SSC_SOURCE_DISABLE;
7024
7025                 /* Turn off SSC1 */
7026                 val &= ~DREF_SSC1_ENABLE;
7027
7028                 I915_WRITE(PCH_DREF_CONTROL, val);
7029                 POSTING_READ(PCH_DREF_CONTROL);
7030                 udelay(200);
7031         }
7032
7033         BUG_ON(val != final);
7034 }
7035
7036 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7037 {
7038         uint32_t tmp;
7039
7040         tmp = I915_READ(SOUTH_CHICKEN2);
7041         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7042         I915_WRITE(SOUTH_CHICKEN2, tmp);
7043
7044         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
7045                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7046                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7047
7048         tmp = I915_READ(SOUTH_CHICKEN2);
7049         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7050         I915_WRITE(SOUTH_CHICKEN2, tmp);
7051
7052         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
7053                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7054                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7055 }
7056
7057 /* WaMPhyProgramming:hsw */
7058 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7059 {
7060         uint32_t tmp;
7061
7062         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7063         tmp &= ~(0xFF << 24);
7064         tmp |= (0x12 << 24);
7065         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7066
7067         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7068         tmp |= (1 << 11);
7069         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7070
7071         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7072         tmp |= (1 << 11);
7073         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7074
7075         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7076         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7077         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7078
7079         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7080         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7081         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7082
7083         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7084         tmp &= ~(7 << 13);
7085         tmp |= (5 << 13);
7086         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7087
7088         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7089         tmp &= ~(7 << 13);
7090         tmp |= (5 << 13);
7091         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7092
7093         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7094         tmp &= ~0xFF;
7095         tmp |= 0x1C;
7096         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7097
7098         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7099         tmp &= ~0xFF;
7100         tmp |= 0x1C;
7101         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7102
7103         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7104         tmp &= ~(0xFF << 16);
7105         tmp |= (0x1C << 16);
7106         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7107
7108         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7109         tmp &= ~(0xFF << 16);
7110         tmp |= (0x1C << 16);
7111         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7112
7113         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7114         tmp |= (1 << 27);
7115         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7116
7117         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7118         tmp |= (1 << 27);
7119         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7120
7121         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7122         tmp &= ~(0xF << 28);
7123         tmp |= (4 << 28);
7124         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7125
7126         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7127         tmp &= ~(0xF << 28);
7128         tmp |= (4 << 28);
7129         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7130 }
7131
7132 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7133  * Programming" based on the parameters passed:
7134  * - Sequence to enable CLKOUT_DP
7135  * - Sequence to enable CLKOUT_DP without spread
7136  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7137  */
7138 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
7139                                  bool with_fdi)
7140 {
7141         struct drm_i915_private *dev_priv = dev->dev_private;
7142         uint32_t reg, tmp;
7143
7144         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7145                 with_spread = true;
7146         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
7147                  with_fdi, "LP PCH doesn't have FDI\n"))
7148                 with_fdi = false;
7149
7150         mutex_lock(&dev_priv->dpio_lock);
7151
7152         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7153         tmp &= ~SBI_SSCCTL_DISABLE;
7154         tmp |= SBI_SSCCTL_PATHALT;
7155         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7156
7157         udelay(24);
7158
7159         if (with_spread) {
7160                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7161                 tmp &= ~SBI_SSCCTL_PATHALT;
7162                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7163
7164                 if (with_fdi) {
7165                         lpt_reset_fdi_mphy(dev_priv);
7166                         lpt_program_fdi_mphy(dev_priv);
7167                 }
7168         }
7169
7170         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7171                SBI_GEN0 : SBI_DBUFF0;
7172         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7173         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7174         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7175
7176         mutex_unlock(&dev_priv->dpio_lock);
7177 }
7178
7179 /* Sequence to disable CLKOUT_DP */
7180 static void lpt_disable_clkout_dp(struct drm_device *dev)
7181 {
7182         struct drm_i915_private *dev_priv = dev->dev_private;
7183         uint32_t reg, tmp;
7184
7185         mutex_lock(&dev_priv->dpio_lock);
7186
7187         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7188                SBI_GEN0 : SBI_DBUFF0;
7189         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7190         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7191         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7192
7193         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7194         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7195                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7196                         tmp |= SBI_SSCCTL_PATHALT;
7197                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7198                         udelay(32);
7199                 }
7200                 tmp |= SBI_SSCCTL_DISABLE;
7201                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7202         }
7203
7204         mutex_unlock(&dev_priv->dpio_lock);
7205 }
7206
7207 static void lpt_init_pch_refclk(struct drm_device *dev)
7208 {
7209         struct intel_encoder *encoder;
7210         bool has_vga = false;
7211
7212         for_each_intel_encoder(dev, encoder) {
7213                 switch (encoder->type) {
7214                 case INTEL_OUTPUT_ANALOG:
7215                         has_vga = true;
7216                         break;
7217                 default:
7218                         break;
7219                 }
7220         }
7221
7222         if (has_vga)
7223                 lpt_enable_clkout_dp(dev, true, true);
7224         else
7225                 lpt_disable_clkout_dp(dev);
7226 }
7227
7228 /*
7229  * Initialize reference clocks when the driver loads
7230  */
7231 void intel_init_pch_refclk(struct drm_device *dev)
7232 {
7233         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
7234                 ironlake_init_pch_refclk(dev);
7235         else if (HAS_PCH_LPT(dev))
7236                 lpt_init_pch_refclk(dev);
7237 }
7238
7239 static int ironlake_get_refclk(struct drm_crtc *crtc)
7240 {
7241         struct drm_device *dev = crtc->dev;
7242         struct drm_i915_private *dev_priv = dev->dev_private;
7243         struct intel_encoder *encoder;
7244         int num_connectors = 0;
7245         bool is_lvds = false;
7246
7247         for_each_intel_encoder(dev, encoder) {
7248                 if (encoder->new_crtc != to_intel_crtc(crtc))
7249                         continue;
7250
7251                 switch (encoder->type) {
7252                 case INTEL_OUTPUT_LVDS:
7253                         is_lvds = true;
7254                         break;
7255                 default:
7256                         break;
7257                 }
7258                 num_connectors++;
7259         }
7260
7261         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7262                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
7263                               dev_priv->vbt.lvds_ssc_freq);
7264                 return dev_priv->vbt.lvds_ssc_freq;
7265         }
7266
7267         return 120000;
7268 }
7269
7270 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7271 {
7272         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
7273         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7274         int pipe = intel_crtc->pipe;
7275         uint32_t val;
7276
7277         val = 0;
7278
7279         switch (intel_crtc->config->pipe_bpp) {
7280         case 18:
7281                 val |= PIPECONF_6BPC;
7282                 break;
7283         case 24:
7284                 val |= PIPECONF_8BPC;
7285                 break;
7286         case 30:
7287                 val |= PIPECONF_10BPC;
7288                 break;
7289         case 36:
7290                 val |= PIPECONF_12BPC;
7291                 break;
7292         default:
7293                 /* Case prevented by intel_choose_pipe_bpp_dither. */
7294                 BUG();
7295         }
7296
7297         if (intel_crtc->config->dither)
7298                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7299
7300         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7301                 val |= PIPECONF_INTERLACED_ILK;
7302         else
7303                 val |= PIPECONF_PROGRESSIVE;
7304
7305         if (intel_crtc->config->limited_color_range)
7306                 val |= PIPECONF_COLOR_RANGE_SELECT;
7307
7308         I915_WRITE(PIPECONF(pipe), val);
7309         POSTING_READ(PIPECONF(pipe));
7310 }
7311
7312 /*
7313  * Set up the pipe CSC unit.
7314  *
7315  * Currently only full range RGB to limited range RGB conversion
7316  * is supported, but eventually this should handle various
7317  * RGB<->YCbCr scenarios as well.
7318  */
7319 static void intel_set_pipe_csc(struct drm_crtc *crtc)
7320 {
7321         struct drm_device *dev = crtc->dev;
7322         struct drm_i915_private *dev_priv = dev->dev_private;
7323         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7324         int pipe = intel_crtc->pipe;
7325         uint16_t coeff = 0x7800; /* 1.0 */
7326
7327         /*
7328          * TODO: Check what kind of values actually come out of the pipe
7329          * with these coeff/postoff values and adjust to get the best
7330          * accuracy. Perhaps we even need to take the bpc value into
7331          * consideration.
7332          */
7333
7334         if (intel_crtc->config->limited_color_range)
7335                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
7336
7337         /*
7338          * GY/GU and RY/RU should be the other way around according
7339          * to BSpec, but reality doesn't agree. Just set them up in
7340          * a way that results in the correct picture.
7341          */
7342         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
7343         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
7344
7345         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
7346         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
7347
7348         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
7349         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
7350
7351         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
7352         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
7353         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
7354
7355         if (INTEL_INFO(dev)->gen > 6) {
7356                 uint16_t postoff = 0;
7357
7358                 if (intel_crtc->config->limited_color_range)
7359                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
7360
7361                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
7362                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
7363                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
7364
7365                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
7366         } else {
7367                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
7368
7369                 if (intel_crtc->config->limited_color_range)
7370                         mode |= CSC_BLACK_SCREEN_OFFSET;
7371
7372                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
7373         }
7374 }
7375
7376 static void haswell_set_pipeconf(struct drm_crtc *crtc)
7377 {
7378         struct drm_device *dev = crtc->dev;
7379         struct drm_i915_private *dev_priv = dev->dev_private;
7380         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7381         enum pipe pipe = intel_crtc->pipe;
7382         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7383         uint32_t val;
7384
7385         val = 0;
7386
7387         if (IS_HASWELL(dev) && intel_crtc->config->dither)
7388                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
7389
7390         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
7391                 val |= PIPECONF_INTERLACED_ILK;
7392         else
7393                 val |= PIPECONF_PROGRESSIVE;
7394
7395         I915_WRITE(PIPECONF(cpu_transcoder), val);
7396         POSTING_READ(PIPECONF(cpu_transcoder));
7397
7398         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
7399         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
7400
7401         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
7402                 val = 0;
7403
7404                 switch (intel_crtc->config->pipe_bpp) {
7405                 case 18:
7406                         val |= PIPEMISC_DITHER_6_BPC;
7407                         break;
7408                 case 24:
7409                         val |= PIPEMISC_DITHER_8_BPC;
7410                         break;
7411                 case 30:
7412                         val |= PIPEMISC_DITHER_10_BPC;
7413                         break;
7414                 case 36:
7415                         val |= PIPEMISC_DITHER_12_BPC;
7416                         break;
7417                 default:
7418                         /* Case prevented by pipe_config_set_bpp. */
7419                         BUG();
7420                 }
7421
7422                 if (intel_crtc->config->dither)
7423                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
7424
7425                 I915_WRITE(PIPEMISC(pipe), val);
7426         }
7427 }
7428
7429 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
7430                                     struct intel_crtc_state *crtc_state,
7431                                     intel_clock_t *clock,
7432                                     bool *has_reduced_clock,
7433                                     intel_clock_t *reduced_clock)
7434 {
7435         struct drm_device *dev = crtc->dev;
7436         struct drm_i915_private *dev_priv = dev->dev_private;
7437         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7438         int refclk;
7439         const intel_limit_t *limit;
7440         bool ret, is_lvds = false;
7441
7442         is_lvds = intel_pipe_will_have_type(intel_crtc, INTEL_OUTPUT_LVDS);
7443
7444         refclk = ironlake_get_refclk(crtc);
7445
7446         /*
7447          * Returns a set of divisors for the desired target clock with the given
7448          * refclk, or FALSE.  The returned values represent the clock equation:
7449          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
7450          */
7451         limit = intel_limit(intel_crtc, refclk);
7452         ret = dev_priv->display.find_dpll(limit, intel_crtc,
7453                                           crtc_state->port_clock,
7454                                           refclk, NULL, clock);
7455         if (!ret)
7456                 return false;
7457
7458         if (is_lvds && dev_priv->lvds_downclock_avail) {
7459                 /*
7460                  * Ensure we match the reduced clock's P to the target clock.
7461                  * If the clocks don't match, we can't switch the display clock
7462                  * by using the FP0/FP1. In such case we will disable the LVDS
7463                  * downclock feature.
7464                 */
7465                 *has_reduced_clock =
7466                         dev_priv->display.find_dpll(limit, intel_crtc,
7467                                                     dev_priv->lvds_downclock,
7468                                                     refclk, clock,
7469                                                     reduced_clock);
7470         }
7471
7472         return true;
7473 }
7474
7475 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
7476 {
7477         /*
7478          * Account for spread spectrum to avoid
7479          * oversubscribing the link. Max center spread
7480          * is 2.5%; use 5% for safety's sake.
7481          */
7482         u32 bps = target_clock * bpp * 21 / 20;
7483         return DIV_ROUND_UP(bps, link_bw * 8);
7484 }
7485
7486 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
7487 {
7488         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
7489 }
7490
7491 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
7492                                       struct intel_crtc_state *crtc_state,
7493                                       u32 *fp,
7494                                       intel_clock_t *reduced_clock, u32 *fp2)
7495 {
7496         struct drm_crtc *crtc = &intel_crtc->base;
7497         struct drm_device *dev = crtc->dev;
7498         struct drm_i915_private *dev_priv = dev->dev_private;
7499         struct intel_encoder *intel_encoder;
7500         uint32_t dpll;
7501         int factor, num_connectors = 0;
7502         bool is_lvds = false, is_sdvo = false;
7503
7504         for_each_intel_encoder(dev, intel_encoder) {
7505                 if (intel_encoder->new_crtc != to_intel_crtc(crtc))
7506                         continue;
7507
7508                 switch (intel_encoder->type) {
7509                 case INTEL_OUTPUT_LVDS:
7510                         is_lvds = true;
7511                         break;
7512                 case INTEL_OUTPUT_SDVO:
7513                 case INTEL_OUTPUT_HDMI:
7514                         is_sdvo = true;
7515                         break;
7516                 default:
7517                         break;
7518                 }
7519
7520                 num_connectors++;
7521         }
7522
7523         /* Enable autotuning of the PLL clock (if permissible) */
7524         factor = 21;
7525         if (is_lvds) {
7526                 if ((intel_panel_use_ssc(dev_priv) &&
7527                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
7528                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
7529                         factor = 25;
7530         } else if (crtc_state->sdvo_tv_clock)
7531                 factor = 20;
7532
7533         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
7534                 *fp |= FP_CB_TUNE;
7535
7536         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
7537                 *fp2 |= FP_CB_TUNE;
7538
7539         dpll = 0;
7540
7541         if (is_lvds)
7542                 dpll |= DPLLB_MODE_LVDS;
7543         else
7544                 dpll |= DPLLB_MODE_DAC_SERIAL;
7545
7546         dpll |= (crtc_state->pixel_multiplier - 1)
7547                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
7548
7549         if (is_sdvo)
7550                 dpll |= DPLL_SDVO_HIGH_SPEED;
7551         if (crtc_state->has_dp_encoder)
7552                 dpll |= DPLL_SDVO_HIGH_SPEED;
7553
7554         /* compute bitmask from p1 value */
7555         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7556         /* also FPA1 */
7557         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7558
7559         switch (crtc_state->dpll.p2) {
7560         case 5:
7561                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7562                 break;
7563         case 7:
7564                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7565                 break;
7566         case 10:
7567                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7568                 break;
7569         case 14:
7570                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7571                 break;
7572         }
7573
7574         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7575                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7576         else
7577                 dpll |= PLL_REF_INPUT_DREFCLK;
7578
7579         return dpll | DPLL_VCO_ENABLE;
7580 }
7581
7582 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
7583                                        struct intel_crtc_state *crtc_state)
7584 {
7585         struct drm_device *dev = crtc->base.dev;
7586         intel_clock_t clock, reduced_clock;
7587         u32 dpll = 0, fp = 0, fp2 = 0;
7588         bool ok, has_reduced_clock = false;
7589         bool is_lvds = false;
7590         struct intel_shared_dpll *pll;
7591
7592         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
7593
7594         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
7595              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
7596
7597         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
7598                                      &has_reduced_clock, &reduced_clock);
7599         if (!ok && !crtc_state->clock_set) {
7600                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7601                 return -EINVAL;
7602         }
7603         /* Compat-code for transition, will disappear. */
7604         if (!crtc_state->clock_set) {
7605                 crtc_state->dpll.n = clock.n;
7606                 crtc_state->dpll.m1 = clock.m1;
7607                 crtc_state->dpll.m2 = clock.m2;
7608                 crtc_state->dpll.p1 = clock.p1;
7609                 crtc_state->dpll.p2 = clock.p2;
7610         }
7611
7612         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
7613         if (crtc_state->has_pch_encoder) {
7614                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7615                 if (has_reduced_clock)
7616                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
7617
7618                 dpll = ironlake_compute_dpll(crtc, crtc_state,
7619                                              &fp, &reduced_clock,
7620                                              has_reduced_clock ? &fp2 : NULL);
7621
7622                 crtc_state->dpll_hw_state.dpll = dpll;
7623                 crtc_state->dpll_hw_state.fp0 = fp;
7624                 if (has_reduced_clock)
7625                         crtc_state->dpll_hw_state.fp1 = fp2;
7626                 else
7627                         crtc_state->dpll_hw_state.fp1 = fp;
7628
7629                 pll = intel_get_shared_dpll(crtc, crtc_state);
7630                 if (pll == NULL) {
7631                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
7632                                          pipe_name(crtc->pipe));
7633                         return -EINVAL;
7634                 }
7635         }
7636
7637         if (is_lvds && has_reduced_clock && i915.powersave)
7638                 crtc->lowfreq_avail = true;
7639         else
7640                 crtc->lowfreq_avail = false;
7641
7642         return 0;
7643 }
7644
7645 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
7646                                          struct intel_link_m_n *m_n)
7647 {
7648         struct drm_device *dev = crtc->base.dev;
7649         struct drm_i915_private *dev_priv = dev->dev_private;
7650         enum pipe pipe = crtc->pipe;
7651
7652         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
7653         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
7654         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
7655                 & ~TU_SIZE_MASK;
7656         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
7657         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
7658                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7659 }
7660
7661 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
7662                                          enum transcoder transcoder,
7663                                          struct intel_link_m_n *m_n,
7664                                          struct intel_link_m_n *m2_n2)
7665 {
7666         struct drm_device *dev = crtc->base.dev;
7667         struct drm_i915_private *dev_priv = dev->dev_private;
7668         enum pipe pipe = crtc->pipe;
7669
7670         if (INTEL_INFO(dev)->gen >= 5) {
7671                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
7672                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
7673                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
7674                         & ~TU_SIZE_MASK;
7675                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
7676                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
7677                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7678                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
7679                  * gen < 8) and if DRRS is supported (to make sure the
7680                  * registers are not unnecessarily read).
7681                  */
7682                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
7683                         crtc->config->has_drrs) {
7684                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
7685                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
7686                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
7687                                         & ~TU_SIZE_MASK;
7688                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
7689                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
7690                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7691                 }
7692         } else {
7693                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
7694                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
7695                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
7696                         & ~TU_SIZE_MASK;
7697                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
7698                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
7699                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
7700         }
7701 }
7702
7703 void intel_dp_get_m_n(struct intel_crtc *crtc,
7704                       struct intel_crtc_state *pipe_config)
7705 {
7706         if (pipe_config->has_pch_encoder)
7707                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
7708         else
7709                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7710                                              &pipe_config->dp_m_n,
7711                                              &pipe_config->dp_m2_n2);
7712 }
7713
7714 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
7715                                         struct intel_crtc_state *pipe_config)
7716 {
7717         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
7718                                      &pipe_config->fdi_m_n, NULL);
7719 }
7720
7721 static void skylake_get_pfit_config(struct intel_crtc *crtc,
7722                                     struct intel_crtc_state *pipe_config)
7723 {
7724         struct drm_device *dev = crtc->base.dev;
7725         struct drm_i915_private *dev_priv = dev->dev_private;
7726         uint32_t tmp;
7727
7728         tmp = I915_READ(PS_CTL(crtc->pipe));
7729
7730         if (tmp & PS_ENABLE) {
7731                 pipe_config->pch_pfit.enabled = true;
7732                 pipe_config->pch_pfit.pos = I915_READ(PS_WIN_POS(crtc->pipe));
7733                 pipe_config->pch_pfit.size = I915_READ(PS_WIN_SZ(crtc->pipe));
7734         }
7735 }
7736
7737 static void
7738 skylake_get_initial_plane_config(struct intel_crtc *crtc,
7739                                  struct intel_initial_plane_config *plane_config)
7740 {
7741         struct drm_device *dev = crtc->base.dev;
7742         struct drm_i915_private *dev_priv = dev->dev_private;
7743         u32 val, base, offset, stride_mult;
7744         int pipe = crtc->pipe;
7745         int fourcc, pixel_format;
7746         int aligned_height;
7747         struct drm_framebuffer *fb;
7748         struct intel_framebuffer *intel_fb;
7749
7750         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7751         if (!intel_fb) {
7752                 DRM_DEBUG_KMS("failed to alloc fb\n");
7753                 return;
7754         }
7755
7756         fb = &intel_fb->base;
7757
7758         val = I915_READ(PLANE_CTL(pipe, 0));
7759         if (!(val & PLANE_CTL_ENABLE))
7760                 goto error;
7761
7762         if (val & PLANE_CTL_TILED_MASK) {
7763                 plane_config->tiling = I915_TILING_X;
7764                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7765         }
7766
7767         pixel_format = val & PLANE_CTL_FORMAT_MASK;
7768         fourcc = skl_format_to_fourcc(pixel_format,
7769                                       val & PLANE_CTL_ORDER_RGBX,
7770                                       val & PLANE_CTL_ALPHA_MASK);
7771         fb->pixel_format = fourcc;
7772         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7773
7774         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
7775         plane_config->base = base;
7776
7777         offset = I915_READ(PLANE_OFFSET(pipe, 0));
7778
7779         val = I915_READ(PLANE_SIZE(pipe, 0));
7780         fb->height = ((val >> 16) & 0xfff) + 1;
7781         fb->width = ((val >> 0) & 0x1fff) + 1;
7782
7783         val = I915_READ(PLANE_STRIDE(pipe, 0));
7784         switch (plane_config->tiling) {
7785         case I915_TILING_NONE:
7786                 stride_mult = 64;
7787                 break;
7788         case I915_TILING_X:
7789                 stride_mult = 512;
7790                 break;
7791         default:
7792                 MISSING_CASE(plane_config->tiling);
7793                 goto error;
7794         }
7795         fb->pitches[0] = (val & 0x3ff) * stride_mult;
7796
7797         aligned_height = intel_fb_align_height(dev, fb->height,
7798                                                fb->pixel_format,
7799                                                fb->modifier[0]);
7800
7801         plane_config->size = ALIGN(fb->pitches[0] * aligned_height, PAGE_SIZE);
7802
7803         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7804                       pipe_name(pipe), fb->width, fb->height,
7805                       fb->bits_per_pixel, base, fb->pitches[0],
7806                       plane_config->size);
7807
7808         plane_config->fb = intel_fb;
7809         return;
7810
7811 error:
7812         kfree(fb);
7813 }
7814
7815 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
7816                                      struct intel_crtc_state *pipe_config)
7817 {
7818         struct drm_device *dev = crtc->base.dev;
7819         struct drm_i915_private *dev_priv = dev->dev_private;
7820         uint32_t tmp;
7821
7822         tmp = I915_READ(PF_CTL(crtc->pipe));
7823
7824         if (tmp & PF_ENABLE) {
7825                 pipe_config->pch_pfit.enabled = true;
7826                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
7827                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
7828
7829                 /* We currently do not free assignements of panel fitters on
7830                  * ivb/hsw (since we don't use the higher upscaling modes which
7831                  * differentiates them) so just WARN about this case for now. */
7832                 if (IS_GEN7(dev)) {
7833                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
7834                                 PF_PIPE_SEL_IVB(crtc->pipe));
7835                 }
7836         }
7837 }
7838
7839 static void
7840 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
7841                                   struct intel_initial_plane_config *plane_config)
7842 {
7843         struct drm_device *dev = crtc->base.dev;
7844         struct drm_i915_private *dev_priv = dev->dev_private;
7845         u32 val, base, offset;
7846         int pipe = crtc->pipe;
7847         int fourcc, pixel_format;
7848         int aligned_height;
7849         struct drm_framebuffer *fb;
7850         struct intel_framebuffer *intel_fb;
7851
7852         val = I915_READ(DSPCNTR(pipe));
7853         if (!(val & DISPLAY_PLANE_ENABLE))
7854                 return;
7855
7856         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7857         if (!intel_fb) {
7858                 DRM_DEBUG_KMS("failed to alloc fb\n");
7859                 return;
7860         }
7861
7862         fb = &intel_fb->base;
7863
7864         if (INTEL_INFO(dev)->gen >= 4) {
7865                 if (val & DISPPLANE_TILED) {
7866                         plane_config->tiling = I915_TILING_X;
7867                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7868                 }
7869         }
7870
7871         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7872         fourcc = i9xx_format_to_fourcc(pixel_format);
7873         fb->pixel_format = fourcc;
7874         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7875
7876         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
7877         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7878                 offset = I915_READ(DSPOFFSET(pipe));
7879         } else {
7880                 if (plane_config->tiling)
7881                         offset = I915_READ(DSPTILEOFF(pipe));
7882                 else
7883                         offset = I915_READ(DSPLINOFF(pipe));
7884         }
7885         plane_config->base = base;
7886
7887         val = I915_READ(PIPESRC(pipe));
7888         fb->width = ((val >> 16) & 0xfff) + 1;
7889         fb->height = ((val >> 0) & 0xfff) + 1;
7890
7891         val = I915_READ(DSPSTRIDE(pipe));
7892         fb->pitches[0] = val & 0xffffffc0;
7893
7894         aligned_height = intel_fb_align_height(dev, fb->height,
7895                                                fb->pixel_format,
7896                                                fb->modifier[0]);
7897
7898         plane_config->size = PAGE_ALIGN(fb->pitches[0] * aligned_height);
7899
7900         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7901                       pipe_name(pipe), fb->width, fb->height,
7902                       fb->bits_per_pixel, base, fb->pitches[0],
7903                       plane_config->size);
7904
7905         plane_config->fb = intel_fb;
7906 }
7907
7908 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
7909                                      struct intel_crtc_state *pipe_config)
7910 {
7911         struct drm_device *dev = crtc->base.dev;
7912         struct drm_i915_private *dev_priv = dev->dev_private;
7913         uint32_t tmp;
7914
7915         if (!intel_display_power_is_enabled(dev_priv,
7916                                             POWER_DOMAIN_PIPE(crtc->pipe)))
7917                 return false;
7918
7919         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7920         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7921
7922         tmp = I915_READ(PIPECONF(crtc->pipe));
7923         if (!(tmp & PIPECONF_ENABLE))
7924                 return false;
7925
7926         switch (tmp & PIPECONF_BPC_MASK) {
7927         case PIPECONF_6BPC:
7928                 pipe_config->pipe_bpp = 18;
7929                 break;
7930         case PIPECONF_8BPC:
7931                 pipe_config->pipe_bpp = 24;
7932                 break;
7933         case PIPECONF_10BPC:
7934                 pipe_config->pipe_bpp = 30;
7935                 break;
7936         case PIPECONF_12BPC:
7937                 pipe_config->pipe_bpp = 36;
7938                 break;
7939         default:
7940                 break;
7941         }
7942
7943         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
7944                 pipe_config->limited_color_range = true;
7945
7946         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
7947                 struct intel_shared_dpll *pll;
7948
7949                 pipe_config->has_pch_encoder = true;
7950
7951                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
7952                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
7953                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
7954
7955                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
7956
7957                 if (HAS_PCH_IBX(dev_priv->dev)) {
7958                         pipe_config->shared_dpll =
7959                                 (enum intel_dpll_id) crtc->pipe;
7960                 } else {
7961                         tmp = I915_READ(PCH_DPLL_SEL);
7962                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
7963                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
7964                         else
7965                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
7966                 }
7967
7968                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
7969
7970                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
7971                                            &pipe_config->dpll_hw_state));
7972
7973                 tmp = pipe_config->dpll_hw_state.dpll;
7974                 pipe_config->pixel_multiplier =
7975                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
7976                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
7977
7978                 ironlake_pch_clock_get(crtc, pipe_config);
7979         } else {
7980                 pipe_config->pixel_multiplier = 1;
7981         }
7982
7983         intel_get_pipe_timings(crtc, pipe_config);
7984
7985         ironlake_get_pfit_config(crtc, pipe_config);
7986
7987         return true;
7988 }
7989
7990 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
7991 {
7992         struct drm_device *dev = dev_priv->dev;
7993         struct intel_crtc *crtc;
7994
7995         for_each_intel_crtc(dev, crtc)
7996                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
7997                      pipe_name(crtc->pipe));
7998
7999         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8000         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8001         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8002         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8003         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
8004         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8005              "CPU PWM1 enabled\n");
8006         if (IS_HASWELL(dev))
8007                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8008                      "CPU PWM2 enabled\n");
8009         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8010              "PCH PWM1 enabled\n");
8011         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8012              "Utility pin enabled\n");
8013         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8014
8015         /*
8016          * In theory we can still leave IRQs enabled, as long as only the HPD
8017          * interrupts remain enabled. We used to check for that, but since it's
8018          * gen-specific and since we only disable LCPLL after we fully disable
8019          * the interrupts, the check below should be enough.
8020          */
8021         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8022 }
8023
8024 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8025 {
8026         struct drm_device *dev = dev_priv->dev;
8027
8028         if (IS_HASWELL(dev))
8029                 return I915_READ(D_COMP_HSW);
8030         else
8031                 return I915_READ(D_COMP_BDW);
8032 }
8033
8034 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8035 {
8036         struct drm_device *dev = dev_priv->dev;
8037
8038         if (IS_HASWELL(dev)) {
8039                 mutex_lock(&dev_priv->rps.hw_lock);
8040                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8041                                             val))
8042                         DRM_ERROR("Failed to write to D_COMP\n");
8043                 mutex_unlock(&dev_priv->rps.hw_lock);
8044         } else {
8045                 I915_WRITE(D_COMP_BDW, val);
8046                 POSTING_READ(D_COMP_BDW);
8047         }
8048 }
8049
8050 /*
8051  * This function implements pieces of two sequences from BSpec:
8052  * - Sequence for display software to disable LCPLL
8053  * - Sequence for display software to allow package C8+
8054  * The steps implemented here are just the steps that actually touch the LCPLL
8055  * register. Callers should take care of disabling all the display engine
8056  * functions, doing the mode unset, fixing interrupts, etc.
8057  */
8058 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8059                               bool switch_to_fclk, bool allow_power_down)
8060 {
8061         uint32_t val;
8062
8063         assert_can_disable_lcpll(dev_priv);
8064
8065         val = I915_READ(LCPLL_CTL);
8066
8067         if (switch_to_fclk) {
8068                 val |= LCPLL_CD_SOURCE_FCLK;
8069                 I915_WRITE(LCPLL_CTL, val);
8070
8071                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
8072                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
8073                         DRM_ERROR("Switching to FCLK failed\n");
8074
8075                 val = I915_READ(LCPLL_CTL);
8076         }
8077
8078         val |= LCPLL_PLL_DISABLE;
8079         I915_WRITE(LCPLL_CTL, val);
8080         POSTING_READ(LCPLL_CTL);
8081
8082         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
8083                 DRM_ERROR("LCPLL still locked\n");
8084
8085         val = hsw_read_dcomp(dev_priv);
8086         val |= D_COMP_COMP_DISABLE;
8087         hsw_write_dcomp(dev_priv, val);
8088         ndelay(100);
8089
8090         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8091                      1))
8092                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8093
8094         if (allow_power_down) {
8095                 val = I915_READ(LCPLL_CTL);
8096                 val |= LCPLL_POWER_DOWN_ALLOW;
8097                 I915_WRITE(LCPLL_CTL, val);
8098                 POSTING_READ(LCPLL_CTL);
8099         }
8100 }
8101
8102 /*
8103  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8104  * source.
8105  */
8106 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8107 {
8108         uint32_t val;
8109
8110         val = I915_READ(LCPLL_CTL);
8111
8112         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8113                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8114                 return;
8115
8116         /*
8117          * Make sure we're not on PC8 state before disabling PC8, otherwise
8118          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8119          */
8120         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8121
8122         if (val & LCPLL_POWER_DOWN_ALLOW) {
8123                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8124                 I915_WRITE(LCPLL_CTL, val);
8125                 POSTING_READ(LCPLL_CTL);
8126         }
8127
8128         val = hsw_read_dcomp(dev_priv);
8129         val |= D_COMP_COMP_FORCE;
8130         val &= ~D_COMP_COMP_DISABLE;
8131         hsw_write_dcomp(dev_priv, val);
8132
8133         val = I915_READ(LCPLL_CTL);
8134         val &= ~LCPLL_PLL_DISABLE;
8135         I915_WRITE(LCPLL_CTL, val);
8136
8137         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
8138                 DRM_ERROR("LCPLL not locked yet\n");
8139
8140         if (val & LCPLL_CD_SOURCE_FCLK) {
8141                 val = I915_READ(LCPLL_CTL);
8142                 val &= ~LCPLL_CD_SOURCE_FCLK;
8143                 I915_WRITE(LCPLL_CTL, val);
8144
8145                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
8146                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8147                         DRM_ERROR("Switching back to LCPLL failed\n");
8148         }
8149
8150         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8151 }
8152
8153 /*
8154  * Package states C8 and deeper are really deep PC states that can only be
8155  * reached when all the devices on the system allow it, so even if the graphics
8156  * device allows PC8+, it doesn't mean the system will actually get to these
8157  * states. Our driver only allows PC8+ when going into runtime PM.
8158  *
8159  * The requirements for PC8+ are that all the outputs are disabled, the power
8160  * well is disabled and most interrupts are disabled, and these are also
8161  * requirements for runtime PM. When these conditions are met, we manually do
8162  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8163  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8164  * hang the machine.
8165  *
8166  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8167  * the state of some registers, so when we come back from PC8+ we need to
8168  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8169  * need to take care of the registers kept by RC6. Notice that this happens even
8170  * if we don't put the device in PCI D3 state (which is what currently happens
8171  * because of the runtime PM support).
8172  *
8173  * For more, read "Display Sequences for Package C8" on the hardware
8174  * documentation.
8175  */
8176 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8177 {
8178         struct drm_device *dev = dev_priv->dev;
8179         uint32_t val;
8180
8181         DRM_DEBUG_KMS("Enabling package C8+\n");
8182
8183         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8184                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8185                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8186                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8187         }
8188
8189         lpt_disable_clkout_dp(dev);
8190         hsw_disable_lcpll(dev_priv, true, true);
8191 }
8192
8193 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8194 {
8195         struct drm_device *dev = dev_priv->dev;
8196         uint32_t val;
8197
8198         DRM_DEBUG_KMS("Disabling package C8+\n");
8199
8200         hsw_restore_lcpll(dev_priv);
8201         lpt_init_pch_refclk(dev);
8202
8203         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8204                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8205                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8206                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8207         }
8208
8209         intel_prepare_ddi(dev);
8210 }
8211
8212 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8213                                       struct intel_crtc_state *crtc_state)
8214 {
8215         if (!intel_ddi_pll_select(crtc, crtc_state))
8216                 return -EINVAL;
8217
8218         crtc->lowfreq_avail = false;
8219
8220         return 0;
8221 }
8222
8223 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8224                                 enum port port,
8225                                 struct intel_crtc_state *pipe_config)
8226 {
8227         u32 temp, dpll_ctl1;
8228
8229         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8230         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
8231
8232         switch (pipe_config->ddi_pll_sel) {
8233         case SKL_DPLL0:
8234                 /*
8235                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
8236                  * of the shared DPLL framework and thus needs to be read out
8237                  * separately
8238                  */
8239                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
8240                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
8241                 break;
8242         case SKL_DPLL1:
8243                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
8244                 break;
8245         case SKL_DPLL2:
8246                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
8247                 break;
8248         case SKL_DPLL3:
8249                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
8250                 break;
8251         }
8252 }
8253
8254 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8255                                 enum port port,
8256                                 struct intel_crtc_state *pipe_config)
8257 {
8258         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8259
8260         switch (pipe_config->ddi_pll_sel) {
8261         case PORT_CLK_SEL_WRPLL1:
8262                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
8263                 break;
8264         case PORT_CLK_SEL_WRPLL2:
8265                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
8266                 break;
8267         }
8268 }
8269
8270 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
8271                                        struct intel_crtc_state *pipe_config)
8272 {
8273         struct drm_device *dev = crtc->base.dev;
8274         struct drm_i915_private *dev_priv = dev->dev_private;
8275         struct intel_shared_dpll *pll;
8276         enum port port;
8277         uint32_t tmp;
8278
8279         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
8280
8281         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
8282
8283         if (IS_SKYLAKE(dev))
8284                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
8285         else
8286                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
8287
8288         if (pipe_config->shared_dpll >= 0) {
8289                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8290
8291                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
8292                                            &pipe_config->dpll_hw_state));
8293         }
8294
8295         /*
8296          * Haswell has only FDI/PCH transcoder A. It is which is connected to
8297          * DDI E. So just check whether this pipe is wired to DDI E and whether
8298          * the PCH transcoder is on.
8299          */
8300         if (INTEL_INFO(dev)->gen < 9 &&
8301             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
8302                 pipe_config->has_pch_encoder = true;
8303
8304                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
8305                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8306                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8307
8308                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8309         }
8310 }
8311
8312 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
8313                                     struct intel_crtc_state *pipe_config)
8314 {
8315         struct drm_device *dev = crtc->base.dev;
8316         struct drm_i915_private *dev_priv = dev->dev_private;
8317         enum intel_display_power_domain pfit_domain;
8318         uint32_t tmp;
8319
8320         if (!intel_display_power_is_enabled(dev_priv,
8321                                          POWER_DOMAIN_PIPE(crtc->pipe)))
8322                 return false;
8323
8324         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8325         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8326
8327         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8328         if (tmp & TRANS_DDI_FUNC_ENABLE) {
8329                 enum pipe trans_edp_pipe;
8330                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8331                 default:
8332                         WARN(1, "unknown pipe linked to edp transcoder\n");
8333                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
8334                 case TRANS_DDI_EDP_INPUT_A_ON:
8335                         trans_edp_pipe = PIPE_A;
8336                         break;
8337                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
8338                         trans_edp_pipe = PIPE_B;
8339                         break;
8340                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
8341                         trans_edp_pipe = PIPE_C;
8342                         break;
8343                 }
8344
8345                 if (trans_edp_pipe == crtc->pipe)
8346                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
8347         }
8348
8349         if (!intel_display_power_is_enabled(dev_priv,
8350                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
8351                 return false;
8352
8353         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
8354         if (!(tmp & PIPECONF_ENABLE))
8355                 return false;
8356
8357         haswell_get_ddi_port_state(crtc, pipe_config);
8358
8359         intel_get_pipe_timings(crtc, pipe_config);
8360
8361         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
8362         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
8363                 if (IS_SKYLAKE(dev))
8364                         skylake_get_pfit_config(crtc, pipe_config);
8365                 else
8366                         ironlake_get_pfit_config(crtc, pipe_config);
8367         }
8368
8369         if (IS_HASWELL(dev))
8370                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
8371                         (I915_READ(IPS_CTL) & IPS_ENABLE);
8372
8373         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
8374                 pipe_config->pixel_multiplier =
8375                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
8376         } else {
8377                 pipe_config->pixel_multiplier = 1;
8378         }
8379
8380         return true;
8381 }
8382
8383 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
8384 {
8385         struct drm_device *dev = crtc->dev;
8386         struct drm_i915_private *dev_priv = dev->dev_private;
8387         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8388         uint32_t cntl = 0, size = 0;
8389
8390         if (base) {
8391                 unsigned int width = intel_crtc->cursor_width;
8392                 unsigned int height = intel_crtc->cursor_height;
8393                 unsigned int stride = roundup_pow_of_two(width) * 4;
8394
8395                 switch (stride) {
8396                 default:
8397                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
8398                                   width, stride);
8399                         stride = 256;
8400                         /* fallthrough */
8401                 case 256:
8402                 case 512:
8403                 case 1024:
8404                 case 2048:
8405                         break;
8406                 }
8407
8408                 cntl |= CURSOR_ENABLE |
8409                         CURSOR_GAMMA_ENABLE |
8410                         CURSOR_FORMAT_ARGB |
8411                         CURSOR_STRIDE(stride);
8412
8413                 size = (height << 12) | width;
8414         }
8415
8416         if (intel_crtc->cursor_cntl != 0 &&
8417             (intel_crtc->cursor_base != base ||
8418              intel_crtc->cursor_size != size ||
8419              intel_crtc->cursor_cntl != cntl)) {
8420                 /* On these chipsets we can only modify the base/size/stride
8421                  * whilst the cursor is disabled.
8422                  */
8423                 I915_WRITE(_CURACNTR, 0);
8424                 POSTING_READ(_CURACNTR);
8425                 intel_crtc->cursor_cntl = 0;
8426         }
8427
8428         if (intel_crtc->cursor_base != base) {
8429                 I915_WRITE(_CURABASE, base);
8430                 intel_crtc->cursor_base = base;
8431         }
8432
8433         if (intel_crtc->cursor_size != size) {
8434                 I915_WRITE(CURSIZE, size);
8435                 intel_crtc->cursor_size = size;
8436         }
8437
8438         if (intel_crtc->cursor_cntl != cntl) {
8439                 I915_WRITE(_CURACNTR, cntl);
8440                 POSTING_READ(_CURACNTR);
8441                 intel_crtc->cursor_cntl = cntl;
8442         }
8443 }
8444
8445 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
8446 {
8447         struct drm_device *dev = crtc->dev;
8448         struct drm_i915_private *dev_priv = dev->dev_private;
8449         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8450         int pipe = intel_crtc->pipe;
8451         uint32_t cntl;
8452
8453         cntl = 0;
8454         if (base) {
8455                 cntl = MCURSOR_GAMMA_ENABLE;
8456                 switch (intel_crtc->cursor_width) {
8457                         case 64:
8458                                 cntl |= CURSOR_MODE_64_ARGB_AX;
8459                                 break;
8460                         case 128:
8461                                 cntl |= CURSOR_MODE_128_ARGB_AX;
8462                                 break;
8463                         case 256:
8464                                 cntl |= CURSOR_MODE_256_ARGB_AX;
8465                                 break;
8466                         default:
8467                                 MISSING_CASE(intel_crtc->cursor_width);
8468                                 return;
8469                 }
8470                 cntl |= pipe << 28; /* Connect to correct pipe */
8471
8472                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
8473                         cntl |= CURSOR_PIPE_CSC_ENABLE;
8474         }
8475
8476         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
8477                 cntl |= CURSOR_ROTATE_180;
8478
8479         if (intel_crtc->cursor_cntl != cntl) {
8480                 I915_WRITE(CURCNTR(pipe), cntl);
8481                 POSTING_READ(CURCNTR(pipe));
8482                 intel_crtc->cursor_cntl = cntl;
8483         }
8484
8485         /* and commit changes on next vblank */
8486         I915_WRITE(CURBASE(pipe), base);
8487         POSTING_READ(CURBASE(pipe));
8488
8489         intel_crtc->cursor_base = base;
8490 }
8491
8492 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
8493 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
8494                                      bool on)
8495 {
8496         struct drm_device *dev = crtc->dev;
8497         struct drm_i915_private *dev_priv = dev->dev_private;
8498         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8499         int pipe = intel_crtc->pipe;
8500         int x = crtc->cursor_x;
8501         int y = crtc->cursor_y;
8502         u32 base = 0, pos = 0;
8503
8504         if (on)
8505                 base = intel_crtc->cursor_addr;
8506
8507         if (x >= intel_crtc->config->pipe_src_w)
8508                 base = 0;
8509
8510         if (y >= intel_crtc->config->pipe_src_h)
8511                 base = 0;
8512
8513         if (x < 0) {
8514                 if (x + intel_crtc->cursor_width <= 0)
8515                         base = 0;
8516
8517                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
8518                 x = -x;
8519         }
8520         pos |= x << CURSOR_X_SHIFT;
8521
8522         if (y < 0) {
8523                 if (y + intel_crtc->cursor_height <= 0)
8524                         base = 0;
8525
8526                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
8527                 y = -y;
8528         }
8529         pos |= y << CURSOR_Y_SHIFT;
8530
8531         if (base == 0 && intel_crtc->cursor_base == 0)
8532                 return;
8533
8534         I915_WRITE(CURPOS(pipe), pos);
8535
8536         /* ILK+ do this automagically */
8537         if (HAS_GMCH_DISPLAY(dev) &&
8538             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
8539                 base += (intel_crtc->cursor_height *
8540                         intel_crtc->cursor_width - 1) * 4;
8541         }
8542
8543         if (IS_845G(dev) || IS_I865G(dev))
8544                 i845_update_cursor(crtc, base);
8545         else
8546                 i9xx_update_cursor(crtc, base);
8547 }
8548
8549 static bool cursor_size_ok(struct drm_device *dev,
8550                            uint32_t width, uint32_t height)
8551 {
8552         if (width == 0 || height == 0)
8553                 return false;
8554
8555         /*
8556          * 845g/865g are special in that they are only limited by
8557          * the width of their cursors, the height is arbitrary up to
8558          * the precision of the register. Everything else requires
8559          * square cursors, limited to a few power-of-two sizes.
8560          */
8561         if (IS_845G(dev) || IS_I865G(dev)) {
8562                 if ((width & 63) != 0)
8563                         return false;
8564
8565                 if (width > (IS_845G(dev) ? 64 : 512))
8566                         return false;
8567
8568                 if (height > 1023)
8569                         return false;
8570         } else {
8571                 switch (width | height) {
8572                 case 256:
8573                 case 128:
8574                         if (IS_GEN2(dev))
8575                                 return false;
8576                 case 64:
8577                         break;
8578                 default:
8579                         return false;
8580                 }
8581         }
8582
8583         return true;
8584 }
8585
8586 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
8587                                  u16 *blue, uint32_t start, uint32_t size)
8588 {
8589         int end = (start + size > 256) ? 256 : start + size, i;
8590         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8591
8592         for (i = start; i < end; i++) {
8593                 intel_crtc->lut_r[i] = red[i] >> 8;
8594                 intel_crtc->lut_g[i] = green[i] >> 8;
8595                 intel_crtc->lut_b[i] = blue[i] >> 8;
8596         }
8597
8598         intel_crtc_load_lut(crtc);
8599 }
8600
8601 /* VESA 640x480x72Hz mode to set on the pipe */
8602 static struct drm_display_mode load_detect_mode = {
8603         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
8604                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
8605 };
8606
8607 struct drm_framebuffer *
8608 __intel_framebuffer_create(struct drm_device *dev,
8609                            struct drm_mode_fb_cmd2 *mode_cmd,
8610                            struct drm_i915_gem_object *obj)
8611 {
8612         struct intel_framebuffer *intel_fb;
8613         int ret;
8614
8615         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8616         if (!intel_fb) {
8617                 drm_gem_object_unreference(&obj->base);
8618                 return ERR_PTR(-ENOMEM);
8619         }
8620
8621         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
8622         if (ret)
8623                 goto err;
8624
8625         return &intel_fb->base;
8626 err:
8627         drm_gem_object_unreference(&obj->base);
8628         kfree(intel_fb);
8629
8630         return ERR_PTR(ret);
8631 }
8632
8633 static struct drm_framebuffer *
8634 intel_framebuffer_create(struct drm_device *dev,
8635                          struct drm_mode_fb_cmd2 *mode_cmd,
8636                          struct drm_i915_gem_object *obj)
8637 {
8638         struct drm_framebuffer *fb;
8639         int ret;
8640
8641         ret = i915_mutex_lock_interruptible(dev);
8642         if (ret)
8643                 return ERR_PTR(ret);
8644         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
8645         mutex_unlock(&dev->struct_mutex);
8646
8647         return fb;
8648 }
8649
8650 static u32
8651 intel_framebuffer_pitch_for_width(int width, int bpp)
8652 {
8653         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
8654         return ALIGN(pitch, 64);
8655 }
8656
8657 static u32
8658 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
8659 {
8660         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
8661         return PAGE_ALIGN(pitch * mode->vdisplay);
8662 }
8663
8664 static struct drm_framebuffer *
8665 intel_framebuffer_create_for_mode(struct drm_device *dev,
8666                                   struct drm_display_mode *mode,
8667                                   int depth, int bpp)
8668 {
8669         struct drm_i915_gem_object *obj;
8670         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
8671
8672         obj = i915_gem_alloc_object(dev,
8673                                     intel_framebuffer_size_for_mode(mode, bpp));
8674         if (obj == NULL)
8675                 return ERR_PTR(-ENOMEM);
8676
8677         mode_cmd.width = mode->hdisplay;
8678         mode_cmd.height = mode->vdisplay;
8679         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
8680                                                                 bpp);
8681         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
8682
8683         return intel_framebuffer_create(dev, &mode_cmd, obj);
8684 }
8685
8686 static struct drm_framebuffer *
8687 mode_fits_in_fbdev(struct drm_device *dev,
8688                    struct drm_display_mode *mode)
8689 {
8690 #ifdef CONFIG_DRM_I915_FBDEV
8691         struct drm_i915_private *dev_priv = dev->dev_private;
8692         struct drm_i915_gem_object *obj;
8693         struct drm_framebuffer *fb;
8694
8695         if (!dev_priv->fbdev)
8696                 return NULL;
8697
8698         if (!dev_priv->fbdev->fb)
8699                 return NULL;
8700
8701         obj = dev_priv->fbdev->fb->obj;
8702         BUG_ON(!obj);
8703
8704         fb = &dev_priv->fbdev->fb->base;
8705         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
8706                                                                fb->bits_per_pixel))
8707                 return NULL;
8708
8709         if (obj->base.size < mode->vdisplay * fb->pitches[0])
8710                 return NULL;
8711
8712         return fb;
8713 #else
8714         return NULL;
8715 #endif
8716 }
8717
8718 bool intel_get_load_detect_pipe(struct drm_connector *connector,
8719                                 struct drm_display_mode *mode,
8720                                 struct intel_load_detect_pipe *old,
8721                                 struct drm_modeset_acquire_ctx *ctx)
8722 {
8723         struct intel_crtc *intel_crtc;
8724         struct intel_encoder *intel_encoder =
8725                 intel_attached_encoder(connector);
8726         struct drm_crtc *possible_crtc;
8727         struct drm_encoder *encoder = &intel_encoder->base;
8728         struct drm_crtc *crtc = NULL;
8729         struct drm_device *dev = encoder->dev;
8730         struct drm_framebuffer *fb;
8731         struct drm_mode_config *config = &dev->mode_config;
8732         int ret, i = -1;
8733
8734         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8735                       connector->base.id, connector->name,
8736                       encoder->base.id, encoder->name);
8737
8738 retry:
8739         ret = drm_modeset_lock(&config->connection_mutex, ctx);
8740         if (ret)
8741                 goto fail_unlock;
8742
8743         /*
8744          * Algorithm gets a little messy:
8745          *
8746          *   - if the connector already has an assigned crtc, use it (but make
8747          *     sure it's on first)
8748          *
8749          *   - try to find the first unused crtc that can drive this connector,
8750          *     and use that if we find one
8751          */
8752
8753         /* See if we already have a CRTC for this connector */
8754         if (encoder->crtc) {
8755                 crtc = encoder->crtc;
8756
8757                 ret = drm_modeset_lock(&crtc->mutex, ctx);
8758                 if (ret)
8759                         goto fail_unlock;
8760                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
8761                 if (ret)
8762                         goto fail_unlock;
8763
8764                 old->dpms_mode = connector->dpms;
8765                 old->load_detect_temp = false;
8766
8767                 /* Make sure the crtc and connector are running */
8768                 if (connector->dpms != DRM_MODE_DPMS_ON)
8769                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
8770
8771                 return true;
8772         }
8773
8774         /* Find an unused one (if possible) */
8775         for_each_crtc(dev, possible_crtc) {
8776                 i++;
8777                 if (!(encoder->possible_crtcs & (1 << i)))
8778                         continue;
8779                 if (possible_crtc->state->enable)
8780                         continue;
8781                 /* This can occur when applying the pipe A quirk on resume. */
8782                 if (to_intel_crtc(possible_crtc)->new_enabled)
8783                         continue;
8784
8785                 crtc = possible_crtc;
8786                 break;
8787         }
8788
8789         /*
8790          * If we didn't find an unused CRTC, don't use any.
8791          */
8792         if (!crtc) {
8793                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
8794                 goto fail_unlock;
8795         }
8796
8797         ret = drm_modeset_lock(&crtc->mutex, ctx);
8798         if (ret)
8799                 goto fail_unlock;
8800         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
8801         if (ret)
8802                 goto fail_unlock;
8803         intel_encoder->new_crtc = to_intel_crtc(crtc);
8804         to_intel_connector(connector)->new_encoder = intel_encoder;
8805
8806         intel_crtc = to_intel_crtc(crtc);
8807         intel_crtc->new_enabled = true;
8808         intel_crtc->new_config = intel_crtc->config;
8809         old->dpms_mode = connector->dpms;
8810         old->load_detect_temp = true;
8811         old->release_fb = NULL;
8812
8813         if (!mode)
8814                 mode = &load_detect_mode;
8815
8816         /* We need a framebuffer large enough to accommodate all accesses
8817          * that the plane may generate whilst we perform load detection.
8818          * We can not rely on the fbcon either being present (we get called
8819          * during its initialisation to detect all boot displays, or it may
8820          * not even exist) or that it is large enough to satisfy the
8821          * requested mode.
8822          */
8823         fb = mode_fits_in_fbdev(dev, mode);
8824         if (fb == NULL) {
8825                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
8826                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
8827                 old->release_fb = fb;
8828         } else
8829                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
8830         if (IS_ERR(fb)) {
8831                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
8832                 goto fail;
8833         }
8834
8835         if (intel_set_mode(crtc, mode, 0, 0, fb)) {
8836                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
8837                 if (old->release_fb)
8838                         old->release_fb->funcs->destroy(old->release_fb);
8839                 goto fail;
8840         }
8841
8842         /* let the connector get through one full cycle before testing */
8843         intel_wait_for_vblank(dev, intel_crtc->pipe);
8844         return true;
8845
8846  fail:
8847         intel_crtc->new_enabled = crtc->state->enable;
8848         if (intel_crtc->new_enabled)
8849                 intel_crtc->new_config = intel_crtc->config;
8850         else
8851                 intel_crtc->new_config = NULL;
8852 fail_unlock:
8853         if (ret == -EDEADLK) {
8854                 drm_modeset_backoff(ctx);
8855                 goto retry;
8856         }
8857
8858         return false;
8859 }
8860
8861 void intel_release_load_detect_pipe(struct drm_connector *connector,
8862                                     struct intel_load_detect_pipe *old)
8863 {
8864         struct intel_encoder *intel_encoder =
8865                 intel_attached_encoder(connector);
8866         struct drm_encoder *encoder = &intel_encoder->base;
8867         struct drm_crtc *crtc = encoder->crtc;
8868         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8869
8870         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
8871                       connector->base.id, connector->name,
8872                       encoder->base.id, encoder->name);
8873
8874         if (old->load_detect_temp) {
8875                 to_intel_connector(connector)->new_encoder = NULL;
8876                 intel_encoder->new_crtc = NULL;
8877                 intel_crtc->new_enabled = false;
8878                 intel_crtc->new_config = NULL;
8879                 intel_set_mode(crtc, NULL, 0, 0, NULL);
8880
8881                 if (old->release_fb) {
8882                         drm_framebuffer_unregister_private(old->release_fb);
8883                         drm_framebuffer_unreference(old->release_fb);
8884                 }
8885
8886                 return;
8887         }
8888
8889         /* Switch crtc and encoder back off if necessary */
8890         if (old->dpms_mode != DRM_MODE_DPMS_ON)
8891                 connector->funcs->dpms(connector, old->dpms_mode);
8892 }
8893
8894 static int i9xx_pll_refclk(struct drm_device *dev,
8895                            const struct intel_crtc_state *pipe_config)
8896 {
8897         struct drm_i915_private *dev_priv = dev->dev_private;
8898         u32 dpll = pipe_config->dpll_hw_state.dpll;
8899
8900         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
8901                 return dev_priv->vbt.lvds_ssc_freq;
8902         else if (HAS_PCH_SPLIT(dev))
8903                 return 120000;
8904         else if (!IS_GEN2(dev))
8905                 return 96000;
8906         else
8907                 return 48000;
8908 }
8909
8910 /* Returns the clock of the currently programmed mode of the given pipe. */
8911 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
8912                                 struct intel_crtc_state *pipe_config)
8913 {
8914         struct drm_device *dev = crtc->base.dev;
8915         struct drm_i915_private *dev_priv = dev->dev_private;
8916         int pipe = pipe_config->cpu_transcoder;
8917         u32 dpll = pipe_config->dpll_hw_state.dpll;
8918         u32 fp;
8919         intel_clock_t clock;
8920         int refclk = i9xx_pll_refclk(dev, pipe_config);
8921
8922         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
8923                 fp = pipe_config->dpll_hw_state.fp0;
8924         else
8925                 fp = pipe_config->dpll_hw_state.fp1;
8926
8927         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
8928         if (IS_PINEVIEW(dev)) {
8929                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
8930                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
8931         } else {
8932                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
8933                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
8934         }
8935
8936         if (!IS_GEN2(dev)) {
8937                 if (IS_PINEVIEW(dev))
8938                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
8939                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
8940                 else
8941                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
8942                                DPLL_FPA01_P1_POST_DIV_SHIFT);
8943
8944                 switch (dpll & DPLL_MODE_MASK) {
8945                 case DPLLB_MODE_DAC_SERIAL:
8946                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
8947                                 5 : 10;
8948                         break;
8949                 case DPLLB_MODE_LVDS:
8950                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
8951                                 7 : 14;
8952                         break;
8953                 default:
8954                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
8955                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
8956                         return;
8957                 }
8958
8959                 if (IS_PINEVIEW(dev))
8960                         pineview_clock(refclk, &clock);
8961                 else
8962                         i9xx_clock(refclk, &clock);
8963         } else {
8964                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
8965                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
8966
8967                 if (is_lvds) {
8968                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
8969                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
8970
8971                         if (lvds & LVDS_CLKB_POWER_UP)
8972                                 clock.p2 = 7;
8973                         else
8974                                 clock.p2 = 14;
8975                 } else {
8976                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
8977                                 clock.p1 = 2;
8978                         else {
8979                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
8980                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
8981                         }
8982                         if (dpll & PLL_P2_DIVIDE_BY_4)
8983                                 clock.p2 = 4;
8984                         else
8985                                 clock.p2 = 2;
8986                 }
8987
8988                 i9xx_clock(refclk, &clock);
8989         }
8990
8991         /*
8992          * This value includes pixel_multiplier. We will use
8993          * port_clock to compute adjusted_mode.crtc_clock in the
8994          * encoder's get_config() function.
8995          */
8996         pipe_config->port_clock = clock.dot;
8997 }
8998
8999 int intel_dotclock_calculate(int link_freq,
9000                              const struct intel_link_m_n *m_n)
9001 {
9002         /*
9003          * The calculation for the data clock is:
9004          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
9005          * But we want to avoid losing precison if possible, so:
9006          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
9007          *
9008          * and the link clock is simpler:
9009          * link_clock = (m * link_clock) / n
9010          */
9011
9012         if (!m_n->link_n)
9013                 return 0;
9014
9015         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
9016 }
9017
9018 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
9019                                    struct intel_crtc_state *pipe_config)
9020 {
9021         struct drm_device *dev = crtc->base.dev;
9022
9023         /* read out port_clock from the DPLL */
9024         i9xx_crtc_clock_get(crtc, pipe_config);
9025
9026         /*
9027          * This value does not include pixel_multiplier.
9028          * We will check that port_clock and adjusted_mode.crtc_clock
9029          * agree once we know their relationship in the encoder's
9030          * get_config() function.
9031          */
9032         pipe_config->base.adjusted_mode.crtc_clock =
9033                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
9034                                          &pipe_config->fdi_m_n);
9035 }
9036
9037 /** Returns the currently programmed mode of the given pipe. */
9038 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
9039                                              struct drm_crtc *crtc)
9040 {
9041         struct drm_i915_private *dev_priv = dev->dev_private;
9042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9043         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9044         struct drm_display_mode *mode;
9045         struct intel_crtc_state pipe_config;
9046         int htot = I915_READ(HTOTAL(cpu_transcoder));
9047         int hsync = I915_READ(HSYNC(cpu_transcoder));
9048         int vtot = I915_READ(VTOTAL(cpu_transcoder));
9049         int vsync = I915_READ(VSYNC(cpu_transcoder));
9050         enum pipe pipe = intel_crtc->pipe;
9051
9052         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
9053         if (!mode)
9054                 return NULL;
9055
9056         /*
9057          * Construct a pipe_config sufficient for getting the clock info
9058          * back out of crtc_clock_get.
9059          *
9060          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
9061          * to use a real value here instead.
9062          */
9063         pipe_config.cpu_transcoder = (enum transcoder) pipe;
9064         pipe_config.pixel_multiplier = 1;
9065         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
9066         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
9067         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
9068         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
9069
9070         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
9071         mode->hdisplay = (htot & 0xffff) + 1;
9072         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
9073         mode->hsync_start = (hsync & 0xffff) + 1;
9074         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
9075         mode->vdisplay = (vtot & 0xffff) + 1;
9076         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
9077         mode->vsync_start = (vsync & 0xffff) + 1;
9078         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
9079
9080         drm_mode_set_name(mode);
9081
9082         return mode;
9083 }
9084
9085 static void intel_decrease_pllclock(struct drm_crtc *crtc)
9086 {
9087         struct drm_device *dev = crtc->dev;
9088         struct drm_i915_private *dev_priv = dev->dev_private;
9089         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9090
9091         if (!HAS_GMCH_DISPLAY(dev))
9092                 return;
9093
9094         if (!dev_priv->lvds_downclock_avail)
9095                 return;
9096
9097         /*
9098          * Since this is called by a timer, we should never get here in
9099          * the manual case.
9100          */
9101         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
9102                 int pipe = intel_crtc->pipe;
9103                 int dpll_reg = DPLL(pipe);
9104                 int dpll;
9105
9106                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
9107
9108                 assert_panel_unlocked(dev_priv, pipe);
9109
9110                 dpll = I915_READ(dpll_reg);
9111                 dpll |= DISPLAY_RATE_SELECT_FPA1;
9112                 I915_WRITE(dpll_reg, dpll);
9113                 intel_wait_for_vblank(dev, pipe);
9114                 dpll = I915_READ(dpll_reg);
9115                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
9116                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
9117         }
9118
9119 }
9120
9121 void intel_mark_busy(struct drm_device *dev)
9122 {
9123         struct drm_i915_private *dev_priv = dev->dev_private;
9124
9125         if (dev_priv->mm.busy)
9126                 return;
9127
9128         intel_runtime_pm_get(dev_priv);
9129         i915_update_gfx_val(dev_priv);
9130         dev_priv->mm.busy = true;
9131 }
9132
9133 void intel_mark_idle(struct drm_device *dev)
9134 {
9135         struct drm_i915_private *dev_priv = dev->dev_private;
9136         struct drm_crtc *crtc;
9137
9138         if (!dev_priv->mm.busy)
9139                 return;
9140
9141         dev_priv->mm.busy = false;
9142
9143         if (!i915.powersave)
9144                 goto out;
9145
9146         for_each_crtc(dev, crtc) {
9147                 if (!crtc->primary->fb)
9148                         continue;
9149
9150                 intel_decrease_pllclock(crtc);
9151         }
9152
9153         if (INTEL_INFO(dev)->gen >= 6)
9154                 gen6_rps_idle(dev->dev_private);
9155
9156 out:
9157         intel_runtime_pm_put(dev_priv);
9158 }
9159
9160 static void intel_crtc_set_state(struct intel_crtc *crtc,
9161                                  struct intel_crtc_state *crtc_state)
9162 {
9163         kfree(crtc->config);
9164         crtc->config = crtc_state;
9165         crtc->base.state = &crtc_state->base;
9166 }
9167
9168 static void intel_crtc_destroy(struct drm_crtc *crtc)
9169 {
9170         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9171         struct drm_device *dev = crtc->dev;
9172         struct intel_unpin_work *work;
9173
9174         spin_lock_irq(&dev->event_lock);
9175         work = intel_crtc->unpin_work;
9176         intel_crtc->unpin_work = NULL;
9177         spin_unlock_irq(&dev->event_lock);
9178
9179         if (work) {
9180                 cancel_work_sync(&work->work);
9181                 kfree(work);
9182         }
9183
9184         intel_crtc_set_state(intel_crtc, NULL);
9185         drm_crtc_cleanup(crtc);
9186
9187         kfree(intel_crtc);
9188 }
9189
9190 static void intel_unpin_work_fn(struct work_struct *__work)
9191 {
9192         struct intel_unpin_work *work =
9193                 container_of(__work, struct intel_unpin_work, work);
9194         struct drm_device *dev = work->crtc->dev;
9195         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
9196
9197         mutex_lock(&dev->struct_mutex);
9198         intel_unpin_fb_obj(intel_fb_obj(work->old_fb));
9199         drm_gem_object_unreference(&work->pending_flip_obj->base);
9200         drm_framebuffer_unreference(work->old_fb);
9201
9202         intel_fbc_update(dev);
9203
9204         if (work->flip_queued_req)
9205                 i915_gem_request_assign(&work->flip_queued_req, NULL);
9206         mutex_unlock(&dev->struct_mutex);
9207
9208         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9209
9210         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
9211         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
9212
9213         kfree(work);
9214 }
9215
9216 static void do_intel_finish_page_flip(struct drm_device *dev,
9217                                       struct drm_crtc *crtc)
9218 {
9219         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9220         struct intel_unpin_work *work;
9221         unsigned long flags;
9222
9223         /* Ignore early vblank irqs */
9224         if (intel_crtc == NULL)
9225                 return;
9226
9227         /*
9228          * This is called both by irq handlers and the reset code (to complete
9229          * lost pageflips) so needs the full irqsave spinlocks.
9230          */
9231         spin_lock_irqsave(&dev->event_lock, flags);
9232         work = intel_crtc->unpin_work;
9233
9234         /* Ensure we don't miss a work->pending update ... */
9235         smp_rmb();
9236
9237         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
9238                 spin_unlock_irqrestore(&dev->event_lock, flags);
9239                 return;
9240         }
9241
9242         page_flip_completed(intel_crtc);
9243
9244         spin_unlock_irqrestore(&dev->event_lock, flags);
9245 }
9246
9247 void intel_finish_page_flip(struct drm_device *dev, int pipe)
9248 {
9249         struct drm_i915_private *dev_priv = dev->dev_private;
9250         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9251
9252         do_intel_finish_page_flip(dev, crtc);
9253 }
9254
9255 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
9256 {
9257         struct drm_i915_private *dev_priv = dev->dev_private;
9258         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
9259
9260         do_intel_finish_page_flip(dev, crtc);
9261 }
9262
9263 /* Is 'a' after or equal to 'b'? */
9264 static bool g4x_flip_count_after_eq(u32 a, u32 b)
9265 {
9266         return !((a - b) & 0x80000000);
9267 }
9268
9269 static bool page_flip_finished(struct intel_crtc *crtc)
9270 {
9271         struct drm_device *dev = crtc->base.dev;
9272         struct drm_i915_private *dev_priv = dev->dev_private;
9273
9274         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
9275             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
9276                 return true;
9277
9278         /*
9279          * The relevant registers doen't exist on pre-ctg.
9280          * As the flip done interrupt doesn't trigger for mmio
9281          * flips on gmch platforms, a flip count check isn't
9282          * really needed there. But since ctg has the registers,
9283          * include it in the check anyway.
9284          */
9285         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
9286                 return true;
9287
9288         /*
9289          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
9290          * used the same base address. In that case the mmio flip might
9291          * have completed, but the CS hasn't even executed the flip yet.
9292          *
9293          * A flip count check isn't enough as the CS might have updated
9294          * the base address just after start of vblank, but before we
9295          * managed to process the interrupt. This means we'd complete the
9296          * CS flip too soon.
9297          *
9298          * Combining both checks should get us a good enough result. It may
9299          * still happen that the CS flip has been executed, but has not
9300          * yet actually completed. But in case the base address is the same
9301          * anyway, we don't really care.
9302          */
9303         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
9304                 crtc->unpin_work->gtt_offset &&
9305                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
9306                                     crtc->unpin_work->flip_count);
9307 }
9308
9309 void intel_prepare_page_flip(struct drm_device *dev, int plane)
9310 {
9311         struct drm_i915_private *dev_priv = dev->dev_private;
9312         struct intel_crtc *intel_crtc =
9313                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
9314         unsigned long flags;
9315
9316
9317         /*
9318          * This is called both by irq handlers and the reset code (to complete
9319          * lost pageflips) so needs the full irqsave spinlocks.
9320          *
9321          * NB: An MMIO update of the plane base pointer will also
9322          * generate a page-flip completion irq, i.e. every modeset
9323          * is also accompanied by a spurious intel_prepare_page_flip().
9324          */
9325         spin_lock_irqsave(&dev->event_lock, flags);
9326         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
9327                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
9328         spin_unlock_irqrestore(&dev->event_lock, flags);
9329 }
9330
9331 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
9332 {
9333         /* Ensure that the work item is consistent when activating it ... */
9334         smp_wmb();
9335         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
9336         /* and that it is marked active as soon as the irq could fire. */
9337         smp_wmb();
9338 }
9339
9340 static int intel_gen2_queue_flip(struct drm_device *dev,
9341                                  struct drm_crtc *crtc,
9342                                  struct drm_framebuffer *fb,
9343                                  struct drm_i915_gem_object *obj,
9344                                  struct intel_engine_cs *ring,
9345                                  uint32_t flags)
9346 {
9347         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9348         u32 flip_mask;
9349         int ret;
9350
9351         ret = intel_ring_begin(ring, 6);
9352         if (ret)
9353                 return ret;
9354
9355         /* Can't queue multiple flips, so wait for the previous
9356          * one to finish before executing the next.
9357          */
9358         if (intel_crtc->plane)
9359                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9360         else
9361                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9362         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9363         intel_ring_emit(ring, MI_NOOP);
9364         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9365                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9366         intel_ring_emit(ring, fb->pitches[0]);
9367         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9368         intel_ring_emit(ring, 0); /* aux display base address, unused */
9369
9370         intel_mark_page_flip_active(intel_crtc);
9371         __intel_ring_advance(ring);
9372         return 0;
9373 }
9374
9375 static int intel_gen3_queue_flip(struct drm_device *dev,
9376                                  struct drm_crtc *crtc,
9377                                  struct drm_framebuffer *fb,
9378                                  struct drm_i915_gem_object *obj,
9379                                  struct intel_engine_cs *ring,
9380                                  uint32_t flags)
9381 {
9382         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9383         u32 flip_mask;
9384         int ret;
9385
9386         ret = intel_ring_begin(ring, 6);
9387         if (ret)
9388                 return ret;
9389
9390         if (intel_crtc->plane)
9391                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
9392         else
9393                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
9394         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
9395         intel_ring_emit(ring, MI_NOOP);
9396         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
9397                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9398         intel_ring_emit(ring, fb->pitches[0]);
9399         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9400         intel_ring_emit(ring, MI_NOOP);
9401
9402         intel_mark_page_flip_active(intel_crtc);
9403         __intel_ring_advance(ring);
9404         return 0;
9405 }
9406
9407 static int intel_gen4_queue_flip(struct drm_device *dev,
9408                                  struct drm_crtc *crtc,
9409                                  struct drm_framebuffer *fb,
9410                                  struct drm_i915_gem_object *obj,
9411                                  struct intel_engine_cs *ring,
9412                                  uint32_t flags)
9413 {
9414         struct drm_i915_private *dev_priv = dev->dev_private;
9415         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9416         uint32_t pf, pipesrc;
9417         int ret;
9418
9419         ret = intel_ring_begin(ring, 4);
9420         if (ret)
9421                 return ret;
9422
9423         /* i965+ uses the linear or tiled offsets from the
9424          * Display Registers (which do not change across a page-flip)
9425          * so we need only reprogram the base address.
9426          */
9427         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9428                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9429         intel_ring_emit(ring, fb->pitches[0]);
9430         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
9431                         obj->tiling_mode);
9432
9433         /* XXX Enabling the panel-fitter across page-flip is so far
9434          * untested on non-native modes, so ignore it for now.
9435          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
9436          */
9437         pf = 0;
9438         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9439         intel_ring_emit(ring, pf | pipesrc);
9440
9441         intel_mark_page_flip_active(intel_crtc);
9442         __intel_ring_advance(ring);
9443         return 0;
9444 }
9445
9446 static int intel_gen6_queue_flip(struct drm_device *dev,
9447                                  struct drm_crtc *crtc,
9448                                  struct drm_framebuffer *fb,
9449                                  struct drm_i915_gem_object *obj,
9450                                  struct intel_engine_cs *ring,
9451                                  uint32_t flags)
9452 {
9453         struct drm_i915_private *dev_priv = dev->dev_private;
9454         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9455         uint32_t pf, pipesrc;
9456         int ret;
9457
9458         ret = intel_ring_begin(ring, 4);
9459         if (ret)
9460                 return ret;
9461
9462         intel_ring_emit(ring, MI_DISPLAY_FLIP |
9463                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
9464         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
9465         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9466
9467         /* Contrary to the suggestions in the documentation,
9468          * "Enable Panel Fitter" does not seem to be required when page
9469          * flipping with a non-native mode, and worse causes a normal
9470          * modeset to fail.
9471          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
9472          */
9473         pf = 0;
9474         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
9475         intel_ring_emit(ring, pf | pipesrc);
9476
9477         intel_mark_page_flip_active(intel_crtc);
9478         __intel_ring_advance(ring);
9479         return 0;
9480 }
9481
9482 static int intel_gen7_queue_flip(struct drm_device *dev,
9483                                  struct drm_crtc *crtc,
9484                                  struct drm_framebuffer *fb,
9485                                  struct drm_i915_gem_object *obj,
9486                                  struct intel_engine_cs *ring,
9487                                  uint32_t flags)
9488 {
9489         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9490         uint32_t plane_bit = 0;
9491         int len, ret;
9492
9493         switch (intel_crtc->plane) {
9494         case PLANE_A:
9495                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
9496                 break;
9497         case PLANE_B:
9498                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
9499                 break;
9500         case PLANE_C:
9501                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
9502                 break;
9503         default:
9504                 WARN_ONCE(1, "unknown plane in flip command\n");
9505                 return -ENODEV;
9506         }
9507
9508         len = 4;
9509         if (ring->id == RCS) {
9510                 len += 6;
9511                 /*
9512                  * On Gen 8, SRM is now taking an extra dword to accommodate
9513                  * 48bits addresses, and we need a NOOP for the batch size to
9514                  * stay even.
9515                  */
9516                 if (IS_GEN8(dev))
9517                         len += 2;
9518         }
9519
9520         /*
9521          * BSpec MI_DISPLAY_FLIP for IVB:
9522          * "The full packet must be contained within the same cache line."
9523          *
9524          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
9525          * cacheline, if we ever start emitting more commands before
9526          * the MI_DISPLAY_FLIP we may need to first emit everything else,
9527          * then do the cacheline alignment, and finally emit the
9528          * MI_DISPLAY_FLIP.
9529          */
9530         ret = intel_ring_cacheline_align(ring);
9531         if (ret)
9532                 return ret;
9533
9534         ret = intel_ring_begin(ring, len);
9535         if (ret)
9536                 return ret;
9537
9538         /* Unmask the flip-done completion message. Note that the bspec says that
9539          * we should do this for both the BCS and RCS, and that we must not unmask
9540          * more than one flip event at any time (or ensure that one flip message
9541          * can be sent by waiting for flip-done prior to queueing new flips).
9542          * Experimentation says that BCS works despite DERRMR masking all
9543          * flip-done completion events and that unmasking all planes at once
9544          * for the RCS also doesn't appear to drop events. Setting the DERRMR
9545          * to zero does lead to lockups within MI_DISPLAY_FLIP.
9546          */
9547         if (ring->id == RCS) {
9548                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
9549                 intel_ring_emit(ring, DERRMR);
9550                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
9551                                         DERRMR_PIPEB_PRI_FLIP_DONE |
9552                                         DERRMR_PIPEC_PRI_FLIP_DONE));
9553                 if (IS_GEN8(dev))
9554                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
9555                                               MI_SRM_LRM_GLOBAL_GTT);
9556                 else
9557                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
9558                                               MI_SRM_LRM_GLOBAL_GTT);
9559                 intel_ring_emit(ring, DERRMR);
9560                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
9561                 if (IS_GEN8(dev)) {
9562                         intel_ring_emit(ring, 0);
9563                         intel_ring_emit(ring, MI_NOOP);
9564                 }
9565         }
9566
9567         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
9568         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
9569         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
9570         intel_ring_emit(ring, (MI_NOOP));
9571
9572         intel_mark_page_flip_active(intel_crtc);
9573         __intel_ring_advance(ring);
9574         return 0;
9575 }
9576
9577 static bool use_mmio_flip(struct intel_engine_cs *ring,
9578                           struct drm_i915_gem_object *obj)
9579 {
9580         /*
9581          * This is not being used for older platforms, because
9582          * non-availability of flip done interrupt forces us to use
9583          * CS flips. Older platforms derive flip done using some clever
9584          * tricks involving the flip_pending status bits and vblank irqs.
9585          * So using MMIO flips there would disrupt this mechanism.
9586          */
9587
9588         if (ring == NULL)
9589                 return true;
9590
9591         if (INTEL_INFO(ring->dev)->gen < 5)
9592                 return false;
9593
9594         if (i915.use_mmio_flip < 0)
9595                 return false;
9596         else if (i915.use_mmio_flip > 0)
9597                 return true;
9598         else if (i915.enable_execlists)
9599                 return true;
9600         else
9601                 return ring != i915_gem_request_get_ring(obj->last_read_req);
9602 }
9603
9604 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
9605 {
9606         struct drm_device *dev = intel_crtc->base.dev;
9607         struct drm_i915_private *dev_priv = dev->dev_private;
9608         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
9609         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
9610         struct drm_i915_gem_object *obj = intel_fb->obj;
9611         const enum pipe pipe = intel_crtc->pipe;
9612         u32 ctl, stride;
9613
9614         ctl = I915_READ(PLANE_CTL(pipe, 0));
9615         ctl &= ~PLANE_CTL_TILED_MASK;
9616         if (obj->tiling_mode == I915_TILING_X)
9617                 ctl |= PLANE_CTL_TILED_X;
9618
9619         /*
9620          * The stride is either expressed as a multiple of 64 bytes chunks for
9621          * linear buffers or in number of tiles for tiled buffers.
9622          */
9623         stride = fb->pitches[0] >> 6;
9624         if (obj->tiling_mode == I915_TILING_X)
9625                 stride = fb->pitches[0] >> 9; /* X tiles are 512 bytes wide */
9626
9627         /*
9628          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
9629          * PLANE_SURF updates, the update is then guaranteed to be atomic.
9630          */
9631         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
9632         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
9633
9634         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
9635         POSTING_READ(PLANE_SURF(pipe, 0));
9636 }
9637
9638 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
9639 {
9640         struct drm_device *dev = intel_crtc->base.dev;
9641         struct drm_i915_private *dev_priv = dev->dev_private;
9642         struct intel_framebuffer *intel_fb =
9643                 to_intel_framebuffer(intel_crtc->base.primary->fb);
9644         struct drm_i915_gem_object *obj = intel_fb->obj;
9645         u32 dspcntr;
9646         u32 reg;
9647
9648         reg = DSPCNTR(intel_crtc->plane);
9649         dspcntr = I915_READ(reg);
9650
9651         if (obj->tiling_mode != I915_TILING_NONE)
9652                 dspcntr |= DISPPLANE_TILED;
9653         else
9654                 dspcntr &= ~DISPPLANE_TILED;
9655
9656         I915_WRITE(reg, dspcntr);
9657
9658         I915_WRITE(DSPSURF(intel_crtc->plane),
9659                    intel_crtc->unpin_work->gtt_offset);
9660         POSTING_READ(DSPSURF(intel_crtc->plane));
9661
9662 }
9663
9664 /*
9665  * XXX: This is the temporary way to update the plane registers until we get
9666  * around to using the usual plane update functions for MMIO flips
9667  */
9668 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
9669 {
9670         struct drm_device *dev = intel_crtc->base.dev;
9671         bool atomic_update;
9672         u32 start_vbl_count;
9673
9674         intel_mark_page_flip_active(intel_crtc);
9675
9676         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
9677
9678         if (INTEL_INFO(dev)->gen >= 9)
9679                 skl_do_mmio_flip(intel_crtc);
9680         else
9681                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
9682                 ilk_do_mmio_flip(intel_crtc);
9683
9684         if (atomic_update)
9685                 intel_pipe_update_end(intel_crtc, start_vbl_count);
9686 }
9687
9688 static void intel_mmio_flip_work_func(struct work_struct *work)
9689 {
9690         struct intel_crtc *crtc =
9691                 container_of(work, struct intel_crtc, mmio_flip.work);
9692         struct intel_mmio_flip *mmio_flip;
9693
9694         mmio_flip = &crtc->mmio_flip;
9695         if (mmio_flip->req)
9696                 WARN_ON(__i915_wait_request(mmio_flip->req,
9697                                             crtc->reset_counter,
9698                                             false, NULL, NULL) != 0);
9699
9700         intel_do_mmio_flip(crtc);
9701         if (mmio_flip->req) {
9702                 mutex_lock(&crtc->base.dev->struct_mutex);
9703                 i915_gem_request_assign(&mmio_flip->req, NULL);
9704                 mutex_unlock(&crtc->base.dev->struct_mutex);
9705         }
9706 }
9707
9708 static int intel_queue_mmio_flip(struct drm_device *dev,
9709                                  struct drm_crtc *crtc,
9710                                  struct drm_framebuffer *fb,
9711                                  struct drm_i915_gem_object *obj,
9712                                  struct intel_engine_cs *ring,
9713                                  uint32_t flags)
9714 {
9715         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9716
9717         i915_gem_request_assign(&intel_crtc->mmio_flip.req,
9718                                 obj->last_write_req);
9719
9720         schedule_work(&intel_crtc->mmio_flip.work);
9721
9722         return 0;
9723 }
9724
9725 static int intel_default_queue_flip(struct drm_device *dev,
9726                                     struct drm_crtc *crtc,
9727                                     struct drm_framebuffer *fb,
9728                                     struct drm_i915_gem_object *obj,
9729                                     struct intel_engine_cs *ring,
9730                                     uint32_t flags)
9731 {
9732         return -ENODEV;
9733 }
9734
9735 static bool __intel_pageflip_stall_check(struct drm_device *dev,
9736                                          struct drm_crtc *crtc)
9737 {
9738         struct drm_i915_private *dev_priv = dev->dev_private;
9739         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9740         struct intel_unpin_work *work = intel_crtc->unpin_work;
9741         u32 addr;
9742
9743         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
9744                 return true;
9745
9746         if (!work->enable_stall_check)
9747                 return false;
9748
9749         if (work->flip_ready_vblank == 0) {
9750                 if (work->flip_queued_req &&
9751                     !i915_gem_request_completed(work->flip_queued_req, true))
9752                         return false;
9753
9754                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
9755         }
9756
9757         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
9758                 return false;
9759
9760         /* Potential stall - if we see that the flip has happened,
9761          * assume a missed interrupt. */
9762         if (INTEL_INFO(dev)->gen >= 4)
9763                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
9764         else
9765                 addr = I915_READ(DSPADDR(intel_crtc->plane));
9766
9767         /* There is a potential issue here with a false positive after a flip
9768          * to the same address. We could address this by checking for a
9769          * non-incrementing frame counter.
9770          */
9771         return addr == work->gtt_offset;
9772 }
9773
9774 void intel_check_page_flip(struct drm_device *dev, int pipe)
9775 {
9776         struct drm_i915_private *dev_priv = dev->dev_private;
9777         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
9778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9779
9780         WARN_ON(!in_irq());
9781
9782         if (crtc == NULL)
9783                 return;
9784
9785         spin_lock(&dev->event_lock);
9786         if (intel_crtc->unpin_work && __intel_pageflip_stall_check(dev, crtc)) {
9787                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
9788                          intel_crtc->unpin_work->flip_queued_vblank,
9789                          drm_vblank_count(dev, pipe));
9790                 page_flip_completed(intel_crtc);
9791         }
9792         spin_unlock(&dev->event_lock);
9793 }
9794
9795 static int intel_crtc_page_flip(struct drm_crtc *crtc,
9796                                 struct drm_framebuffer *fb,
9797                                 struct drm_pending_vblank_event *event,
9798                                 uint32_t page_flip_flags)
9799 {
9800         struct drm_device *dev = crtc->dev;
9801         struct drm_i915_private *dev_priv = dev->dev_private;
9802         struct drm_framebuffer *old_fb = crtc->primary->fb;
9803         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9804         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9805         struct drm_plane *primary = crtc->primary;
9806         enum pipe pipe = intel_crtc->pipe;
9807         struct intel_unpin_work *work;
9808         struct intel_engine_cs *ring;
9809         int ret;
9810
9811         /*
9812          * drm_mode_page_flip_ioctl() should already catch this, but double
9813          * check to be safe.  In the future we may enable pageflipping from
9814          * a disabled primary plane.
9815          */
9816         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
9817                 return -EBUSY;
9818
9819         /* Can't change pixel format via MI display flips. */
9820         if (fb->pixel_format != crtc->primary->fb->pixel_format)
9821                 return -EINVAL;
9822
9823         /*
9824          * TILEOFF/LINOFF registers can't be changed via MI display flips.
9825          * Note that pitch changes could also affect these register.
9826          */
9827         if (INTEL_INFO(dev)->gen > 3 &&
9828             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
9829              fb->pitches[0] != crtc->primary->fb->pitches[0]))
9830                 return -EINVAL;
9831
9832         if (i915_terminally_wedged(&dev_priv->gpu_error))
9833                 goto out_hang;
9834
9835         work = kzalloc(sizeof(*work), GFP_KERNEL);
9836         if (work == NULL)
9837                 return -ENOMEM;
9838
9839         work->event = event;
9840         work->crtc = crtc;
9841         work->old_fb = old_fb;
9842         INIT_WORK(&work->work, intel_unpin_work_fn);
9843
9844         ret = drm_crtc_vblank_get(crtc);
9845         if (ret)
9846                 goto free_work;
9847
9848         /* We borrow the event spin lock for protecting unpin_work */
9849         spin_lock_irq(&dev->event_lock);
9850         if (intel_crtc->unpin_work) {
9851                 /* Before declaring the flip queue wedged, check if
9852                  * the hardware completed the operation behind our backs.
9853                  */
9854                 if (__intel_pageflip_stall_check(dev, crtc)) {
9855                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
9856                         page_flip_completed(intel_crtc);
9857                 } else {
9858                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
9859                         spin_unlock_irq(&dev->event_lock);
9860
9861                         drm_crtc_vblank_put(crtc);
9862                         kfree(work);
9863                         return -EBUSY;
9864                 }
9865         }
9866         intel_crtc->unpin_work = work;
9867         spin_unlock_irq(&dev->event_lock);
9868
9869         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
9870                 flush_workqueue(dev_priv->wq);
9871
9872         ret = i915_mutex_lock_interruptible(dev);
9873         if (ret)
9874                 goto cleanup;
9875
9876         /* Reference the objects for the scheduled work. */
9877         drm_framebuffer_reference(work->old_fb);
9878         drm_gem_object_reference(&obj->base);
9879
9880         crtc->primary->fb = fb;
9881         update_state_fb(crtc->primary);
9882
9883         work->pending_flip_obj = obj;
9884
9885         atomic_inc(&intel_crtc->unpin_work_count);
9886         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
9887
9888         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
9889                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
9890
9891         if (IS_VALLEYVIEW(dev)) {
9892                 ring = &dev_priv->ring[BCS];
9893                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
9894                         /* vlv: DISPLAY_FLIP fails to change tiling */
9895                         ring = NULL;
9896         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
9897                 ring = &dev_priv->ring[BCS];
9898         } else if (INTEL_INFO(dev)->gen >= 7) {
9899                 ring = i915_gem_request_get_ring(obj->last_read_req);
9900                 if (ring == NULL || ring->id != RCS)
9901                         ring = &dev_priv->ring[BCS];
9902         } else {
9903                 ring = &dev_priv->ring[RCS];
9904         }
9905
9906         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb, ring);
9907         if (ret)
9908                 goto cleanup_pending;
9909
9910         work->gtt_offset =
9911                 i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset;
9912
9913         if (use_mmio_flip(ring, obj)) {
9914                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
9915                                             page_flip_flags);
9916                 if (ret)
9917                         goto cleanup_unpin;
9918
9919                 i915_gem_request_assign(&work->flip_queued_req,
9920                                         obj->last_write_req);
9921         } else {
9922                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
9923                                                    page_flip_flags);
9924                 if (ret)
9925                         goto cleanup_unpin;
9926
9927                 i915_gem_request_assign(&work->flip_queued_req,
9928                                         intel_ring_get_request(ring));
9929         }
9930
9931         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
9932         work->enable_stall_check = true;
9933
9934         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
9935                           INTEL_FRONTBUFFER_PRIMARY(pipe));
9936
9937         intel_fbc_disable(dev);
9938         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
9939         mutex_unlock(&dev->struct_mutex);
9940
9941         trace_i915_flip_request(intel_crtc->plane, obj);
9942
9943         return 0;
9944
9945 cleanup_unpin:
9946         intel_unpin_fb_obj(obj);
9947 cleanup_pending:
9948         atomic_dec(&intel_crtc->unpin_work_count);
9949         crtc->primary->fb = old_fb;
9950         update_state_fb(crtc->primary);
9951         drm_framebuffer_unreference(work->old_fb);
9952         drm_gem_object_unreference(&obj->base);
9953         mutex_unlock(&dev->struct_mutex);
9954
9955 cleanup:
9956         spin_lock_irq(&dev->event_lock);
9957         intel_crtc->unpin_work = NULL;
9958         spin_unlock_irq(&dev->event_lock);
9959
9960         drm_crtc_vblank_put(crtc);
9961 free_work:
9962         kfree(work);
9963
9964         if (ret == -EIO) {
9965 out_hang:
9966                 ret = intel_plane_restore(primary);
9967                 if (ret == 0 && event) {
9968                         spin_lock_irq(&dev->event_lock);
9969                         drm_send_vblank_event(dev, pipe, event);
9970                         spin_unlock_irq(&dev->event_lock);
9971                 }
9972         }
9973         return ret;
9974 }
9975
9976 static struct drm_crtc_helper_funcs intel_helper_funcs = {
9977         .mode_set_base_atomic = intel_pipe_set_base_atomic,
9978         .load_lut = intel_crtc_load_lut,
9979         .atomic_begin = intel_begin_crtc_commit,
9980         .atomic_flush = intel_finish_crtc_commit,
9981 };
9982
9983 /**
9984  * intel_modeset_update_staged_output_state
9985  *
9986  * Updates the staged output configuration state, e.g. after we've read out the
9987  * current hw state.
9988  */
9989 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
9990 {
9991         struct intel_crtc *crtc;
9992         struct intel_encoder *encoder;
9993         struct intel_connector *connector;
9994
9995         list_for_each_entry(connector, &dev->mode_config.connector_list,
9996                             base.head) {
9997                 connector->new_encoder =
9998                         to_intel_encoder(connector->base.encoder);
9999         }
10000
10001         for_each_intel_encoder(dev, encoder) {
10002                 encoder->new_crtc =
10003                         to_intel_crtc(encoder->base.crtc);
10004         }
10005
10006         for_each_intel_crtc(dev, crtc) {
10007                 crtc->new_enabled = crtc->base.state->enable;
10008
10009                 if (crtc->new_enabled)
10010                         crtc->new_config = crtc->config;
10011                 else
10012                         crtc->new_config = NULL;
10013         }
10014 }
10015
10016 /**
10017  * intel_modeset_commit_output_state
10018  *
10019  * This function copies the stage display pipe configuration to the real one.
10020  */
10021 static void intel_modeset_commit_output_state(struct drm_device *dev)
10022 {
10023         struct intel_crtc *crtc;
10024         struct intel_encoder *encoder;
10025         struct intel_connector *connector;
10026
10027         list_for_each_entry(connector, &dev->mode_config.connector_list,
10028                             base.head) {
10029                 connector->base.encoder = &connector->new_encoder->base;
10030         }
10031
10032         for_each_intel_encoder(dev, encoder) {
10033                 encoder->base.crtc = &encoder->new_crtc->base;
10034         }
10035
10036         for_each_intel_crtc(dev, crtc) {
10037                 crtc->base.state->enable = crtc->new_enabled;
10038                 crtc->base.enabled = crtc->new_enabled;
10039         }
10040 }
10041
10042 static void
10043 connected_sink_compute_bpp(struct intel_connector *connector,
10044                            struct intel_crtc_state *pipe_config)
10045 {
10046         int bpp = pipe_config->pipe_bpp;
10047
10048         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10049                 connector->base.base.id,
10050                 connector->base.name);
10051
10052         /* Don't use an invalid EDID bpc value */
10053         if (connector->base.display_info.bpc &&
10054             connector->base.display_info.bpc * 3 < bpp) {
10055                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10056                               bpp, connector->base.display_info.bpc*3);
10057                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
10058         }
10059
10060         /* Clamp bpp to 8 on screens without EDID 1.4 */
10061         if (connector->base.display_info.bpc == 0 && bpp > 24) {
10062                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10063                               bpp);
10064                 pipe_config->pipe_bpp = 24;
10065         }
10066 }
10067
10068 static int
10069 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10070                           struct drm_framebuffer *fb,
10071                           struct intel_crtc_state *pipe_config)
10072 {
10073         struct drm_device *dev = crtc->base.dev;
10074         struct intel_connector *connector;
10075         int bpp;
10076
10077         switch (fb->pixel_format) {
10078         case DRM_FORMAT_C8:
10079                 bpp = 8*3; /* since we go through a colormap */
10080                 break;
10081         case DRM_FORMAT_XRGB1555:
10082         case DRM_FORMAT_ARGB1555:
10083                 /* checked in intel_framebuffer_init already */
10084                 if (WARN_ON(INTEL_INFO(dev)->gen > 3))
10085                         return -EINVAL;
10086         case DRM_FORMAT_RGB565:
10087                 bpp = 6*3; /* min is 18bpp */
10088                 break;
10089         case DRM_FORMAT_XBGR8888:
10090         case DRM_FORMAT_ABGR8888:
10091                 /* checked in intel_framebuffer_init already */
10092                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10093                         return -EINVAL;
10094         case DRM_FORMAT_XRGB8888:
10095         case DRM_FORMAT_ARGB8888:
10096                 bpp = 8*3;
10097                 break;
10098         case DRM_FORMAT_XRGB2101010:
10099         case DRM_FORMAT_ARGB2101010:
10100         case DRM_FORMAT_XBGR2101010:
10101         case DRM_FORMAT_ABGR2101010:
10102                 /* checked in intel_framebuffer_init already */
10103                 if (WARN_ON(INTEL_INFO(dev)->gen < 4))
10104                         return -EINVAL;
10105                 bpp = 10*3;
10106                 break;
10107         /* TODO: gen4+ supports 16 bpc floating point, too. */
10108         default:
10109                 DRM_DEBUG_KMS("unsupported depth\n");
10110                 return -EINVAL;
10111         }
10112
10113         pipe_config->pipe_bpp = bpp;
10114
10115         /* Clamp display bpp to EDID value */
10116         list_for_each_entry(connector, &dev->mode_config.connector_list,
10117                             base.head) {
10118                 if (!connector->new_encoder ||
10119                     connector->new_encoder->new_crtc != crtc)
10120                         continue;
10121
10122                 connected_sink_compute_bpp(connector, pipe_config);
10123         }
10124
10125         return bpp;
10126 }
10127
10128 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10129 {
10130         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10131                         "type: 0x%x flags: 0x%x\n",
10132                 mode->crtc_clock,
10133                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10134                 mode->crtc_hsync_end, mode->crtc_htotal,
10135                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10136                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10137 }
10138
10139 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10140                                    struct intel_crtc_state *pipe_config,
10141                                    const char *context)
10142 {
10143         DRM_DEBUG_KMS("[CRTC:%d]%s config for pipe %c\n", crtc->base.base.id,
10144                       context, pipe_name(crtc->pipe));
10145
10146         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
10147         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
10148                       pipe_config->pipe_bpp, pipe_config->dither);
10149         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10150                       pipe_config->has_pch_encoder,
10151                       pipe_config->fdi_lanes,
10152                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
10153                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
10154                       pipe_config->fdi_m_n.tu);
10155         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10156                       pipe_config->has_dp_encoder,
10157                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
10158                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
10159                       pipe_config->dp_m_n.tu);
10160
10161         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
10162                       pipe_config->has_dp_encoder,
10163                       pipe_config->dp_m2_n2.gmch_m,
10164                       pipe_config->dp_m2_n2.gmch_n,
10165                       pipe_config->dp_m2_n2.link_m,
10166                       pipe_config->dp_m2_n2.link_n,
10167                       pipe_config->dp_m2_n2.tu);
10168
10169         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10170                       pipe_config->has_audio,
10171                       pipe_config->has_infoframe);
10172
10173         DRM_DEBUG_KMS("requested mode:\n");
10174         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10175         DRM_DEBUG_KMS("adjusted mode:\n");
10176         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10177         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10178         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
10179         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
10180                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
10181         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10182                       pipe_config->gmch_pfit.control,
10183                       pipe_config->gmch_pfit.pgm_ratios,
10184                       pipe_config->gmch_pfit.lvds_border_bits);
10185         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10186                       pipe_config->pch_pfit.pos,
10187                       pipe_config->pch_pfit.size,
10188                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
10189         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
10190         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
10191 }
10192
10193 static bool encoders_cloneable(const struct intel_encoder *a,
10194                                const struct intel_encoder *b)
10195 {
10196         /* masks could be asymmetric, so check both ways */
10197         return a == b || (a->cloneable & (1 << b->type) &&
10198                           b->cloneable & (1 << a->type));
10199 }
10200
10201 static bool check_single_encoder_cloning(struct intel_crtc *crtc,
10202                                          struct intel_encoder *encoder)
10203 {
10204         struct drm_device *dev = crtc->base.dev;
10205         struct intel_encoder *source_encoder;
10206
10207         for_each_intel_encoder(dev, source_encoder) {
10208                 if (source_encoder->new_crtc != crtc)
10209                         continue;
10210
10211                 if (!encoders_cloneable(encoder, source_encoder))
10212                         return false;
10213         }
10214
10215         return true;
10216 }
10217
10218 static bool check_encoder_cloning(struct intel_crtc *crtc)
10219 {
10220         struct drm_device *dev = crtc->base.dev;
10221         struct intel_encoder *encoder;
10222
10223         for_each_intel_encoder(dev, encoder) {
10224                 if (encoder->new_crtc != crtc)
10225                         continue;
10226
10227                 if (!check_single_encoder_cloning(crtc, encoder))
10228                         return false;
10229         }
10230
10231         return true;
10232 }
10233
10234 static bool check_digital_port_conflicts(struct drm_device *dev)
10235 {
10236         struct intel_connector *connector;
10237         unsigned int used_ports = 0;
10238
10239         /*
10240          * Walk the connector list instead of the encoder
10241          * list to detect the problem on ddi platforms
10242          * where there's just one encoder per digital port.
10243          */
10244         list_for_each_entry(connector,
10245                             &dev->mode_config.connector_list, base.head) {
10246                 struct intel_encoder *encoder = connector->new_encoder;
10247
10248                 if (!encoder)
10249                         continue;
10250
10251                 WARN_ON(!encoder->new_crtc);
10252
10253                 switch (encoder->type) {
10254                         unsigned int port_mask;
10255                 case INTEL_OUTPUT_UNKNOWN:
10256                         if (WARN_ON(!HAS_DDI(dev)))
10257                                 break;
10258                 case INTEL_OUTPUT_DISPLAYPORT:
10259                 case INTEL_OUTPUT_HDMI:
10260                 case INTEL_OUTPUT_EDP:
10261                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
10262
10263                         /* the same port mustn't appear more than once */
10264                         if (used_ports & port_mask)
10265                                 return false;
10266
10267                         used_ports |= port_mask;
10268                 default:
10269                         break;
10270                 }
10271         }
10272
10273         return true;
10274 }
10275
10276 static struct intel_crtc_state *
10277 intel_modeset_pipe_config(struct drm_crtc *crtc,
10278                           struct drm_framebuffer *fb,
10279                           struct drm_display_mode *mode)
10280 {
10281         struct drm_device *dev = crtc->dev;
10282         struct intel_encoder *encoder;
10283         struct intel_crtc_state *pipe_config;
10284         int plane_bpp, ret = -EINVAL;
10285         bool retry = true;
10286
10287         if (!check_encoder_cloning(to_intel_crtc(crtc))) {
10288                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10289                 return ERR_PTR(-EINVAL);
10290         }
10291
10292         if (!check_digital_port_conflicts(dev)) {
10293                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
10294                 return ERR_PTR(-EINVAL);
10295         }
10296
10297         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10298         if (!pipe_config)
10299                 return ERR_PTR(-ENOMEM);
10300
10301         pipe_config->base.crtc = crtc;
10302         drm_mode_copy(&pipe_config->base.adjusted_mode, mode);
10303         drm_mode_copy(&pipe_config->base.mode, mode);
10304
10305         pipe_config->cpu_transcoder =
10306                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10307         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
10308
10309         /*
10310          * Sanitize sync polarity flags based on requested ones. If neither
10311          * positive or negative polarity is requested, treat this as meaning
10312          * negative polarity.
10313          */
10314         if (!(pipe_config->base.adjusted_mode.flags &
10315               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10316                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10317
10318         if (!(pipe_config->base.adjusted_mode.flags &
10319               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10320                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10321
10322         /* Compute a starting value for pipe_config->pipe_bpp taking the source
10323          * plane pixel format and any sink constraints into account. Returns the
10324          * source plane bpp so that dithering can be selected on mismatches
10325          * after encoders and crtc also have had their say. */
10326         plane_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10327                                               fb, pipe_config);
10328         if (plane_bpp < 0)
10329                 goto fail;
10330
10331         /*
10332          * Determine the real pipe dimensions. Note that stereo modes can
10333          * increase the actual pipe size due to the frame doubling and
10334          * insertion of additional space for blanks between the frame. This
10335          * is stored in the crtc timings. We use the requested mode to do this
10336          * computation to clearly distinguish it from the adjusted mode, which
10337          * can be changed by the connectors in the below retry loop.
10338          */
10339         drm_crtc_get_hv_timing(&pipe_config->base.mode,
10340                                &pipe_config->pipe_src_w,
10341                                &pipe_config->pipe_src_h);
10342
10343 encoder_retry:
10344         /* Ensure the port clock defaults are reset when retrying. */
10345         pipe_config->port_clock = 0;
10346         pipe_config->pixel_multiplier = 1;
10347
10348         /* Fill in default crtc timings, allow encoders to overwrite them. */
10349         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10350                               CRTC_STEREO_DOUBLE);
10351
10352         /* Pass our mode to the connectors and the CRTC to give them a chance to
10353          * adjust it according to limitations or connector properties, and also
10354          * a chance to reject the mode entirely.
10355          */
10356         for_each_intel_encoder(dev, encoder) {
10357
10358                 if (&encoder->new_crtc->base != crtc)
10359                         continue;
10360
10361                 if (!(encoder->compute_config(encoder, pipe_config))) {
10362                         DRM_DEBUG_KMS("Encoder config failure\n");
10363                         goto fail;
10364                 }
10365         }
10366
10367         /* Set default port clock if not overwritten by the encoder. Needs to be
10368          * done afterwards in case the encoder adjusts the mode. */
10369         if (!pipe_config->port_clock)
10370                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10371                         * pipe_config->pixel_multiplier;
10372
10373         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10374         if (ret < 0) {
10375                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10376                 goto fail;
10377         }
10378
10379         if (ret == RETRY) {
10380                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10381                         ret = -EINVAL;
10382                         goto fail;
10383                 }
10384
10385                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10386                 retry = false;
10387                 goto encoder_retry;
10388         }
10389
10390         pipe_config->dither = pipe_config->pipe_bpp != plane_bpp;
10391         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
10392                       plane_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10393
10394         return pipe_config;
10395 fail:
10396         kfree(pipe_config);
10397         return ERR_PTR(ret);
10398 }
10399
10400 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
10401  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
10402 static void
10403 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
10404                              unsigned *prepare_pipes, unsigned *disable_pipes)
10405 {
10406         struct intel_crtc *intel_crtc;
10407         struct drm_device *dev = crtc->dev;
10408         struct intel_encoder *encoder;
10409         struct intel_connector *connector;
10410         struct drm_crtc *tmp_crtc;
10411
10412         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
10413
10414         /* Check which crtcs have changed outputs connected to them, these need
10415          * to be part of the prepare_pipes mask. We don't (yet) support global
10416          * modeset across multiple crtcs, so modeset_pipes will only have one
10417          * bit set at most. */
10418         list_for_each_entry(connector, &dev->mode_config.connector_list,
10419                             base.head) {
10420                 if (connector->base.encoder == &connector->new_encoder->base)
10421                         continue;
10422
10423                 if (connector->base.encoder) {
10424                         tmp_crtc = connector->base.encoder->crtc;
10425
10426                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10427                 }
10428
10429                 if (connector->new_encoder)
10430                         *prepare_pipes |=
10431                                 1 << connector->new_encoder->new_crtc->pipe;
10432         }
10433
10434         for_each_intel_encoder(dev, encoder) {
10435                 if (encoder->base.crtc == &encoder->new_crtc->base)
10436                         continue;
10437
10438                 if (encoder->base.crtc) {
10439                         tmp_crtc = encoder->base.crtc;
10440
10441                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
10442                 }
10443
10444                 if (encoder->new_crtc)
10445                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
10446         }
10447
10448         /* Check for pipes that will be enabled/disabled ... */
10449         for_each_intel_crtc(dev, intel_crtc) {
10450                 if (intel_crtc->base.state->enable == intel_crtc->new_enabled)
10451                         continue;
10452
10453                 if (!intel_crtc->new_enabled)
10454                         *disable_pipes |= 1 << intel_crtc->pipe;
10455                 else
10456                         *prepare_pipes |= 1 << intel_crtc->pipe;
10457         }
10458
10459
10460         /* set_mode is also used to update properties on life display pipes. */
10461         intel_crtc = to_intel_crtc(crtc);
10462         if (intel_crtc->new_enabled)
10463                 *prepare_pipes |= 1 << intel_crtc->pipe;
10464
10465         /*
10466          * For simplicity do a full modeset on any pipe where the output routing
10467          * changed. We could be more clever, but that would require us to be
10468          * more careful with calling the relevant encoder->mode_set functions.
10469          */
10470         if (*prepare_pipes)
10471                 *modeset_pipes = *prepare_pipes;
10472
10473         /* ... and mask these out. */
10474         *modeset_pipes &= ~(*disable_pipes);
10475         *prepare_pipes &= ~(*disable_pipes);
10476
10477         /*
10478          * HACK: We don't (yet) fully support global modesets. intel_set_config
10479          * obies this rule, but the modeset restore mode of
10480          * intel_modeset_setup_hw_state does not.
10481          */
10482         *modeset_pipes &= 1 << intel_crtc->pipe;
10483         *prepare_pipes &= 1 << intel_crtc->pipe;
10484
10485         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
10486                       *modeset_pipes, *prepare_pipes, *disable_pipes);
10487 }
10488
10489 static bool intel_crtc_in_use(struct drm_crtc *crtc)
10490 {
10491         struct drm_encoder *encoder;
10492         struct drm_device *dev = crtc->dev;
10493
10494         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
10495                 if (encoder->crtc == crtc)
10496                         return true;
10497
10498         return false;
10499 }
10500
10501 static void
10502 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
10503 {
10504         struct drm_i915_private *dev_priv = dev->dev_private;
10505         struct intel_encoder *intel_encoder;
10506         struct intel_crtc *intel_crtc;
10507         struct drm_connector *connector;
10508
10509         intel_shared_dpll_commit(dev_priv);
10510
10511         for_each_intel_encoder(dev, intel_encoder) {
10512                 if (!intel_encoder->base.crtc)
10513                         continue;
10514
10515                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
10516
10517                 if (prepare_pipes & (1 << intel_crtc->pipe))
10518                         intel_encoder->connectors_active = false;
10519         }
10520
10521         intel_modeset_commit_output_state(dev);
10522
10523         /* Double check state. */
10524         for_each_intel_crtc(dev, intel_crtc) {
10525                 WARN_ON(intel_crtc->base.state->enable != intel_crtc_in_use(&intel_crtc->base));
10526                 WARN_ON(intel_crtc->new_config &&
10527                         intel_crtc->new_config != intel_crtc->config);
10528                 WARN_ON(intel_crtc->base.state->enable != !!intel_crtc->new_config);
10529         }
10530
10531         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
10532                 if (!connector->encoder || !connector->encoder->crtc)
10533                         continue;
10534
10535                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
10536
10537                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
10538                         struct drm_property *dpms_property =
10539                                 dev->mode_config.dpms_property;
10540
10541                         connector->dpms = DRM_MODE_DPMS_ON;
10542                         drm_object_property_set_value(&connector->base,
10543                                                          dpms_property,
10544                                                          DRM_MODE_DPMS_ON);
10545
10546                         intel_encoder = to_intel_encoder(connector->encoder);
10547                         intel_encoder->connectors_active = true;
10548                 }
10549         }
10550
10551 }
10552
10553 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10554 {
10555         int diff;
10556
10557         if (clock1 == clock2)
10558                 return true;
10559
10560         if (!clock1 || !clock2)
10561                 return false;
10562
10563         diff = abs(clock1 - clock2);
10564
10565         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10566                 return true;
10567
10568         return false;
10569 }
10570
10571 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
10572         list_for_each_entry((intel_crtc), \
10573                             &(dev)->mode_config.crtc_list, \
10574                             base.head) \
10575                 if (mask & (1 <<(intel_crtc)->pipe))
10576
10577 static bool
10578 intel_pipe_config_compare(struct drm_device *dev,
10579                           struct intel_crtc_state *current_config,
10580                           struct intel_crtc_state *pipe_config)
10581 {
10582 #define PIPE_CONF_CHECK_X(name) \
10583         if (current_config->name != pipe_config->name) { \
10584                 DRM_ERROR("mismatch in " #name " " \
10585                           "(expected 0x%08x, found 0x%08x)\n", \
10586                           current_config->name, \
10587                           pipe_config->name); \
10588                 return false; \
10589         }
10590
10591 #define PIPE_CONF_CHECK_I(name) \
10592         if (current_config->name != pipe_config->name) { \
10593                 DRM_ERROR("mismatch in " #name " " \
10594                           "(expected %i, found %i)\n", \
10595                           current_config->name, \
10596                           pipe_config->name); \
10597                 return false; \
10598         }
10599
10600 /* This is required for BDW+ where there is only one set of registers for
10601  * switching between high and low RR.
10602  * This macro can be used whenever a comparison has to be made between one
10603  * hw state and multiple sw state variables.
10604  */
10605 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
10606         if ((current_config->name != pipe_config->name) && \
10607                 (current_config->alt_name != pipe_config->name)) { \
10608                         DRM_ERROR("mismatch in " #name " " \
10609                                   "(expected %i or %i, found %i)\n", \
10610                                   current_config->name, \
10611                                   current_config->alt_name, \
10612                                   pipe_config->name); \
10613                         return false; \
10614         }
10615
10616 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
10617         if ((current_config->name ^ pipe_config->name) & (mask)) { \
10618                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
10619                           "(expected %i, found %i)\n", \
10620                           current_config->name & (mask), \
10621                           pipe_config->name & (mask)); \
10622                 return false; \
10623         }
10624
10625 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
10626         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
10627                 DRM_ERROR("mismatch in " #name " " \
10628                           "(expected %i, found %i)\n", \
10629                           current_config->name, \
10630                           pipe_config->name); \
10631                 return false; \
10632         }
10633
10634 #define PIPE_CONF_QUIRK(quirk)  \
10635         ((current_config->quirks | pipe_config->quirks) & (quirk))
10636
10637         PIPE_CONF_CHECK_I(cpu_transcoder);
10638
10639         PIPE_CONF_CHECK_I(has_pch_encoder);
10640         PIPE_CONF_CHECK_I(fdi_lanes);
10641         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
10642         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
10643         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
10644         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
10645         PIPE_CONF_CHECK_I(fdi_m_n.tu);
10646
10647         PIPE_CONF_CHECK_I(has_dp_encoder);
10648
10649         if (INTEL_INFO(dev)->gen < 8) {
10650                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
10651                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
10652                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
10653                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
10654                 PIPE_CONF_CHECK_I(dp_m_n.tu);
10655
10656                 if (current_config->has_drrs) {
10657                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
10658                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
10659                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
10660                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
10661                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
10662                 }
10663         } else {
10664                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
10665                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
10666                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
10667                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
10668                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
10669         }
10670
10671         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
10672         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
10673         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
10674         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
10675         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
10676         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
10677
10678         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
10679         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
10680         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
10681         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
10682         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
10683         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
10684
10685         PIPE_CONF_CHECK_I(pixel_multiplier);
10686         PIPE_CONF_CHECK_I(has_hdmi_sink);
10687         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
10688             IS_VALLEYVIEW(dev))
10689                 PIPE_CONF_CHECK_I(limited_color_range);
10690         PIPE_CONF_CHECK_I(has_infoframe);
10691
10692         PIPE_CONF_CHECK_I(has_audio);
10693
10694         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10695                               DRM_MODE_FLAG_INTERLACE);
10696
10697         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
10698                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10699                                       DRM_MODE_FLAG_PHSYNC);
10700                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10701                                       DRM_MODE_FLAG_NHSYNC);
10702                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10703                                       DRM_MODE_FLAG_PVSYNC);
10704                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
10705                                       DRM_MODE_FLAG_NVSYNC);
10706         }
10707
10708         PIPE_CONF_CHECK_I(pipe_src_w);
10709         PIPE_CONF_CHECK_I(pipe_src_h);
10710
10711         /*
10712          * FIXME: BIOS likes to set up a cloned config with lvds+external
10713          * screen. Since we don't yet re-compute the pipe config when moving
10714          * just the lvds port away to another pipe the sw tracking won't match.
10715          *
10716          * Proper atomic modesets with recomputed global state will fix this.
10717          * Until then just don't check gmch state for inherited modes.
10718          */
10719         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
10720                 PIPE_CONF_CHECK_I(gmch_pfit.control);
10721                 /* pfit ratios are autocomputed by the hw on gen4+ */
10722                 if (INTEL_INFO(dev)->gen < 4)
10723                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
10724                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
10725         }
10726
10727         PIPE_CONF_CHECK_I(pch_pfit.enabled);
10728         if (current_config->pch_pfit.enabled) {
10729                 PIPE_CONF_CHECK_I(pch_pfit.pos);
10730                 PIPE_CONF_CHECK_I(pch_pfit.size);
10731         }
10732
10733         /* BDW+ don't expose a synchronous way to read the state */
10734         if (IS_HASWELL(dev))
10735                 PIPE_CONF_CHECK_I(ips_enabled);
10736
10737         PIPE_CONF_CHECK_I(double_wide);
10738
10739         PIPE_CONF_CHECK_X(ddi_pll_sel);
10740
10741         PIPE_CONF_CHECK_I(shared_dpll);
10742         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
10743         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
10744         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
10745         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
10746         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
10747         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
10748         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
10749         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
10750
10751         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
10752                 PIPE_CONF_CHECK_I(pipe_bpp);
10753
10754         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
10755         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
10756
10757 #undef PIPE_CONF_CHECK_X
10758 #undef PIPE_CONF_CHECK_I
10759 #undef PIPE_CONF_CHECK_I_ALT
10760 #undef PIPE_CONF_CHECK_FLAGS
10761 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
10762 #undef PIPE_CONF_QUIRK
10763
10764         return true;
10765 }
10766
10767 static void check_wm_state(struct drm_device *dev)
10768 {
10769         struct drm_i915_private *dev_priv = dev->dev_private;
10770         struct skl_ddb_allocation hw_ddb, *sw_ddb;
10771         struct intel_crtc *intel_crtc;
10772         int plane;
10773
10774         if (INTEL_INFO(dev)->gen < 9)
10775                 return;
10776
10777         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
10778         sw_ddb = &dev_priv->wm.skl_hw.ddb;
10779
10780         for_each_intel_crtc(dev, intel_crtc) {
10781                 struct skl_ddb_entry *hw_entry, *sw_entry;
10782                 const enum pipe pipe = intel_crtc->pipe;
10783
10784                 if (!intel_crtc->active)
10785                         continue;
10786
10787                 /* planes */
10788                 for_each_plane(pipe, plane) {
10789                         hw_entry = &hw_ddb.plane[pipe][plane];
10790                         sw_entry = &sw_ddb->plane[pipe][plane];
10791
10792                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
10793                                 continue;
10794
10795                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
10796                                   "(expected (%u,%u), found (%u,%u))\n",
10797                                   pipe_name(pipe), plane + 1,
10798                                   sw_entry->start, sw_entry->end,
10799                                   hw_entry->start, hw_entry->end);
10800                 }
10801
10802                 /* cursor */
10803                 hw_entry = &hw_ddb.cursor[pipe];
10804                 sw_entry = &sw_ddb->cursor[pipe];
10805
10806                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
10807                         continue;
10808
10809                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
10810                           "(expected (%u,%u), found (%u,%u))\n",
10811                           pipe_name(pipe),
10812                           sw_entry->start, sw_entry->end,
10813                           hw_entry->start, hw_entry->end);
10814         }
10815 }
10816
10817 static void
10818 check_connector_state(struct drm_device *dev)
10819 {
10820         struct intel_connector *connector;
10821
10822         list_for_each_entry(connector, &dev->mode_config.connector_list,
10823                             base.head) {
10824                 /* This also checks the encoder/connector hw state with the
10825                  * ->get_hw_state callbacks. */
10826                 intel_connector_check_state(connector);
10827
10828                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
10829                      "connector's staged encoder doesn't match current encoder\n");
10830         }
10831 }
10832
10833 static void
10834 check_encoder_state(struct drm_device *dev)
10835 {
10836         struct intel_encoder *encoder;
10837         struct intel_connector *connector;
10838
10839         for_each_intel_encoder(dev, encoder) {
10840                 bool enabled = false;
10841                 bool active = false;
10842                 enum pipe pipe, tracked_pipe;
10843
10844                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
10845                               encoder->base.base.id,
10846                               encoder->base.name);
10847
10848                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
10849                      "encoder's stage crtc doesn't match current crtc\n");
10850                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
10851                      "encoder's active_connectors set, but no crtc\n");
10852
10853                 list_for_each_entry(connector, &dev->mode_config.connector_list,
10854                                     base.head) {
10855                         if (connector->base.encoder != &encoder->base)
10856                                 continue;
10857                         enabled = true;
10858                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
10859                                 active = true;
10860                 }
10861                 /*
10862                  * for MST connectors if we unplug the connector is gone
10863                  * away but the encoder is still connected to a crtc
10864                  * until a modeset happens in response to the hotplug.
10865                  */
10866                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
10867                         continue;
10868
10869                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
10870                      "encoder's enabled state mismatch "
10871                      "(expected %i, found %i)\n",
10872                      !!encoder->base.crtc, enabled);
10873                 I915_STATE_WARN(active && !encoder->base.crtc,
10874                      "active encoder with no crtc\n");
10875
10876                 I915_STATE_WARN(encoder->connectors_active != active,
10877                      "encoder's computed active state doesn't match tracked active state "
10878                      "(expected %i, found %i)\n", active, encoder->connectors_active);
10879
10880                 active = encoder->get_hw_state(encoder, &pipe);
10881                 I915_STATE_WARN(active != encoder->connectors_active,
10882                      "encoder's hw state doesn't match sw tracking "
10883                      "(expected %i, found %i)\n",
10884                      encoder->connectors_active, active);
10885
10886                 if (!encoder->base.crtc)
10887                         continue;
10888
10889                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
10890                 I915_STATE_WARN(active && pipe != tracked_pipe,
10891                      "active encoder's pipe doesn't match"
10892                      "(expected %i, found %i)\n",
10893                      tracked_pipe, pipe);
10894
10895         }
10896 }
10897
10898 static void
10899 check_crtc_state(struct drm_device *dev)
10900 {
10901         struct drm_i915_private *dev_priv = dev->dev_private;
10902         struct intel_crtc *crtc;
10903         struct intel_encoder *encoder;
10904         struct intel_crtc_state pipe_config;
10905
10906         for_each_intel_crtc(dev, crtc) {
10907                 bool enabled = false;
10908                 bool active = false;
10909
10910                 memset(&pipe_config, 0, sizeof(pipe_config));
10911
10912                 DRM_DEBUG_KMS("[CRTC:%d]\n",
10913                               crtc->base.base.id);
10914
10915                 I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
10916                      "active crtc, but not enabled in sw tracking\n");
10917
10918                 for_each_intel_encoder(dev, encoder) {
10919                         if (encoder->base.crtc != &crtc->base)
10920                                 continue;
10921                         enabled = true;
10922                         if (encoder->connectors_active)
10923                                 active = true;
10924                 }
10925
10926                 I915_STATE_WARN(active != crtc->active,
10927                      "crtc's computed active state doesn't match tracked active state "
10928                      "(expected %i, found %i)\n", active, crtc->active);
10929                 I915_STATE_WARN(enabled != crtc->base.state->enable,
10930                      "crtc's computed enabled state doesn't match tracked enabled state "
10931                      "(expected %i, found %i)\n", enabled,
10932                                 crtc->base.state->enable);
10933
10934                 active = dev_priv->display.get_pipe_config(crtc,
10935                                                            &pipe_config);
10936
10937                 /* hw state is inconsistent with the pipe quirk */
10938                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
10939                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
10940                         active = crtc->active;
10941
10942                 for_each_intel_encoder(dev, encoder) {
10943                         enum pipe pipe;
10944                         if (encoder->base.crtc != &crtc->base)
10945                                 continue;
10946                         if (encoder->get_hw_state(encoder, &pipe))
10947                                 encoder->get_config(encoder, &pipe_config);
10948                 }
10949
10950                 I915_STATE_WARN(crtc->active != active,
10951                      "crtc active state doesn't match with hw state "
10952                      "(expected %i, found %i)\n", crtc->active, active);
10953
10954                 if (active &&
10955                     !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
10956                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
10957                         intel_dump_pipe_config(crtc, &pipe_config,
10958                                                "[hw state]");
10959                         intel_dump_pipe_config(crtc, crtc->config,
10960                                                "[sw state]");
10961                 }
10962         }
10963 }
10964
10965 static void
10966 check_shared_dpll_state(struct drm_device *dev)
10967 {
10968         struct drm_i915_private *dev_priv = dev->dev_private;
10969         struct intel_crtc *crtc;
10970         struct intel_dpll_hw_state dpll_hw_state;
10971         int i;
10972
10973         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
10974                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
10975                 int enabled_crtcs = 0, active_crtcs = 0;
10976                 bool active;
10977
10978                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
10979
10980                 DRM_DEBUG_KMS("%s\n", pll->name);
10981
10982                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
10983
10984                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
10985                      "more active pll users than references: %i vs %i\n",
10986                      pll->active, hweight32(pll->config.crtc_mask));
10987                 I915_STATE_WARN(pll->active && !pll->on,
10988                      "pll in active use but not on in sw tracking\n");
10989                 I915_STATE_WARN(pll->on && !pll->active,
10990                      "pll in on but not on in use in sw tracking\n");
10991                 I915_STATE_WARN(pll->on != active,
10992                      "pll on state mismatch (expected %i, found %i)\n",
10993                      pll->on, active);
10994
10995                 for_each_intel_crtc(dev, crtc) {
10996                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
10997                                 enabled_crtcs++;
10998                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
10999                                 active_crtcs++;
11000                 }
11001                 I915_STATE_WARN(pll->active != active_crtcs,
11002                      "pll active crtcs mismatch (expected %i, found %i)\n",
11003                      pll->active, active_crtcs);
11004                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
11005                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
11006                      hweight32(pll->config.crtc_mask), enabled_crtcs);
11007
11008                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
11009                                        sizeof(dpll_hw_state)),
11010                      "pll hw state mismatch\n");
11011         }
11012 }
11013
11014 void
11015 intel_modeset_check_state(struct drm_device *dev)
11016 {
11017         check_wm_state(dev);
11018         check_connector_state(dev);
11019         check_encoder_state(dev);
11020         check_crtc_state(dev);
11021         check_shared_dpll_state(dev);
11022 }
11023
11024 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
11025                                      int dotclock)
11026 {
11027         /*
11028          * FDI already provided one idea for the dotclock.
11029          * Yell if the encoder disagrees.
11030          */
11031         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
11032              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11033              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
11034 }
11035
11036 static void update_scanline_offset(struct intel_crtc *crtc)
11037 {
11038         struct drm_device *dev = crtc->base.dev;
11039
11040         /*
11041          * The scanline counter increments at the leading edge of hsync.
11042          *
11043          * On most platforms it starts counting from vtotal-1 on the
11044          * first active line. That means the scanline counter value is
11045          * always one less than what we would expect. Ie. just after
11046          * start of vblank, which also occurs at start of hsync (on the
11047          * last active line), the scanline counter will read vblank_start-1.
11048          *
11049          * On gen2 the scanline counter starts counting from 1 instead
11050          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11051          * to keep the value positive), instead of adding one.
11052          *
11053          * On HSW+ the behaviour of the scanline counter depends on the output
11054          * type. For DP ports it behaves like most other platforms, but on HDMI
11055          * there's an extra 1 line difference. So we need to add two instead of
11056          * one to the value.
11057          */
11058         if (IS_GEN2(dev)) {
11059                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
11060                 int vtotal;
11061
11062                 vtotal = mode->crtc_vtotal;
11063                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
11064                         vtotal /= 2;
11065
11066                 crtc->scanline_offset = vtotal - 1;
11067         } else if (HAS_DDI(dev) &&
11068                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
11069                 crtc->scanline_offset = 2;
11070         } else
11071                 crtc->scanline_offset = 1;
11072 }
11073
11074 static struct intel_crtc_state *
11075 intel_modeset_compute_config(struct drm_crtc *crtc,
11076                              struct drm_display_mode *mode,
11077                              struct drm_framebuffer *fb,
11078                              unsigned *modeset_pipes,
11079                              unsigned *prepare_pipes,
11080                              unsigned *disable_pipes)
11081 {
11082         struct intel_crtc_state *pipe_config = NULL;
11083
11084         intel_modeset_affected_pipes(crtc, modeset_pipes,
11085                                      prepare_pipes, disable_pipes);
11086
11087         if ((*modeset_pipes) == 0)
11088                 goto out;
11089
11090         /*
11091          * Note this needs changes when we start tracking multiple modes
11092          * and crtcs.  At that point we'll need to compute the whole config
11093          * (i.e. one pipe_config for each crtc) rather than just the one
11094          * for this crtc.
11095          */
11096         pipe_config = intel_modeset_pipe_config(crtc, fb, mode);
11097         if (IS_ERR(pipe_config)) {
11098                 goto out;
11099         }
11100         intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
11101                                "[modeset]");
11102
11103 out:
11104         return pipe_config;
11105 }
11106
11107 static int __intel_set_mode_setup_plls(struct drm_device *dev,
11108                                        unsigned modeset_pipes,
11109                                        unsigned disable_pipes)
11110 {
11111         struct drm_i915_private *dev_priv = to_i915(dev);
11112         unsigned clear_pipes = modeset_pipes | disable_pipes;
11113         struct intel_crtc *intel_crtc;
11114         int ret = 0;
11115
11116         if (!dev_priv->display.crtc_compute_clock)
11117                 return 0;
11118
11119         ret = intel_shared_dpll_start_config(dev_priv, clear_pipes);
11120         if (ret)
11121                 goto done;
11122
11123         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11124                 struct intel_crtc_state *state = intel_crtc->new_config;
11125                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11126                                                            state);
11127                 if (ret) {
11128                         intel_shared_dpll_abort_config(dev_priv);
11129                         goto done;
11130                 }
11131         }
11132
11133 done:
11134         return ret;
11135 }
11136
11137 static int __intel_set_mode(struct drm_crtc *crtc,
11138                             struct drm_display_mode *mode,
11139                             int x, int y, struct drm_framebuffer *fb,
11140                             struct intel_crtc_state *pipe_config,
11141                             unsigned modeset_pipes,
11142                             unsigned prepare_pipes,
11143                             unsigned disable_pipes)
11144 {
11145         struct drm_device *dev = crtc->dev;
11146         struct drm_i915_private *dev_priv = dev->dev_private;
11147         struct drm_display_mode *saved_mode;
11148         struct intel_crtc *intel_crtc;
11149         int ret = 0;
11150
11151         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
11152         if (!saved_mode)
11153                 return -ENOMEM;
11154
11155         *saved_mode = crtc->mode;
11156
11157         if (modeset_pipes)
11158                 to_intel_crtc(crtc)->new_config = pipe_config;
11159
11160         /*
11161          * See if the config requires any additional preparation, e.g.
11162          * to adjust global state with pipes off.  We need to do this
11163          * here so we can get the modeset_pipe updated config for the new
11164          * mode set on this crtc.  For other crtcs we need to use the
11165          * adjusted_mode bits in the crtc directly.
11166          */
11167         if (IS_VALLEYVIEW(dev)) {
11168                 valleyview_modeset_global_pipes(dev, &prepare_pipes);
11169
11170                 /* may have added more to prepare_pipes than we should */
11171                 prepare_pipes &= ~disable_pipes;
11172         }
11173
11174         ret = __intel_set_mode_setup_plls(dev, modeset_pipes, disable_pipes);
11175         if (ret)
11176                 goto done;
11177
11178         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
11179                 intel_crtc_disable(&intel_crtc->base);
11180
11181         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11182                 if (intel_crtc->base.state->enable)
11183                         dev_priv->display.crtc_disable(&intel_crtc->base);
11184         }
11185
11186         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
11187          * to set it here already despite that we pass it down the callchain.
11188          *
11189          * Note we'll need to fix this up when we start tracking multiple
11190          * pipes; here we assume a single modeset_pipe and only track the
11191          * single crtc and mode.
11192          */
11193         if (modeset_pipes) {
11194                 crtc->mode = *mode;
11195                 /* mode_set/enable/disable functions rely on a correct pipe
11196                  * config. */
11197                 intel_crtc_set_state(to_intel_crtc(crtc), pipe_config);
11198
11199                 /*
11200                  * Calculate and store various constants which
11201                  * are later needed by vblank and swap-completion
11202                  * timestamping. They are derived from true hwmode.
11203                  */
11204                 drm_calc_timestamping_constants(crtc,
11205                                                 &pipe_config->base.adjusted_mode);
11206         }
11207
11208         /* Only after disabling all output pipelines that will be changed can we
11209          * update the the output configuration. */
11210         intel_modeset_update_state(dev, prepare_pipes);
11211
11212         modeset_update_crtc_power_domains(dev);
11213
11214         /* Set up the DPLL and any encoders state that needs to adjust or depend
11215          * on the DPLL.
11216          */
11217         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
11218                 struct drm_plane *primary = intel_crtc->base.primary;
11219                 int vdisplay, hdisplay;
11220
11221                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11222                 ret = primary->funcs->update_plane(primary, &intel_crtc->base,
11223                                                    fb, 0, 0,
11224                                                    hdisplay, vdisplay,
11225                                                    x << 16, y << 16,
11226                                                    hdisplay << 16, vdisplay << 16);
11227         }
11228
11229         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
11230         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
11231                 update_scanline_offset(intel_crtc);
11232
11233                 dev_priv->display.crtc_enable(&intel_crtc->base);
11234         }
11235
11236         /* FIXME: add subpixel order */
11237 done:
11238         if (ret && crtc->state->enable)
11239                 crtc->mode = *saved_mode;
11240
11241         kfree(saved_mode);
11242         return ret;
11243 }
11244
11245 static int intel_set_mode_pipes(struct drm_crtc *crtc,
11246                                 struct drm_display_mode *mode,
11247                                 int x, int y, struct drm_framebuffer *fb,
11248                                 struct intel_crtc_state *pipe_config,
11249                                 unsigned modeset_pipes,
11250                                 unsigned prepare_pipes,
11251                                 unsigned disable_pipes)
11252 {
11253         int ret;
11254
11255         ret = __intel_set_mode(crtc, mode, x, y, fb, pipe_config, modeset_pipes,
11256                                prepare_pipes, disable_pipes);
11257
11258         if (ret == 0)
11259                 intel_modeset_check_state(crtc->dev);
11260
11261         return ret;
11262 }
11263
11264 static int intel_set_mode(struct drm_crtc *crtc,
11265                           struct drm_display_mode *mode,
11266                           int x, int y, struct drm_framebuffer *fb)
11267 {
11268         struct intel_crtc_state *pipe_config;
11269         unsigned modeset_pipes, prepare_pipes, disable_pipes;
11270
11271         pipe_config = intel_modeset_compute_config(crtc, mode, fb,
11272                                                    &modeset_pipes,
11273                                                    &prepare_pipes,
11274                                                    &disable_pipes);
11275
11276         if (IS_ERR(pipe_config))
11277                 return PTR_ERR(pipe_config);
11278
11279         return intel_set_mode_pipes(crtc, mode, x, y, fb, pipe_config,
11280                                     modeset_pipes, prepare_pipes,
11281                                     disable_pipes);
11282 }
11283
11284 void intel_crtc_restore_mode(struct drm_crtc *crtc)
11285 {
11286         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb);
11287 }
11288
11289 #undef for_each_intel_crtc_masked
11290
11291 static void intel_set_config_free(struct intel_set_config *config)
11292 {
11293         if (!config)
11294                 return;
11295
11296         kfree(config->save_connector_encoders);
11297         kfree(config->save_encoder_crtcs);
11298         kfree(config->save_crtc_enabled);
11299         kfree(config);
11300 }
11301
11302 static int intel_set_config_save_state(struct drm_device *dev,
11303                                        struct intel_set_config *config)
11304 {
11305         struct drm_crtc *crtc;
11306         struct drm_encoder *encoder;
11307         struct drm_connector *connector;
11308         int count;
11309
11310         config->save_crtc_enabled =
11311                 kcalloc(dev->mode_config.num_crtc,
11312                         sizeof(bool), GFP_KERNEL);
11313         if (!config->save_crtc_enabled)
11314                 return -ENOMEM;
11315
11316         config->save_encoder_crtcs =
11317                 kcalloc(dev->mode_config.num_encoder,
11318                         sizeof(struct drm_crtc *), GFP_KERNEL);
11319         if (!config->save_encoder_crtcs)
11320                 return -ENOMEM;
11321
11322         config->save_connector_encoders =
11323                 kcalloc(dev->mode_config.num_connector,
11324                         sizeof(struct drm_encoder *), GFP_KERNEL);
11325         if (!config->save_connector_encoders)
11326                 return -ENOMEM;
11327
11328         /* Copy data. Note that driver private data is not affected.
11329          * Should anything bad happen only the expected state is
11330          * restored, not the drivers personal bookkeeping.
11331          */
11332         count = 0;
11333         for_each_crtc(dev, crtc) {
11334                 config->save_crtc_enabled[count++] = crtc->state->enable;
11335         }
11336
11337         count = 0;
11338         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
11339                 config->save_encoder_crtcs[count++] = encoder->crtc;
11340         }
11341
11342         count = 0;
11343         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
11344                 config->save_connector_encoders[count++] = connector->encoder;
11345         }
11346
11347         return 0;
11348 }
11349
11350 static void intel_set_config_restore_state(struct drm_device *dev,
11351                                            struct intel_set_config *config)
11352 {
11353         struct intel_crtc *crtc;
11354         struct intel_encoder *encoder;
11355         struct intel_connector *connector;
11356         int count;
11357
11358         count = 0;
11359         for_each_intel_crtc(dev, crtc) {
11360                 crtc->new_enabled = config->save_crtc_enabled[count++];
11361
11362                 if (crtc->new_enabled)
11363                         crtc->new_config = crtc->config;
11364                 else
11365                         crtc->new_config = NULL;
11366         }
11367
11368         count = 0;
11369         for_each_intel_encoder(dev, encoder) {
11370                 encoder->new_crtc =
11371                         to_intel_crtc(config->save_encoder_crtcs[count++]);
11372         }
11373
11374         count = 0;
11375         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
11376                 connector->new_encoder =
11377                         to_intel_encoder(config->save_connector_encoders[count++]);
11378         }
11379 }
11380
11381 static bool
11382 is_crtc_connector_off(struct drm_mode_set *set)
11383 {
11384         int i;
11385
11386         if (set->num_connectors == 0)
11387                 return false;
11388
11389         if (WARN_ON(set->connectors == NULL))
11390                 return false;
11391
11392         for (i = 0; i < set->num_connectors; i++)
11393                 if (set->connectors[i]->encoder &&
11394                     set->connectors[i]->encoder->crtc == set->crtc &&
11395                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
11396                         return true;
11397
11398         return false;
11399 }
11400
11401 static void
11402 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
11403                                       struct intel_set_config *config)
11404 {
11405
11406         /* We should be able to check here if the fb has the same properties
11407          * and then just flip_or_move it */
11408         if (is_crtc_connector_off(set)) {
11409                 config->mode_changed = true;
11410         } else if (set->crtc->primary->fb != set->fb) {
11411                 /*
11412                  * If we have no fb, we can only flip as long as the crtc is
11413                  * active, otherwise we need a full mode set.  The crtc may
11414                  * be active if we've only disabled the primary plane, or
11415                  * in fastboot situations.
11416                  */
11417                 if (set->crtc->primary->fb == NULL) {
11418                         struct intel_crtc *intel_crtc =
11419                                 to_intel_crtc(set->crtc);
11420
11421                         if (intel_crtc->active) {
11422                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
11423                                 config->fb_changed = true;
11424                         } else {
11425                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
11426                                 config->mode_changed = true;
11427                         }
11428                 } else if (set->fb == NULL) {
11429                         config->mode_changed = true;
11430                 } else if (set->fb->pixel_format !=
11431                            set->crtc->primary->fb->pixel_format) {
11432                         config->mode_changed = true;
11433                 } else {
11434                         config->fb_changed = true;
11435                 }
11436         }
11437
11438         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
11439                 config->fb_changed = true;
11440
11441         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
11442                 DRM_DEBUG_KMS("modes are different, full mode set\n");
11443                 drm_mode_debug_printmodeline(&set->crtc->mode);
11444                 drm_mode_debug_printmodeline(set->mode);
11445                 config->mode_changed = true;
11446         }
11447
11448         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
11449                         set->crtc->base.id, config->mode_changed, config->fb_changed);
11450 }
11451
11452 static int
11453 intel_modeset_stage_output_state(struct drm_device *dev,
11454                                  struct drm_mode_set *set,
11455                                  struct intel_set_config *config)
11456 {
11457         struct intel_connector *connector;
11458         struct intel_encoder *encoder;
11459         struct intel_crtc *crtc;
11460         int ro;
11461
11462         /* The upper layers ensure that we either disable a crtc or have a list
11463          * of connectors. For paranoia, double-check this. */
11464         WARN_ON(!set->fb && (set->num_connectors != 0));
11465         WARN_ON(set->fb && (set->num_connectors == 0));
11466
11467         list_for_each_entry(connector, &dev->mode_config.connector_list,
11468                             base.head) {
11469                 /* Otherwise traverse passed in connector list and get encoders
11470                  * for them. */
11471                 for (ro = 0; ro < set->num_connectors; ro++) {
11472                         if (set->connectors[ro] == &connector->base) {
11473                                 connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
11474                                 break;
11475                         }
11476                 }
11477
11478                 /* If we disable the crtc, disable all its connectors. Also, if
11479                  * the connector is on the changing crtc but not on the new
11480                  * connector list, disable it. */
11481                 if ((!set->fb || ro == set->num_connectors) &&
11482                     connector->base.encoder &&
11483                     connector->base.encoder->crtc == set->crtc) {
11484                         connector->new_encoder = NULL;
11485
11486                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
11487                                 connector->base.base.id,
11488                                 connector->base.name);
11489                 }
11490
11491
11492                 if (&connector->new_encoder->base != connector->base.encoder) {
11493                         DRM_DEBUG_KMS("encoder changed, full mode switch\n");
11494                         config->mode_changed = true;
11495                 }
11496         }
11497         /* connector->new_encoder is now updated for all connectors. */
11498
11499         /* Update crtc of enabled connectors. */
11500         list_for_each_entry(connector, &dev->mode_config.connector_list,
11501                             base.head) {
11502                 struct drm_crtc *new_crtc;
11503
11504                 if (!connector->new_encoder)
11505                         continue;
11506
11507                 new_crtc = connector->new_encoder->base.crtc;
11508
11509                 for (ro = 0; ro < set->num_connectors; ro++) {
11510                         if (set->connectors[ro] == &connector->base)
11511                                 new_crtc = set->crtc;
11512                 }
11513
11514                 /* Make sure the new CRTC will work with the encoder */
11515                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
11516                                          new_crtc)) {
11517                         return -EINVAL;
11518                 }
11519                 connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
11520
11521                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
11522                         connector->base.base.id,
11523                         connector->base.name,
11524                         new_crtc->base.id);
11525         }
11526
11527         /* Check for any encoders that needs to be disabled. */
11528         for_each_intel_encoder(dev, encoder) {
11529                 int num_connectors = 0;
11530                 list_for_each_entry(connector,
11531                                     &dev->mode_config.connector_list,
11532                                     base.head) {
11533                         if (connector->new_encoder == encoder) {
11534                                 WARN_ON(!connector->new_encoder->new_crtc);
11535                                 num_connectors++;
11536                         }
11537                 }
11538
11539                 if (num_connectors == 0)
11540                         encoder->new_crtc = NULL;
11541                 else if (num_connectors > 1)
11542                         return -EINVAL;
11543
11544                 /* Only now check for crtc changes so we don't miss encoders
11545                  * that will be disabled. */
11546                 if (&encoder->new_crtc->base != encoder->base.crtc) {
11547                         DRM_DEBUG_KMS("crtc changed, full mode switch\n");
11548                         config->mode_changed = true;
11549                 }
11550         }
11551         /* Now we've also updated encoder->new_crtc for all encoders. */
11552         list_for_each_entry(connector, &dev->mode_config.connector_list,
11553                             base.head) {
11554                 if (connector->new_encoder)
11555                         if (connector->new_encoder != connector->encoder)
11556                                 connector->encoder = connector->new_encoder;
11557         }
11558         for_each_intel_crtc(dev, crtc) {
11559                 crtc->new_enabled = false;
11560
11561                 for_each_intel_encoder(dev, encoder) {
11562                         if (encoder->new_crtc == crtc) {
11563                                 crtc->new_enabled = true;
11564                                 break;
11565                         }
11566                 }
11567
11568                 if (crtc->new_enabled != crtc->base.state->enable) {
11569                         DRM_DEBUG_KMS("crtc %sabled, full mode switch\n",
11570                                       crtc->new_enabled ? "en" : "dis");
11571                         config->mode_changed = true;
11572                 }
11573
11574                 if (crtc->new_enabled)
11575                         crtc->new_config = crtc->config;
11576                 else
11577                         crtc->new_config = NULL;
11578         }
11579
11580         return 0;
11581 }
11582
11583 static void disable_crtc_nofb(struct intel_crtc *crtc)
11584 {
11585         struct drm_device *dev = crtc->base.dev;
11586         struct intel_encoder *encoder;
11587         struct intel_connector *connector;
11588
11589         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
11590                       pipe_name(crtc->pipe));
11591
11592         list_for_each_entry(connector, &dev->mode_config.connector_list, base.head) {
11593                 if (connector->new_encoder &&
11594                     connector->new_encoder->new_crtc == crtc)
11595                         connector->new_encoder = NULL;
11596         }
11597
11598         for_each_intel_encoder(dev, encoder) {
11599                 if (encoder->new_crtc == crtc)
11600                         encoder->new_crtc = NULL;
11601         }
11602
11603         crtc->new_enabled = false;
11604         crtc->new_config = NULL;
11605 }
11606
11607 static int intel_crtc_set_config(struct drm_mode_set *set)
11608 {
11609         struct drm_device *dev;
11610         struct drm_mode_set save_set;
11611         struct intel_set_config *config;
11612         struct intel_crtc_state *pipe_config;
11613         unsigned modeset_pipes, prepare_pipes, disable_pipes;
11614         int ret;
11615
11616         BUG_ON(!set);
11617         BUG_ON(!set->crtc);
11618         BUG_ON(!set->crtc->helper_private);
11619
11620         /* Enforce sane interface api - has been abused by the fb helper. */
11621         BUG_ON(!set->mode && set->fb);
11622         BUG_ON(set->fb && set->num_connectors == 0);
11623
11624         if (set->fb) {
11625                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
11626                                 set->crtc->base.id, set->fb->base.id,
11627                                 (int)set->num_connectors, set->x, set->y);
11628         } else {
11629                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
11630         }
11631
11632         dev = set->crtc->dev;
11633
11634         ret = -ENOMEM;
11635         config = kzalloc(sizeof(*config), GFP_KERNEL);
11636         if (!config)
11637                 goto out_config;
11638
11639         ret = intel_set_config_save_state(dev, config);
11640         if (ret)
11641                 goto out_config;
11642
11643         save_set.crtc = set->crtc;
11644         save_set.mode = &set->crtc->mode;
11645         save_set.x = set->crtc->x;
11646         save_set.y = set->crtc->y;
11647         save_set.fb = set->crtc->primary->fb;
11648
11649         /* Compute whether we need a full modeset, only an fb base update or no
11650          * change at all. In the future we might also check whether only the
11651          * mode changed, e.g. for LVDS where we only change the panel fitter in
11652          * such cases. */
11653         intel_set_config_compute_mode_changes(set, config);
11654
11655         ret = intel_modeset_stage_output_state(dev, set, config);
11656         if (ret)
11657                 goto fail;
11658
11659         pipe_config = intel_modeset_compute_config(set->crtc, set->mode,
11660                                                    set->fb,
11661                                                    &modeset_pipes,
11662                                                    &prepare_pipes,
11663                                                    &disable_pipes);
11664         if (IS_ERR(pipe_config)) {
11665                 ret = PTR_ERR(pipe_config);
11666                 goto fail;
11667         } else if (pipe_config) {
11668                 if (pipe_config->has_audio !=
11669                     to_intel_crtc(set->crtc)->config->has_audio)
11670                         config->mode_changed = true;
11671
11672                 /*
11673                  * Note we have an issue here with infoframes: current code
11674                  * only updates them on the full mode set path per hw
11675                  * requirements.  So here we should be checking for any
11676                  * required changes and forcing a mode set.
11677                  */
11678         }
11679
11680         /* set_mode will free it in the mode_changed case */
11681         if (!config->mode_changed)
11682                 kfree(pipe_config);
11683
11684         intel_update_pipe_size(to_intel_crtc(set->crtc));
11685
11686         if (config->mode_changed) {
11687                 ret = intel_set_mode_pipes(set->crtc, set->mode,
11688                                            set->x, set->y, set->fb, pipe_config,
11689                                            modeset_pipes, prepare_pipes,
11690                                            disable_pipes);
11691         } else if (config->fb_changed) {
11692                 struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
11693                 struct drm_plane *primary = set->crtc->primary;
11694                 int vdisplay, hdisplay;
11695
11696                 drm_crtc_get_hv_timing(set->mode, &hdisplay, &vdisplay);
11697                 ret = primary->funcs->update_plane(primary, set->crtc, set->fb,
11698                                                    0, 0, hdisplay, vdisplay,
11699                                                    set->x << 16, set->y << 16,
11700                                                    hdisplay << 16, vdisplay << 16);
11701
11702                 /*
11703                  * We need to make sure the primary plane is re-enabled if it
11704                  * has previously been turned off.
11705                  */
11706                 if (!intel_crtc->primary_enabled && ret == 0) {
11707                         WARN_ON(!intel_crtc->active);
11708                         intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
11709                 }
11710
11711                 /*
11712                  * In the fastboot case this may be our only check of the
11713                  * state after boot.  It would be better to only do it on
11714                  * the first update, but we don't have a nice way of doing that
11715                  * (and really, set_config isn't used much for high freq page
11716                  * flipping, so increasing its cost here shouldn't be a big
11717                  * deal).
11718                  */
11719                 if (i915.fastboot && ret == 0)
11720                         intel_modeset_check_state(set->crtc->dev);
11721         }
11722
11723         if (ret) {
11724                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
11725                               set->crtc->base.id, ret);
11726 fail:
11727                 intel_set_config_restore_state(dev, config);
11728
11729                 /*
11730                  * HACK: if the pipe was on, but we didn't have a framebuffer,
11731                  * force the pipe off to avoid oopsing in the modeset code
11732                  * due to fb==NULL. This should only happen during boot since
11733                  * we don't yet reconstruct the FB from the hardware state.
11734                  */
11735                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
11736                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
11737
11738                 /* Try to restore the config */
11739                 if (config->mode_changed &&
11740                     intel_set_mode(save_set.crtc, save_set.mode,
11741                                    save_set.x, save_set.y, save_set.fb))
11742                         DRM_ERROR("failed to restore config after modeset failure\n");
11743         }
11744
11745 out_config:
11746         intel_set_config_free(config);
11747         return ret;
11748 }
11749
11750 static const struct drm_crtc_funcs intel_crtc_funcs = {
11751         .gamma_set = intel_crtc_gamma_set,
11752         .set_config = intel_crtc_set_config,
11753         .destroy = intel_crtc_destroy,
11754         .page_flip = intel_crtc_page_flip,
11755         .atomic_duplicate_state = intel_crtc_duplicate_state,
11756         .atomic_destroy_state = intel_crtc_destroy_state,
11757 };
11758
11759 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
11760                                       struct intel_shared_dpll *pll,
11761                                       struct intel_dpll_hw_state *hw_state)
11762 {
11763         uint32_t val;
11764
11765         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
11766                 return false;
11767
11768         val = I915_READ(PCH_DPLL(pll->id));
11769         hw_state->dpll = val;
11770         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
11771         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
11772
11773         return val & DPLL_VCO_ENABLE;
11774 }
11775
11776 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
11777                                   struct intel_shared_dpll *pll)
11778 {
11779         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
11780         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
11781 }
11782
11783 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
11784                                 struct intel_shared_dpll *pll)
11785 {
11786         /* PCH refclock must be enabled first */
11787         ibx_assert_pch_refclk_enabled(dev_priv);
11788
11789         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
11790
11791         /* Wait for the clocks to stabilize. */
11792         POSTING_READ(PCH_DPLL(pll->id));
11793         udelay(150);
11794
11795         /* The pixel multiplier can only be updated once the
11796          * DPLL is enabled and the clocks are stable.
11797          *
11798          * So write it again.
11799          */
11800         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
11801         POSTING_READ(PCH_DPLL(pll->id));
11802         udelay(200);
11803 }
11804
11805 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
11806                                  struct intel_shared_dpll *pll)
11807 {
11808         struct drm_device *dev = dev_priv->dev;
11809         struct intel_crtc *crtc;
11810
11811         /* Make sure no transcoder isn't still depending on us. */
11812         for_each_intel_crtc(dev, crtc) {
11813                 if (intel_crtc_to_shared_dpll(crtc) == pll)
11814                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
11815         }
11816
11817         I915_WRITE(PCH_DPLL(pll->id), 0);
11818         POSTING_READ(PCH_DPLL(pll->id));
11819         udelay(200);
11820 }
11821
11822 static char *ibx_pch_dpll_names[] = {
11823         "PCH DPLL A",
11824         "PCH DPLL B",
11825 };
11826
11827 static void ibx_pch_dpll_init(struct drm_device *dev)
11828 {
11829         struct drm_i915_private *dev_priv = dev->dev_private;
11830         int i;
11831
11832         dev_priv->num_shared_dpll = 2;
11833
11834         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11835                 dev_priv->shared_dplls[i].id = i;
11836                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
11837                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
11838                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
11839                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
11840                 dev_priv->shared_dplls[i].get_hw_state =
11841                         ibx_pch_dpll_get_hw_state;
11842         }
11843 }
11844
11845 static void intel_shared_dpll_init(struct drm_device *dev)
11846 {
11847         struct drm_i915_private *dev_priv = dev->dev_private;
11848
11849         if (HAS_DDI(dev))
11850                 intel_ddi_pll_init(dev);
11851         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
11852                 ibx_pch_dpll_init(dev);
11853         else
11854                 dev_priv->num_shared_dpll = 0;
11855
11856         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
11857 }
11858
11859 /**
11860  * intel_prepare_plane_fb - Prepare fb for usage on plane
11861  * @plane: drm plane to prepare for
11862  * @fb: framebuffer to prepare for presentation
11863  *
11864  * Prepares a framebuffer for usage on a display plane.  Generally this
11865  * involves pinning the underlying object and updating the frontbuffer tracking
11866  * bits.  Some older platforms need special physical address handling for
11867  * cursor planes.
11868  *
11869  * Returns 0 on success, negative error code on failure.
11870  */
11871 int
11872 intel_prepare_plane_fb(struct drm_plane *plane,
11873                        struct drm_framebuffer *fb)
11874 {
11875         struct drm_device *dev = plane->dev;
11876         struct intel_plane *intel_plane = to_intel_plane(plane);
11877         enum pipe pipe = intel_plane->pipe;
11878         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11879         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
11880         unsigned frontbuffer_bits = 0;
11881         int ret = 0;
11882
11883         if (!obj)
11884                 return 0;
11885
11886         switch (plane->type) {
11887         case DRM_PLANE_TYPE_PRIMARY:
11888                 frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
11889                 break;
11890         case DRM_PLANE_TYPE_CURSOR:
11891                 frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
11892                 break;
11893         case DRM_PLANE_TYPE_OVERLAY:
11894                 frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
11895                 break;
11896         }
11897
11898         mutex_lock(&dev->struct_mutex);
11899
11900         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11901             INTEL_INFO(dev)->cursor_needs_physical) {
11902                 int align = IS_I830(dev) ? 16 * 1024 : 256;
11903                 ret = i915_gem_object_attach_phys(obj, align);
11904                 if (ret)
11905                         DRM_DEBUG_KMS("failed to attach phys object\n");
11906         } else {
11907                 ret = intel_pin_and_fence_fb_obj(plane, fb, NULL);
11908         }
11909
11910         if (ret == 0)
11911                 i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
11912
11913         mutex_unlock(&dev->struct_mutex);
11914
11915         return ret;
11916 }
11917
11918 /**
11919  * intel_cleanup_plane_fb - Cleans up an fb after plane use
11920  * @plane: drm plane to clean up for
11921  * @fb: old framebuffer that was on plane
11922  *
11923  * Cleans up a framebuffer that has just been removed from a plane.
11924  */
11925 void
11926 intel_cleanup_plane_fb(struct drm_plane *plane,
11927                        struct drm_framebuffer *fb)
11928 {
11929         struct drm_device *dev = plane->dev;
11930         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11931
11932         if (WARN_ON(!obj))
11933                 return;
11934
11935         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
11936             !INTEL_INFO(dev)->cursor_needs_physical) {
11937                 mutex_lock(&dev->struct_mutex);
11938                 intel_unpin_fb_obj(obj);
11939                 mutex_unlock(&dev->struct_mutex);
11940         }
11941 }
11942
11943 static int
11944 intel_check_primary_plane(struct drm_plane *plane,
11945                           struct intel_plane_state *state)
11946 {
11947         struct drm_device *dev = plane->dev;
11948         struct drm_i915_private *dev_priv = dev->dev_private;
11949         struct drm_crtc *crtc = state->base.crtc;
11950         struct intel_crtc *intel_crtc;
11951         struct drm_framebuffer *fb = state->base.fb;
11952         struct drm_rect *dest = &state->dst;
11953         struct drm_rect *src = &state->src;
11954         const struct drm_rect *clip = &state->clip;
11955         int ret;
11956
11957         crtc = crtc ? crtc : plane->crtc;
11958         intel_crtc = to_intel_crtc(crtc);
11959
11960         ret = drm_plane_helper_check_update(plane, crtc, fb,
11961                                             src, dest, clip,
11962                                             DRM_PLANE_HELPER_NO_SCALING,
11963                                             DRM_PLANE_HELPER_NO_SCALING,
11964                                             false, true, &state->visible);
11965         if (ret)
11966                 return ret;
11967
11968         if (intel_crtc->active) {
11969                 intel_crtc->atomic.wait_for_flips = true;
11970
11971                 /*
11972                  * FBC does not work on some platforms for rotated
11973                  * planes, so disable it when rotation is not 0 and
11974                  * update it when rotation is set back to 0.
11975                  *
11976                  * FIXME: This is redundant with the fbc update done in
11977                  * the primary plane enable function except that that
11978                  * one is done too late. We eventually need to unify
11979                  * this.
11980                  */
11981                 if (intel_crtc->primary_enabled &&
11982                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11983                     dev_priv->fbc.crtc == intel_crtc &&
11984                     state->base.rotation != BIT(DRM_ROTATE_0)) {
11985                         intel_crtc->atomic.disable_fbc = true;
11986                 }
11987
11988                 if (state->visible) {
11989                         /*
11990                          * BDW signals flip done immediately if the plane
11991                          * is disabled, even if the plane enable is already
11992                          * armed to occur at the next vblank :(
11993                          */
11994                         if (IS_BROADWELL(dev) && !intel_crtc->primary_enabled)
11995                                 intel_crtc->atomic.wait_vblank = true;
11996                 }
11997
11998                 intel_crtc->atomic.fb_bits |=
11999                         INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
12000
12001                 intel_crtc->atomic.update_fbc = true;
12002         }
12003
12004         return 0;
12005 }
12006
12007 static void
12008 intel_commit_primary_plane(struct drm_plane *plane,
12009                            struct intel_plane_state *state)
12010 {
12011         struct drm_crtc *crtc = state->base.crtc;
12012         struct drm_framebuffer *fb = state->base.fb;
12013         struct drm_device *dev = plane->dev;
12014         struct drm_i915_private *dev_priv = dev->dev_private;
12015         struct intel_crtc *intel_crtc;
12016         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12017         struct intel_plane *intel_plane = to_intel_plane(plane);
12018         struct drm_rect *src = &state->src;
12019
12020         crtc = crtc ? crtc : plane->crtc;
12021         intel_crtc = to_intel_crtc(crtc);
12022
12023         plane->fb = fb;
12024         crtc->x = src->x1 >> 16;
12025         crtc->y = src->y1 >> 16;
12026
12027         intel_plane->obj = obj;
12028
12029         if (intel_crtc->active) {
12030                 if (state->visible) {
12031                         /* FIXME: kill this fastboot hack */
12032                         intel_update_pipe_size(intel_crtc);
12033
12034                         intel_crtc->primary_enabled = true;
12035
12036                         dev_priv->display.update_primary_plane(crtc, plane->fb,
12037                                         crtc->x, crtc->y);
12038                 } else {
12039                         /*
12040                          * If clipping results in a non-visible primary plane,
12041                          * we'll disable the primary plane.  Note that this is
12042                          * a bit different than what happens if userspace
12043                          * explicitly disables the plane by passing fb=0
12044                          * because plane->fb still gets set and pinned.
12045                          */
12046                         intel_disable_primary_hw_plane(plane, crtc);
12047                 }
12048         }
12049 }
12050
12051 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
12052 {
12053         struct drm_device *dev = crtc->dev;
12054         struct drm_i915_private *dev_priv = dev->dev_private;
12055         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12056         struct intel_plane *intel_plane;
12057         struct drm_plane *p;
12058         unsigned fb_bits = 0;
12059
12060         /* Track fb's for any planes being disabled */
12061         list_for_each_entry(p, &dev->mode_config.plane_list, head) {
12062                 intel_plane = to_intel_plane(p);
12063
12064                 if (intel_crtc->atomic.disabled_planes &
12065                     (1 << drm_plane_index(p))) {
12066                         switch (p->type) {
12067                         case DRM_PLANE_TYPE_PRIMARY:
12068                                 fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
12069                                 break;
12070                         case DRM_PLANE_TYPE_CURSOR:
12071                                 fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
12072                                 break;
12073                         case DRM_PLANE_TYPE_OVERLAY:
12074                                 fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
12075                                 break;
12076                         }
12077
12078                         mutex_lock(&dev->struct_mutex);
12079                         i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
12080                         mutex_unlock(&dev->struct_mutex);
12081                 }
12082         }
12083
12084         if (intel_crtc->atomic.wait_for_flips)
12085                 intel_crtc_wait_for_pending_flips(crtc);
12086
12087         if (intel_crtc->atomic.disable_fbc)
12088                 intel_fbc_disable(dev);
12089
12090         if (intel_crtc->atomic.pre_disable_primary)
12091                 intel_pre_disable_primary(crtc);
12092
12093         if (intel_crtc->atomic.update_wm)
12094                 intel_update_watermarks(crtc);
12095
12096         intel_runtime_pm_get(dev_priv);
12097
12098         /* Perform vblank evasion around commit operation */
12099         if (intel_crtc->active)
12100                 intel_crtc->atomic.evade =
12101                         intel_pipe_update_start(intel_crtc,
12102                                                 &intel_crtc->atomic.start_vbl_count);
12103 }
12104
12105 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
12106 {
12107         struct drm_device *dev = crtc->dev;
12108         struct drm_i915_private *dev_priv = dev->dev_private;
12109         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12110         struct drm_plane *p;
12111
12112         if (intel_crtc->atomic.evade)
12113                 intel_pipe_update_end(intel_crtc,
12114                                       intel_crtc->atomic.start_vbl_count);
12115
12116         intel_runtime_pm_put(dev_priv);
12117
12118         if (intel_crtc->atomic.wait_vblank)
12119                 intel_wait_for_vblank(dev, intel_crtc->pipe);
12120
12121         intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
12122
12123         if (intel_crtc->atomic.update_fbc) {
12124                 mutex_lock(&dev->struct_mutex);
12125                 intel_fbc_update(dev);
12126                 mutex_unlock(&dev->struct_mutex);
12127         }
12128
12129         if (intel_crtc->atomic.post_enable_primary)
12130                 intel_post_enable_primary(crtc);
12131
12132         drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
12133                 if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
12134                         intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
12135                                                        false, false);
12136
12137         memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
12138 }
12139
12140 /**
12141  * intel_plane_destroy - destroy a plane
12142  * @plane: plane to destroy
12143  *
12144  * Common destruction function for all types of planes (primary, cursor,
12145  * sprite).
12146  */
12147 void intel_plane_destroy(struct drm_plane *plane)
12148 {
12149         struct intel_plane *intel_plane = to_intel_plane(plane);
12150         drm_plane_cleanup(plane);
12151         kfree(intel_plane);
12152 }
12153
12154 const struct drm_plane_funcs intel_plane_funcs = {
12155         .update_plane = drm_atomic_helper_update_plane,
12156         .disable_plane = drm_atomic_helper_disable_plane,
12157         .destroy = intel_plane_destroy,
12158         .set_property = drm_atomic_helper_plane_set_property,
12159         .atomic_get_property = intel_plane_atomic_get_property,
12160         .atomic_set_property = intel_plane_atomic_set_property,
12161         .atomic_duplicate_state = intel_plane_duplicate_state,
12162         .atomic_destroy_state = intel_plane_destroy_state,
12163
12164 };
12165
12166 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
12167                                                     int pipe)
12168 {
12169         struct intel_plane *primary;
12170         struct intel_plane_state *state;
12171         const uint32_t *intel_primary_formats;
12172         int num_formats;
12173
12174         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
12175         if (primary == NULL)
12176                 return NULL;
12177
12178         state = intel_create_plane_state(&primary->base);
12179         if (!state) {
12180                 kfree(primary);
12181                 return NULL;
12182         }
12183         primary->base.state = &state->base;
12184
12185         primary->can_scale = false;
12186         primary->max_downscale = 1;
12187         primary->pipe = pipe;
12188         primary->plane = pipe;
12189         primary->check_plane = intel_check_primary_plane;
12190         primary->commit_plane = intel_commit_primary_plane;
12191         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
12192                 primary->plane = !pipe;
12193
12194         if (INTEL_INFO(dev)->gen <= 3) {
12195                 intel_primary_formats = intel_primary_formats_gen2;
12196                 num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
12197         } else {
12198                 intel_primary_formats = intel_primary_formats_gen4;
12199                 num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
12200         }
12201
12202         drm_universal_plane_init(dev, &primary->base, 0,
12203                                  &intel_plane_funcs,
12204                                  intel_primary_formats, num_formats,
12205                                  DRM_PLANE_TYPE_PRIMARY);
12206
12207         if (INTEL_INFO(dev)->gen >= 4) {
12208                 if (!dev->mode_config.rotation_property)
12209                         dev->mode_config.rotation_property =
12210                                 drm_mode_create_rotation_property(dev,
12211                                                         BIT(DRM_ROTATE_0) |
12212                                                         BIT(DRM_ROTATE_180));
12213                 if (dev->mode_config.rotation_property)
12214                         drm_object_attach_property(&primary->base.base,
12215                                 dev->mode_config.rotation_property,
12216                                 state->base.rotation);
12217         }
12218
12219         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
12220
12221         return &primary->base;
12222 }
12223
12224 static int
12225 intel_check_cursor_plane(struct drm_plane *plane,
12226                          struct intel_plane_state *state)
12227 {
12228         struct drm_crtc *crtc = state->base.crtc;
12229         struct drm_device *dev = plane->dev;
12230         struct drm_framebuffer *fb = state->base.fb;
12231         struct drm_rect *dest = &state->dst;
12232         struct drm_rect *src = &state->src;
12233         const struct drm_rect *clip = &state->clip;
12234         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12235         struct intel_crtc *intel_crtc;
12236         unsigned stride;
12237         int ret;
12238
12239         crtc = crtc ? crtc : plane->crtc;
12240         intel_crtc = to_intel_crtc(crtc);
12241
12242         ret = drm_plane_helper_check_update(plane, crtc, fb,
12243                                             src, dest, clip,
12244                                             DRM_PLANE_HELPER_NO_SCALING,
12245                                             DRM_PLANE_HELPER_NO_SCALING,
12246                                             true, true, &state->visible);
12247         if (ret)
12248                 return ret;
12249
12250
12251         /* if we want to turn off the cursor ignore width and height */
12252         if (!obj)
12253                 goto finish;
12254
12255         /* Check for which cursor types we support */
12256         if (!cursor_size_ok(dev, state->base.crtc_w, state->base.crtc_h)) {
12257                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
12258                           state->base.crtc_w, state->base.crtc_h);
12259                 return -EINVAL;
12260         }
12261
12262         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
12263         if (obj->base.size < stride * state->base.crtc_h) {
12264                 DRM_DEBUG_KMS("buffer is too small\n");
12265                 return -ENOMEM;
12266         }
12267
12268         if (fb == crtc->cursor->fb)
12269                 return 0;
12270
12271         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
12272                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
12273                 ret = -EINVAL;
12274         }
12275
12276 finish:
12277         if (intel_crtc->active) {
12278                 if (intel_crtc->cursor_width != state->base.crtc_w)
12279                         intel_crtc->atomic.update_wm = true;
12280
12281                 intel_crtc->atomic.fb_bits |=
12282                         INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
12283         }
12284
12285         return ret;
12286 }
12287
12288 static void
12289 intel_commit_cursor_plane(struct drm_plane *plane,
12290                           struct intel_plane_state *state)
12291 {
12292         struct drm_crtc *crtc = state->base.crtc;
12293         struct drm_device *dev = plane->dev;
12294         struct intel_crtc *intel_crtc;
12295         struct intel_plane *intel_plane = to_intel_plane(plane);
12296         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
12297         uint32_t addr;
12298
12299         crtc = crtc ? crtc : plane->crtc;
12300         intel_crtc = to_intel_crtc(crtc);
12301
12302         plane->fb = state->base.fb;
12303         crtc->cursor_x = state->base.crtc_x;
12304         crtc->cursor_y = state->base.crtc_y;
12305
12306         intel_plane->obj = obj;
12307
12308         if (intel_crtc->cursor_bo == obj)
12309                 goto update;
12310
12311         if (!obj)
12312                 addr = 0;
12313         else if (!INTEL_INFO(dev)->cursor_needs_physical)
12314                 addr = i915_gem_obj_ggtt_offset(obj);
12315         else
12316                 addr = obj->phys_handle->busaddr;
12317
12318         intel_crtc->cursor_addr = addr;
12319         intel_crtc->cursor_bo = obj;
12320 update:
12321         intel_crtc->cursor_width = state->base.crtc_w;
12322         intel_crtc->cursor_height = state->base.crtc_h;
12323
12324         if (intel_crtc->active)
12325                 intel_crtc_update_cursor(crtc, state->visible);
12326 }
12327
12328 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
12329                                                    int pipe)
12330 {
12331         struct intel_plane *cursor;
12332         struct intel_plane_state *state;
12333
12334         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
12335         if (cursor == NULL)
12336                 return NULL;
12337
12338         state = intel_create_plane_state(&cursor->base);
12339         if (!state) {
12340                 kfree(cursor);
12341                 return NULL;
12342         }
12343         cursor->base.state = &state->base;
12344
12345         cursor->can_scale = false;
12346         cursor->max_downscale = 1;
12347         cursor->pipe = pipe;
12348         cursor->plane = pipe;
12349         cursor->check_plane = intel_check_cursor_plane;
12350         cursor->commit_plane = intel_commit_cursor_plane;
12351
12352         drm_universal_plane_init(dev, &cursor->base, 0,
12353                                  &intel_plane_funcs,
12354                                  intel_cursor_formats,
12355                                  ARRAY_SIZE(intel_cursor_formats),
12356                                  DRM_PLANE_TYPE_CURSOR);
12357
12358         if (INTEL_INFO(dev)->gen >= 4) {
12359                 if (!dev->mode_config.rotation_property)
12360                         dev->mode_config.rotation_property =
12361                                 drm_mode_create_rotation_property(dev,
12362                                                         BIT(DRM_ROTATE_0) |
12363                                                         BIT(DRM_ROTATE_180));
12364                 if (dev->mode_config.rotation_property)
12365                         drm_object_attach_property(&cursor->base.base,
12366                                 dev->mode_config.rotation_property,
12367                                 state->base.rotation);
12368         }
12369
12370         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
12371
12372         return &cursor->base;
12373 }
12374
12375 static void intel_crtc_init(struct drm_device *dev, int pipe)
12376 {
12377         struct drm_i915_private *dev_priv = dev->dev_private;
12378         struct intel_crtc *intel_crtc;
12379         struct intel_crtc_state *crtc_state = NULL;
12380         struct drm_plane *primary = NULL;
12381         struct drm_plane *cursor = NULL;
12382         int i, ret;
12383
12384         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
12385         if (intel_crtc == NULL)
12386                 return;
12387
12388         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
12389         if (!crtc_state)
12390                 goto fail;
12391         intel_crtc_set_state(intel_crtc, crtc_state);
12392         crtc_state->base.crtc = &intel_crtc->base;
12393
12394         primary = intel_primary_plane_create(dev, pipe);
12395         if (!primary)
12396                 goto fail;
12397
12398         cursor = intel_cursor_plane_create(dev, pipe);
12399         if (!cursor)
12400                 goto fail;
12401
12402         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
12403                                         cursor, &intel_crtc_funcs);
12404         if (ret)
12405                 goto fail;
12406
12407         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
12408         for (i = 0; i < 256; i++) {
12409                 intel_crtc->lut_r[i] = i;
12410                 intel_crtc->lut_g[i] = i;
12411                 intel_crtc->lut_b[i] = i;
12412         }
12413
12414         /*
12415          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
12416          * is hooked to pipe B. Hence we want plane A feeding pipe B.
12417          */
12418         intel_crtc->pipe = pipe;
12419         intel_crtc->plane = pipe;
12420         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
12421                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
12422                 intel_crtc->plane = !pipe;
12423         }
12424
12425         intel_crtc->cursor_base = ~0;
12426         intel_crtc->cursor_cntl = ~0;
12427         intel_crtc->cursor_size = ~0;
12428
12429         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
12430                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
12431         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
12432         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
12433
12434         INIT_WORK(&intel_crtc->mmio_flip.work, intel_mmio_flip_work_func);
12435
12436         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
12437
12438         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
12439         return;
12440
12441 fail:
12442         if (primary)
12443                 drm_plane_cleanup(primary);
12444         if (cursor)
12445                 drm_plane_cleanup(cursor);
12446         kfree(crtc_state);
12447         kfree(intel_crtc);
12448 }
12449
12450 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
12451 {
12452         struct drm_encoder *encoder = connector->base.encoder;
12453         struct drm_device *dev = connector->base.dev;
12454
12455         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
12456
12457         if (!encoder || WARN_ON(!encoder->crtc))
12458                 return INVALID_PIPE;
12459
12460         return to_intel_crtc(encoder->crtc)->pipe;
12461 }
12462
12463 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
12464                                 struct drm_file *file)
12465 {
12466         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
12467         struct drm_crtc *drmmode_crtc;
12468         struct intel_crtc *crtc;
12469
12470         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
12471
12472         if (!drmmode_crtc) {
12473                 DRM_ERROR("no such CRTC id\n");
12474                 return -ENOENT;
12475         }
12476
12477         crtc = to_intel_crtc(drmmode_crtc);
12478         pipe_from_crtc_id->pipe = crtc->pipe;
12479
12480         return 0;
12481 }
12482
12483 static int intel_encoder_clones(struct intel_encoder *encoder)
12484 {
12485         struct drm_device *dev = encoder->base.dev;
12486         struct intel_encoder *source_encoder;
12487         int index_mask = 0;
12488         int entry = 0;
12489
12490         for_each_intel_encoder(dev, source_encoder) {
12491                 if (encoders_cloneable(encoder, source_encoder))
12492                         index_mask |= (1 << entry);
12493
12494                 entry++;
12495         }
12496
12497         return index_mask;
12498 }
12499
12500 static bool has_edp_a(struct drm_device *dev)
12501 {
12502         struct drm_i915_private *dev_priv = dev->dev_private;
12503
12504         if (!IS_MOBILE(dev))
12505                 return false;
12506
12507         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
12508                 return false;
12509
12510         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
12511                 return false;
12512
12513         return true;
12514 }
12515
12516 static bool intel_crt_present(struct drm_device *dev)
12517 {
12518         struct drm_i915_private *dev_priv = dev->dev_private;
12519
12520         if (INTEL_INFO(dev)->gen >= 9)
12521                 return false;
12522
12523         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
12524                 return false;
12525
12526         if (IS_CHERRYVIEW(dev))
12527                 return false;
12528
12529         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
12530                 return false;
12531
12532         return true;
12533 }
12534
12535 static void intel_setup_outputs(struct drm_device *dev)
12536 {
12537         struct drm_i915_private *dev_priv = dev->dev_private;
12538         struct intel_encoder *encoder;
12539         struct drm_connector *connector;
12540         bool dpd_is_edp = false;
12541
12542         intel_lvds_init(dev);
12543
12544         if (intel_crt_present(dev))
12545                 intel_crt_init(dev);
12546
12547         if (HAS_DDI(dev)) {
12548                 int found;
12549
12550                 /* Haswell uses DDI functions to detect digital outputs */
12551                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
12552                 /* DDI A only supports eDP */
12553                 if (found)
12554                         intel_ddi_init(dev, PORT_A);
12555
12556                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
12557                  * register */
12558                 found = I915_READ(SFUSE_STRAP);
12559
12560                 if (found & SFUSE_STRAP_DDIB_DETECTED)
12561                         intel_ddi_init(dev, PORT_B);
12562                 if (found & SFUSE_STRAP_DDIC_DETECTED)
12563                         intel_ddi_init(dev, PORT_C);
12564                 if (found & SFUSE_STRAP_DDID_DETECTED)
12565                         intel_ddi_init(dev, PORT_D);
12566         } else if (HAS_PCH_SPLIT(dev)) {
12567                 int found;
12568                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
12569
12570                 if (has_edp_a(dev))
12571                         intel_dp_init(dev, DP_A, PORT_A);
12572
12573                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
12574                         /* PCH SDVOB multiplex with HDMIB */
12575                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
12576                         if (!found)
12577                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
12578                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
12579                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
12580                 }
12581
12582                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
12583                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
12584
12585                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
12586                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
12587
12588                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
12589                         intel_dp_init(dev, PCH_DP_C, PORT_C);
12590
12591                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
12592                         intel_dp_init(dev, PCH_DP_D, PORT_D);
12593         } else if (IS_VALLEYVIEW(dev)) {
12594                 /*
12595                  * The DP_DETECTED bit is the latched state of the DDC
12596                  * SDA pin at boot. However since eDP doesn't require DDC
12597                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
12598                  * eDP ports may have been muxed to an alternate function.
12599                  * Thus we can't rely on the DP_DETECTED bit alone to detect
12600                  * eDP ports. Consult the VBT as well as DP_DETECTED to
12601                  * detect eDP ports.
12602                  */
12603                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
12604                     !intel_dp_is_edp(dev, PORT_B))
12605                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
12606                                         PORT_B);
12607                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
12608                     intel_dp_is_edp(dev, PORT_B))
12609                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
12610
12611                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
12612                     !intel_dp_is_edp(dev, PORT_C))
12613                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
12614                                         PORT_C);
12615                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
12616                     intel_dp_is_edp(dev, PORT_C))
12617                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
12618
12619                 if (IS_CHERRYVIEW(dev)) {
12620                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
12621                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
12622                                                 PORT_D);
12623                         /* eDP not supported on port D, so don't check VBT */
12624                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
12625                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
12626                 }
12627
12628                 intel_dsi_init(dev);
12629         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
12630                 bool found = false;
12631
12632                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12633                         DRM_DEBUG_KMS("probing SDVOB\n");
12634                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
12635                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
12636                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
12637                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
12638                         }
12639
12640                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
12641                                 intel_dp_init(dev, DP_B, PORT_B);
12642                 }
12643
12644                 /* Before G4X SDVOC doesn't have its own detect register */
12645
12646                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
12647                         DRM_DEBUG_KMS("probing SDVOC\n");
12648                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
12649                 }
12650
12651                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
12652
12653                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
12654                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
12655                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
12656                         }
12657                         if (SUPPORTS_INTEGRATED_DP(dev))
12658                                 intel_dp_init(dev, DP_C, PORT_C);
12659                 }
12660
12661                 if (SUPPORTS_INTEGRATED_DP(dev) &&
12662                     (I915_READ(DP_D) & DP_DETECTED))
12663                         intel_dp_init(dev, DP_D, PORT_D);
12664         } else if (IS_GEN2(dev))
12665                 intel_dvo_init(dev);
12666
12667         if (SUPPORTS_TV(dev))
12668                 intel_tv_init(dev);
12669
12670         /*
12671          * FIXME:  We don't have full atomic support yet, but we want to be
12672          * able to enable/test plane updates via the atomic interface in the
12673          * meantime.  However as soon as we flip DRIVER_ATOMIC on, the DRM core
12674          * will take some atomic codepaths to lookup properties during
12675          * drmModeGetConnector() that unconditionally dereference
12676          * connector->state.
12677          *
12678          * We create a dummy connector state here for each connector to ensure
12679          * the DRM core doesn't try to dereference a NULL connector->state.
12680          * The actual connector properties will never be updated or contain
12681          * useful information, but since we're doing this specifically for
12682          * testing/debug of the plane operations (and only when a specific
12683          * kernel module option is given), that shouldn't really matter.
12684          *
12685          * Once atomic support for crtc's + connectors lands, this loop should
12686          * be removed since we'll be setting up real connector state, which
12687          * will contain Intel-specific properties.
12688          */
12689         if (drm_core_check_feature(dev, DRIVER_ATOMIC)) {
12690                 list_for_each_entry(connector,
12691                                     &dev->mode_config.connector_list,
12692                                     head) {
12693                         if (!WARN_ON(connector->state)) {
12694                                 connector->state =
12695                                         kzalloc(sizeof(*connector->state),
12696                                                 GFP_KERNEL);
12697                         }
12698                 }
12699         }
12700
12701         intel_psr_init(dev);
12702
12703         for_each_intel_encoder(dev, encoder) {
12704                 encoder->base.possible_crtcs = encoder->crtc_mask;
12705                 encoder->base.possible_clones =
12706                         intel_encoder_clones(encoder);
12707         }
12708
12709         intel_init_pch_refclk(dev);
12710
12711         drm_helper_move_panel_connectors_to_head(dev);
12712 }
12713
12714 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
12715 {
12716         struct drm_device *dev = fb->dev;
12717         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12718
12719         drm_framebuffer_cleanup(fb);
12720         mutex_lock(&dev->struct_mutex);
12721         WARN_ON(!intel_fb->obj->framebuffer_references--);
12722         drm_gem_object_unreference(&intel_fb->obj->base);
12723         mutex_unlock(&dev->struct_mutex);
12724         kfree(intel_fb);
12725 }
12726
12727 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
12728                                                 struct drm_file *file,
12729                                                 unsigned int *handle)
12730 {
12731         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
12732         struct drm_i915_gem_object *obj = intel_fb->obj;
12733
12734         return drm_gem_handle_create(file, &obj->base, handle);
12735 }
12736
12737 static const struct drm_framebuffer_funcs intel_fb_funcs = {
12738         .destroy = intel_user_framebuffer_destroy,
12739         .create_handle = intel_user_framebuffer_create_handle,
12740 };
12741
12742 static
12743 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
12744                          uint32_t pixel_format)
12745 {
12746         u32 gen = INTEL_INFO(dev)->gen;
12747
12748         if (gen >= 9) {
12749                 /* "The stride in bytes must not exceed the of the size of 8K
12750                  *  pixels and 32K bytes."
12751                  */
12752                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
12753         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
12754                 return 32*1024;
12755         } else if (gen >= 4) {
12756                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
12757                         return 16*1024;
12758                 else
12759                         return 32*1024;
12760         } else if (gen >= 3) {
12761                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
12762                         return 8*1024;
12763                 else
12764                         return 16*1024;
12765         } else {
12766                 /* XXX DSPC is limited to 4k tiled */
12767                 return 8*1024;
12768         }
12769 }
12770
12771 static int intel_framebuffer_init(struct drm_device *dev,
12772                                   struct intel_framebuffer *intel_fb,
12773                                   struct drm_mode_fb_cmd2 *mode_cmd,
12774                                   struct drm_i915_gem_object *obj)
12775 {
12776         int aligned_height;
12777         int ret;
12778         u32 pitch_limit, stride_alignment;
12779
12780         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
12781
12782         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
12783                 /* Enforce that fb modifier and tiling mode match, but only for
12784                  * X-tiled. This is needed for FBC. */
12785                 if (!!(obj->tiling_mode == I915_TILING_X) !=
12786                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
12787                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
12788                         return -EINVAL;
12789                 }
12790         } else {
12791                 if (obj->tiling_mode == I915_TILING_X)
12792                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
12793                 else if (obj->tiling_mode == I915_TILING_Y) {
12794                         DRM_DEBUG("No Y tiling for legacy addfb\n");
12795                         return -EINVAL;
12796                 }
12797         }
12798
12799         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_Y_TILED) {
12800                 DRM_DEBUG("hardware does not support tiling Y\n");
12801                 return -EINVAL;
12802         }
12803
12804         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
12805                                                      mode_cmd->pixel_format);
12806         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
12807                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
12808                           mode_cmd->pitches[0], stride_alignment);
12809                 return -EINVAL;
12810         }
12811
12812         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
12813                                            mode_cmd->pixel_format);
12814         if (mode_cmd->pitches[0] > pitch_limit) {
12815                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
12816                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
12817                           "tiled" : "linear",
12818                           mode_cmd->pitches[0], pitch_limit);
12819                 return -EINVAL;
12820         }
12821
12822         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
12823             mode_cmd->pitches[0] != obj->stride) {
12824                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
12825                           mode_cmd->pitches[0], obj->stride);
12826                 return -EINVAL;
12827         }
12828
12829         /* Reject formats not supported by any plane early. */
12830         switch (mode_cmd->pixel_format) {
12831         case DRM_FORMAT_C8:
12832         case DRM_FORMAT_RGB565:
12833         case DRM_FORMAT_XRGB8888:
12834         case DRM_FORMAT_ARGB8888:
12835                 break;
12836         case DRM_FORMAT_XRGB1555:
12837         case DRM_FORMAT_ARGB1555:
12838                 if (INTEL_INFO(dev)->gen > 3) {
12839                         DRM_DEBUG("unsupported pixel format: %s\n",
12840                                   drm_get_format_name(mode_cmd->pixel_format));
12841                         return -EINVAL;
12842                 }
12843                 break;
12844         case DRM_FORMAT_XBGR8888:
12845         case DRM_FORMAT_ABGR8888:
12846         case DRM_FORMAT_XRGB2101010:
12847         case DRM_FORMAT_ARGB2101010:
12848         case DRM_FORMAT_XBGR2101010:
12849         case DRM_FORMAT_ABGR2101010:
12850                 if (INTEL_INFO(dev)->gen < 4) {
12851                         DRM_DEBUG("unsupported pixel format: %s\n",
12852                                   drm_get_format_name(mode_cmd->pixel_format));
12853                         return -EINVAL;
12854                 }
12855                 break;
12856         case DRM_FORMAT_YUYV:
12857         case DRM_FORMAT_UYVY:
12858         case DRM_FORMAT_YVYU:
12859         case DRM_FORMAT_VYUY:
12860                 if (INTEL_INFO(dev)->gen < 5) {
12861                         DRM_DEBUG("unsupported pixel format: %s\n",
12862                                   drm_get_format_name(mode_cmd->pixel_format));
12863                         return -EINVAL;
12864                 }
12865                 break;
12866         default:
12867                 DRM_DEBUG("unsupported pixel format: %s\n",
12868                           drm_get_format_name(mode_cmd->pixel_format));
12869                 return -EINVAL;
12870         }
12871
12872         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
12873         if (mode_cmd->offsets[0] != 0)
12874                 return -EINVAL;
12875
12876         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
12877                                                mode_cmd->pixel_format,
12878                                                mode_cmd->modifier[0]);
12879         /* FIXME drm helper for size checks (especially planar formats)? */
12880         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
12881                 return -EINVAL;
12882
12883         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
12884         intel_fb->obj = obj;
12885         intel_fb->obj->framebuffer_references++;
12886
12887         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
12888         if (ret) {
12889                 DRM_ERROR("framebuffer init failed %d\n", ret);
12890                 return ret;
12891         }
12892
12893         return 0;
12894 }
12895
12896 static struct drm_framebuffer *
12897 intel_user_framebuffer_create(struct drm_device *dev,
12898                               struct drm_file *filp,
12899                               struct drm_mode_fb_cmd2 *mode_cmd)
12900 {
12901         struct drm_i915_gem_object *obj;
12902
12903         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
12904                                                 mode_cmd->handles[0]));
12905         if (&obj->base == NULL)
12906                 return ERR_PTR(-ENOENT);
12907
12908         return intel_framebuffer_create(dev, mode_cmd, obj);
12909 }
12910
12911 #ifndef CONFIG_DRM_I915_FBDEV
12912 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
12913 {
12914 }
12915 #endif
12916
12917 static const struct drm_mode_config_funcs intel_mode_funcs = {
12918         .fb_create = intel_user_framebuffer_create,
12919         .output_poll_changed = intel_fbdev_output_poll_changed,
12920         .atomic_check = intel_atomic_check,
12921         .atomic_commit = intel_atomic_commit,
12922 };
12923
12924 /* Set up chip specific display functions */
12925 static void intel_init_display(struct drm_device *dev)
12926 {
12927         struct drm_i915_private *dev_priv = dev->dev_private;
12928
12929         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
12930                 dev_priv->display.find_dpll = g4x_find_best_dpll;
12931         else if (IS_CHERRYVIEW(dev))
12932                 dev_priv->display.find_dpll = chv_find_best_dpll;
12933         else if (IS_VALLEYVIEW(dev))
12934                 dev_priv->display.find_dpll = vlv_find_best_dpll;
12935         else if (IS_PINEVIEW(dev))
12936                 dev_priv->display.find_dpll = pnv_find_best_dpll;
12937         else
12938                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
12939
12940         if (INTEL_INFO(dev)->gen >= 9) {
12941                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
12942                 dev_priv->display.get_initial_plane_config =
12943                         skylake_get_initial_plane_config;
12944                 dev_priv->display.crtc_compute_clock =
12945                         haswell_crtc_compute_clock;
12946                 dev_priv->display.crtc_enable = haswell_crtc_enable;
12947                 dev_priv->display.crtc_disable = haswell_crtc_disable;
12948                 dev_priv->display.off = ironlake_crtc_off;
12949                 dev_priv->display.update_primary_plane =
12950                         skylake_update_primary_plane;
12951         } else if (HAS_DDI(dev)) {
12952                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
12953                 dev_priv->display.get_initial_plane_config =
12954                         ironlake_get_initial_plane_config;
12955                 dev_priv->display.crtc_compute_clock =
12956                         haswell_crtc_compute_clock;
12957                 dev_priv->display.crtc_enable = haswell_crtc_enable;
12958                 dev_priv->display.crtc_disable = haswell_crtc_disable;
12959                 dev_priv->display.off = ironlake_crtc_off;
12960                 dev_priv->display.update_primary_plane =
12961                         ironlake_update_primary_plane;
12962         } else if (HAS_PCH_SPLIT(dev)) {
12963                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
12964                 dev_priv->display.get_initial_plane_config =
12965                         ironlake_get_initial_plane_config;
12966                 dev_priv->display.crtc_compute_clock =
12967                         ironlake_crtc_compute_clock;
12968                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
12969                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
12970                 dev_priv->display.off = ironlake_crtc_off;
12971                 dev_priv->display.update_primary_plane =
12972                         ironlake_update_primary_plane;
12973         } else if (IS_VALLEYVIEW(dev)) {
12974                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12975                 dev_priv->display.get_initial_plane_config =
12976                         i9xx_get_initial_plane_config;
12977                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
12978                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
12979                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12980                 dev_priv->display.off = i9xx_crtc_off;
12981                 dev_priv->display.update_primary_plane =
12982                         i9xx_update_primary_plane;
12983         } else {
12984                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
12985                 dev_priv->display.get_initial_plane_config =
12986                         i9xx_get_initial_plane_config;
12987                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
12988                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
12989                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
12990                 dev_priv->display.off = i9xx_crtc_off;
12991                 dev_priv->display.update_primary_plane =
12992                         i9xx_update_primary_plane;
12993         }
12994
12995         /* Returns the core display clock speed */
12996         if (IS_VALLEYVIEW(dev))
12997                 dev_priv->display.get_display_clock_speed =
12998                         valleyview_get_display_clock_speed;
12999         else if (IS_I945G(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
13000                 dev_priv->display.get_display_clock_speed =
13001                         i945_get_display_clock_speed;
13002         else if (IS_I915G(dev))
13003                 dev_priv->display.get_display_clock_speed =
13004                         i915_get_display_clock_speed;
13005         else if (IS_I945GM(dev) || IS_845G(dev))
13006                 dev_priv->display.get_display_clock_speed =
13007                         i9xx_misc_get_display_clock_speed;
13008         else if (IS_PINEVIEW(dev))
13009                 dev_priv->display.get_display_clock_speed =
13010                         pnv_get_display_clock_speed;
13011         else if (IS_I915GM(dev))
13012                 dev_priv->display.get_display_clock_speed =
13013                         i915gm_get_display_clock_speed;
13014         else if (IS_I865G(dev))
13015                 dev_priv->display.get_display_clock_speed =
13016                         i865_get_display_clock_speed;
13017         else if (IS_I85X(dev))
13018                 dev_priv->display.get_display_clock_speed =
13019                         i855_get_display_clock_speed;
13020         else /* 852, 830 */
13021                 dev_priv->display.get_display_clock_speed =
13022                         i830_get_display_clock_speed;
13023
13024         if (IS_GEN5(dev)) {
13025                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
13026         } else if (IS_GEN6(dev)) {
13027                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
13028         } else if (IS_IVYBRIDGE(dev)) {
13029                 /* FIXME: detect B0+ stepping and use auto training */
13030                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
13031                 dev_priv->display.modeset_global_resources =
13032                         ivb_modeset_global_resources;
13033         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
13034                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
13035         } else if (IS_VALLEYVIEW(dev)) {
13036                 dev_priv->display.modeset_global_resources =
13037                         valleyview_modeset_global_resources;
13038         }
13039
13040         switch (INTEL_INFO(dev)->gen) {
13041         case 2:
13042                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
13043                 break;
13044
13045         case 3:
13046                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
13047                 break;
13048
13049         case 4:
13050         case 5:
13051                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
13052                 break;
13053
13054         case 6:
13055                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
13056                 break;
13057         case 7:
13058         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
13059                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
13060                 break;
13061         case 9:
13062                 /* Drop through - unsupported since execlist only. */
13063         default:
13064                 /* Default just returns -ENODEV to indicate unsupported */
13065                 dev_priv->display.queue_flip = intel_default_queue_flip;
13066         }
13067
13068         intel_panel_init_backlight_funcs(dev);
13069
13070         mutex_init(&dev_priv->pps_mutex);
13071 }
13072
13073 /*
13074  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
13075  * resume, or other times.  This quirk makes sure that's the case for
13076  * affected systems.
13077  */
13078 static void quirk_pipea_force(struct drm_device *dev)
13079 {
13080         struct drm_i915_private *dev_priv = dev->dev_private;
13081
13082         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
13083         DRM_INFO("applying pipe a force quirk\n");
13084 }
13085
13086 static void quirk_pipeb_force(struct drm_device *dev)
13087 {
13088         struct drm_i915_private *dev_priv = dev->dev_private;
13089
13090         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
13091         DRM_INFO("applying pipe b force quirk\n");
13092 }
13093
13094 /*
13095  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
13096  */
13097 static void quirk_ssc_force_disable(struct drm_device *dev)
13098 {
13099         struct drm_i915_private *dev_priv = dev->dev_private;
13100         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
13101         DRM_INFO("applying lvds SSC disable quirk\n");
13102 }
13103
13104 /*
13105  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
13106  * brightness value
13107  */
13108 static void quirk_invert_brightness(struct drm_device *dev)
13109 {
13110         struct drm_i915_private *dev_priv = dev->dev_private;
13111         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
13112         DRM_INFO("applying inverted panel brightness quirk\n");
13113 }
13114
13115 /* Some VBT's incorrectly indicate no backlight is present */
13116 static void quirk_backlight_present(struct drm_device *dev)
13117 {
13118         struct drm_i915_private *dev_priv = dev->dev_private;
13119         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
13120         DRM_INFO("applying backlight present quirk\n");
13121 }
13122
13123 struct intel_quirk {
13124         int device;
13125         int subsystem_vendor;
13126         int subsystem_device;
13127         void (*hook)(struct drm_device *dev);
13128 };
13129
13130 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
13131 struct intel_dmi_quirk {
13132         void (*hook)(struct drm_device *dev);
13133         const struct dmi_system_id (*dmi_id_list)[];
13134 };
13135
13136 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
13137 {
13138         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
13139         return 1;
13140 }
13141
13142 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
13143         {
13144                 .dmi_id_list = &(const struct dmi_system_id[]) {
13145                         {
13146                                 .callback = intel_dmi_reverse_brightness,
13147                                 .ident = "NCR Corporation",
13148                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
13149                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
13150                                 },
13151                         },
13152                         { }  /* terminating entry */
13153                 },
13154                 .hook = quirk_invert_brightness,
13155         },
13156 };
13157
13158 static struct intel_quirk intel_quirks[] = {
13159         /* HP Mini needs pipe A force quirk (LP: #322104) */
13160         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
13161
13162         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
13163         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
13164
13165         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
13166         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
13167
13168         /* 830 needs to leave pipe A & dpll A up */
13169         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
13170
13171         /* 830 needs to leave pipe B & dpll B up */
13172         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
13173
13174         /* Lenovo U160 cannot use SSC on LVDS */
13175         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
13176
13177         /* Sony Vaio Y cannot use SSC on LVDS */
13178         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
13179
13180         /* Acer Aspire 5734Z must invert backlight brightness */
13181         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
13182
13183         /* Acer/eMachines G725 */
13184         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
13185
13186         /* Acer/eMachines e725 */
13187         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
13188
13189         /* Acer/Packard Bell NCL20 */
13190         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
13191
13192         /* Acer Aspire 4736Z */
13193         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
13194
13195         /* Acer Aspire 5336 */
13196         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
13197
13198         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
13199         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
13200
13201         /* Acer C720 Chromebook (Core i3 4005U) */
13202         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
13203
13204         /* Apple Macbook 2,1 (Core 2 T7400) */
13205         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
13206
13207         /* Toshiba CB35 Chromebook (Celeron 2955U) */
13208         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
13209
13210         /* HP Chromebook 14 (Celeron 2955U) */
13211         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
13212 };
13213
13214 static void intel_init_quirks(struct drm_device *dev)
13215 {
13216         struct pci_dev *d = dev->pdev;
13217         int i;
13218
13219         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
13220                 struct intel_quirk *q = &intel_quirks[i];
13221
13222                 if (d->device == q->device &&
13223                     (d->subsystem_vendor == q->subsystem_vendor ||
13224                      q->subsystem_vendor == PCI_ANY_ID) &&
13225                     (d->subsystem_device == q->subsystem_device ||
13226                      q->subsystem_device == PCI_ANY_ID))
13227                         q->hook(dev);
13228         }
13229         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
13230                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
13231                         intel_dmi_quirks[i].hook(dev);
13232         }
13233 }
13234
13235 /* Disable the VGA plane that we never use */
13236 static void i915_disable_vga(struct drm_device *dev)
13237 {
13238         struct drm_i915_private *dev_priv = dev->dev_private;
13239         u8 sr1;
13240         u32 vga_reg = i915_vgacntrl_reg(dev);
13241
13242         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
13243         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
13244         outb(SR01, VGA_SR_INDEX);
13245         sr1 = inb(VGA_SR_DATA);
13246         outb(sr1 | 1<<5, VGA_SR_DATA);
13247         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
13248         udelay(300);
13249
13250         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
13251         POSTING_READ(vga_reg);
13252 }
13253
13254 void intel_modeset_init_hw(struct drm_device *dev)
13255 {
13256         intel_prepare_ddi(dev);
13257
13258         if (IS_VALLEYVIEW(dev))
13259                 vlv_update_cdclk(dev);
13260
13261         intel_init_clock_gating(dev);
13262
13263         intel_enable_gt_powersave(dev);
13264 }
13265
13266 void intel_modeset_init(struct drm_device *dev)
13267 {
13268         struct drm_i915_private *dev_priv = dev->dev_private;
13269         int sprite, ret;
13270         enum pipe pipe;
13271         struct intel_crtc *crtc;
13272
13273         drm_mode_config_init(dev);
13274
13275         dev->mode_config.min_width = 0;
13276         dev->mode_config.min_height = 0;
13277
13278         dev->mode_config.preferred_depth = 24;
13279         dev->mode_config.prefer_shadow = 1;
13280
13281         dev->mode_config.allow_fb_modifiers = true;
13282
13283         dev->mode_config.funcs = &intel_mode_funcs;
13284
13285         intel_init_quirks(dev);
13286
13287         intel_init_pm(dev);
13288
13289         if (INTEL_INFO(dev)->num_pipes == 0)
13290                 return;
13291
13292         intel_init_display(dev);
13293         intel_init_audio(dev);
13294
13295         if (IS_GEN2(dev)) {
13296                 dev->mode_config.max_width = 2048;
13297                 dev->mode_config.max_height = 2048;
13298         } else if (IS_GEN3(dev)) {
13299                 dev->mode_config.max_width = 4096;
13300                 dev->mode_config.max_height = 4096;
13301         } else {
13302                 dev->mode_config.max_width = 8192;
13303                 dev->mode_config.max_height = 8192;
13304         }
13305
13306         if (IS_845G(dev) || IS_I865G(dev)) {
13307                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
13308                 dev->mode_config.cursor_height = 1023;
13309         } else if (IS_GEN2(dev)) {
13310                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
13311                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
13312         } else {
13313                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
13314                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
13315         }
13316
13317         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
13318
13319         DRM_DEBUG_KMS("%d display pipe%s available.\n",
13320                       INTEL_INFO(dev)->num_pipes,
13321                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
13322
13323         for_each_pipe(dev_priv, pipe) {
13324                 intel_crtc_init(dev, pipe);
13325                 for_each_sprite(pipe, sprite) {
13326                         ret = intel_plane_init(dev, pipe, sprite);
13327                         if (ret)
13328                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
13329                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
13330                 }
13331         }
13332
13333         intel_init_dpio(dev);
13334
13335         intel_shared_dpll_init(dev);
13336
13337         /* Just disable it once at startup */
13338         i915_disable_vga(dev);
13339         intel_setup_outputs(dev);
13340
13341         /* Just in case the BIOS is doing something questionable. */
13342         intel_fbc_disable(dev);
13343
13344         drm_modeset_lock_all(dev);
13345         intel_modeset_setup_hw_state(dev, false);
13346         drm_modeset_unlock_all(dev);
13347
13348         for_each_intel_crtc(dev, crtc) {
13349                 if (!crtc->active)
13350                         continue;
13351
13352                 /*
13353                  * Note that reserving the BIOS fb up front prevents us
13354                  * from stuffing other stolen allocations like the ring
13355                  * on top.  This prevents some ugliness at boot time, and
13356                  * can even allow for smooth boot transitions if the BIOS
13357                  * fb is large enough for the active pipe configuration.
13358                  */
13359                 if (dev_priv->display.get_initial_plane_config) {
13360                         dev_priv->display.get_initial_plane_config(crtc,
13361                                                            &crtc->plane_config);
13362                         /*
13363                          * If the fb is shared between multiple heads, we'll
13364                          * just get the first one.
13365                          */
13366                         intel_find_plane_obj(crtc, &crtc->plane_config);
13367                 }
13368         }
13369 }
13370
13371 static void intel_enable_pipe_a(struct drm_device *dev)
13372 {
13373         struct intel_connector *connector;
13374         struct drm_connector *crt = NULL;
13375         struct intel_load_detect_pipe load_detect_temp;
13376         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
13377
13378         /* We can't just switch on the pipe A, we need to set things up with a
13379          * proper mode and output configuration. As a gross hack, enable pipe A
13380          * by enabling the load detect pipe once. */
13381         list_for_each_entry(connector,
13382                             &dev->mode_config.connector_list,
13383                             base.head) {
13384                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
13385                         crt = &connector->base;
13386                         break;
13387                 }
13388         }
13389
13390         if (!crt)
13391                 return;
13392
13393         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
13394                 intel_release_load_detect_pipe(crt, &load_detect_temp);
13395 }
13396
13397 static bool
13398 intel_check_plane_mapping(struct intel_crtc *crtc)
13399 {
13400         struct drm_device *dev = crtc->base.dev;
13401         struct drm_i915_private *dev_priv = dev->dev_private;
13402         u32 reg, val;
13403
13404         if (INTEL_INFO(dev)->num_pipes == 1)
13405                 return true;
13406
13407         reg = DSPCNTR(!crtc->plane);
13408         val = I915_READ(reg);
13409
13410         if ((val & DISPLAY_PLANE_ENABLE) &&
13411             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
13412                 return false;
13413
13414         return true;
13415 }
13416
13417 static void intel_sanitize_crtc(struct intel_crtc *crtc)
13418 {
13419         struct drm_device *dev = crtc->base.dev;
13420         struct drm_i915_private *dev_priv = dev->dev_private;
13421         u32 reg;
13422
13423         /* Clear any frame start delays used for debugging left by the BIOS */
13424         reg = PIPECONF(crtc->config->cpu_transcoder);
13425         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
13426
13427         /* restore vblank interrupts to correct state */
13428         drm_crtc_vblank_reset(&crtc->base);
13429         if (crtc->active) {
13430                 update_scanline_offset(crtc);
13431                 drm_crtc_vblank_on(&crtc->base);
13432         }
13433
13434         /* We need to sanitize the plane -> pipe mapping first because this will
13435          * disable the crtc (and hence change the state) if it is wrong. Note
13436          * that gen4+ has a fixed plane -> pipe mapping.  */
13437         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
13438                 struct intel_connector *connector;
13439                 bool plane;
13440
13441                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
13442                               crtc->base.base.id);
13443
13444                 /* Pipe has the wrong plane attached and the plane is active.
13445                  * Temporarily change the plane mapping and disable everything
13446                  * ...  */
13447                 plane = crtc->plane;
13448                 crtc->plane = !plane;
13449                 crtc->primary_enabled = true;
13450                 dev_priv->display.crtc_disable(&crtc->base);
13451                 crtc->plane = plane;
13452
13453                 /* ... and break all links. */
13454                 list_for_each_entry(connector, &dev->mode_config.connector_list,
13455                                     base.head) {
13456                         if (connector->encoder->base.crtc != &crtc->base)
13457                                 continue;
13458
13459                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13460                         connector->base.encoder = NULL;
13461                 }
13462                 /* multiple connectors may have the same encoder:
13463                  *  handle them and break crtc link separately */
13464                 list_for_each_entry(connector, &dev->mode_config.connector_list,
13465                                     base.head)
13466                         if (connector->encoder->base.crtc == &crtc->base) {
13467                                 connector->encoder->base.crtc = NULL;
13468                                 connector->encoder->connectors_active = false;
13469                         }
13470
13471                 WARN_ON(crtc->active);
13472                 crtc->base.state->enable = false;
13473                 crtc->base.enabled = false;
13474         }
13475
13476         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
13477             crtc->pipe == PIPE_A && !crtc->active) {
13478                 /* BIOS forgot to enable pipe A, this mostly happens after
13479                  * resume. Force-enable the pipe to fix this, the update_dpms
13480                  * call below we restore the pipe to the right state, but leave
13481                  * the required bits on. */
13482                 intel_enable_pipe_a(dev);
13483         }
13484
13485         /* Adjust the state of the output pipe according to whether we
13486          * have active connectors/encoders. */
13487         intel_crtc_update_dpms(&crtc->base);
13488
13489         if (crtc->active != crtc->base.state->enable) {
13490                 struct intel_encoder *encoder;
13491
13492                 /* This can happen either due to bugs in the get_hw_state
13493                  * functions or because the pipe is force-enabled due to the
13494                  * pipe A quirk. */
13495                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
13496                               crtc->base.base.id,
13497                               crtc->base.state->enable ? "enabled" : "disabled",
13498                               crtc->active ? "enabled" : "disabled");
13499
13500                 crtc->base.state->enable = crtc->active;
13501                 crtc->base.enabled = crtc->active;
13502
13503                 /* Because we only establish the connector -> encoder ->
13504                  * crtc links if something is active, this means the
13505                  * crtc is now deactivated. Break the links. connector
13506                  * -> encoder links are only establish when things are
13507                  *  actually up, hence no need to break them. */
13508                 WARN_ON(crtc->active);
13509
13510                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
13511                         WARN_ON(encoder->connectors_active);
13512                         encoder->base.crtc = NULL;
13513                 }
13514         }
13515
13516         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
13517                 /*
13518                  * We start out with underrun reporting disabled to avoid races.
13519                  * For correct bookkeeping mark this on active crtcs.
13520                  *
13521                  * Also on gmch platforms we dont have any hardware bits to
13522                  * disable the underrun reporting. Which means we need to start
13523                  * out with underrun reporting disabled also on inactive pipes,
13524                  * since otherwise we'll complain about the garbage we read when
13525                  * e.g. coming up after runtime pm.
13526                  *
13527                  * No protection against concurrent access is required - at
13528                  * worst a fifo underrun happens which also sets this to false.
13529                  */
13530                 crtc->cpu_fifo_underrun_disabled = true;
13531                 crtc->pch_fifo_underrun_disabled = true;
13532         }
13533 }
13534
13535 static void intel_sanitize_encoder(struct intel_encoder *encoder)
13536 {
13537         struct intel_connector *connector;
13538         struct drm_device *dev = encoder->base.dev;
13539
13540         /* We need to check both for a crtc link (meaning that the
13541          * encoder is active and trying to read from a pipe) and the
13542          * pipe itself being active. */
13543         bool has_active_crtc = encoder->base.crtc &&
13544                 to_intel_crtc(encoder->base.crtc)->active;
13545
13546         if (encoder->connectors_active && !has_active_crtc) {
13547                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
13548                               encoder->base.base.id,
13549                               encoder->base.name);
13550
13551                 /* Connector is active, but has no active pipe. This is
13552                  * fallout from our resume register restoring. Disable
13553                  * the encoder manually again. */
13554                 if (encoder->base.crtc) {
13555                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
13556                                       encoder->base.base.id,
13557                                       encoder->base.name);
13558                         encoder->disable(encoder);
13559                         if (encoder->post_disable)
13560                                 encoder->post_disable(encoder);
13561                 }
13562                 encoder->base.crtc = NULL;
13563                 encoder->connectors_active = false;
13564
13565                 /* Inconsistent output/port/pipe state happens presumably due to
13566                  * a bug in one of the get_hw_state functions. Or someplace else
13567                  * in our code, like the register restore mess on resume. Clamp
13568                  * things to off as a safer default. */
13569                 list_for_each_entry(connector,
13570                                     &dev->mode_config.connector_list,
13571                                     base.head) {
13572                         if (connector->encoder != encoder)
13573                                 continue;
13574                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13575                         connector->base.encoder = NULL;
13576                 }
13577         }
13578         /* Enabled encoders without active connectors will be fixed in
13579          * the crtc fixup. */
13580 }
13581
13582 void i915_redisable_vga_power_on(struct drm_device *dev)
13583 {
13584         struct drm_i915_private *dev_priv = dev->dev_private;
13585         u32 vga_reg = i915_vgacntrl_reg(dev);
13586
13587         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
13588                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
13589                 i915_disable_vga(dev);
13590         }
13591 }
13592
13593 void i915_redisable_vga(struct drm_device *dev)
13594 {
13595         struct drm_i915_private *dev_priv = dev->dev_private;
13596
13597         /* This function can be called both from intel_modeset_setup_hw_state or
13598          * at a very early point in our resume sequence, where the power well
13599          * structures are not yet restored. Since this function is at a very
13600          * paranoid "someone might have enabled VGA while we were not looking"
13601          * level, just check if the power well is enabled instead of trying to
13602          * follow the "don't touch the power well if we don't need it" policy
13603          * the rest of the driver uses. */
13604         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
13605                 return;
13606
13607         i915_redisable_vga_power_on(dev);
13608 }
13609
13610 static bool primary_get_hw_state(struct intel_crtc *crtc)
13611 {
13612         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
13613
13614         if (!crtc->active)
13615                 return false;
13616
13617         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
13618 }
13619
13620 static void intel_modeset_readout_hw_state(struct drm_device *dev)
13621 {
13622         struct drm_i915_private *dev_priv = dev->dev_private;
13623         enum pipe pipe;
13624         struct intel_crtc *crtc;
13625         struct intel_encoder *encoder;
13626         struct intel_connector *connector;
13627         int i;
13628
13629         for_each_intel_crtc(dev, crtc) {
13630                 memset(crtc->config, 0, sizeof(*crtc->config));
13631
13632                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
13633
13634                 crtc->active = dev_priv->display.get_pipe_config(crtc,
13635                                                                  crtc->config);
13636
13637                 crtc->base.state->enable = crtc->active;
13638                 crtc->base.enabled = crtc->active;
13639                 crtc->primary_enabled = primary_get_hw_state(crtc);
13640
13641                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
13642                               crtc->base.base.id,
13643                               crtc->active ? "enabled" : "disabled");
13644         }
13645
13646         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13647                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13648
13649                 pll->on = pll->get_hw_state(dev_priv, pll,
13650                                             &pll->config.hw_state);
13651                 pll->active = 0;
13652                 pll->config.crtc_mask = 0;
13653                 for_each_intel_crtc(dev, crtc) {
13654                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
13655                                 pll->active++;
13656                                 pll->config.crtc_mask |= 1 << crtc->pipe;
13657                         }
13658                 }
13659
13660                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
13661                               pll->name, pll->config.crtc_mask, pll->on);
13662
13663                 if (pll->config.crtc_mask)
13664                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
13665         }
13666
13667         for_each_intel_encoder(dev, encoder) {
13668                 pipe = 0;
13669
13670                 if (encoder->get_hw_state(encoder, &pipe)) {
13671                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13672                         encoder->base.crtc = &crtc->base;
13673                         encoder->get_config(encoder, crtc->config);
13674                 } else {
13675                         encoder->base.crtc = NULL;
13676                 }
13677
13678                 encoder->connectors_active = false;
13679                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
13680                               encoder->base.base.id,
13681                               encoder->base.name,
13682                               encoder->base.crtc ? "enabled" : "disabled",
13683                               pipe_name(pipe));
13684         }
13685
13686         list_for_each_entry(connector, &dev->mode_config.connector_list,
13687                             base.head) {
13688                 if (connector->get_hw_state(connector)) {
13689                         connector->base.dpms = DRM_MODE_DPMS_ON;
13690                         connector->encoder->connectors_active = true;
13691                         connector->base.encoder = &connector->encoder->base;
13692                 } else {
13693                         connector->base.dpms = DRM_MODE_DPMS_OFF;
13694                         connector->base.encoder = NULL;
13695                 }
13696                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
13697                               connector->base.base.id,
13698                               connector->base.name,
13699                               connector->base.encoder ? "enabled" : "disabled");
13700         }
13701 }
13702
13703 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
13704  * and i915 state tracking structures. */
13705 void intel_modeset_setup_hw_state(struct drm_device *dev,
13706                                   bool force_restore)
13707 {
13708         struct drm_i915_private *dev_priv = dev->dev_private;
13709         enum pipe pipe;
13710         struct intel_crtc *crtc;
13711         struct intel_encoder *encoder;
13712         int i;
13713
13714         intel_modeset_readout_hw_state(dev);
13715
13716         /*
13717          * Now that we have the config, copy it to each CRTC struct
13718          * Note that this could go away if we move to using crtc_config
13719          * checking everywhere.
13720          */
13721         for_each_intel_crtc(dev, crtc) {
13722                 if (crtc->active && i915.fastboot) {
13723                         intel_mode_from_pipe_config(&crtc->base.mode,
13724                                                     crtc->config);
13725                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
13726                                       crtc->base.base.id);
13727                         drm_mode_debug_printmodeline(&crtc->base.mode);
13728                 }
13729         }
13730
13731         /* HW state is read out, now we need to sanitize this mess. */
13732         for_each_intel_encoder(dev, encoder) {
13733                 intel_sanitize_encoder(encoder);
13734         }
13735
13736         for_each_pipe(dev_priv, pipe) {
13737                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
13738                 intel_sanitize_crtc(crtc);
13739                 intel_dump_pipe_config(crtc, crtc->config,
13740                                        "[setup_hw_state]");
13741         }
13742
13743         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13744                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13745
13746                 if (!pll->on || pll->active)
13747                         continue;
13748
13749                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
13750
13751                 pll->disable(dev_priv, pll);
13752                 pll->on = false;
13753         }
13754
13755         if (IS_GEN9(dev))
13756                 skl_wm_get_hw_state(dev);
13757         else if (HAS_PCH_SPLIT(dev))
13758                 ilk_wm_get_hw_state(dev);
13759
13760         if (force_restore) {
13761                 i915_redisable_vga(dev);
13762
13763                 /*
13764                  * We need to use raw interfaces for restoring state to avoid
13765                  * checking (bogus) intermediate states.
13766                  */
13767                 for_each_pipe(dev_priv, pipe) {
13768                         struct drm_crtc *crtc =
13769                                 dev_priv->pipe_to_crtc_mapping[pipe];
13770
13771                         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y,
13772                                        crtc->primary->fb);
13773                 }
13774         } else {
13775                 intel_modeset_update_staged_output_state(dev);
13776         }
13777
13778         intel_modeset_check_state(dev);
13779 }
13780
13781 void intel_modeset_gem_init(struct drm_device *dev)
13782 {
13783         struct drm_i915_private *dev_priv = dev->dev_private;
13784         struct drm_crtc *c;
13785         struct drm_i915_gem_object *obj;
13786
13787         mutex_lock(&dev->struct_mutex);
13788         intel_init_gt_powersave(dev);
13789         mutex_unlock(&dev->struct_mutex);
13790
13791         /*
13792          * There may be no VBT; and if the BIOS enabled SSC we can
13793          * just keep using it to avoid unnecessary flicker.  Whereas if the
13794          * BIOS isn't using it, don't assume it will work even if the VBT
13795          * indicates as much.
13796          */
13797         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13798                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
13799                                                 DREF_SSC1_ENABLE);
13800
13801         intel_modeset_init_hw(dev);
13802
13803         intel_setup_overlay(dev);
13804
13805         /*
13806          * Make sure any fbs we allocated at startup are properly
13807          * pinned & fenced.  When we do the allocation it's too early
13808          * for this.
13809          */
13810         mutex_lock(&dev->struct_mutex);
13811         for_each_crtc(dev, c) {
13812                 obj = intel_fb_obj(c->primary->fb);
13813                 if (obj == NULL)
13814                         continue;
13815
13816                 if (intel_pin_and_fence_fb_obj(c->primary,
13817                                                c->primary->fb,
13818                                                NULL)) {
13819                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
13820                                   to_intel_crtc(c)->pipe);
13821                         drm_framebuffer_unreference(c->primary->fb);
13822                         c->primary->fb = NULL;
13823                         update_state_fb(c->primary);
13824                 }
13825         }
13826         mutex_unlock(&dev->struct_mutex);
13827
13828         intel_backlight_register(dev);
13829 }
13830
13831 void intel_connector_unregister(struct intel_connector *intel_connector)
13832 {
13833         struct drm_connector *connector = &intel_connector->base;
13834
13835         intel_panel_destroy_backlight(connector);
13836         drm_connector_unregister(connector);
13837 }
13838
13839 void intel_modeset_cleanup(struct drm_device *dev)
13840 {
13841         struct drm_i915_private *dev_priv = dev->dev_private;
13842         struct drm_connector *connector;
13843
13844         intel_disable_gt_powersave(dev);
13845
13846         intel_backlight_unregister(dev);
13847
13848         /*
13849          * Interrupts and polling as the first thing to avoid creating havoc.
13850          * Too much stuff here (turning of connectors, ...) would
13851          * experience fancy races otherwise.
13852          */
13853         intel_irq_uninstall(dev_priv);
13854
13855         /*
13856          * Due to the hpd irq storm handling the hotplug work can re-arm the
13857          * poll handlers. Hence disable polling after hpd handling is shut down.
13858          */
13859         drm_kms_helper_poll_fini(dev);
13860
13861         mutex_lock(&dev->struct_mutex);
13862
13863         intel_unregister_dsm_handler();
13864
13865         intel_fbc_disable(dev);
13866
13867         ironlake_teardown_rc6(dev);
13868
13869         mutex_unlock(&dev->struct_mutex);
13870
13871         /* flush any delayed tasks or pending work */
13872         flush_scheduled_work();
13873
13874         /* destroy the backlight and sysfs files before encoders/connectors */
13875         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
13876                 struct intel_connector *intel_connector;
13877
13878                 intel_connector = to_intel_connector(connector);
13879                 intel_connector->unregister(intel_connector);
13880         }
13881
13882         drm_mode_config_cleanup(dev);
13883
13884         intel_cleanup_overlay(dev);
13885
13886         mutex_lock(&dev->struct_mutex);
13887         intel_cleanup_gt_powersave(dev);
13888         mutex_unlock(&dev->struct_mutex);
13889 }
13890
13891 /*
13892  * Return which encoder is currently attached for connector.
13893  */
13894 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
13895 {
13896         return &intel_attached_encoder(connector)->base;
13897 }
13898
13899 void intel_connector_attach_encoder(struct intel_connector *connector,
13900                                     struct intel_encoder *encoder)
13901 {
13902         connector->encoder = encoder;
13903         drm_mode_connector_attach_encoder(&connector->base,
13904                                           &encoder->base);
13905 }
13906
13907 /*
13908  * set vga decode state - true == enable VGA decode
13909  */
13910 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
13911 {
13912         struct drm_i915_private *dev_priv = dev->dev_private;
13913         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
13914         u16 gmch_ctrl;
13915
13916         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
13917                 DRM_ERROR("failed to read control word\n");
13918                 return -EIO;
13919         }
13920
13921         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
13922                 return 0;
13923
13924         if (state)
13925                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
13926         else
13927                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
13928
13929         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
13930                 DRM_ERROR("failed to write control word\n");
13931                 return -EIO;
13932         }
13933
13934         return 0;
13935 }
13936
13937 struct intel_display_error_state {
13938
13939         u32 power_well_driver;
13940
13941         int num_transcoders;
13942
13943         struct intel_cursor_error_state {
13944                 u32 control;
13945                 u32 position;
13946                 u32 base;
13947                 u32 size;
13948         } cursor[I915_MAX_PIPES];
13949
13950         struct intel_pipe_error_state {
13951                 bool power_domain_on;
13952                 u32 source;
13953                 u32 stat;
13954         } pipe[I915_MAX_PIPES];
13955
13956         struct intel_plane_error_state {
13957                 u32 control;
13958                 u32 stride;
13959                 u32 size;
13960                 u32 pos;
13961                 u32 addr;
13962                 u32 surface;
13963                 u32 tile_offset;
13964         } plane[I915_MAX_PIPES];
13965
13966         struct intel_transcoder_error_state {
13967                 bool power_domain_on;
13968                 enum transcoder cpu_transcoder;
13969
13970                 u32 conf;
13971
13972                 u32 htotal;
13973                 u32 hblank;
13974                 u32 hsync;
13975                 u32 vtotal;
13976                 u32 vblank;
13977                 u32 vsync;
13978         } transcoder[4];
13979 };
13980
13981 struct intel_display_error_state *
13982 intel_display_capture_error_state(struct drm_device *dev)
13983 {
13984         struct drm_i915_private *dev_priv = dev->dev_private;
13985         struct intel_display_error_state *error;
13986         int transcoders[] = {
13987                 TRANSCODER_A,
13988                 TRANSCODER_B,
13989                 TRANSCODER_C,
13990                 TRANSCODER_EDP,
13991         };
13992         int i;
13993
13994         if (INTEL_INFO(dev)->num_pipes == 0)
13995                 return NULL;
13996
13997         error = kzalloc(sizeof(*error), GFP_ATOMIC);
13998         if (error == NULL)
13999                 return NULL;
14000
14001         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
14002                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
14003
14004         for_each_pipe(dev_priv, i) {
14005                 error->pipe[i].power_domain_on =
14006                         __intel_display_power_is_enabled(dev_priv,
14007                                                          POWER_DOMAIN_PIPE(i));
14008                 if (!error->pipe[i].power_domain_on)
14009                         continue;
14010
14011                 error->cursor[i].control = I915_READ(CURCNTR(i));
14012                 error->cursor[i].position = I915_READ(CURPOS(i));
14013                 error->cursor[i].base = I915_READ(CURBASE(i));
14014
14015                 error->plane[i].control = I915_READ(DSPCNTR(i));
14016                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
14017                 if (INTEL_INFO(dev)->gen <= 3) {
14018                         error->plane[i].size = I915_READ(DSPSIZE(i));
14019                         error->plane[i].pos = I915_READ(DSPPOS(i));
14020                 }
14021                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
14022                         error->plane[i].addr = I915_READ(DSPADDR(i));
14023                 if (INTEL_INFO(dev)->gen >= 4) {
14024                         error->plane[i].surface = I915_READ(DSPSURF(i));
14025                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
14026                 }
14027
14028                 error->pipe[i].source = I915_READ(PIPESRC(i));
14029
14030                 if (HAS_GMCH_DISPLAY(dev))
14031                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
14032         }
14033
14034         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
14035         if (HAS_DDI(dev_priv->dev))
14036                 error->num_transcoders++; /* Account for eDP. */
14037
14038         for (i = 0; i < error->num_transcoders; i++) {
14039                 enum transcoder cpu_transcoder = transcoders[i];
14040
14041                 error->transcoder[i].power_domain_on =
14042                         __intel_display_power_is_enabled(dev_priv,
14043                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
14044                 if (!error->transcoder[i].power_domain_on)
14045                         continue;
14046
14047                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
14048
14049                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
14050                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
14051                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
14052                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
14053                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
14054                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
14055                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
14056         }
14057
14058         return error;
14059 }
14060
14061 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
14062
14063 void
14064 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
14065                                 struct drm_device *dev,
14066                                 struct intel_display_error_state *error)
14067 {
14068         struct drm_i915_private *dev_priv = dev->dev_private;
14069         int i;
14070
14071         if (!error)
14072                 return;
14073
14074         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
14075         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
14076                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
14077                            error->power_well_driver);
14078         for_each_pipe(dev_priv, i) {
14079                 err_printf(m, "Pipe [%d]:\n", i);
14080                 err_printf(m, "  Power: %s\n",
14081                            error->pipe[i].power_domain_on ? "on" : "off");
14082                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
14083                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
14084
14085                 err_printf(m, "Plane [%d]:\n", i);
14086                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
14087                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
14088                 if (INTEL_INFO(dev)->gen <= 3) {
14089                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
14090                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
14091                 }
14092                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
14093                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
14094                 if (INTEL_INFO(dev)->gen >= 4) {
14095                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
14096                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
14097                 }
14098
14099                 err_printf(m, "Cursor [%d]:\n", i);
14100                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
14101                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
14102                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
14103         }
14104
14105         for (i = 0; i < error->num_transcoders; i++) {
14106                 err_printf(m, "CPU transcoder: %c\n",
14107                            transcoder_name(error->transcoder[i].cpu_transcoder));
14108                 err_printf(m, "  Power: %s\n",
14109                            error->transcoder[i].power_domain_on ? "on" : "off");
14110                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
14111                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
14112                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
14113                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
14114                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
14115                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
14116                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
14117         }
14118 }
14119
14120 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
14121 {
14122         struct intel_crtc *crtc;
14123
14124         for_each_intel_crtc(dev, crtc) {
14125                 struct intel_unpin_work *work;
14126
14127                 spin_lock_irq(&dev->event_lock);
14128
14129                 work = crtc->unpin_work;
14130
14131                 if (work && work->event &&
14132                     work->event->base.file_priv == file) {
14133                         kfree(work->event);
14134                         work->event = NULL;
14135                 }
14136
14137                 spin_unlock_irq(&dev->event_lock);
14138         }
14139 }