]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Drop checks for max_pixclk failures in cdclk computation
[linux-beck.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 "intel_dsi.h"
40 #include "i915_trace.h"
41 #include <drm/drm_atomic.h>
42 #include <drm/drm_atomic_helper.h>
43 #include <drm/drm_dp_helper.h>
44 #include <drm/drm_crtc_helper.h>
45 #include <drm/drm_plane_helper.h>
46 #include <drm/drm_rect.h>
47 #include <linux/dma_remapping.h>
48 #include <linux/reservation.h>
49 #include <linux/dma-buf.h>
50
51 /* Primary plane formats for gen <= 3 */
52 static const uint32_t i8xx_primary_formats[] = {
53         DRM_FORMAT_C8,
54         DRM_FORMAT_RGB565,
55         DRM_FORMAT_XRGB1555,
56         DRM_FORMAT_XRGB8888,
57 };
58
59 /* Primary plane formats for gen >= 4 */
60 static const uint32_t i965_primary_formats[] = {
61         DRM_FORMAT_C8,
62         DRM_FORMAT_RGB565,
63         DRM_FORMAT_XRGB8888,
64         DRM_FORMAT_XBGR8888,
65         DRM_FORMAT_XRGB2101010,
66         DRM_FORMAT_XBGR2101010,
67 };
68
69 static const uint32_t skl_primary_formats[] = {
70         DRM_FORMAT_C8,
71         DRM_FORMAT_RGB565,
72         DRM_FORMAT_XRGB8888,
73         DRM_FORMAT_XBGR8888,
74         DRM_FORMAT_ARGB8888,
75         DRM_FORMAT_ABGR8888,
76         DRM_FORMAT_XRGB2101010,
77         DRM_FORMAT_XBGR2101010,
78         DRM_FORMAT_YUYV,
79         DRM_FORMAT_YVYU,
80         DRM_FORMAT_UYVY,
81         DRM_FORMAT_VYUY,
82 };
83
84 /* Cursor formats */
85 static const uint32_t intel_cursor_formats[] = {
86         DRM_FORMAT_ARGB8888,
87 };
88
89 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
90                                 struct intel_crtc_state *pipe_config);
91 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
92                                    struct intel_crtc_state *pipe_config);
93
94 static int intel_framebuffer_init(struct drm_device *dev,
95                                   struct intel_framebuffer *ifb,
96                                   struct drm_mode_fb_cmd2 *mode_cmd,
97                                   struct drm_i915_gem_object *obj);
98 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
99 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
100 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
101 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
102                                          struct intel_link_m_n *m_n,
103                                          struct intel_link_m_n *m2_n2);
104 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
105 static void haswell_set_pipeconf(struct drm_crtc *crtc);
106 static void haswell_set_pipemisc(struct drm_crtc *crtc);
107 static void vlv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void chv_prepare_pll(struct intel_crtc *crtc,
110                             const struct intel_crtc_state *pipe_config);
111 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
112 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
113 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
114         struct intel_crtc_state *crtc_state);
115 static void skylake_pfit_enable(struct intel_crtc *crtc);
116 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
117 static void ironlake_pfit_enable(struct intel_crtc *crtc);
118 static void intel_modeset_setup_hw_state(struct drm_device *dev);
119 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
120
121 struct intel_limit {
122         struct {
123                 int min, max;
124         } dot, vco, n, m, m1, m2, p, p1;
125
126         struct {
127                 int dot_limit;
128                 int p2_slow, p2_fast;
129         } p2;
130 };
131
132 /* returns HPLL frequency in kHz */
133 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
134 {
135         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
136
137         /* Obtain SKU information */
138         mutex_lock(&dev_priv->sb_lock);
139         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
140                 CCK_FUSE_HPLL_FREQ_MASK;
141         mutex_unlock(&dev_priv->sb_lock);
142
143         return vco_freq[hpll_freq] * 1000;
144 }
145
146 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
147                       const char *name, u32 reg, int ref_freq)
148 {
149         u32 val;
150         int divider;
151
152         mutex_lock(&dev_priv->sb_lock);
153         val = vlv_cck_read(dev_priv, reg);
154         mutex_unlock(&dev_priv->sb_lock);
155
156         divider = val & CCK_FREQUENCY_VALUES;
157
158         WARN((val & CCK_FREQUENCY_STATUS) !=
159              (divider << CCK_FREQUENCY_STATUS_SHIFT),
160              "%s change in progress\n", name);
161
162         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
163 }
164
165 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
166                                   const char *name, u32 reg)
167 {
168         if (dev_priv->hpll_freq == 0)
169                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
170
171         return vlv_get_cck_clock(dev_priv, name, reg,
172                                  dev_priv->hpll_freq);
173 }
174
175 static int
176 intel_pch_rawclk(struct drm_i915_private *dev_priv)
177 {
178         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
179 }
180
181 static int
182 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
183 {
184         /* RAWCLK_FREQ_VLV register updated from power well code */
185         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
186                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
187 }
188
189 static int
190 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         uint32_t clkcfg;
193
194         /* hrawclock is 1/4 the FSB frequency */
195         clkcfg = I915_READ(CLKCFG);
196         switch (clkcfg & CLKCFG_FSB_MASK) {
197         case CLKCFG_FSB_400:
198                 return 100000;
199         case CLKCFG_FSB_533:
200                 return 133333;
201         case CLKCFG_FSB_667:
202                 return 166667;
203         case CLKCFG_FSB_800:
204                 return 200000;
205         case CLKCFG_FSB_1067:
206                 return 266667;
207         case CLKCFG_FSB_1333:
208                 return 333333;
209         /* these two are just a guess; one of them might be right */
210         case CLKCFG_FSB_1600:
211         case CLKCFG_FSB_1600_ALT:
212                 return 400000;
213         default:
214                 return 133333;
215         }
216 }
217
218 void intel_update_rawclk(struct drm_i915_private *dev_priv)
219 {
220         if (HAS_PCH_SPLIT(dev_priv))
221                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
222         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
223                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
224         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
225                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
226         else
227                 return; /* no rawclk on other platforms, or no need to know it */
228
229         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
230 }
231
232 static void intel_update_czclk(struct drm_i915_private *dev_priv)
233 {
234         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
235                 return;
236
237         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
238                                                       CCK_CZ_CLOCK_CONTROL);
239
240         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
241 }
242
243 static inline u32 /* units of 100MHz */
244 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
245                     const struct intel_crtc_state *pipe_config)
246 {
247         if (HAS_DDI(dev_priv))
248                 return pipe_config->port_clock; /* SPLL */
249         else if (IS_GEN5(dev_priv))
250                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
251         else
252                 return 270000;
253 }
254
255 static const struct intel_limit intel_limits_i8xx_dac = {
256         .dot = { .min = 25000, .max = 350000 },
257         .vco = { .min = 908000, .max = 1512000 },
258         .n = { .min = 2, .max = 16 },
259         .m = { .min = 96, .max = 140 },
260         .m1 = { .min = 18, .max = 26 },
261         .m2 = { .min = 6, .max = 16 },
262         .p = { .min = 4, .max = 128 },
263         .p1 = { .min = 2, .max = 33 },
264         .p2 = { .dot_limit = 165000,
265                 .p2_slow = 4, .p2_fast = 2 },
266 };
267
268 static const struct intel_limit intel_limits_i8xx_dvo = {
269         .dot = { .min = 25000, .max = 350000 },
270         .vco = { .min = 908000, .max = 1512000 },
271         .n = { .min = 2, .max = 16 },
272         .m = { .min = 96, .max = 140 },
273         .m1 = { .min = 18, .max = 26 },
274         .m2 = { .min = 6, .max = 16 },
275         .p = { .min = 4, .max = 128 },
276         .p1 = { .min = 2, .max = 33 },
277         .p2 = { .dot_limit = 165000,
278                 .p2_slow = 4, .p2_fast = 4 },
279 };
280
281 static const struct intel_limit intel_limits_i8xx_lvds = {
282         .dot = { .min = 25000, .max = 350000 },
283         .vco = { .min = 908000, .max = 1512000 },
284         .n = { .min = 2, .max = 16 },
285         .m = { .min = 96, .max = 140 },
286         .m1 = { .min = 18, .max = 26 },
287         .m2 = { .min = 6, .max = 16 },
288         .p = { .min = 4, .max = 128 },
289         .p1 = { .min = 1, .max = 6 },
290         .p2 = { .dot_limit = 165000,
291                 .p2_slow = 14, .p2_fast = 7 },
292 };
293
294 static const struct intel_limit intel_limits_i9xx_sdvo = {
295         .dot = { .min = 20000, .max = 400000 },
296         .vco = { .min = 1400000, .max = 2800000 },
297         .n = { .min = 1, .max = 6 },
298         .m = { .min = 70, .max = 120 },
299         .m1 = { .min = 8, .max = 18 },
300         .m2 = { .min = 3, .max = 7 },
301         .p = { .min = 5, .max = 80 },
302         .p1 = { .min = 1, .max = 8 },
303         .p2 = { .dot_limit = 200000,
304                 .p2_slow = 10, .p2_fast = 5 },
305 };
306
307 static const struct intel_limit intel_limits_i9xx_lvds = {
308         .dot = { .min = 20000, .max = 400000 },
309         .vco = { .min = 1400000, .max = 2800000 },
310         .n = { .min = 1, .max = 6 },
311         .m = { .min = 70, .max = 120 },
312         .m1 = { .min = 8, .max = 18 },
313         .m2 = { .min = 3, .max = 7 },
314         .p = { .min = 7, .max = 98 },
315         .p1 = { .min = 1, .max = 8 },
316         .p2 = { .dot_limit = 112000,
317                 .p2_slow = 14, .p2_fast = 7 },
318 };
319
320
321 static const struct intel_limit intel_limits_g4x_sdvo = {
322         .dot = { .min = 25000, .max = 270000 },
323         .vco = { .min = 1750000, .max = 3500000},
324         .n = { .min = 1, .max = 4 },
325         .m = { .min = 104, .max = 138 },
326         .m1 = { .min = 17, .max = 23 },
327         .m2 = { .min = 5, .max = 11 },
328         .p = { .min = 10, .max = 30 },
329         .p1 = { .min = 1, .max = 3},
330         .p2 = { .dot_limit = 270000,
331                 .p2_slow = 10,
332                 .p2_fast = 10
333         },
334 };
335
336 static const struct intel_limit intel_limits_g4x_hdmi = {
337         .dot = { .min = 22000, .max = 400000 },
338         .vco = { .min = 1750000, .max = 3500000},
339         .n = { .min = 1, .max = 4 },
340         .m = { .min = 104, .max = 138 },
341         .m1 = { .min = 16, .max = 23 },
342         .m2 = { .min = 5, .max = 11 },
343         .p = { .min = 5, .max = 80 },
344         .p1 = { .min = 1, .max = 8},
345         .p2 = { .dot_limit = 165000,
346                 .p2_slow = 10, .p2_fast = 5 },
347 };
348
349 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
350         .dot = { .min = 20000, .max = 115000 },
351         .vco = { .min = 1750000, .max = 3500000 },
352         .n = { .min = 1, .max = 3 },
353         .m = { .min = 104, .max = 138 },
354         .m1 = { .min = 17, .max = 23 },
355         .m2 = { .min = 5, .max = 11 },
356         .p = { .min = 28, .max = 112 },
357         .p1 = { .min = 2, .max = 8 },
358         .p2 = { .dot_limit = 0,
359                 .p2_slow = 14, .p2_fast = 14
360         },
361 };
362
363 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
364         .dot = { .min = 80000, .max = 224000 },
365         .vco = { .min = 1750000, .max = 3500000 },
366         .n = { .min = 1, .max = 3 },
367         .m = { .min = 104, .max = 138 },
368         .m1 = { .min = 17, .max = 23 },
369         .m2 = { .min = 5, .max = 11 },
370         .p = { .min = 14, .max = 42 },
371         .p1 = { .min = 2, .max = 6 },
372         .p2 = { .dot_limit = 0,
373                 .p2_slow = 7, .p2_fast = 7
374         },
375 };
376
377 static const struct intel_limit intel_limits_pineview_sdvo = {
378         .dot = { .min = 20000, .max = 400000},
379         .vco = { .min = 1700000, .max = 3500000 },
380         /* Pineview's Ncounter is a ring counter */
381         .n = { .min = 3, .max = 6 },
382         .m = { .min = 2, .max = 256 },
383         /* Pineview only has one combined m divider, which we treat as m2. */
384         .m1 = { .min = 0, .max = 0 },
385         .m2 = { .min = 0, .max = 254 },
386         .p = { .min = 5, .max = 80 },
387         .p1 = { .min = 1, .max = 8 },
388         .p2 = { .dot_limit = 200000,
389                 .p2_slow = 10, .p2_fast = 5 },
390 };
391
392 static const struct intel_limit intel_limits_pineview_lvds = {
393         .dot = { .min = 20000, .max = 400000 },
394         .vco = { .min = 1700000, .max = 3500000 },
395         .n = { .min = 3, .max = 6 },
396         .m = { .min = 2, .max = 256 },
397         .m1 = { .min = 0, .max = 0 },
398         .m2 = { .min = 0, .max = 254 },
399         .p = { .min = 7, .max = 112 },
400         .p1 = { .min = 1, .max = 8 },
401         .p2 = { .dot_limit = 112000,
402                 .p2_slow = 14, .p2_fast = 14 },
403 };
404
405 /* Ironlake / Sandybridge
406  *
407  * We calculate clock using (register_value + 2) for N/M1/M2, so here
408  * the range value for them is (actual_value - 2).
409  */
410 static const struct intel_limit intel_limits_ironlake_dac = {
411         .dot = { .min = 25000, .max = 350000 },
412         .vco = { .min = 1760000, .max = 3510000 },
413         .n = { .min = 1, .max = 5 },
414         .m = { .min = 79, .max = 127 },
415         .m1 = { .min = 12, .max = 22 },
416         .m2 = { .min = 5, .max = 9 },
417         .p = { .min = 5, .max = 80 },
418         .p1 = { .min = 1, .max = 8 },
419         .p2 = { .dot_limit = 225000,
420                 .p2_slow = 10, .p2_fast = 5 },
421 };
422
423 static const struct intel_limit intel_limits_ironlake_single_lvds = {
424         .dot = { .min = 25000, .max = 350000 },
425         .vco = { .min = 1760000, .max = 3510000 },
426         .n = { .min = 1, .max = 3 },
427         .m = { .min = 79, .max = 118 },
428         .m1 = { .min = 12, .max = 22 },
429         .m2 = { .min = 5, .max = 9 },
430         .p = { .min = 28, .max = 112 },
431         .p1 = { .min = 2, .max = 8 },
432         .p2 = { .dot_limit = 225000,
433                 .p2_slow = 14, .p2_fast = 14 },
434 };
435
436 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
437         .dot = { .min = 25000, .max = 350000 },
438         .vco = { .min = 1760000, .max = 3510000 },
439         .n = { .min = 1, .max = 3 },
440         .m = { .min = 79, .max = 127 },
441         .m1 = { .min = 12, .max = 22 },
442         .m2 = { .min = 5, .max = 9 },
443         .p = { .min = 14, .max = 56 },
444         .p1 = { .min = 2, .max = 8 },
445         .p2 = { .dot_limit = 225000,
446                 .p2_slow = 7, .p2_fast = 7 },
447 };
448
449 /* LVDS 100mhz refclk limits. */
450 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
451         .dot = { .min = 25000, .max = 350000 },
452         .vco = { .min = 1760000, .max = 3510000 },
453         .n = { .min = 1, .max = 2 },
454         .m = { .min = 79, .max = 126 },
455         .m1 = { .min = 12, .max = 22 },
456         .m2 = { .min = 5, .max = 9 },
457         .p = { .min = 28, .max = 112 },
458         .p1 = { .min = 2, .max = 8 },
459         .p2 = { .dot_limit = 225000,
460                 .p2_slow = 14, .p2_fast = 14 },
461 };
462
463 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
464         .dot = { .min = 25000, .max = 350000 },
465         .vco = { .min = 1760000, .max = 3510000 },
466         .n = { .min = 1, .max = 3 },
467         .m = { .min = 79, .max = 126 },
468         .m1 = { .min = 12, .max = 22 },
469         .m2 = { .min = 5, .max = 9 },
470         .p = { .min = 14, .max = 42 },
471         .p1 = { .min = 2, .max = 6 },
472         .p2 = { .dot_limit = 225000,
473                 .p2_slow = 7, .p2_fast = 7 },
474 };
475
476 static const struct intel_limit intel_limits_vlv = {
477          /*
478           * These are the data rate limits (measured in fast clocks)
479           * since those are the strictest limits we have. The fast
480           * clock and actual rate limits are more relaxed, so checking
481           * them would make no difference.
482           */
483         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
484         .vco = { .min = 4000000, .max = 6000000 },
485         .n = { .min = 1, .max = 7 },
486         .m1 = { .min = 2, .max = 3 },
487         .m2 = { .min = 11, .max = 156 },
488         .p1 = { .min = 2, .max = 3 },
489         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
490 };
491
492 static const struct intel_limit intel_limits_chv = {
493         /*
494          * These are the data rate limits (measured in fast clocks)
495          * since those are the strictest limits we have.  The fast
496          * clock and actual rate limits are more relaxed, so checking
497          * them would make no difference.
498          */
499         .dot = { .min = 25000 * 5, .max = 540000 * 5},
500         .vco = { .min = 4800000, .max = 6480000 },
501         .n = { .min = 1, .max = 1 },
502         .m1 = { .min = 2, .max = 2 },
503         .m2 = { .min = 24 << 22, .max = 175 << 22 },
504         .p1 = { .min = 2, .max = 4 },
505         .p2 = { .p2_slow = 1, .p2_fast = 14 },
506 };
507
508 static const struct intel_limit intel_limits_bxt = {
509         /* FIXME: find real dot limits */
510         .dot = { .min = 0, .max = INT_MAX },
511         .vco = { .min = 4800000, .max = 6700000 },
512         .n = { .min = 1, .max = 1 },
513         .m1 = { .min = 2, .max = 2 },
514         /* FIXME: find real m2 limits */
515         .m2 = { .min = 2 << 22, .max = 255 << 22 },
516         .p1 = { .min = 2, .max = 4 },
517         .p2 = { .p2_slow = 1, .p2_fast = 20 },
518 };
519
520 static bool
521 needs_modeset(struct drm_crtc_state *state)
522 {
523         return drm_atomic_crtc_needs_modeset(state);
524 }
525
526 /**
527  * Returns whether any output on the specified pipe is of the specified type
528  */
529 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
530 {
531         struct drm_device *dev = crtc->base.dev;
532         struct intel_encoder *encoder;
533
534         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
535                 if (encoder->type == type)
536                         return true;
537
538         return false;
539 }
540
541 /**
542  * Returns whether any output on the specified pipe will have the specified
543  * type after a staged modeset is complete, i.e., the same as
544  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
545  * encoder->crtc.
546  */
547 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
548                                       int type)
549 {
550         struct drm_atomic_state *state = crtc_state->base.state;
551         struct drm_connector *connector;
552         struct drm_connector_state *connector_state;
553         struct intel_encoder *encoder;
554         int i, num_connectors = 0;
555
556         for_each_connector_in_state(state, connector, connector_state, i) {
557                 if (connector_state->crtc != crtc_state->base.crtc)
558                         continue;
559
560                 num_connectors++;
561
562                 encoder = to_intel_encoder(connector_state->best_encoder);
563                 if (encoder->type == type)
564                         return true;
565         }
566
567         WARN_ON(num_connectors == 0);
568
569         return false;
570 }
571
572 /*
573  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
574  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
575  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
576  * The helpers' return value is the rate of the clock that is fed to the
577  * display engine's pipe which can be the above fast dot clock rate or a
578  * divided-down version of it.
579  */
580 /* m1 is reserved as 0 in Pineview, n is a ring counter */
581 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
582 {
583         clock->m = clock->m2 + 2;
584         clock->p = clock->p1 * clock->p2;
585         if (WARN_ON(clock->n == 0 || clock->p == 0))
586                 return 0;
587         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
588         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
589
590         return clock->dot;
591 }
592
593 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
594 {
595         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
596 }
597
598 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
599 {
600         clock->m = i9xx_dpll_compute_m(clock);
601         clock->p = clock->p1 * clock->p2;
602         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
603                 return 0;
604         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
605         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
606
607         return clock->dot;
608 }
609
610 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
611 {
612         clock->m = clock->m1 * clock->m2;
613         clock->p = clock->p1 * clock->p2;
614         if (WARN_ON(clock->n == 0 || clock->p == 0))
615                 return 0;
616         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
617         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
618
619         return clock->dot / 5;
620 }
621
622 int chv_calc_dpll_params(int refclk, struct dpll *clock)
623 {
624         clock->m = clock->m1 * clock->m2;
625         clock->p = clock->p1 * clock->p2;
626         if (WARN_ON(clock->n == 0 || clock->p == 0))
627                 return 0;
628         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
629                         clock->n << 22);
630         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
631
632         return clock->dot / 5;
633 }
634
635 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
636 /**
637  * Returns whether the given set of divisors are valid for a given refclk with
638  * the given connectors.
639  */
640
641 static bool intel_PLL_is_valid(struct drm_device *dev,
642                                const struct intel_limit *limit,
643                                const struct dpll *clock)
644 {
645         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
646                 INTELPllInvalid("n out of range\n");
647         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
648                 INTELPllInvalid("p1 out of range\n");
649         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
650                 INTELPllInvalid("m2 out of range\n");
651         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
652                 INTELPllInvalid("m1 out of range\n");
653
654         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
655             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
656                 if (clock->m1 <= clock->m2)
657                         INTELPllInvalid("m1 <= m2\n");
658
659         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
660                 if (clock->p < limit->p.min || limit->p.max < clock->p)
661                         INTELPllInvalid("p out of range\n");
662                 if (clock->m < limit->m.min || limit->m.max < clock->m)
663                         INTELPllInvalid("m out of range\n");
664         }
665
666         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
667                 INTELPllInvalid("vco out of range\n");
668         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
669          * connector, etc., rather than just a single range.
670          */
671         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
672                 INTELPllInvalid("dot out of range\n");
673
674         return true;
675 }
676
677 static int
678 i9xx_select_p2_div(const struct intel_limit *limit,
679                    const struct intel_crtc_state *crtc_state,
680                    int target)
681 {
682         struct drm_device *dev = crtc_state->base.crtc->dev;
683
684         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
685                 /*
686                  * For LVDS just rely on its current settings for dual-channel.
687                  * We haven't figured out how to reliably set up different
688                  * single/dual channel state, if we even can.
689                  */
690                 if (intel_is_dual_link_lvds(dev))
691                         return limit->p2.p2_fast;
692                 else
693                         return limit->p2.p2_slow;
694         } else {
695                 if (target < limit->p2.dot_limit)
696                         return limit->p2.p2_slow;
697                 else
698                         return limit->p2.p2_fast;
699         }
700 }
701
702 /*
703  * Returns a set of divisors for the desired target clock with the given
704  * refclk, or FALSE.  The returned values represent the clock equation:
705  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
706  *
707  * Target and reference clocks are specified in kHz.
708  *
709  * If match_clock is provided, then best_clock P divider must match the P
710  * divider from @match_clock used for LVDS downclocking.
711  */
712 static bool
713 i9xx_find_best_dpll(const struct intel_limit *limit,
714                     struct intel_crtc_state *crtc_state,
715                     int target, int refclk, struct dpll *match_clock,
716                     struct dpll *best_clock)
717 {
718         struct drm_device *dev = crtc_state->base.crtc->dev;
719         struct dpll clock;
720         int err = target;
721
722         memset(best_clock, 0, sizeof(*best_clock));
723
724         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
725
726         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
727              clock.m1++) {
728                 for (clock.m2 = limit->m2.min;
729                      clock.m2 <= limit->m2.max; clock.m2++) {
730                         if (clock.m2 >= clock.m1)
731                                 break;
732                         for (clock.n = limit->n.min;
733                              clock.n <= limit->n.max; clock.n++) {
734                                 for (clock.p1 = limit->p1.min;
735                                         clock.p1 <= limit->p1.max; clock.p1++) {
736                                         int this_err;
737
738                                         i9xx_calc_dpll_params(refclk, &clock);
739                                         if (!intel_PLL_is_valid(dev, limit,
740                                                                 &clock))
741                                                 continue;
742                                         if (match_clock &&
743                                             clock.p != match_clock->p)
744                                                 continue;
745
746                                         this_err = abs(clock.dot - target);
747                                         if (this_err < err) {
748                                                 *best_clock = clock;
749                                                 err = this_err;
750                                         }
751                                 }
752                         }
753                 }
754         }
755
756         return (err != target);
757 }
758
759 /*
760  * Returns a set of divisors for the desired target clock with the given
761  * refclk, or FALSE.  The returned values represent the clock equation:
762  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
763  *
764  * Target and reference clocks are specified in kHz.
765  *
766  * If match_clock is provided, then best_clock P divider must match the P
767  * divider from @match_clock used for LVDS downclocking.
768  */
769 static bool
770 pnv_find_best_dpll(const struct intel_limit *limit,
771                    struct intel_crtc_state *crtc_state,
772                    int target, int refclk, struct dpll *match_clock,
773                    struct dpll *best_clock)
774 {
775         struct drm_device *dev = crtc_state->base.crtc->dev;
776         struct dpll clock;
777         int err = target;
778
779         memset(best_clock, 0, sizeof(*best_clock));
780
781         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
782
783         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
784              clock.m1++) {
785                 for (clock.m2 = limit->m2.min;
786                      clock.m2 <= limit->m2.max; clock.m2++) {
787                         for (clock.n = limit->n.min;
788                              clock.n <= limit->n.max; clock.n++) {
789                                 for (clock.p1 = limit->p1.min;
790                                         clock.p1 <= limit->p1.max; clock.p1++) {
791                                         int this_err;
792
793                                         pnv_calc_dpll_params(refclk, &clock);
794                                         if (!intel_PLL_is_valid(dev, limit,
795                                                                 &clock))
796                                                 continue;
797                                         if (match_clock &&
798                                             clock.p != match_clock->p)
799                                                 continue;
800
801                                         this_err = abs(clock.dot - target);
802                                         if (this_err < err) {
803                                                 *best_clock = clock;
804                                                 err = this_err;
805                                         }
806                                 }
807                         }
808                 }
809         }
810
811         return (err != target);
812 }
813
814 /*
815  * Returns a set of divisors for the desired target clock with the given
816  * refclk, or FALSE.  The returned values represent the clock equation:
817  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
818  *
819  * Target and reference clocks are specified in kHz.
820  *
821  * If match_clock is provided, then best_clock P divider must match the P
822  * divider from @match_clock used for LVDS downclocking.
823  */
824 static bool
825 g4x_find_best_dpll(const struct intel_limit *limit,
826                    struct intel_crtc_state *crtc_state,
827                    int target, int refclk, struct dpll *match_clock,
828                    struct dpll *best_clock)
829 {
830         struct drm_device *dev = crtc_state->base.crtc->dev;
831         struct dpll clock;
832         int max_n;
833         bool found = false;
834         /* approximately equals target * 0.00585 */
835         int err_most = (target >> 8) + (target >> 9);
836
837         memset(best_clock, 0, sizeof(*best_clock));
838
839         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
840
841         max_n = limit->n.max;
842         /* based on hardware requirement, prefer smaller n to precision */
843         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
844                 /* based on hardware requirement, prefere larger m1,m2 */
845                 for (clock.m1 = limit->m1.max;
846                      clock.m1 >= limit->m1.min; clock.m1--) {
847                         for (clock.m2 = limit->m2.max;
848                              clock.m2 >= limit->m2.min; clock.m2--) {
849                                 for (clock.p1 = limit->p1.max;
850                                      clock.p1 >= limit->p1.min; clock.p1--) {
851                                         int this_err;
852
853                                         i9xx_calc_dpll_params(refclk, &clock);
854                                         if (!intel_PLL_is_valid(dev, limit,
855                                                                 &clock))
856                                                 continue;
857
858                                         this_err = abs(clock.dot - target);
859                                         if (this_err < err_most) {
860                                                 *best_clock = clock;
861                                                 err_most = this_err;
862                                                 max_n = clock.n;
863                                                 found = true;
864                                         }
865                                 }
866                         }
867                 }
868         }
869         return found;
870 }
871
872 /*
873  * Check if the calculated PLL configuration is more optimal compared to the
874  * best configuration and error found so far. Return the calculated error.
875  */
876 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
877                                const struct dpll *calculated_clock,
878                                const struct dpll *best_clock,
879                                unsigned int best_error_ppm,
880                                unsigned int *error_ppm)
881 {
882         /*
883          * For CHV ignore the error and consider only the P value.
884          * Prefer a bigger P value based on HW requirements.
885          */
886         if (IS_CHERRYVIEW(dev)) {
887                 *error_ppm = 0;
888
889                 return calculated_clock->p > best_clock->p;
890         }
891
892         if (WARN_ON_ONCE(!target_freq))
893                 return false;
894
895         *error_ppm = div_u64(1000000ULL *
896                                 abs(target_freq - calculated_clock->dot),
897                              target_freq);
898         /*
899          * Prefer a better P value over a better (smaller) error if the error
900          * is small. Ensure this preference for future configurations too by
901          * setting the error to 0.
902          */
903         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
904                 *error_ppm = 0;
905
906                 return true;
907         }
908
909         return *error_ppm + 10 < best_error_ppm;
910 }
911
912 /*
913  * Returns a set of divisors for the desired target clock with the given
914  * refclk, or FALSE.  The returned values represent the clock equation:
915  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
916  */
917 static bool
918 vlv_find_best_dpll(const struct intel_limit *limit,
919                    struct intel_crtc_state *crtc_state,
920                    int target, int refclk, struct dpll *match_clock,
921                    struct dpll *best_clock)
922 {
923         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
924         struct drm_device *dev = crtc->base.dev;
925         struct dpll clock;
926         unsigned int bestppm = 1000000;
927         /* min update 19.2 MHz */
928         int max_n = min(limit->n.max, refclk / 19200);
929         bool found = false;
930
931         target *= 5; /* fast clock */
932
933         memset(best_clock, 0, sizeof(*best_clock));
934
935         /* based on hardware requirement, prefer smaller n to precision */
936         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
937                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
938                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
939                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
940                                 clock.p = clock.p1 * clock.p2;
941                                 /* based on hardware requirement, prefer bigger m1,m2 values */
942                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
943                                         unsigned int ppm;
944
945                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
946                                                                      refclk * clock.m1);
947
948                                         vlv_calc_dpll_params(refclk, &clock);
949
950                                         if (!intel_PLL_is_valid(dev, limit,
951                                                                 &clock))
952                                                 continue;
953
954                                         if (!vlv_PLL_is_optimal(dev, target,
955                                                                 &clock,
956                                                                 best_clock,
957                                                                 bestppm, &ppm))
958                                                 continue;
959
960                                         *best_clock = clock;
961                                         bestppm = ppm;
962                                         found = true;
963                                 }
964                         }
965                 }
966         }
967
968         return found;
969 }
970
971 /*
972  * Returns a set of divisors for the desired target clock with the given
973  * refclk, or FALSE.  The returned values represent the clock equation:
974  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
975  */
976 static bool
977 chv_find_best_dpll(const struct intel_limit *limit,
978                    struct intel_crtc_state *crtc_state,
979                    int target, int refclk, struct dpll *match_clock,
980                    struct dpll *best_clock)
981 {
982         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
983         struct drm_device *dev = crtc->base.dev;
984         unsigned int best_error_ppm;
985         struct dpll clock;
986         uint64_t m2;
987         int found = false;
988
989         memset(best_clock, 0, sizeof(*best_clock));
990         best_error_ppm = 1000000;
991
992         /*
993          * Based on hardware doc, the n always set to 1, and m1 always
994          * set to 2.  If requires to support 200Mhz refclk, we need to
995          * revisit this because n may not 1 anymore.
996          */
997         clock.n = 1, clock.m1 = 2;
998         target *= 5;    /* fast clock */
999
1000         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1001                 for (clock.p2 = limit->p2.p2_fast;
1002                                 clock.p2 >= limit->p2.p2_slow;
1003                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1004                         unsigned int error_ppm;
1005
1006                         clock.p = clock.p1 * clock.p2;
1007
1008                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1009                                         clock.n) << 22, refclk * clock.m1);
1010
1011                         if (m2 > INT_MAX/clock.m1)
1012                                 continue;
1013
1014                         clock.m2 = m2;
1015
1016                         chv_calc_dpll_params(refclk, &clock);
1017
1018                         if (!intel_PLL_is_valid(dev, limit, &clock))
1019                                 continue;
1020
1021                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1022                                                 best_error_ppm, &error_ppm))
1023                                 continue;
1024
1025                         *best_clock = clock;
1026                         best_error_ppm = error_ppm;
1027                         found = true;
1028                 }
1029         }
1030
1031         return found;
1032 }
1033
1034 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1035                         struct dpll *best_clock)
1036 {
1037         int refclk = 100000;
1038         const struct intel_limit *limit = &intel_limits_bxt;
1039
1040         return chv_find_best_dpll(limit, crtc_state,
1041                                   target_clock, refclk, NULL, best_clock);
1042 }
1043
1044 bool intel_crtc_active(struct drm_crtc *crtc)
1045 {
1046         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1047
1048         /* Be paranoid as we can arrive here with only partial
1049          * state retrieved from the hardware during setup.
1050          *
1051          * We can ditch the adjusted_mode.crtc_clock check as soon
1052          * as Haswell has gained clock readout/fastboot support.
1053          *
1054          * We can ditch the crtc->primary->fb check as soon as we can
1055          * properly reconstruct framebuffers.
1056          *
1057          * FIXME: The intel_crtc->active here should be switched to
1058          * crtc->state->active once we have proper CRTC states wired up
1059          * for atomic.
1060          */
1061         return intel_crtc->active && crtc->primary->state->fb &&
1062                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1063 }
1064
1065 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1066                                              enum pipe pipe)
1067 {
1068         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1069         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1070
1071         return intel_crtc->config->cpu_transcoder;
1072 }
1073
1074 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1075 {
1076         struct drm_i915_private *dev_priv = dev->dev_private;
1077         i915_reg_t reg = PIPEDSL(pipe);
1078         u32 line1, line2;
1079         u32 line_mask;
1080
1081         if (IS_GEN2(dev))
1082                 line_mask = DSL_LINEMASK_GEN2;
1083         else
1084                 line_mask = DSL_LINEMASK_GEN3;
1085
1086         line1 = I915_READ(reg) & line_mask;
1087         msleep(5);
1088         line2 = I915_READ(reg) & line_mask;
1089
1090         return line1 == line2;
1091 }
1092
1093 /*
1094  * intel_wait_for_pipe_off - wait for pipe to turn off
1095  * @crtc: crtc whose pipe to wait for
1096  *
1097  * After disabling a pipe, we can't wait for vblank in the usual way,
1098  * spinning on the vblank interrupt status bit, since we won't actually
1099  * see an interrupt when the pipe is disabled.
1100  *
1101  * On Gen4 and above:
1102  *   wait for the pipe register state bit to turn off
1103  *
1104  * Otherwise:
1105  *   wait for the display line value to settle (it usually
1106  *   ends up stopping at the start of the next frame).
1107  *
1108  */
1109 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1110 {
1111         struct drm_device *dev = crtc->base.dev;
1112         struct drm_i915_private *dev_priv = dev->dev_private;
1113         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1114         enum pipe pipe = crtc->pipe;
1115
1116         if (INTEL_INFO(dev)->gen >= 4) {
1117                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1118
1119                 /* Wait for the Pipe State to go off */
1120                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1121                              100))
1122                         WARN(1, "pipe_off wait timed out\n");
1123         } else {
1124                 /* Wait for the display line to settle */
1125                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1126                         WARN(1, "pipe_off wait timed out\n");
1127         }
1128 }
1129
1130 /* Only for pre-ILK configs */
1131 void assert_pll(struct drm_i915_private *dev_priv,
1132                 enum pipe pipe, bool state)
1133 {
1134         u32 val;
1135         bool cur_state;
1136
1137         val = I915_READ(DPLL(pipe));
1138         cur_state = !!(val & DPLL_VCO_ENABLE);
1139         I915_STATE_WARN(cur_state != state,
1140              "PLL state assertion failure (expected %s, current %s)\n",
1141                         onoff(state), onoff(cur_state));
1142 }
1143
1144 /* XXX: the dsi pll is shared between MIPI DSI ports */
1145 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1146 {
1147         u32 val;
1148         bool cur_state;
1149
1150         mutex_lock(&dev_priv->sb_lock);
1151         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1152         mutex_unlock(&dev_priv->sb_lock);
1153
1154         cur_state = val & DSI_PLL_VCO_EN;
1155         I915_STATE_WARN(cur_state != state,
1156              "DSI PLL state assertion failure (expected %s, current %s)\n",
1157                         onoff(state), onoff(cur_state));
1158 }
1159
1160 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1161                           enum pipe pipe, bool state)
1162 {
1163         bool cur_state;
1164         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1165                                                                       pipe);
1166
1167         if (HAS_DDI(dev_priv)) {
1168                 /* DDI does not have a specific FDI_TX register */
1169                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1170                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1171         } else {
1172                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1173                 cur_state = !!(val & FDI_TX_ENABLE);
1174         }
1175         I915_STATE_WARN(cur_state != state,
1176              "FDI TX state assertion failure (expected %s, current %s)\n",
1177                         onoff(state), onoff(cur_state));
1178 }
1179 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1180 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1181
1182 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1183                           enum pipe pipe, bool state)
1184 {
1185         u32 val;
1186         bool cur_state;
1187
1188         val = I915_READ(FDI_RX_CTL(pipe));
1189         cur_state = !!(val & FDI_RX_ENABLE);
1190         I915_STATE_WARN(cur_state != state,
1191              "FDI RX state assertion failure (expected %s, current %s)\n",
1192                         onoff(state), onoff(cur_state));
1193 }
1194 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1195 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1196
1197 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1198                                       enum pipe pipe)
1199 {
1200         u32 val;
1201
1202         /* ILK FDI PLL is always enabled */
1203         if (IS_GEN5(dev_priv))
1204                 return;
1205
1206         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1207         if (HAS_DDI(dev_priv))
1208                 return;
1209
1210         val = I915_READ(FDI_TX_CTL(pipe));
1211         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1212 }
1213
1214 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1215                        enum pipe pipe, bool state)
1216 {
1217         u32 val;
1218         bool cur_state;
1219
1220         val = I915_READ(FDI_RX_CTL(pipe));
1221         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1222         I915_STATE_WARN(cur_state != state,
1223              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1224                         onoff(state), onoff(cur_state));
1225 }
1226
1227 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1228                            enum pipe pipe)
1229 {
1230         struct drm_device *dev = dev_priv->dev;
1231         i915_reg_t pp_reg;
1232         u32 val;
1233         enum pipe panel_pipe = PIPE_A;
1234         bool locked = true;
1235
1236         if (WARN_ON(HAS_DDI(dev)))
1237                 return;
1238
1239         if (HAS_PCH_SPLIT(dev)) {
1240                 u32 port_sel;
1241
1242                 pp_reg = PCH_PP_CONTROL;
1243                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1244
1245                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1246                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1247                         panel_pipe = PIPE_B;
1248                 /* XXX: else fix for eDP */
1249         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1250                 /* presumably write lock depends on pipe, not port select */
1251                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1252                 panel_pipe = pipe;
1253         } else {
1254                 pp_reg = PP_CONTROL;
1255                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1256                         panel_pipe = PIPE_B;
1257         }
1258
1259         val = I915_READ(pp_reg);
1260         if (!(val & PANEL_POWER_ON) ||
1261             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1262                 locked = false;
1263
1264         I915_STATE_WARN(panel_pipe == pipe && locked,
1265              "panel assertion failure, pipe %c regs locked\n",
1266              pipe_name(pipe));
1267 }
1268
1269 static void assert_cursor(struct drm_i915_private *dev_priv,
1270                           enum pipe pipe, bool state)
1271 {
1272         struct drm_device *dev = dev_priv->dev;
1273         bool cur_state;
1274
1275         if (IS_845G(dev) || IS_I865G(dev))
1276                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1277         else
1278                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1279
1280         I915_STATE_WARN(cur_state != state,
1281              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1282                         pipe_name(pipe), onoff(state), onoff(cur_state));
1283 }
1284 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1285 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1286
1287 void assert_pipe(struct drm_i915_private *dev_priv,
1288                  enum pipe pipe, bool state)
1289 {
1290         bool cur_state;
1291         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1292                                                                       pipe);
1293         enum intel_display_power_domain power_domain;
1294
1295         /* if we need the pipe quirk it must be always on */
1296         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1297             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1298                 state = true;
1299
1300         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1301         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1302                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1303                 cur_state = !!(val & PIPECONF_ENABLE);
1304
1305                 intel_display_power_put(dev_priv, power_domain);
1306         } else {
1307                 cur_state = false;
1308         }
1309
1310         I915_STATE_WARN(cur_state != state,
1311              "pipe %c assertion failure (expected %s, current %s)\n",
1312                         pipe_name(pipe), onoff(state), onoff(cur_state));
1313 }
1314
1315 static void assert_plane(struct drm_i915_private *dev_priv,
1316                          enum plane plane, bool state)
1317 {
1318         u32 val;
1319         bool cur_state;
1320
1321         val = I915_READ(DSPCNTR(plane));
1322         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1323         I915_STATE_WARN(cur_state != state,
1324              "plane %c assertion failure (expected %s, current %s)\n",
1325                         plane_name(plane), onoff(state), onoff(cur_state));
1326 }
1327
1328 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1329 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1330
1331 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1332                                    enum pipe pipe)
1333 {
1334         struct drm_device *dev = dev_priv->dev;
1335         int i;
1336
1337         /* Primary planes are fixed to pipes on gen4+ */
1338         if (INTEL_INFO(dev)->gen >= 4) {
1339                 u32 val = I915_READ(DSPCNTR(pipe));
1340                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1341                      "plane %c assertion failure, should be disabled but not\n",
1342                      plane_name(pipe));
1343                 return;
1344         }
1345
1346         /* Need to check both planes against the pipe */
1347         for_each_pipe(dev_priv, i) {
1348                 u32 val = I915_READ(DSPCNTR(i));
1349                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1350                         DISPPLANE_SEL_PIPE_SHIFT;
1351                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1352                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1353                      plane_name(i), pipe_name(pipe));
1354         }
1355 }
1356
1357 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1358                                     enum pipe pipe)
1359 {
1360         struct drm_device *dev = dev_priv->dev;
1361         int sprite;
1362
1363         if (INTEL_INFO(dev)->gen >= 9) {
1364                 for_each_sprite(dev_priv, pipe, sprite) {
1365                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1366                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1367                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1368                              sprite, pipe_name(pipe));
1369                 }
1370         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1371                 for_each_sprite(dev_priv, pipe, sprite) {
1372                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1373                         I915_STATE_WARN(val & SP_ENABLE,
1374                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1375                              sprite_name(pipe, sprite), pipe_name(pipe));
1376                 }
1377         } else if (INTEL_INFO(dev)->gen >= 7) {
1378                 u32 val = I915_READ(SPRCTL(pipe));
1379                 I915_STATE_WARN(val & SPRITE_ENABLE,
1380                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1381                      plane_name(pipe), pipe_name(pipe));
1382         } else if (INTEL_INFO(dev)->gen >= 5) {
1383                 u32 val = I915_READ(DVSCNTR(pipe));
1384                 I915_STATE_WARN(val & DVS_ENABLE,
1385                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1386                      plane_name(pipe), pipe_name(pipe));
1387         }
1388 }
1389
1390 static void assert_vblank_disabled(struct drm_crtc *crtc)
1391 {
1392         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1393                 drm_crtc_vblank_put(crtc);
1394 }
1395
1396 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1397                                     enum pipe pipe)
1398 {
1399         u32 val;
1400         bool enabled;
1401
1402         val = I915_READ(PCH_TRANSCONF(pipe));
1403         enabled = !!(val & TRANS_ENABLE);
1404         I915_STATE_WARN(enabled,
1405              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1406              pipe_name(pipe));
1407 }
1408
1409 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1410                             enum pipe pipe, u32 port_sel, u32 val)
1411 {
1412         if ((val & DP_PORT_EN) == 0)
1413                 return false;
1414
1415         if (HAS_PCH_CPT(dev_priv)) {
1416                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1417                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1418                         return false;
1419         } else if (IS_CHERRYVIEW(dev_priv)) {
1420                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1421                         return false;
1422         } else {
1423                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1424                         return false;
1425         }
1426         return true;
1427 }
1428
1429 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1430                               enum pipe pipe, u32 val)
1431 {
1432         if ((val & SDVO_ENABLE) == 0)
1433                 return false;
1434
1435         if (HAS_PCH_CPT(dev_priv)) {
1436                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1437                         return false;
1438         } else if (IS_CHERRYVIEW(dev_priv)) {
1439                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1440                         return false;
1441         } else {
1442                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1443                         return false;
1444         }
1445         return true;
1446 }
1447
1448 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1449                               enum pipe pipe, u32 val)
1450 {
1451         if ((val & LVDS_PORT_EN) == 0)
1452                 return false;
1453
1454         if (HAS_PCH_CPT(dev_priv)) {
1455                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1456                         return false;
1457         } else {
1458                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1459                         return false;
1460         }
1461         return true;
1462 }
1463
1464 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1465                               enum pipe pipe, u32 val)
1466 {
1467         if ((val & ADPA_DAC_ENABLE) == 0)
1468                 return false;
1469         if (HAS_PCH_CPT(dev_priv)) {
1470                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1471                         return false;
1472         } else {
1473                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1474                         return false;
1475         }
1476         return true;
1477 }
1478
1479 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1480                                    enum pipe pipe, i915_reg_t reg,
1481                                    u32 port_sel)
1482 {
1483         u32 val = I915_READ(reg);
1484         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1485              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1486              i915_mmio_reg_offset(reg), pipe_name(pipe));
1487
1488         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1489              && (val & DP_PIPEB_SELECT),
1490              "IBX PCH dp port still using transcoder B\n");
1491 }
1492
1493 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1494                                      enum pipe pipe, i915_reg_t reg)
1495 {
1496         u32 val = I915_READ(reg);
1497         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1498              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1499              i915_mmio_reg_offset(reg), pipe_name(pipe));
1500
1501         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1502              && (val & SDVO_PIPE_B_SELECT),
1503              "IBX PCH hdmi port still using transcoder B\n");
1504 }
1505
1506 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1507                                       enum pipe pipe)
1508 {
1509         u32 val;
1510
1511         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1512         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1513         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1514
1515         val = I915_READ(PCH_ADPA);
1516         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1517              "PCH VGA enabled on transcoder %c, should be disabled\n",
1518              pipe_name(pipe));
1519
1520         val = I915_READ(PCH_LVDS);
1521         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1522              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1523              pipe_name(pipe));
1524
1525         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1526         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1527         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1528 }
1529
1530 static void _vlv_enable_pll(struct intel_crtc *crtc,
1531                             const struct intel_crtc_state *pipe_config)
1532 {
1533         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1534         enum pipe pipe = crtc->pipe;
1535
1536         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1537         POSTING_READ(DPLL(pipe));
1538         udelay(150);
1539
1540         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1541                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1542 }
1543
1544 static void vlv_enable_pll(struct intel_crtc *crtc,
1545                            const struct intel_crtc_state *pipe_config)
1546 {
1547         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1548         enum pipe pipe = crtc->pipe;
1549
1550         assert_pipe_disabled(dev_priv, pipe);
1551
1552         /* PLL is protected by panel, make sure we can write it */
1553         assert_panel_unlocked(dev_priv, pipe);
1554
1555         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1556                 _vlv_enable_pll(crtc, pipe_config);
1557
1558         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1559         POSTING_READ(DPLL_MD(pipe));
1560 }
1561
1562
1563 static void _chv_enable_pll(struct intel_crtc *crtc,
1564                             const struct intel_crtc_state *pipe_config)
1565 {
1566         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1567         enum pipe pipe = crtc->pipe;
1568         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1569         u32 tmp;
1570
1571         mutex_lock(&dev_priv->sb_lock);
1572
1573         /* Enable back the 10bit clock to display controller */
1574         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1575         tmp |= DPIO_DCLKP_EN;
1576         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1577
1578         mutex_unlock(&dev_priv->sb_lock);
1579
1580         /*
1581          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1582          */
1583         udelay(1);
1584
1585         /* Enable PLL */
1586         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1587
1588         /* Check PLL is locked */
1589         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1590                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1591 }
1592
1593 static void chv_enable_pll(struct intel_crtc *crtc,
1594                            const struct intel_crtc_state *pipe_config)
1595 {
1596         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1597         enum pipe pipe = crtc->pipe;
1598
1599         assert_pipe_disabled(dev_priv, pipe);
1600
1601         /* PLL is protected by panel, make sure we can write it */
1602         assert_panel_unlocked(dev_priv, pipe);
1603
1604         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1605                 _chv_enable_pll(crtc, pipe_config);
1606
1607         if (pipe != PIPE_A) {
1608                 /*
1609                  * WaPixelRepeatModeFixForC0:chv
1610                  *
1611                  * DPLLCMD is AWOL. Use chicken bits to propagate
1612                  * the value from DPLLBMD to either pipe B or C.
1613                  */
1614                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1615                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1616                 I915_WRITE(CBR4_VLV, 0);
1617                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1618
1619                 /*
1620                  * DPLLB VGA mode also seems to cause problems.
1621                  * We should always have it disabled.
1622                  */
1623                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1624         } else {
1625                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1626                 POSTING_READ(DPLL_MD(pipe));
1627         }
1628 }
1629
1630 static int intel_num_dvo_pipes(struct drm_device *dev)
1631 {
1632         struct intel_crtc *crtc;
1633         int count = 0;
1634
1635         for_each_intel_crtc(dev, crtc)
1636                 count += crtc->base.state->active &&
1637                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1638
1639         return count;
1640 }
1641
1642 static void i9xx_enable_pll(struct intel_crtc *crtc)
1643 {
1644         struct drm_device *dev = crtc->base.dev;
1645         struct drm_i915_private *dev_priv = dev->dev_private;
1646         i915_reg_t reg = DPLL(crtc->pipe);
1647         u32 dpll = crtc->config->dpll_hw_state.dpll;
1648
1649         assert_pipe_disabled(dev_priv, crtc->pipe);
1650
1651         /* PLL is protected by panel, make sure we can write it */
1652         if (IS_MOBILE(dev) && !IS_I830(dev))
1653                 assert_panel_unlocked(dev_priv, crtc->pipe);
1654
1655         /* Enable DVO 2x clock on both PLLs if necessary */
1656         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1657                 /*
1658                  * It appears to be important that we don't enable this
1659                  * for the current pipe before otherwise configuring the
1660                  * PLL. No idea how this should be handled if multiple
1661                  * DVO outputs are enabled simultaneosly.
1662                  */
1663                 dpll |= DPLL_DVO_2X_MODE;
1664                 I915_WRITE(DPLL(!crtc->pipe),
1665                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1666         }
1667
1668         /*
1669          * Apparently we need to have VGA mode enabled prior to changing
1670          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1671          * dividers, even though the register value does change.
1672          */
1673         I915_WRITE(reg, 0);
1674
1675         I915_WRITE(reg, dpll);
1676
1677         /* Wait for the clocks to stabilize. */
1678         POSTING_READ(reg);
1679         udelay(150);
1680
1681         if (INTEL_INFO(dev)->gen >= 4) {
1682                 I915_WRITE(DPLL_MD(crtc->pipe),
1683                            crtc->config->dpll_hw_state.dpll_md);
1684         } else {
1685                 /* The pixel multiplier can only be updated once the
1686                  * DPLL is enabled and the clocks are stable.
1687                  *
1688                  * So write it again.
1689                  */
1690                 I915_WRITE(reg, dpll);
1691         }
1692
1693         /* We do this three times for luck */
1694         I915_WRITE(reg, dpll);
1695         POSTING_READ(reg);
1696         udelay(150); /* wait for warmup */
1697         I915_WRITE(reg, dpll);
1698         POSTING_READ(reg);
1699         udelay(150); /* wait for warmup */
1700         I915_WRITE(reg, dpll);
1701         POSTING_READ(reg);
1702         udelay(150); /* wait for warmup */
1703 }
1704
1705 /**
1706  * i9xx_disable_pll - disable a PLL
1707  * @dev_priv: i915 private structure
1708  * @pipe: pipe PLL to disable
1709  *
1710  * Disable the PLL for @pipe, making sure the pipe is off first.
1711  *
1712  * Note!  This is for pre-ILK only.
1713  */
1714 static void i9xx_disable_pll(struct intel_crtc *crtc)
1715 {
1716         struct drm_device *dev = crtc->base.dev;
1717         struct drm_i915_private *dev_priv = dev->dev_private;
1718         enum pipe pipe = crtc->pipe;
1719
1720         /* Disable DVO 2x clock on both PLLs if necessary */
1721         if (IS_I830(dev) &&
1722             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1723             !intel_num_dvo_pipes(dev)) {
1724                 I915_WRITE(DPLL(PIPE_B),
1725                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1726                 I915_WRITE(DPLL(PIPE_A),
1727                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1728         }
1729
1730         /* Don't disable pipe or pipe PLLs if needed */
1731         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1732             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1733                 return;
1734
1735         /* Make sure the pipe isn't still relying on us */
1736         assert_pipe_disabled(dev_priv, pipe);
1737
1738         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1739         POSTING_READ(DPLL(pipe));
1740 }
1741
1742 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1743 {
1744         u32 val;
1745
1746         /* Make sure the pipe isn't still relying on us */
1747         assert_pipe_disabled(dev_priv, pipe);
1748
1749         val = DPLL_INTEGRATED_REF_CLK_VLV |
1750                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1751         if (pipe != PIPE_A)
1752                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1753
1754         I915_WRITE(DPLL(pipe), val);
1755         POSTING_READ(DPLL(pipe));
1756 }
1757
1758 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1759 {
1760         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1761         u32 val;
1762
1763         /* Make sure the pipe isn't still relying on us */
1764         assert_pipe_disabled(dev_priv, pipe);
1765
1766         val = DPLL_SSC_REF_CLK_CHV |
1767                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1768         if (pipe != PIPE_A)
1769                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1770
1771         I915_WRITE(DPLL(pipe), val);
1772         POSTING_READ(DPLL(pipe));
1773
1774         mutex_lock(&dev_priv->sb_lock);
1775
1776         /* Disable 10bit clock to display controller */
1777         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1778         val &= ~DPIO_DCLKP_EN;
1779         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1780
1781         mutex_unlock(&dev_priv->sb_lock);
1782 }
1783
1784 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1785                          struct intel_digital_port *dport,
1786                          unsigned int expected_mask)
1787 {
1788         u32 port_mask;
1789         i915_reg_t dpll_reg;
1790
1791         switch (dport->port) {
1792         case PORT_B:
1793                 port_mask = DPLL_PORTB_READY_MASK;
1794                 dpll_reg = DPLL(0);
1795                 break;
1796         case PORT_C:
1797                 port_mask = DPLL_PORTC_READY_MASK;
1798                 dpll_reg = DPLL(0);
1799                 expected_mask <<= 4;
1800                 break;
1801         case PORT_D:
1802                 port_mask = DPLL_PORTD_READY_MASK;
1803                 dpll_reg = DPIO_PHY_STATUS;
1804                 break;
1805         default:
1806                 BUG();
1807         }
1808
1809         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1810                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1811                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1812 }
1813
1814 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1815                                            enum pipe pipe)
1816 {
1817         struct drm_device *dev = dev_priv->dev;
1818         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1819         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1820         i915_reg_t reg;
1821         uint32_t val, pipeconf_val;
1822
1823         /* Make sure PCH DPLL is enabled */
1824         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1825
1826         /* FDI must be feeding us bits for PCH ports */
1827         assert_fdi_tx_enabled(dev_priv, pipe);
1828         assert_fdi_rx_enabled(dev_priv, pipe);
1829
1830         if (HAS_PCH_CPT(dev)) {
1831                 /* Workaround: Set the timing override bit before enabling the
1832                  * pch transcoder. */
1833                 reg = TRANS_CHICKEN2(pipe);
1834                 val = I915_READ(reg);
1835                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1836                 I915_WRITE(reg, val);
1837         }
1838
1839         reg = PCH_TRANSCONF(pipe);
1840         val = I915_READ(reg);
1841         pipeconf_val = I915_READ(PIPECONF(pipe));
1842
1843         if (HAS_PCH_IBX(dev_priv)) {
1844                 /*
1845                  * Make the BPC in transcoder be consistent with
1846                  * that in pipeconf reg. For HDMI we must use 8bpc
1847                  * here for both 8bpc and 12bpc.
1848                  */
1849                 val &= ~PIPECONF_BPC_MASK;
1850                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1851                         val |= PIPECONF_8BPC;
1852                 else
1853                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1854         }
1855
1856         val &= ~TRANS_INTERLACE_MASK;
1857         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1858                 if (HAS_PCH_IBX(dev_priv) &&
1859                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1860                         val |= TRANS_LEGACY_INTERLACED_ILK;
1861                 else
1862                         val |= TRANS_INTERLACED;
1863         else
1864                 val |= TRANS_PROGRESSIVE;
1865
1866         I915_WRITE(reg, val | TRANS_ENABLE);
1867         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1868                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1869 }
1870
1871 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1872                                       enum transcoder cpu_transcoder)
1873 {
1874         u32 val, pipeconf_val;
1875
1876         /* FDI must be feeding us bits for PCH ports */
1877         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1878         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1879
1880         /* Workaround: set timing override bit. */
1881         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1882         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1883         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1884
1885         val = TRANS_ENABLE;
1886         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1887
1888         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1889             PIPECONF_INTERLACED_ILK)
1890                 val |= TRANS_INTERLACED;
1891         else
1892                 val |= TRANS_PROGRESSIVE;
1893
1894         I915_WRITE(LPT_TRANSCONF, val);
1895         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1896                 DRM_ERROR("Failed to enable PCH transcoder\n");
1897 }
1898
1899 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1900                                             enum pipe pipe)
1901 {
1902         struct drm_device *dev = dev_priv->dev;
1903         i915_reg_t reg;
1904         uint32_t val;
1905
1906         /* FDI relies on the transcoder */
1907         assert_fdi_tx_disabled(dev_priv, pipe);
1908         assert_fdi_rx_disabled(dev_priv, pipe);
1909
1910         /* Ports must be off as well */
1911         assert_pch_ports_disabled(dev_priv, pipe);
1912
1913         reg = PCH_TRANSCONF(pipe);
1914         val = I915_READ(reg);
1915         val &= ~TRANS_ENABLE;
1916         I915_WRITE(reg, val);
1917         /* wait for PCH transcoder off, transcoder state */
1918         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1919                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1920
1921         if (HAS_PCH_CPT(dev)) {
1922                 /* Workaround: Clear the timing override chicken bit again. */
1923                 reg = TRANS_CHICKEN2(pipe);
1924                 val = I915_READ(reg);
1925                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1926                 I915_WRITE(reg, val);
1927         }
1928 }
1929
1930 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1931 {
1932         u32 val;
1933
1934         val = I915_READ(LPT_TRANSCONF);
1935         val &= ~TRANS_ENABLE;
1936         I915_WRITE(LPT_TRANSCONF, val);
1937         /* wait for PCH transcoder off, transcoder state */
1938         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1939                 DRM_ERROR("Failed to disable PCH transcoder\n");
1940
1941         /* Workaround: clear timing override bit. */
1942         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1943         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1944         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1945 }
1946
1947 /**
1948  * intel_enable_pipe - enable a pipe, asserting requirements
1949  * @crtc: crtc responsible for the pipe
1950  *
1951  * Enable @crtc's pipe, making sure that various hardware specific requirements
1952  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1953  */
1954 static void intel_enable_pipe(struct intel_crtc *crtc)
1955 {
1956         struct drm_device *dev = crtc->base.dev;
1957         struct drm_i915_private *dev_priv = dev->dev_private;
1958         enum pipe pipe = crtc->pipe;
1959         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1960         enum pipe pch_transcoder;
1961         i915_reg_t reg;
1962         u32 val;
1963
1964         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1965
1966         assert_planes_disabled(dev_priv, pipe);
1967         assert_cursor_disabled(dev_priv, pipe);
1968         assert_sprites_disabled(dev_priv, pipe);
1969
1970         if (HAS_PCH_LPT(dev_priv))
1971                 pch_transcoder = TRANSCODER_A;
1972         else
1973                 pch_transcoder = pipe;
1974
1975         /*
1976          * A pipe without a PLL won't actually be able to drive bits from
1977          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1978          * need the check.
1979          */
1980         if (HAS_GMCH_DISPLAY(dev_priv))
1981                 if (crtc->config->has_dsi_encoder)
1982                         assert_dsi_pll_enabled(dev_priv);
1983                 else
1984                         assert_pll_enabled(dev_priv, pipe);
1985         else {
1986                 if (crtc->config->has_pch_encoder) {
1987                         /* if driving the PCH, we need FDI enabled */
1988                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1989                         assert_fdi_tx_pll_enabled(dev_priv,
1990                                                   (enum pipe) cpu_transcoder);
1991                 }
1992                 /* FIXME: assert CPU port conditions for SNB+ */
1993         }
1994
1995         reg = PIPECONF(cpu_transcoder);
1996         val = I915_READ(reg);
1997         if (val & PIPECONF_ENABLE) {
1998                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1999                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2000                 return;
2001         }
2002
2003         I915_WRITE(reg, val | PIPECONF_ENABLE);
2004         POSTING_READ(reg);
2005
2006         /*
2007          * Until the pipe starts DSL will read as 0, which would cause
2008          * an apparent vblank timestamp jump, which messes up also the
2009          * frame count when it's derived from the timestamps. So let's
2010          * wait for the pipe to start properly before we call
2011          * drm_crtc_vblank_on()
2012          */
2013         if (dev->max_vblank_count == 0 &&
2014             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2015                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2016 }
2017
2018 /**
2019  * intel_disable_pipe - disable a pipe, asserting requirements
2020  * @crtc: crtc whose pipes is to be disabled
2021  *
2022  * Disable the pipe of @crtc, making sure that various hardware
2023  * specific requirements are met, if applicable, e.g. plane
2024  * disabled, panel fitter off, etc.
2025  *
2026  * Will wait until the pipe has shut down before returning.
2027  */
2028 static void intel_disable_pipe(struct intel_crtc *crtc)
2029 {
2030         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2031         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2032         enum pipe pipe = crtc->pipe;
2033         i915_reg_t reg;
2034         u32 val;
2035
2036         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2037
2038         /*
2039          * Make sure planes won't keep trying to pump pixels to us,
2040          * or we might hang the display.
2041          */
2042         assert_planes_disabled(dev_priv, pipe);
2043         assert_cursor_disabled(dev_priv, pipe);
2044         assert_sprites_disabled(dev_priv, pipe);
2045
2046         reg = PIPECONF(cpu_transcoder);
2047         val = I915_READ(reg);
2048         if ((val & PIPECONF_ENABLE) == 0)
2049                 return;
2050
2051         /*
2052          * Double wide has implications for planes
2053          * so best keep it disabled when not needed.
2054          */
2055         if (crtc->config->double_wide)
2056                 val &= ~PIPECONF_DOUBLE_WIDE;
2057
2058         /* Don't disable pipe or pipe PLLs if needed */
2059         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2060             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2061                 val &= ~PIPECONF_ENABLE;
2062
2063         I915_WRITE(reg, val);
2064         if ((val & PIPECONF_ENABLE) == 0)
2065                 intel_wait_for_pipe_off(crtc);
2066 }
2067
2068 static bool need_vtd_wa(struct drm_device *dev)
2069 {
2070 #ifdef CONFIG_INTEL_IOMMU
2071         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2072                 return true;
2073 #endif
2074         return false;
2075 }
2076
2077 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2078 {
2079         return IS_GEN2(dev_priv) ? 2048 : 4096;
2080 }
2081
2082 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2083                                            uint64_t fb_modifier, unsigned int cpp)
2084 {
2085         switch (fb_modifier) {
2086         case DRM_FORMAT_MOD_NONE:
2087                 return cpp;
2088         case I915_FORMAT_MOD_X_TILED:
2089                 if (IS_GEN2(dev_priv))
2090                         return 128;
2091                 else
2092                         return 512;
2093         case I915_FORMAT_MOD_Y_TILED:
2094                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2095                         return 128;
2096                 else
2097                         return 512;
2098         case I915_FORMAT_MOD_Yf_TILED:
2099                 switch (cpp) {
2100                 case 1:
2101                         return 64;
2102                 case 2:
2103                 case 4:
2104                         return 128;
2105                 case 8:
2106                 case 16:
2107                         return 256;
2108                 default:
2109                         MISSING_CASE(cpp);
2110                         return cpp;
2111                 }
2112                 break;
2113         default:
2114                 MISSING_CASE(fb_modifier);
2115                 return cpp;
2116         }
2117 }
2118
2119 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2120                                uint64_t fb_modifier, unsigned int cpp)
2121 {
2122         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2123                 return 1;
2124         else
2125                 return intel_tile_size(dev_priv) /
2126                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2127 }
2128
2129 /* Return the tile dimensions in pixel units */
2130 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2131                             unsigned int *tile_width,
2132                             unsigned int *tile_height,
2133                             uint64_t fb_modifier,
2134                             unsigned int cpp)
2135 {
2136         unsigned int tile_width_bytes =
2137                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2138
2139         *tile_width = tile_width_bytes / cpp;
2140         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2141 }
2142
2143 unsigned int
2144 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2145                       uint32_t pixel_format, uint64_t fb_modifier)
2146 {
2147         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2148         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2149
2150         return ALIGN(height, tile_height);
2151 }
2152
2153 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2154 {
2155         unsigned int size = 0;
2156         int i;
2157
2158         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2159                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2160
2161         return size;
2162 }
2163
2164 static void
2165 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2166                         const struct drm_framebuffer *fb,
2167                         unsigned int rotation)
2168 {
2169         if (intel_rotation_90_or_270(rotation)) {
2170                 *view = i915_ggtt_view_rotated;
2171                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2172         } else {
2173                 *view = i915_ggtt_view_normal;
2174         }
2175 }
2176
2177 static void
2178 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2179                    struct drm_framebuffer *fb)
2180 {
2181         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2182         unsigned int tile_size, tile_width, tile_height, cpp;
2183
2184         tile_size = intel_tile_size(dev_priv);
2185
2186         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2187         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2188                         fb->modifier[0], cpp);
2189
2190         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2191         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2192
2193         if (info->pixel_format == DRM_FORMAT_NV12) {
2194                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2195                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2196                                 fb->modifier[1], cpp);
2197
2198                 info->uv_offset = fb->offsets[1];
2199                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2200                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2201         }
2202 }
2203
2204 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2205 {
2206         if (INTEL_INFO(dev_priv)->gen >= 9)
2207                 return 256 * 1024;
2208         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2209                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2210                 return 128 * 1024;
2211         else if (INTEL_INFO(dev_priv)->gen >= 4)
2212                 return 4 * 1024;
2213         else
2214                 return 0;
2215 }
2216
2217 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2218                                          uint64_t fb_modifier)
2219 {
2220         switch (fb_modifier) {
2221         case DRM_FORMAT_MOD_NONE:
2222                 return intel_linear_alignment(dev_priv);
2223         case I915_FORMAT_MOD_X_TILED:
2224                 if (INTEL_INFO(dev_priv)->gen >= 9)
2225                         return 256 * 1024;
2226                 return 0;
2227         case I915_FORMAT_MOD_Y_TILED:
2228         case I915_FORMAT_MOD_Yf_TILED:
2229                 return 1 * 1024 * 1024;
2230         default:
2231                 MISSING_CASE(fb_modifier);
2232                 return 0;
2233         }
2234 }
2235
2236 int
2237 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2238                            unsigned int rotation)
2239 {
2240         struct drm_device *dev = fb->dev;
2241         struct drm_i915_private *dev_priv = dev->dev_private;
2242         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2243         struct i915_ggtt_view view;
2244         u32 alignment;
2245         int ret;
2246
2247         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2248
2249         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2250
2251         intel_fill_fb_ggtt_view(&view, fb, rotation);
2252
2253         /* Note that the w/a also requires 64 PTE of padding following the
2254          * bo. We currently fill all unused PTE with the shadow page and so
2255          * we should always have valid PTE following the scanout preventing
2256          * the VT-d warning.
2257          */
2258         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2259                 alignment = 256 * 1024;
2260
2261         /*
2262          * Global gtt pte registers are special registers which actually forward
2263          * writes to a chunk of system memory. Which means that there is no risk
2264          * that the register values disappear as soon as we call
2265          * intel_runtime_pm_put(), so it is correct to wrap only the
2266          * pin/unpin/fence and not more.
2267          */
2268         intel_runtime_pm_get(dev_priv);
2269
2270         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2271                                                    &view);
2272         if (ret)
2273                 goto err_pm;
2274
2275         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2276          * fence, whereas 965+ only requires a fence if using
2277          * framebuffer compression.  For simplicity, we always install
2278          * a fence as the cost is not that onerous.
2279          */
2280         if (view.type == I915_GGTT_VIEW_NORMAL) {
2281                 ret = i915_gem_object_get_fence(obj);
2282                 if (ret == -EDEADLK) {
2283                         /*
2284                          * -EDEADLK means there are no free fences
2285                          * no pending flips.
2286                          *
2287                          * This is propagated to atomic, but it uses
2288                          * -EDEADLK to force a locking recovery, so
2289                          * change the returned error to -EBUSY.
2290                          */
2291                         ret = -EBUSY;
2292                         goto err_unpin;
2293                 } else if (ret)
2294                         goto err_unpin;
2295
2296                 i915_gem_object_pin_fence(obj);
2297         }
2298
2299         intel_runtime_pm_put(dev_priv);
2300         return 0;
2301
2302 err_unpin:
2303         i915_gem_object_unpin_from_display_plane(obj, &view);
2304 err_pm:
2305         intel_runtime_pm_put(dev_priv);
2306         return ret;
2307 }
2308
2309 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2310 {
2311         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2312         struct i915_ggtt_view view;
2313
2314         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2315
2316         intel_fill_fb_ggtt_view(&view, fb, rotation);
2317
2318         if (view.type == I915_GGTT_VIEW_NORMAL)
2319                 i915_gem_object_unpin_fence(obj);
2320
2321         i915_gem_object_unpin_from_display_plane(obj, &view);
2322 }
2323
2324 /*
2325  * Adjust the tile offset by moving the difference into
2326  * the x/y offsets.
2327  *
2328  * Input tile dimensions and pitch must already be
2329  * rotated to match x and y, and in pixel units.
2330  */
2331 static u32 intel_adjust_tile_offset(int *x, int *y,
2332                                     unsigned int tile_width,
2333                                     unsigned int tile_height,
2334                                     unsigned int tile_size,
2335                                     unsigned int pitch_tiles,
2336                                     u32 old_offset,
2337                                     u32 new_offset)
2338 {
2339         unsigned int tiles;
2340
2341         WARN_ON(old_offset & (tile_size - 1));
2342         WARN_ON(new_offset & (tile_size - 1));
2343         WARN_ON(new_offset > old_offset);
2344
2345         tiles = (old_offset - new_offset) / tile_size;
2346
2347         *y += tiles / pitch_tiles * tile_height;
2348         *x += tiles % pitch_tiles * tile_width;
2349
2350         return new_offset;
2351 }
2352
2353 /*
2354  * Computes the linear offset to the base tile and adjusts
2355  * x, y. bytes per pixel is assumed to be a power-of-two.
2356  *
2357  * In the 90/270 rotated case, x and y are assumed
2358  * to be already rotated to match the rotated GTT view, and
2359  * pitch is the tile_height aligned framebuffer height.
2360  */
2361 u32 intel_compute_tile_offset(int *x, int *y,
2362                               const struct drm_framebuffer *fb, int plane,
2363                               unsigned int pitch,
2364                               unsigned int rotation)
2365 {
2366         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2367         uint64_t fb_modifier = fb->modifier[plane];
2368         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2369         u32 offset, offset_aligned, alignment;
2370
2371         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2372         if (alignment)
2373                 alignment--;
2374
2375         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2376                 unsigned int tile_size, tile_width, tile_height;
2377                 unsigned int tile_rows, tiles, pitch_tiles;
2378
2379                 tile_size = intel_tile_size(dev_priv);
2380                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2381                                 fb_modifier, cpp);
2382
2383                 if (intel_rotation_90_or_270(rotation)) {
2384                         pitch_tiles = pitch / tile_height;
2385                         swap(tile_width, tile_height);
2386                 } else {
2387                         pitch_tiles = pitch / (tile_width * cpp);
2388                 }
2389
2390                 tile_rows = *y / tile_height;
2391                 *y %= tile_height;
2392
2393                 tiles = *x / tile_width;
2394                 *x %= tile_width;
2395
2396                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2397                 offset_aligned = offset & ~alignment;
2398
2399                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2400                                          tile_size, pitch_tiles,
2401                                          offset, offset_aligned);
2402         } else {
2403                 offset = *y * pitch + *x * cpp;
2404                 offset_aligned = offset & ~alignment;
2405
2406                 *y = (offset & alignment) / pitch;
2407                 *x = ((offset & alignment) - *y * pitch) / cpp;
2408         }
2409
2410         return offset_aligned;
2411 }
2412
2413 static int i9xx_format_to_fourcc(int format)
2414 {
2415         switch (format) {
2416         case DISPPLANE_8BPP:
2417                 return DRM_FORMAT_C8;
2418         case DISPPLANE_BGRX555:
2419                 return DRM_FORMAT_XRGB1555;
2420         case DISPPLANE_BGRX565:
2421                 return DRM_FORMAT_RGB565;
2422         default:
2423         case DISPPLANE_BGRX888:
2424                 return DRM_FORMAT_XRGB8888;
2425         case DISPPLANE_RGBX888:
2426                 return DRM_FORMAT_XBGR8888;
2427         case DISPPLANE_BGRX101010:
2428                 return DRM_FORMAT_XRGB2101010;
2429         case DISPPLANE_RGBX101010:
2430                 return DRM_FORMAT_XBGR2101010;
2431         }
2432 }
2433
2434 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2435 {
2436         switch (format) {
2437         case PLANE_CTL_FORMAT_RGB_565:
2438                 return DRM_FORMAT_RGB565;
2439         default:
2440         case PLANE_CTL_FORMAT_XRGB_8888:
2441                 if (rgb_order) {
2442                         if (alpha)
2443                                 return DRM_FORMAT_ABGR8888;
2444                         else
2445                                 return DRM_FORMAT_XBGR8888;
2446                 } else {
2447                         if (alpha)
2448                                 return DRM_FORMAT_ARGB8888;
2449                         else
2450                                 return DRM_FORMAT_XRGB8888;
2451                 }
2452         case PLANE_CTL_FORMAT_XRGB_2101010:
2453                 if (rgb_order)
2454                         return DRM_FORMAT_XBGR2101010;
2455                 else
2456                         return DRM_FORMAT_XRGB2101010;
2457         }
2458 }
2459
2460 static bool
2461 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2462                               struct intel_initial_plane_config *plane_config)
2463 {
2464         struct drm_device *dev = crtc->base.dev;
2465         struct drm_i915_private *dev_priv = to_i915(dev);
2466         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2467         struct drm_i915_gem_object *obj = NULL;
2468         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2469         struct drm_framebuffer *fb = &plane_config->fb->base;
2470         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2471         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2472                                     PAGE_SIZE);
2473
2474         size_aligned -= base_aligned;
2475
2476         if (plane_config->size == 0)
2477                 return false;
2478
2479         /* If the FB is too big, just don't use it since fbdev is not very
2480          * important and we should probably use that space with FBC or other
2481          * features. */
2482         if (size_aligned * 2 > ggtt->stolen_usable_size)
2483                 return false;
2484
2485         mutex_lock(&dev->struct_mutex);
2486
2487         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2488                                                              base_aligned,
2489                                                              base_aligned,
2490                                                              size_aligned);
2491         if (!obj) {
2492                 mutex_unlock(&dev->struct_mutex);
2493                 return false;
2494         }
2495
2496         obj->tiling_mode = plane_config->tiling;
2497         if (obj->tiling_mode == I915_TILING_X)
2498                 obj->stride = fb->pitches[0];
2499
2500         mode_cmd.pixel_format = fb->pixel_format;
2501         mode_cmd.width = fb->width;
2502         mode_cmd.height = fb->height;
2503         mode_cmd.pitches[0] = fb->pitches[0];
2504         mode_cmd.modifier[0] = fb->modifier[0];
2505         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2506
2507         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2508                                    &mode_cmd, obj)) {
2509                 DRM_DEBUG_KMS("intel fb init failed\n");
2510                 goto out_unref_obj;
2511         }
2512
2513         mutex_unlock(&dev->struct_mutex);
2514
2515         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2516         return true;
2517
2518 out_unref_obj:
2519         drm_gem_object_unreference(&obj->base);
2520         mutex_unlock(&dev->struct_mutex);
2521         return false;
2522 }
2523
2524 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2525 static void
2526 update_state_fb(struct drm_plane *plane)
2527 {
2528         if (plane->fb == plane->state->fb)
2529                 return;
2530
2531         if (plane->state->fb)
2532                 drm_framebuffer_unreference(plane->state->fb);
2533         plane->state->fb = plane->fb;
2534         if (plane->state->fb)
2535                 drm_framebuffer_reference(plane->state->fb);
2536 }
2537
2538 static void
2539 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2540                              struct intel_initial_plane_config *plane_config)
2541 {
2542         struct drm_device *dev = intel_crtc->base.dev;
2543         struct drm_i915_private *dev_priv = dev->dev_private;
2544         struct drm_crtc *c;
2545         struct intel_crtc *i;
2546         struct drm_i915_gem_object *obj;
2547         struct drm_plane *primary = intel_crtc->base.primary;
2548         struct drm_plane_state *plane_state = primary->state;
2549         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2550         struct intel_plane *intel_plane = to_intel_plane(primary);
2551         struct intel_plane_state *intel_state =
2552                 to_intel_plane_state(plane_state);
2553         struct drm_framebuffer *fb;
2554
2555         if (!plane_config->fb)
2556                 return;
2557
2558         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2559                 fb = &plane_config->fb->base;
2560                 goto valid_fb;
2561         }
2562
2563         kfree(plane_config->fb);
2564
2565         /*
2566          * Failed to alloc the obj, check to see if we should share
2567          * an fb with another CRTC instead
2568          */
2569         for_each_crtc(dev, c) {
2570                 i = to_intel_crtc(c);
2571
2572                 if (c == &intel_crtc->base)
2573                         continue;
2574
2575                 if (!i->active)
2576                         continue;
2577
2578                 fb = c->primary->fb;
2579                 if (!fb)
2580                         continue;
2581
2582                 obj = intel_fb_obj(fb);
2583                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2584                         drm_framebuffer_reference(fb);
2585                         goto valid_fb;
2586                 }
2587         }
2588
2589         /*
2590          * We've failed to reconstruct the BIOS FB.  Current display state
2591          * indicates that the primary plane is visible, but has a NULL FB,
2592          * which will lead to problems later if we don't fix it up.  The
2593          * simplest solution is to just disable the primary plane now and
2594          * pretend the BIOS never had it enabled.
2595          */
2596         to_intel_plane_state(plane_state)->visible = false;
2597         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2598         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2599         intel_plane->disable_plane(primary, &intel_crtc->base);
2600
2601         return;
2602
2603 valid_fb:
2604         plane_state->src_x = 0;
2605         plane_state->src_y = 0;
2606         plane_state->src_w = fb->width << 16;
2607         plane_state->src_h = fb->height << 16;
2608
2609         plane_state->crtc_x = 0;
2610         plane_state->crtc_y = 0;
2611         plane_state->crtc_w = fb->width;
2612         plane_state->crtc_h = fb->height;
2613
2614         intel_state->src.x1 = plane_state->src_x;
2615         intel_state->src.y1 = plane_state->src_y;
2616         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2617         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2618         intel_state->dst.x1 = plane_state->crtc_x;
2619         intel_state->dst.y1 = plane_state->crtc_y;
2620         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2621         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2622
2623         obj = intel_fb_obj(fb);
2624         if (obj->tiling_mode != I915_TILING_NONE)
2625                 dev_priv->preserve_bios_swizzle = true;
2626
2627         drm_framebuffer_reference(fb);
2628         primary->fb = primary->state->fb = fb;
2629         primary->crtc = primary->state->crtc = &intel_crtc->base;
2630         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2631         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2632 }
2633
2634 static void i9xx_update_primary_plane(struct drm_plane *primary,
2635                                       const struct intel_crtc_state *crtc_state,
2636                                       const struct intel_plane_state *plane_state)
2637 {
2638         struct drm_device *dev = primary->dev;
2639         struct drm_i915_private *dev_priv = dev->dev_private;
2640         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2641         struct drm_framebuffer *fb = plane_state->base.fb;
2642         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2643         int plane = intel_crtc->plane;
2644         u32 linear_offset;
2645         u32 dspcntr;
2646         i915_reg_t reg = DSPCNTR(plane);
2647         unsigned int rotation = plane_state->base.rotation;
2648         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2649         int x = plane_state->src.x1 >> 16;
2650         int y = plane_state->src.y1 >> 16;
2651
2652         dspcntr = DISPPLANE_GAMMA_ENABLE;
2653
2654         dspcntr |= DISPLAY_PLANE_ENABLE;
2655
2656         if (INTEL_INFO(dev)->gen < 4) {
2657                 if (intel_crtc->pipe == PIPE_B)
2658                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2659
2660                 /* pipesrc and dspsize control the size that is scaled from,
2661                  * which should always be the user's requested size.
2662                  */
2663                 I915_WRITE(DSPSIZE(plane),
2664                            ((crtc_state->pipe_src_h - 1) << 16) |
2665                            (crtc_state->pipe_src_w - 1));
2666                 I915_WRITE(DSPPOS(plane), 0);
2667         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2668                 I915_WRITE(PRIMSIZE(plane),
2669                            ((crtc_state->pipe_src_h - 1) << 16) |
2670                            (crtc_state->pipe_src_w - 1));
2671                 I915_WRITE(PRIMPOS(plane), 0);
2672                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2673         }
2674
2675         switch (fb->pixel_format) {
2676         case DRM_FORMAT_C8:
2677                 dspcntr |= DISPPLANE_8BPP;
2678                 break;
2679         case DRM_FORMAT_XRGB1555:
2680                 dspcntr |= DISPPLANE_BGRX555;
2681                 break;
2682         case DRM_FORMAT_RGB565:
2683                 dspcntr |= DISPPLANE_BGRX565;
2684                 break;
2685         case DRM_FORMAT_XRGB8888:
2686                 dspcntr |= DISPPLANE_BGRX888;
2687                 break;
2688         case DRM_FORMAT_XBGR8888:
2689                 dspcntr |= DISPPLANE_RGBX888;
2690                 break;
2691         case DRM_FORMAT_XRGB2101010:
2692                 dspcntr |= DISPPLANE_BGRX101010;
2693                 break;
2694         case DRM_FORMAT_XBGR2101010:
2695                 dspcntr |= DISPPLANE_RGBX101010;
2696                 break;
2697         default:
2698                 BUG();
2699         }
2700
2701         if (INTEL_INFO(dev)->gen >= 4 &&
2702             obj->tiling_mode != I915_TILING_NONE)
2703                 dspcntr |= DISPPLANE_TILED;
2704
2705         if (IS_G4X(dev))
2706                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2707
2708         linear_offset = y * fb->pitches[0] + x * cpp;
2709
2710         if (INTEL_INFO(dev)->gen >= 4) {
2711                 intel_crtc->dspaddr_offset =
2712                         intel_compute_tile_offset(&x, &y, fb, 0,
2713                                                   fb->pitches[0], rotation);
2714                 linear_offset -= intel_crtc->dspaddr_offset;
2715         } else {
2716                 intel_crtc->dspaddr_offset = linear_offset;
2717         }
2718
2719         if (rotation == BIT(DRM_ROTATE_180)) {
2720                 dspcntr |= DISPPLANE_ROTATE_180;
2721
2722                 x += (crtc_state->pipe_src_w - 1);
2723                 y += (crtc_state->pipe_src_h - 1);
2724
2725                 /* Finding the last pixel of the last line of the display
2726                 data and adding to linear_offset*/
2727                 linear_offset +=
2728                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2729                         (crtc_state->pipe_src_w - 1) * cpp;
2730         }
2731
2732         intel_crtc->adjusted_x = x;
2733         intel_crtc->adjusted_y = y;
2734
2735         I915_WRITE(reg, dspcntr);
2736
2737         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2738         if (INTEL_INFO(dev)->gen >= 4) {
2739                 I915_WRITE(DSPSURF(plane),
2740                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2741                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2742                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2743         } else
2744                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2745         POSTING_READ(reg);
2746 }
2747
2748 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2749                                        struct drm_crtc *crtc)
2750 {
2751         struct drm_device *dev = crtc->dev;
2752         struct drm_i915_private *dev_priv = dev->dev_private;
2753         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2754         int plane = intel_crtc->plane;
2755
2756         I915_WRITE(DSPCNTR(plane), 0);
2757         if (INTEL_INFO(dev_priv)->gen >= 4)
2758                 I915_WRITE(DSPSURF(plane), 0);
2759         else
2760                 I915_WRITE(DSPADDR(plane), 0);
2761         POSTING_READ(DSPCNTR(plane));
2762 }
2763
2764 static void ironlake_update_primary_plane(struct drm_plane *primary,
2765                                           const struct intel_crtc_state *crtc_state,
2766                                           const struct intel_plane_state *plane_state)
2767 {
2768         struct drm_device *dev = primary->dev;
2769         struct drm_i915_private *dev_priv = dev->dev_private;
2770         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2771         struct drm_framebuffer *fb = plane_state->base.fb;
2772         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2773         int plane = intel_crtc->plane;
2774         u32 linear_offset;
2775         u32 dspcntr;
2776         i915_reg_t reg = DSPCNTR(plane);
2777         unsigned int rotation = plane_state->base.rotation;
2778         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2779         int x = plane_state->src.x1 >> 16;
2780         int y = plane_state->src.y1 >> 16;
2781
2782         dspcntr = DISPPLANE_GAMMA_ENABLE;
2783         dspcntr |= DISPLAY_PLANE_ENABLE;
2784
2785         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2786                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2787
2788         switch (fb->pixel_format) {
2789         case DRM_FORMAT_C8:
2790                 dspcntr |= DISPPLANE_8BPP;
2791                 break;
2792         case DRM_FORMAT_RGB565:
2793                 dspcntr |= DISPPLANE_BGRX565;
2794                 break;
2795         case DRM_FORMAT_XRGB8888:
2796                 dspcntr |= DISPPLANE_BGRX888;
2797                 break;
2798         case DRM_FORMAT_XBGR8888:
2799                 dspcntr |= DISPPLANE_RGBX888;
2800                 break;
2801         case DRM_FORMAT_XRGB2101010:
2802                 dspcntr |= DISPPLANE_BGRX101010;
2803                 break;
2804         case DRM_FORMAT_XBGR2101010:
2805                 dspcntr |= DISPPLANE_RGBX101010;
2806                 break;
2807         default:
2808                 BUG();
2809         }
2810
2811         if (obj->tiling_mode != I915_TILING_NONE)
2812                 dspcntr |= DISPPLANE_TILED;
2813
2814         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2815                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2816
2817         linear_offset = y * fb->pitches[0] + x * cpp;
2818         intel_crtc->dspaddr_offset =
2819                 intel_compute_tile_offset(&x, &y, fb, 0,
2820                                           fb->pitches[0], rotation);
2821         linear_offset -= intel_crtc->dspaddr_offset;
2822         if (rotation == BIT(DRM_ROTATE_180)) {
2823                 dspcntr |= DISPPLANE_ROTATE_180;
2824
2825                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2826                         x += (crtc_state->pipe_src_w - 1);
2827                         y += (crtc_state->pipe_src_h - 1);
2828
2829                         /* Finding the last pixel of the last line of the display
2830                         data and adding to linear_offset*/
2831                         linear_offset +=
2832                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2833                                 (crtc_state->pipe_src_w - 1) * cpp;
2834                 }
2835         }
2836
2837         intel_crtc->adjusted_x = x;
2838         intel_crtc->adjusted_y = y;
2839
2840         I915_WRITE(reg, dspcntr);
2841
2842         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2843         I915_WRITE(DSPSURF(plane),
2844                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2845         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2846                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2847         } else {
2848                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2849                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2850         }
2851         POSTING_READ(reg);
2852 }
2853
2854 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2855                               uint64_t fb_modifier, uint32_t pixel_format)
2856 {
2857         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2858                 return 64;
2859         } else {
2860                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2861
2862                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2863         }
2864 }
2865
2866 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2867                            struct drm_i915_gem_object *obj,
2868                            unsigned int plane)
2869 {
2870         struct i915_ggtt_view view;
2871         struct i915_vma *vma;
2872         u64 offset;
2873
2874         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2875                                 intel_plane->base.state->rotation);
2876
2877         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2878         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2879                 view.type))
2880                 return -1;
2881
2882         offset = vma->node.start;
2883
2884         if (plane == 1) {
2885                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2886                           PAGE_SIZE;
2887         }
2888
2889         WARN_ON(upper_32_bits(offset));
2890
2891         return lower_32_bits(offset);
2892 }
2893
2894 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2895 {
2896         struct drm_device *dev = intel_crtc->base.dev;
2897         struct drm_i915_private *dev_priv = dev->dev_private;
2898
2899         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2900         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2901         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2902 }
2903
2904 /*
2905  * This function detaches (aka. unbinds) unused scalers in hardware
2906  */
2907 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2908 {
2909         struct intel_crtc_scaler_state *scaler_state;
2910         int i;
2911
2912         scaler_state = &intel_crtc->config->scaler_state;
2913
2914         /* loop through and disable scalers that aren't in use */
2915         for (i = 0; i < intel_crtc->num_scalers; i++) {
2916                 if (!scaler_state->scalers[i].in_use)
2917                         skl_detach_scaler(intel_crtc, i);
2918         }
2919 }
2920
2921 u32 skl_plane_ctl_format(uint32_t pixel_format)
2922 {
2923         switch (pixel_format) {
2924         case DRM_FORMAT_C8:
2925                 return PLANE_CTL_FORMAT_INDEXED;
2926         case DRM_FORMAT_RGB565:
2927                 return PLANE_CTL_FORMAT_RGB_565;
2928         case DRM_FORMAT_XBGR8888:
2929                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2930         case DRM_FORMAT_XRGB8888:
2931                 return PLANE_CTL_FORMAT_XRGB_8888;
2932         /*
2933          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2934          * to be already pre-multiplied. We need to add a knob (or a different
2935          * DRM_FORMAT) for user-space to configure that.
2936          */
2937         case DRM_FORMAT_ABGR8888:
2938                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2939                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2940         case DRM_FORMAT_ARGB8888:
2941                 return PLANE_CTL_FORMAT_XRGB_8888 |
2942                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2943         case DRM_FORMAT_XRGB2101010:
2944                 return PLANE_CTL_FORMAT_XRGB_2101010;
2945         case DRM_FORMAT_XBGR2101010:
2946                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2947         case DRM_FORMAT_YUYV:
2948                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2949         case DRM_FORMAT_YVYU:
2950                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2951         case DRM_FORMAT_UYVY:
2952                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2953         case DRM_FORMAT_VYUY:
2954                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2955         default:
2956                 MISSING_CASE(pixel_format);
2957         }
2958
2959         return 0;
2960 }
2961
2962 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2963 {
2964         switch (fb_modifier) {
2965         case DRM_FORMAT_MOD_NONE:
2966                 break;
2967         case I915_FORMAT_MOD_X_TILED:
2968                 return PLANE_CTL_TILED_X;
2969         case I915_FORMAT_MOD_Y_TILED:
2970                 return PLANE_CTL_TILED_Y;
2971         case I915_FORMAT_MOD_Yf_TILED:
2972                 return PLANE_CTL_TILED_YF;
2973         default:
2974                 MISSING_CASE(fb_modifier);
2975         }
2976
2977         return 0;
2978 }
2979
2980 u32 skl_plane_ctl_rotation(unsigned int rotation)
2981 {
2982         switch (rotation) {
2983         case BIT(DRM_ROTATE_0):
2984                 break;
2985         /*
2986          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2987          * while i915 HW rotation is clockwise, thats why this swapping.
2988          */
2989         case BIT(DRM_ROTATE_90):
2990                 return PLANE_CTL_ROTATE_270;
2991         case BIT(DRM_ROTATE_180):
2992                 return PLANE_CTL_ROTATE_180;
2993         case BIT(DRM_ROTATE_270):
2994                 return PLANE_CTL_ROTATE_90;
2995         default:
2996                 MISSING_CASE(rotation);
2997         }
2998
2999         return 0;
3000 }
3001
3002 static void skylake_update_primary_plane(struct drm_plane *plane,
3003                                          const struct intel_crtc_state *crtc_state,
3004                                          const struct intel_plane_state *plane_state)
3005 {
3006         struct drm_device *dev = plane->dev;
3007         struct drm_i915_private *dev_priv = dev->dev_private;
3008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3009         struct drm_framebuffer *fb = plane_state->base.fb;
3010         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3011         int pipe = intel_crtc->pipe;
3012         u32 plane_ctl, stride_div, stride;
3013         u32 tile_height, plane_offset, plane_size;
3014         unsigned int rotation = plane_state->base.rotation;
3015         int x_offset, y_offset;
3016         u32 surf_addr;
3017         int scaler_id = plane_state->scaler_id;
3018         int src_x = plane_state->src.x1 >> 16;
3019         int src_y = plane_state->src.y1 >> 16;
3020         int src_w = drm_rect_width(&plane_state->src) >> 16;
3021         int src_h = drm_rect_height(&plane_state->src) >> 16;
3022         int dst_x = plane_state->dst.x1;
3023         int dst_y = plane_state->dst.y1;
3024         int dst_w = drm_rect_width(&plane_state->dst);
3025         int dst_h = drm_rect_height(&plane_state->dst);
3026
3027         plane_ctl = PLANE_CTL_ENABLE |
3028                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3029                     PLANE_CTL_PIPE_CSC_ENABLE;
3030
3031         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3032         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3033         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3034         plane_ctl |= skl_plane_ctl_rotation(rotation);
3035
3036         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3037                                                fb->pixel_format);
3038         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3039
3040         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3041
3042         if (intel_rotation_90_or_270(rotation)) {
3043                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3044
3045                 /* stride = Surface height in tiles */
3046                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3047                 stride = DIV_ROUND_UP(fb->height, tile_height);
3048                 x_offset = stride * tile_height - src_y - src_h;
3049                 y_offset = src_x;
3050                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3051         } else {
3052                 stride = fb->pitches[0] / stride_div;
3053                 x_offset = src_x;
3054                 y_offset = src_y;
3055                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3056         }
3057         plane_offset = y_offset << 16 | x_offset;
3058
3059         intel_crtc->adjusted_x = x_offset;
3060         intel_crtc->adjusted_y = y_offset;
3061
3062         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3063         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3064         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3065         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3066
3067         if (scaler_id >= 0) {
3068                 uint32_t ps_ctrl = 0;
3069
3070                 WARN_ON(!dst_w || !dst_h);
3071                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3072                         crtc_state->scaler_state.scalers[scaler_id].mode;
3073                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3074                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3075                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3076                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3077                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3078         } else {
3079                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3080         }
3081
3082         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3083
3084         POSTING_READ(PLANE_SURF(pipe, 0));
3085 }
3086
3087 static void skylake_disable_primary_plane(struct drm_plane *primary,
3088                                           struct drm_crtc *crtc)
3089 {
3090         struct drm_device *dev = crtc->dev;
3091         struct drm_i915_private *dev_priv = dev->dev_private;
3092         int pipe = to_intel_crtc(crtc)->pipe;
3093
3094         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3095         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3096         POSTING_READ(PLANE_SURF(pipe, 0));
3097 }
3098
3099 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3100 static int
3101 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3102                            int x, int y, enum mode_set_atomic state)
3103 {
3104         /* Support for kgdboc is disabled, this needs a major rework. */
3105         DRM_ERROR("legacy panic handler not supported any more.\n");
3106
3107         return -ENODEV;
3108 }
3109
3110 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3111 {
3112         struct drm_crtc *crtc;
3113
3114         for_each_crtc(dev_priv->dev, crtc) {
3115                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3116                 enum plane plane = intel_crtc->plane;
3117
3118                 intel_prepare_page_flip(dev_priv, plane);
3119                 intel_finish_page_flip_plane(dev_priv, plane);
3120         }
3121 }
3122
3123 static void intel_update_primary_planes(struct drm_device *dev)
3124 {
3125         struct drm_crtc *crtc;
3126
3127         for_each_crtc(dev, crtc) {
3128                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3129                 struct intel_plane_state *plane_state;
3130
3131                 drm_modeset_lock_crtc(crtc, &plane->base);
3132                 plane_state = to_intel_plane_state(plane->base.state);
3133
3134                 if (plane_state->visible)
3135                         plane->update_plane(&plane->base,
3136                                             to_intel_crtc_state(crtc->state),
3137                                             plane_state);
3138
3139                 drm_modeset_unlock_crtc(crtc);
3140         }
3141 }
3142
3143 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3144 {
3145         /* no reset support for gen2 */
3146         if (IS_GEN2(dev_priv))
3147                 return;
3148
3149         /* reset doesn't touch the display */
3150         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3151                 return;
3152
3153         drm_modeset_lock_all(dev_priv->dev);
3154         /*
3155          * Disabling the crtcs gracefully seems nicer. Also the
3156          * g33 docs say we should at least disable all the planes.
3157          */
3158         intel_display_suspend(dev_priv->dev);
3159 }
3160
3161 void intel_finish_reset(struct drm_i915_private *dev_priv)
3162 {
3163         /*
3164          * Flips in the rings will be nuked by the reset,
3165          * so complete all pending flips so that user space
3166          * will get its events and not get stuck.
3167          */
3168         intel_complete_page_flips(dev_priv);
3169
3170         /* no reset support for gen2 */
3171         if (IS_GEN2(dev_priv))
3172                 return;
3173
3174         /* reset doesn't touch the display */
3175         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3176                 /*
3177                  * Flips in the rings have been nuked by the reset,
3178                  * so update the base address of all primary
3179                  * planes to the the last fb to make sure we're
3180                  * showing the correct fb after a reset.
3181                  *
3182                  * FIXME: Atomic will make this obsolete since we won't schedule
3183                  * CS-based flips (which might get lost in gpu resets) any more.
3184                  */
3185                 intel_update_primary_planes(dev_priv->dev);
3186                 return;
3187         }
3188
3189         /*
3190          * The display has been reset as well,
3191          * so need a full re-initialization.
3192          */
3193         intel_runtime_pm_disable_interrupts(dev_priv);
3194         intel_runtime_pm_enable_interrupts(dev_priv);
3195
3196         intel_modeset_init_hw(dev_priv->dev);
3197
3198         spin_lock_irq(&dev_priv->irq_lock);
3199         if (dev_priv->display.hpd_irq_setup)
3200                 dev_priv->display.hpd_irq_setup(dev_priv);
3201         spin_unlock_irq(&dev_priv->irq_lock);
3202
3203         intel_display_resume(dev_priv->dev);
3204
3205         intel_hpd_init(dev_priv);
3206
3207         drm_modeset_unlock_all(dev_priv->dev);
3208 }
3209
3210 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3211 {
3212         struct drm_device *dev = crtc->dev;
3213         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3214         unsigned reset_counter;
3215         bool pending;
3216
3217         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3218         if (intel_crtc->reset_counter != reset_counter)
3219                 return false;
3220
3221         spin_lock_irq(&dev->event_lock);
3222         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3223         spin_unlock_irq(&dev->event_lock);
3224
3225         return pending;
3226 }
3227
3228 static void intel_update_pipe_config(struct intel_crtc *crtc,
3229                                      struct intel_crtc_state *old_crtc_state)
3230 {
3231         struct drm_device *dev = crtc->base.dev;
3232         struct drm_i915_private *dev_priv = dev->dev_private;
3233         struct intel_crtc_state *pipe_config =
3234                 to_intel_crtc_state(crtc->base.state);
3235
3236         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3237         crtc->base.mode = crtc->base.state->mode;
3238
3239         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3240                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3241                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3242
3243         /*
3244          * Update pipe size and adjust fitter if needed: the reason for this is
3245          * that in compute_mode_changes we check the native mode (not the pfit
3246          * mode) to see if we can flip rather than do a full mode set. In the
3247          * fastboot case, we'll flip, but if we don't update the pipesrc and
3248          * pfit state, we'll end up with a big fb scanned out into the wrong
3249          * sized surface.
3250          */
3251
3252         I915_WRITE(PIPESRC(crtc->pipe),
3253                    ((pipe_config->pipe_src_w - 1) << 16) |
3254                    (pipe_config->pipe_src_h - 1));
3255
3256         /* on skylake this is done by detaching scalers */
3257         if (INTEL_INFO(dev)->gen >= 9) {
3258                 skl_detach_scalers(crtc);
3259
3260                 if (pipe_config->pch_pfit.enabled)
3261                         skylake_pfit_enable(crtc);
3262         } else if (HAS_PCH_SPLIT(dev)) {
3263                 if (pipe_config->pch_pfit.enabled)
3264                         ironlake_pfit_enable(crtc);
3265                 else if (old_crtc_state->pch_pfit.enabled)
3266                         ironlake_pfit_disable(crtc, true);
3267         }
3268 }
3269
3270 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3271 {
3272         struct drm_device *dev = crtc->dev;
3273         struct drm_i915_private *dev_priv = dev->dev_private;
3274         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3275         int pipe = intel_crtc->pipe;
3276         i915_reg_t reg;
3277         u32 temp;
3278
3279         /* enable normal train */
3280         reg = FDI_TX_CTL(pipe);
3281         temp = I915_READ(reg);
3282         if (IS_IVYBRIDGE(dev)) {
3283                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3284                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3285         } else {
3286                 temp &= ~FDI_LINK_TRAIN_NONE;
3287                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3288         }
3289         I915_WRITE(reg, temp);
3290
3291         reg = FDI_RX_CTL(pipe);
3292         temp = I915_READ(reg);
3293         if (HAS_PCH_CPT(dev)) {
3294                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3295                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3296         } else {
3297                 temp &= ~FDI_LINK_TRAIN_NONE;
3298                 temp |= FDI_LINK_TRAIN_NONE;
3299         }
3300         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3301
3302         /* wait one idle pattern time */
3303         POSTING_READ(reg);
3304         udelay(1000);
3305
3306         /* IVB wants error correction enabled */
3307         if (IS_IVYBRIDGE(dev))
3308                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3309                            FDI_FE_ERRC_ENABLE);
3310 }
3311
3312 /* The FDI link training functions for ILK/Ibexpeak. */
3313 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3314 {
3315         struct drm_device *dev = crtc->dev;
3316         struct drm_i915_private *dev_priv = dev->dev_private;
3317         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3318         int pipe = intel_crtc->pipe;
3319         i915_reg_t reg;
3320         u32 temp, tries;
3321
3322         /* FDI needs bits from pipe first */
3323         assert_pipe_enabled(dev_priv, pipe);
3324
3325         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3326            for train result */
3327         reg = FDI_RX_IMR(pipe);
3328         temp = I915_READ(reg);
3329         temp &= ~FDI_RX_SYMBOL_LOCK;
3330         temp &= ~FDI_RX_BIT_LOCK;
3331         I915_WRITE(reg, temp);
3332         I915_READ(reg);
3333         udelay(150);
3334
3335         /* enable CPU FDI TX and PCH FDI RX */
3336         reg = FDI_TX_CTL(pipe);
3337         temp = I915_READ(reg);
3338         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3339         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3340         temp &= ~FDI_LINK_TRAIN_NONE;
3341         temp |= FDI_LINK_TRAIN_PATTERN_1;
3342         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3343
3344         reg = FDI_RX_CTL(pipe);
3345         temp = I915_READ(reg);
3346         temp &= ~FDI_LINK_TRAIN_NONE;
3347         temp |= FDI_LINK_TRAIN_PATTERN_1;
3348         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3349
3350         POSTING_READ(reg);
3351         udelay(150);
3352
3353         /* Ironlake workaround, enable clock pointer after FDI enable*/
3354         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3355         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3356                    FDI_RX_PHASE_SYNC_POINTER_EN);
3357
3358         reg = FDI_RX_IIR(pipe);
3359         for (tries = 0; tries < 5; tries++) {
3360                 temp = I915_READ(reg);
3361                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3362
3363                 if ((temp & FDI_RX_BIT_LOCK)) {
3364                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3365                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3366                         break;
3367                 }
3368         }
3369         if (tries == 5)
3370                 DRM_ERROR("FDI train 1 fail!\n");
3371
3372         /* Train 2 */
3373         reg = FDI_TX_CTL(pipe);
3374         temp = I915_READ(reg);
3375         temp &= ~FDI_LINK_TRAIN_NONE;
3376         temp |= FDI_LINK_TRAIN_PATTERN_2;
3377         I915_WRITE(reg, temp);
3378
3379         reg = FDI_RX_CTL(pipe);
3380         temp = I915_READ(reg);
3381         temp &= ~FDI_LINK_TRAIN_NONE;
3382         temp |= FDI_LINK_TRAIN_PATTERN_2;
3383         I915_WRITE(reg, temp);
3384
3385         POSTING_READ(reg);
3386         udelay(150);
3387
3388         reg = FDI_RX_IIR(pipe);
3389         for (tries = 0; tries < 5; tries++) {
3390                 temp = I915_READ(reg);
3391                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3392
3393                 if (temp & FDI_RX_SYMBOL_LOCK) {
3394                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3395                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3396                         break;
3397                 }
3398         }
3399         if (tries == 5)
3400                 DRM_ERROR("FDI train 2 fail!\n");
3401
3402         DRM_DEBUG_KMS("FDI train done\n");
3403
3404 }
3405
3406 static const int snb_b_fdi_train_param[] = {
3407         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3408         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3409         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3410         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3411 };
3412
3413 /* The FDI link training functions for SNB/Cougarpoint. */
3414 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3415 {
3416         struct drm_device *dev = crtc->dev;
3417         struct drm_i915_private *dev_priv = dev->dev_private;
3418         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3419         int pipe = intel_crtc->pipe;
3420         i915_reg_t reg;
3421         u32 temp, i, retry;
3422
3423         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3424            for train result */
3425         reg = FDI_RX_IMR(pipe);
3426         temp = I915_READ(reg);
3427         temp &= ~FDI_RX_SYMBOL_LOCK;
3428         temp &= ~FDI_RX_BIT_LOCK;
3429         I915_WRITE(reg, temp);
3430
3431         POSTING_READ(reg);
3432         udelay(150);
3433
3434         /* enable CPU FDI TX and PCH FDI RX */
3435         reg = FDI_TX_CTL(pipe);
3436         temp = I915_READ(reg);
3437         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3438         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3439         temp &= ~FDI_LINK_TRAIN_NONE;
3440         temp |= FDI_LINK_TRAIN_PATTERN_1;
3441         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3442         /* SNB-B */
3443         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3444         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3445
3446         I915_WRITE(FDI_RX_MISC(pipe),
3447                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3448
3449         reg = FDI_RX_CTL(pipe);
3450         temp = I915_READ(reg);
3451         if (HAS_PCH_CPT(dev)) {
3452                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3453                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3454         } else {
3455                 temp &= ~FDI_LINK_TRAIN_NONE;
3456                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3457         }
3458         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3459
3460         POSTING_READ(reg);
3461         udelay(150);
3462
3463         for (i = 0; i < 4; i++) {
3464                 reg = FDI_TX_CTL(pipe);
3465                 temp = I915_READ(reg);
3466                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3467                 temp |= snb_b_fdi_train_param[i];
3468                 I915_WRITE(reg, temp);
3469
3470                 POSTING_READ(reg);
3471                 udelay(500);
3472
3473                 for (retry = 0; retry < 5; retry++) {
3474                         reg = FDI_RX_IIR(pipe);
3475                         temp = I915_READ(reg);
3476                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3477                         if (temp & FDI_RX_BIT_LOCK) {
3478                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3479                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3480                                 break;
3481                         }
3482                         udelay(50);
3483                 }
3484                 if (retry < 5)
3485                         break;
3486         }
3487         if (i == 4)
3488                 DRM_ERROR("FDI train 1 fail!\n");
3489
3490         /* Train 2 */
3491         reg = FDI_TX_CTL(pipe);
3492         temp = I915_READ(reg);
3493         temp &= ~FDI_LINK_TRAIN_NONE;
3494         temp |= FDI_LINK_TRAIN_PATTERN_2;
3495         if (IS_GEN6(dev)) {
3496                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3497                 /* SNB-B */
3498                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3499         }
3500         I915_WRITE(reg, temp);
3501
3502         reg = FDI_RX_CTL(pipe);
3503         temp = I915_READ(reg);
3504         if (HAS_PCH_CPT(dev)) {
3505                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3506                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3507         } else {
3508                 temp &= ~FDI_LINK_TRAIN_NONE;
3509                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3510         }
3511         I915_WRITE(reg, temp);
3512
3513         POSTING_READ(reg);
3514         udelay(150);
3515
3516         for (i = 0; i < 4; i++) {
3517                 reg = FDI_TX_CTL(pipe);
3518                 temp = I915_READ(reg);
3519                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3520                 temp |= snb_b_fdi_train_param[i];
3521                 I915_WRITE(reg, temp);
3522
3523                 POSTING_READ(reg);
3524                 udelay(500);
3525
3526                 for (retry = 0; retry < 5; retry++) {
3527                         reg = FDI_RX_IIR(pipe);
3528                         temp = I915_READ(reg);
3529                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3530                         if (temp & FDI_RX_SYMBOL_LOCK) {
3531                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3532                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3533                                 break;
3534                         }
3535                         udelay(50);
3536                 }
3537                 if (retry < 5)
3538                         break;
3539         }
3540         if (i == 4)
3541                 DRM_ERROR("FDI train 2 fail!\n");
3542
3543         DRM_DEBUG_KMS("FDI train done.\n");
3544 }
3545
3546 /* Manual link training for Ivy Bridge A0 parts */
3547 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3548 {
3549         struct drm_device *dev = crtc->dev;
3550         struct drm_i915_private *dev_priv = dev->dev_private;
3551         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3552         int pipe = intel_crtc->pipe;
3553         i915_reg_t reg;
3554         u32 temp, i, j;
3555
3556         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3557            for train result */
3558         reg = FDI_RX_IMR(pipe);
3559         temp = I915_READ(reg);
3560         temp &= ~FDI_RX_SYMBOL_LOCK;
3561         temp &= ~FDI_RX_BIT_LOCK;
3562         I915_WRITE(reg, temp);
3563
3564         POSTING_READ(reg);
3565         udelay(150);
3566
3567         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3568                       I915_READ(FDI_RX_IIR(pipe)));
3569
3570         /* Try each vswing and preemphasis setting twice before moving on */
3571         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3572                 /* disable first in case we need to retry */
3573                 reg = FDI_TX_CTL(pipe);
3574                 temp = I915_READ(reg);
3575                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3576                 temp &= ~FDI_TX_ENABLE;
3577                 I915_WRITE(reg, temp);
3578
3579                 reg = FDI_RX_CTL(pipe);
3580                 temp = I915_READ(reg);
3581                 temp &= ~FDI_LINK_TRAIN_AUTO;
3582                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3583                 temp &= ~FDI_RX_ENABLE;
3584                 I915_WRITE(reg, temp);
3585
3586                 /* enable CPU FDI TX and PCH FDI RX */
3587                 reg = FDI_TX_CTL(pipe);
3588                 temp = I915_READ(reg);
3589                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3590                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3591                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3592                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3593                 temp |= snb_b_fdi_train_param[j/2];
3594                 temp |= FDI_COMPOSITE_SYNC;
3595                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3596
3597                 I915_WRITE(FDI_RX_MISC(pipe),
3598                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3599
3600                 reg = FDI_RX_CTL(pipe);
3601                 temp = I915_READ(reg);
3602                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3603                 temp |= FDI_COMPOSITE_SYNC;
3604                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3605
3606                 POSTING_READ(reg);
3607                 udelay(1); /* should be 0.5us */
3608
3609                 for (i = 0; i < 4; i++) {
3610                         reg = FDI_RX_IIR(pipe);
3611                         temp = I915_READ(reg);
3612                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3613
3614                         if (temp & FDI_RX_BIT_LOCK ||
3615                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3616                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3617                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3618                                               i);
3619                                 break;
3620                         }
3621                         udelay(1); /* should be 0.5us */
3622                 }
3623                 if (i == 4) {
3624                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3625                         continue;
3626                 }
3627
3628                 /* Train 2 */
3629                 reg = FDI_TX_CTL(pipe);
3630                 temp = I915_READ(reg);
3631                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3632                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3633                 I915_WRITE(reg, temp);
3634
3635                 reg = FDI_RX_CTL(pipe);
3636                 temp = I915_READ(reg);
3637                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3638                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3639                 I915_WRITE(reg, temp);
3640
3641                 POSTING_READ(reg);
3642                 udelay(2); /* should be 1.5us */
3643
3644                 for (i = 0; i < 4; i++) {
3645                         reg = FDI_RX_IIR(pipe);
3646                         temp = I915_READ(reg);
3647                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3648
3649                         if (temp & FDI_RX_SYMBOL_LOCK ||
3650                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3651                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3652                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3653                                               i);
3654                                 goto train_done;
3655                         }
3656                         udelay(2); /* should be 1.5us */
3657                 }
3658                 if (i == 4)
3659                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3660         }
3661
3662 train_done:
3663         DRM_DEBUG_KMS("FDI train done.\n");
3664 }
3665
3666 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3667 {
3668         struct drm_device *dev = intel_crtc->base.dev;
3669         struct drm_i915_private *dev_priv = dev->dev_private;
3670         int pipe = intel_crtc->pipe;
3671         i915_reg_t reg;
3672         u32 temp;
3673
3674         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3675         reg = FDI_RX_CTL(pipe);
3676         temp = I915_READ(reg);
3677         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3678         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3679         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3680         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3681
3682         POSTING_READ(reg);
3683         udelay(200);
3684
3685         /* Switch from Rawclk to PCDclk */
3686         temp = I915_READ(reg);
3687         I915_WRITE(reg, temp | FDI_PCDCLK);
3688
3689         POSTING_READ(reg);
3690         udelay(200);
3691
3692         /* Enable CPU FDI TX PLL, always on for Ironlake */
3693         reg = FDI_TX_CTL(pipe);
3694         temp = I915_READ(reg);
3695         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3696                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3697
3698                 POSTING_READ(reg);
3699                 udelay(100);
3700         }
3701 }
3702
3703 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3704 {
3705         struct drm_device *dev = intel_crtc->base.dev;
3706         struct drm_i915_private *dev_priv = dev->dev_private;
3707         int pipe = intel_crtc->pipe;
3708         i915_reg_t reg;
3709         u32 temp;
3710
3711         /* Switch from PCDclk to Rawclk */
3712         reg = FDI_RX_CTL(pipe);
3713         temp = I915_READ(reg);
3714         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3715
3716         /* Disable CPU FDI TX PLL */
3717         reg = FDI_TX_CTL(pipe);
3718         temp = I915_READ(reg);
3719         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3720
3721         POSTING_READ(reg);
3722         udelay(100);
3723
3724         reg = FDI_RX_CTL(pipe);
3725         temp = I915_READ(reg);
3726         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3727
3728         /* Wait for the clocks to turn off. */
3729         POSTING_READ(reg);
3730         udelay(100);
3731 }
3732
3733 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3734 {
3735         struct drm_device *dev = crtc->dev;
3736         struct drm_i915_private *dev_priv = dev->dev_private;
3737         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3738         int pipe = intel_crtc->pipe;
3739         i915_reg_t reg;
3740         u32 temp;
3741
3742         /* disable CPU FDI tx and PCH FDI rx */
3743         reg = FDI_TX_CTL(pipe);
3744         temp = I915_READ(reg);
3745         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3746         POSTING_READ(reg);
3747
3748         reg = FDI_RX_CTL(pipe);
3749         temp = I915_READ(reg);
3750         temp &= ~(0x7 << 16);
3751         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3752         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3753
3754         POSTING_READ(reg);
3755         udelay(100);
3756
3757         /* Ironlake workaround, disable clock pointer after downing FDI */
3758         if (HAS_PCH_IBX(dev))
3759                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3760
3761         /* still set train pattern 1 */
3762         reg = FDI_TX_CTL(pipe);
3763         temp = I915_READ(reg);
3764         temp &= ~FDI_LINK_TRAIN_NONE;
3765         temp |= FDI_LINK_TRAIN_PATTERN_1;
3766         I915_WRITE(reg, temp);
3767
3768         reg = FDI_RX_CTL(pipe);
3769         temp = I915_READ(reg);
3770         if (HAS_PCH_CPT(dev)) {
3771                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3772                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3773         } else {
3774                 temp &= ~FDI_LINK_TRAIN_NONE;
3775                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3776         }
3777         /* BPC in FDI rx is consistent with that in PIPECONF */
3778         temp &= ~(0x07 << 16);
3779         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3780         I915_WRITE(reg, temp);
3781
3782         POSTING_READ(reg);
3783         udelay(100);
3784 }
3785
3786 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3787 {
3788         struct intel_crtc *crtc;
3789
3790         /* Note that we don't need to be called with mode_config.lock here
3791          * as our list of CRTC objects is static for the lifetime of the
3792          * device and so cannot disappear as we iterate. Similarly, we can
3793          * happily treat the predicates as racy, atomic checks as userspace
3794          * cannot claim and pin a new fb without at least acquring the
3795          * struct_mutex and so serialising with us.
3796          */
3797         for_each_intel_crtc(dev, crtc) {
3798                 if (atomic_read(&crtc->unpin_work_count) == 0)
3799                         continue;
3800
3801                 if (crtc->unpin_work)
3802                         intel_wait_for_vblank(dev, crtc->pipe);
3803
3804                 return true;
3805         }
3806
3807         return false;
3808 }
3809
3810 static void page_flip_completed(struct intel_crtc *intel_crtc)
3811 {
3812         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3813         struct intel_unpin_work *work = intel_crtc->unpin_work;
3814
3815         /* ensure that the unpin work is consistent wrt ->pending. */
3816         smp_rmb();
3817         intel_crtc->unpin_work = NULL;
3818
3819         if (work->event)
3820                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3821
3822         drm_crtc_vblank_put(&intel_crtc->base);
3823
3824         wake_up_all(&dev_priv->pending_flip_queue);
3825         queue_work(dev_priv->wq, &work->work);
3826
3827         trace_i915_flip_complete(intel_crtc->plane,
3828                                  work->pending_flip_obj);
3829 }
3830
3831 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3832 {
3833         struct drm_device *dev = crtc->dev;
3834         struct drm_i915_private *dev_priv = dev->dev_private;
3835         long ret;
3836
3837         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3838
3839         ret = wait_event_interruptible_timeout(
3840                                         dev_priv->pending_flip_queue,
3841                                         !intel_crtc_has_pending_flip(crtc),
3842                                         60*HZ);
3843
3844         if (ret < 0)
3845                 return ret;
3846
3847         if (ret == 0) {
3848                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3849
3850                 spin_lock_irq(&dev->event_lock);
3851                 if (intel_crtc->unpin_work) {
3852                         WARN_ONCE(1, "Removing stuck page flip\n");
3853                         page_flip_completed(intel_crtc);
3854                 }
3855                 spin_unlock_irq(&dev->event_lock);
3856         }
3857
3858         return 0;
3859 }
3860
3861 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3862 {
3863         u32 temp;
3864
3865         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3866
3867         mutex_lock(&dev_priv->sb_lock);
3868
3869         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3870         temp |= SBI_SSCCTL_DISABLE;
3871         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3872
3873         mutex_unlock(&dev_priv->sb_lock);
3874 }
3875
3876 /* Program iCLKIP clock to the desired frequency */
3877 static void lpt_program_iclkip(struct drm_crtc *crtc)
3878 {
3879         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3880         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3881         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3882         u32 temp;
3883
3884         lpt_disable_iclkip(dev_priv);
3885
3886         /* The iCLK virtual clock root frequency is in MHz,
3887          * but the adjusted_mode->crtc_clock in in KHz. To get the
3888          * divisors, it is necessary to divide one by another, so we
3889          * convert the virtual clock precision to KHz here for higher
3890          * precision.
3891          */
3892         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3893                 u32 iclk_virtual_root_freq = 172800 * 1000;
3894                 u32 iclk_pi_range = 64;
3895                 u32 desired_divisor;
3896
3897                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3898                                                     clock << auxdiv);
3899                 divsel = (desired_divisor / iclk_pi_range) - 2;
3900                 phaseinc = desired_divisor % iclk_pi_range;
3901
3902                 /*
3903                  * Near 20MHz is a corner case which is
3904                  * out of range for the 7-bit divisor
3905                  */
3906                 if (divsel <= 0x7f)
3907                         break;
3908         }
3909
3910         /* This should not happen with any sane values */
3911         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3912                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3913         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3914                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3915
3916         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3917                         clock,
3918                         auxdiv,
3919                         divsel,
3920                         phasedir,
3921                         phaseinc);
3922
3923         mutex_lock(&dev_priv->sb_lock);
3924
3925         /* Program SSCDIVINTPHASE6 */
3926         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3927         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3928         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3929         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3930         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3931         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3932         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3933         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3934
3935         /* Program SSCAUXDIV */
3936         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3937         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3938         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3939         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3940
3941         /* Enable modulator and associated divider */
3942         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3943         temp &= ~SBI_SSCCTL_DISABLE;
3944         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3945
3946         mutex_unlock(&dev_priv->sb_lock);
3947
3948         /* Wait for initialization time */
3949         udelay(24);
3950
3951         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3952 }
3953
3954 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3955 {
3956         u32 divsel, phaseinc, auxdiv;
3957         u32 iclk_virtual_root_freq = 172800 * 1000;
3958         u32 iclk_pi_range = 64;
3959         u32 desired_divisor;
3960         u32 temp;
3961
3962         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3963                 return 0;
3964
3965         mutex_lock(&dev_priv->sb_lock);
3966
3967         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3968         if (temp & SBI_SSCCTL_DISABLE) {
3969                 mutex_unlock(&dev_priv->sb_lock);
3970                 return 0;
3971         }
3972
3973         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3974         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3975                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3976         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3977                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3978
3979         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3980         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3981                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3982
3983         mutex_unlock(&dev_priv->sb_lock);
3984
3985         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3986
3987         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3988                                  desired_divisor << auxdiv);
3989 }
3990
3991 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3992                                                 enum pipe pch_transcoder)
3993 {
3994         struct drm_device *dev = crtc->base.dev;
3995         struct drm_i915_private *dev_priv = dev->dev_private;
3996         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3997
3998         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3999                    I915_READ(HTOTAL(cpu_transcoder)));
4000         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4001                    I915_READ(HBLANK(cpu_transcoder)));
4002         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4003                    I915_READ(HSYNC(cpu_transcoder)));
4004
4005         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4006                    I915_READ(VTOTAL(cpu_transcoder)));
4007         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4008                    I915_READ(VBLANK(cpu_transcoder)));
4009         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4010                    I915_READ(VSYNC(cpu_transcoder)));
4011         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4012                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4013 }
4014
4015 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4016 {
4017         struct drm_i915_private *dev_priv = dev->dev_private;
4018         uint32_t temp;
4019
4020         temp = I915_READ(SOUTH_CHICKEN1);
4021         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4022                 return;
4023
4024         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4025         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4026
4027         temp &= ~FDI_BC_BIFURCATION_SELECT;
4028         if (enable)
4029                 temp |= FDI_BC_BIFURCATION_SELECT;
4030
4031         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4032         I915_WRITE(SOUTH_CHICKEN1, temp);
4033         POSTING_READ(SOUTH_CHICKEN1);
4034 }
4035
4036 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4037 {
4038         struct drm_device *dev = intel_crtc->base.dev;
4039
4040         switch (intel_crtc->pipe) {
4041         case PIPE_A:
4042                 break;
4043         case PIPE_B:
4044                 if (intel_crtc->config->fdi_lanes > 2)
4045                         cpt_set_fdi_bc_bifurcation(dev, false);
4046                 else
4047                         cpt_set_fdi_bc_bifurcation(dev, true);
4048
4049                 break;
4050         case PIPE_C:
4051                 cpt_set_fdi_bc_bifurcation(dev, true);
4052
4053                 break;
4054         default:
4055                 BUG();
4056         }
4057 }
4058
4059 /* Return which DP Port should be selected for Transcoder DP control */
4060 static enum port
4061 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4062 {
4063         struct drm_device *dev = crtc->dev;
4064         struct intel_encoder *encoder;
4065
4066         for_each_encoder_on_crtc(dev, crtc, encoder) {
4067                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4068                     encoder->type == INTEL_OUTPUT_EDP)
4069                         return enc_to_dig_port(&encoder->base)->port;
4070         }
4071
4072         return -1;
4073 }
4074
4075 /*
4076  * Enable PCH resources required for PCH ports:
4077  *   - PCH PLLs
4078  *   - FDI training & RX/TX
4079  *   - update transcoder timings
4080  *   - DP transcoding bits
4081  *   - transcoder
4082  */
4083 static void ironlake_pch_enable(struct drm_crtc *crtc)
4084 {
4085         struct drm_device *dev = crtc->dev;
4086         struct drm_i915_private *dev_priv = dev->dev_private;
4087         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4088         int pipe = intel_crtc->pipe;
4089         u32 temp;
4090
4091         assert_pch_transcoder_disabled(dev_priv, pipe);
4092
4093         if (IS_IVYBRIDGE(dev))
4094                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4095
4096         /* Write the TU size bits before fdi link training, so that error
4097          * detection works. */
4098         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4099                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4100
4101         /* For PCH output, training FDI link */
4102         dev_priv->display.fdi_link_train(crtc);
4103
4104         /* We need to program the right clock selection before writing the pixel
4105          * mutliplier into the DPLL. */
4106         if (HAS_PCH_CPT(dev)) {
4107                 u32 sel;
4108
4109                 temp = I915_READ(PCH_DPLL_SEL);
4110                 temp |= TRANS_DPLL_ENABLE(pipe);
4111                 sel = TRANS_DPLLB_SEL(pipe);
4112                 if (intel_crtc->config->shared_dpll ==
4113                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4114                         temp |= sel;
4115                 else
4116                         temp &= ~sel;
4117                 I915_WRITE(PCH_DPLL_SEL, temp);
4118         }
4119
4120         /* XXX: pch pll's can be enabled any time before we enable the PCH
4121          * transcoder, and we actually should do this to not upset any PCH
4122          * transcoder that already use the clock when we share it.
4123          *
4124          * Note that enable_shared_dpll tries to do the right thing, but
4125          * get_shared_dpll unconditionally resets the pll - we need that to have
4126          * the right LVDS enable sequence. */
4127         intel_enable_shared_dpll(intel_crtc);
4128
4129         /* set transcoder timing, panel must allow it */
4130         assert_panel_unlocked(dev_priv, pipe);
4131         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4132
4133         intel_fdi_normal_train(crtc);
4134
4135         /* For PCH DP, enable TRANS_DP_CTL */
4136         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4137                 const struct drm_display_mode *adjusted_mode =
4138                         &intel_crtc->config->base.adjusted_mode;
4139                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4140                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4141                 temp = I915_READ(reg);
4142                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4143                           TRANS_DP_SYNC_MASK |
4144                           TRANS_DP_BPC_MASK);
4145                 temp |= TRANS_DP_OUTPUT_ENABLE;
4146                 temp |= bpc << 9; /* same format but at 11:9 */
4147
4148                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4149                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4150                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4151                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4152
4153                 switch (intel_trans_dp_port_sel(crtc)) {
4154                 case PORT_B:
4155                         temp |= TRANS_DP_PORT_SEL_B;
4156                         break;
4157                 case PORT_C:
4158                         temp |= TRANS_DP_PORT_SEL_C;
4159                         break;
4160                 case PORT_D:
4161                         temp |= TRANS_DP_PORT_SEL_D;
4162                         break;
4163                 default:
4164                         BUG();
4165                 }
4166
4167                 I915_WRITE(reg, temp);
4168         }
4169
4170         ironlake_enable_pch_transcoder(dev_priv, pipe);
4171 }
4172
4173 static void lpt_pch_enable(struct drm_crtc *crtc)
4174 {
4175         struct drm_device *dev = crtc->dev;
4176         struct drm_i915_private *dev_priv = dev->dev_private;
4177         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4178         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4179
4180         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4181
4182         lpt_program_iclkip(crtc);
4183
4184         /* Set transcoder timing. */
4185         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4186
4187         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4188 }
4189
4190 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4191 {
4192         struct drm_i915_private *dev_priv = dev->dev_private;
4193         i915_reg_t dslreg = PIPEDSL(pipe);
4194         u32 temp;
4195
4196         temp = I915_READ(dslreg);
4197         udelay(500);
4198         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4199                 if (wait_for(I915_READ(dslreg) != temp, 5))
4200                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4201         }
4202 }
4203
4204 static int
4205 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4206                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4207                   int src_w, int src_h, int dst_w, int dst_h)
4208 {
4209         struct intel_crtc_scaler_state *scaler_state =
4210                 &crtc_state->scaler_state;
4211         struct intel_crtc *intel_crtc =
4212                 to_intel_crtc(crtc_state->base.crtc);
4213         int need_scaling;
4214
4215         need_scaling = intel_rotation_90_or_270(rotation) ?
4216                 (src_h != dst_w || src_w != dst_h):
4217                 (src_w != dst_w || src_h != dst_h);
4218
4219         /*
4220          * if plane is being disabled or scaler is no more required or force detach
4221          *  - free scaler binded to this plane/crtc
4222          *  - in order to do this, update crtc->scaler_usage
4223          *
4224          * Here scaler state in crtc_state is set free so that
4225          * scaler can be assigned to other user. Actual register
4226          * update to free the scaler is done in plane/panel-fit programming.
4227          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4228          */
4229         if (force_detach || !need_scaling) {
4230                 if (*scaler_id >= 0) {
4231                         scaler_state->scaler_users &= ~(1 << scaler_user);
4232                         scaler_state->scalers[*scaler_id].in_use = 0;
4233
4234                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4235                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4236                                 intel_crtc->pipe, scaler_user, *scaler_id,
4237                                 scaler_state->scaler_users);
4238                         *scaler_id = -1;
4239                 }
4240                 return 0;
4241         }
4242
4243         /* range checks */
4244         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4245                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4246
4247                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4248                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4249                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4250                         "size is out of scaler range\n",
4251                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4252                 return -EINVAL;
4253         }
4254
4255         /* mark this plane as a scaler user in crtc_state */
4256         scaler_state->scaler_users |= (1 << scaler_user);
4257         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4258                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4259                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4260                 scaler_state->scaler_users);
4261
4262         return 0;
4263 }
4264
4265 /**
4266  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4267  *
4268  * @state: crtc's scaler state
4269  *
4270  * Return
4271  *     0 - scaler_usage updated successfully
4272  *    error - requested scaling cannot be supported or other error condition
4273  */
4274 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4275 {
4276         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4277         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4278
4279         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4280                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4281
4282         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4283                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4284                 state->pipe_src_w, state->pipe_src_h,
4285                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4286 }
4287
4288 /**
4289  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4290  *
4291  * @state: crtc's scaler state
4292  * @plane_state: atomic plane state to update
4293  *
4294  * Return
4295  *     0 - scaler_usage updated successfully
4296  *    error - requested scaling cannot be supported or other error condition
4297  */
4298 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4299                                    struct intel_plane_state *plane_state)
4300 {
4301
4302         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4303         struct intel_plane *intel_plane =
4304                 to_intel_plane(plane_state->base.plane);
4305         struct drm_framebuffer *fb = plane_state->base.fb;
4306         int ret;
4307
4308         bool force_detach = !fb || !plane_state->visible;
4309
4310         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4311                       intel_plane->base.base.id, intel_crtc->pipe,
4312                       drm_plane_index(&intel_plane->base));
4313
4314         ret = skl_update_scaler(crtc_state, force_detach,
4315                                 drm_plane_index(&intel_plane->base),
4316                                 &plane_state->scaler_id,
4317                                 plane_state->base.rotation,
4318                                 drm_rect_width(&plane_state->src) >> 16,
4319                                 drm_rect_height(&plane_state->src) >> 16,
4320                                 drm_rect_width(&plane_state->dst),
4321                                 drm_rect_height(&plane_state->dst));
4322
4323         if (ret || plane_state->scaler_id < 0)
4324                 return ret;
4325
4326         /* check colorkey */
4327         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4328                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4329                               intel_plane->base.base.id);
4330                 return -EINVAL;
4331         }
4332
4333         /* Check src format */
4334         switch (fb->pixel_format) {
4335         case DRM_FORMAT_RGB565:
4336         case DRM_FORMAT_XBGR8888:
4337         case DRM_FORMAT_XRGB8888:
4338         case DRM_FORMAT_ABGR8888:
4339         case DRM_FORMAT_ARGB8888:
4340         case DRM_FORMAT_XRGB2101010:
4341         case DRM_FORMAT_XBGR2101010:
4342         case DRM_FORMAT_YUYV:
4343         case DRM_FORMAT_YVYU:
4344         case DRM_FORMAT_UYVY:
4345         case DRM_FORMAT_VYUY:
4346                 break;
4347         default:
4348                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4349                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4350                 return -EINVAL;
4351         }
4352
4353         return 0;
4354 }
4355
4356 static void skylake_scaler_disable(struct intel_crtc *crtc)
4357 {
4358         int i;
4359
4360         for (i = 0; i < crtc->num_scalers; i++)
4361                 skl_detach_scaler(crtc, i);
4362 }
4363
4364 static void skylake_pfit_enable(struct intel_crtc *crtc)
4365 {
4366         struct drm_device *dev = crtc->base.dev;
4367         struct drm_i915_private *dev_priv = dev->dev_private;
4368         int pipe = crtc->pipe;
4369         struct intel_crtc_scaler_state *scaler_state =
4370                 &crtc->config->scaler_state;
4371
4372         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4373
4374         if (crtc->config->pch_pfit.enabled) {
4375                 int id;
4376
4377                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4378                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4379                         return;
4380                 }
4381
4382                 id = scaler_state->scaler_id;
4383                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4384                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4385                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4386                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4387
4388                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4389         }
4390 }
4391
4392 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4393 {
4394         struct drm_device *dev = crtc->base.dev;
4395         struct drm_i915_private *dev_priv = dev->dev_private;
4396         int pipe = crtc->pipe;
4397
4398         if (crtc->config->pch_pfit.enabled) {
4399                 /* Force use of hard-coded filter coefficients
4400                  * as some pre-programmed values are broken,
4401                  * e.g. x201.
4402                  */
4403                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4404                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4405                                                  PF_PIPE_SEL_IVB(pipe));
4406                 else
4407                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4408                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4409                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4410         }
4411 }
4412
4413 void hsw_enable_ips(struct intel_crtc *crtc)
4414 {
4415         struct drm_device *dev = crtc->base.dev;
4416         struct drm_i915_private *dev_priv = dev->dev_private;
4417
4418         if (!crtc->config->ips_enabled)
4419                 return;
4420
4421         /*
4422          * We can only enable IPS after we enable a plane and wait for a vblank
4423          * This function is called from post_plane_update, which is run after
4424          * a vblank wait.
4425          */
4426
4427         assert_plane_enabled(dev_priv, crtc->plane);
4428         if (IS_BROADWELL(dev)) {
4429                 mutex_lock(&dev_priv->rps.hw_lock);
4430                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4431                 mutex_unlock(&dev_priv->rps.hw_lock);
4432                 /* Quoting Art Runyan: "its not safe to expect any particular
4433                  * value in IPS_CTL bit 31 after enabling IPS through the
4434                  * mailbox." Moreover, the mailbox may return a bogus state,
4435                  * so we need to just enable it and continue on.
4436                  */
4437         } else {
4438                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4439                 /* The bit only becomes 1 in the next vblank, so this wait here
4440                  * is essentially intel_wait_for_vblank. If we don't have this
4441                  * and don't wait for vblanks until the end of crtc_enable, then
4442                  * the HW state readout code will complain that the expected
4443                  * IPS_CTL value is not the one we read. */
4444                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4445                         DRM_ERROR("Timed out waiting for IPS enable\n");
4446         }
4447 }
4448
4449 void hsw_disable_ips(struct intel_crtc *crtc)
4450 {
4451         struct drm_device *dev = crtc->base.dev;
4452         struct drm_i915_private *dev_priv = dev->dev_private;
4453
4454         if (!crtc->config->ips_enabled)
4455                 return;
4456
4457         assert_plane_enabled(dev_priv, crtc->plane);
4458         if (IS_BROADWELL(dev)) {
4459                 mutex_lock(&dev_priv->rps.hw_lock);
4460                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4461                 mutex_unlock(&dev_priv->rps.hw_lock);
4462                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4463                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4464                         DRM_ERROR("Timed out waiting for IPS disable\n");
4465         } else {
4466                 I915_WRITE(IPS_CTL, 0);
4467                 POSTING_READ(IPS_CTL);
4468         }
4469
4470         /* We need to wait for a vblank before we can disable the plane. */
4471         intel_wait_for_vblank(dev, crtc->pipe);
4472 }
4473
4474 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4475 {
4476         if (intel_crtc->overlay) {
4477                 struct drm_device *dev = intel_crtc->base.dev;
4478                 struct drm_i915_private *dev_priv = dev->dev_private;
4479
4480                 mutex_lock(&dev->struct_mutex);
4481                 dev_priv->mm.interruptible = false;
4482                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4483                 dev_priv->mm.interruptible = true;
4484                 mutex_unlock(&dev->struct_mutex);
4485         }
4486
4487         /* Let userspace switch the overlay on again. In most cases userspace
4488          * has to recompute where to put it anyway.
4489          */
4490 }
4491
4492 /**
4493  * intel_post_enable_primary - Perform operations after enabling primary plane
4494  * @crtc: the CRTC whose primary plane was just enabled
4495  *
4496  * Performs potentially sleeping operations that must be done after the primary
4497  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4498  * called due to an explicit primary plane update, or due to an implicit
4499  * re-enable that is caused when a sprite plane is updated to no longer
4500  * completely hide the primary plane.
4501  */
4502 static void
4503 intel_post_enable_primary(struct drm_crtc *crtc)
4504 {
4505         struct drm_device *dev = crtc->dev;
4506         struct drm_i915_private *dev_priv = dev->dev_private;
4507         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4508         int pipe = intel_crtc->pipe;
4509
4510         /*
4511          * FIXME IPS should be fine as long as one plane is
4512          * enabled, but in practice it seems to have problems
4513          * when going from primary only to sprite only and vice
4514          * versa.
4515          */
4516         hsw_enable_ips(intel_crtc);
4517
4518         /*
4519          * Gen2 reports pipe underruns whenever all planes are disabled.
4520          * So don't enable underrun reporting before at least some planes
4521          * are enabled.
4522          * FIXME: Need to fix the logic to work when we turn off all planes
4523          * but leave the pipe running.
4524          */
4525         if (IS_GEN2(dev))
4526                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4527
4528         /* Underruns don't always raise interrupts, so check manually. */
4529         intel_check_cpu_fifo_underruns(dev_priv);
4530         intel_check_pch_fifo_underruns(dev_priv);
4531 }
4532
4533 /* FIXME move all this to pre_plane_update() with proper state tracking */
4534 static void
4535 intel_pre_disable_primary(struct drm_crtc *crtc)
4536 {
4537         struct drm_device *dev = crtc->dev;
4538         struct drm_i915_private *dev_priv = dev->dev_private;
4539         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4540         int pipe = intel_crtc->pipe;
4541
4542         /*
4543          * Gen2 reports pipe underruns whenever all planes are disabled.
4544          * So diasble underrun reporting before all the planes get disabled.
4545          * FIXME: Need to fix the logic to work when we turn off all planes
4546          * but leave the pipe running.
4547          */
4548         if (IS_GEN2(dev))
4549                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4550
4551         /*
4552          * FIXME IPS should be fine as long as one plane is
4553          * enabled, but in practice it seems to have problems
4554          * when going from primary only to sprite only and vice
4555          * versa.
4556          */
4557         hsw_disable_ips(intel_crtc);
4558 }
4559
4560 /* FIXME get rid of this and use pre_plane_update */
4561 static void
4562 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4563 {
4564         struct drm_device *dev = crtc->dev;
4565         struct drm_i915_private *dev_priv = dev->dev_private;
4566         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4567         int pipe = intel_crtc->pipe;
4568
4569         intel_pre_disable_primary(crtc);
4570
4571         /*
4572          * Vblank time updates from the shadow to live plane control register
4573          * are blocked if the memory self-refresh mode is active at that
4574          * moment. So to make sure the plane gets truly disabled, disable
4575          * first the self-refresh mode. The self-refresh enable bit in turn
4576          * will be checked/applied by the HW only at the next frame start
4577          * event which is after the vblank start event, so we need to have a
4578          * wait-for-vblank between disabling the plane and the pipe.
4579          */
4580         if (HAS_GMCH_DISPLAY(dev)) {
4581                 intel_set_memory_cxsr(dev_priv, false);
4582                 dev_priv->wm.vlv.cxsr = false;
4583                 intel_wait_for_vblank(dev, pipe);
4584         }
4585 }
4586
4587 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4588 {
4589         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4590         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4591         struct intel_crtc_state *pipe_config =
4592                 to_intel_crtc_state(crtc->base.state);
4593         struct drm_device *dev = crtc->base.dev;
4594         struct drm_plane *primary = crtc->base.primary;
4595         struct drm_plane_state *old_pri_state =
4596                 drm_atomic_get_existing_plane_state(old_state, primary);
4597
4598         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4599
4600         crtc->wm.cxsr_allowed = true;
4601
4602         if (pipe_config->update_wm_post && pipe_config->base.active)
4603                 intel_update_watermarks(&crtc->base);
4604
4605         if (old_pri_state) {
4606                 struct intel_plane_state *primary_state =
4607                         to_intel_plane_state(primary->state);
4608                 struct intel_plane_state *old_primary_state =
4609                         to_intel_plane_state(old_pri_state);
4610
4611                 intel_fbc_post_update(crtc);
4612
4613                 if (primary_state->visible &&
4614                     (needs_modeset(&pipe_config->base) ||
4615                      !old_primary_state->visible))
4616                         intel_post_enable_primary(&crtc->base);
4617         }
4618 }
4619
4620 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4621 {
4622         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4623         struct drm_device *dev = crtc->base.dev;
4624         struct drm_i915_private *dev_priv = dev->dev_private;
4625         struct intel_crtc_state *pipe_config =
4626                 to_intel_crtc_state(crtc->base.state);
4627         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4628         struct drm_plane *primary = crtc->base.primary;
4629         struct drm_plane_state *old_pri_state =
4630                 drm_atomic_get_existing_plane_state(old_state, primary);
4631         bool modeset = needs_modeset(&pipe_config->base);
4632
4633         if (old_pri_state) {
4634                 struct intel_plane_state *primary_state =
4635                         to_intel_plane_state(primary->state);
4636                 struct intel_plane_state *old_primary_state =
4637                         to_intel_plane_state(old_pri_state);
4638
4639                 intel_fbc_pre_update(crtc);
4640
4641                 if (old_primary_state->visible &&
4642                     (modeset || !primary_state->visible))
4643                         intel_pre_disable_primary(&crtc->base);
4644         }
4645
4646         if (pipe_config->disable_cxsr) {
4647                 crtc->wm.cxsr_allowed = false;
4648
4649                 /*
4650                  * Vblank time updates from the shadow to live plane control register
4651                  * are blocked if the memory self-refresh mode is active at that
4652                  * moment. So to make sure the plane gets truly disabled, disable
4653                  * first the self-refresh mode. The self-refresh enable bit in turn
4654                  * will be checked/applied by the HW only at the next frame start
4655                  * event which is after the vblank start event, so we need to have a
4656                  * wait-for-vblank between disabling the plane and the pipe.
4657                  */
4658                 if (old_crtc_state->base.active) {
4659                         intel_set_memory_cxsr(dev_priv, false);
4660                         dev_priv->wm.vlv.cxsr = false;
4661                         intel_wait_for_vblank(dev, crtc->pipe);
4662                 }
4663         }
4664
4665         /*
4666          * IVB workaround: must disable low power watermarks for at least
4667          * one frame before enabling scaling.  LP watermarks can be re-enabled
4668          * when scaling is disabled.
4669          *
4670          * WaCxSRDisabledForSpriteScaling:ivb
4671          */
4672         if (pipe_config->disable_lp_wm) {
4673                 ilk_disable_lp_wm(dev);
4674                 intel_wait_for_vblank(dev, crtc->pipe);
4675         }
4676
4677         /*
4678          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4679          * watermark programming here.
4680          */
4681         if (needs_modeset(&pipe_config->base))
4682                 return;
4683
4684         /*
4685          * For platforms that support atomic watermarks, program the
4686          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4687          * will be the intermediate values that are safe for both pre- and
4688          * post- vblank; when vblank happens, the 'active' values will be set
4689          * to the final 'target' values and we'll do this again to get the
4690          * optimal watermarks.  For gen9+ platforms, the values we program here
4691          * will be the final target values which will get automatically latched
4692          * at vblank time; no further programming will be necessary.
4693          *
4694          * If a platform hasn't been transitioned to atomic watermarks yet,
4695          * we'll continue to update watermarks the old way, if flags tell
4696          * us to.
4697          */
4698         if (dev_priv->display.initial_watermarks != NULL)
4699                 dev_priv->display.initial_watermarks(pipe_config);
4700         else if (pipe_config->update_wm_pre)
4701                 intel_update_watermarks(&crtc->base);
4702 }
4703
4704 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4705 {
4706         struct drm_device *dev = crtc->dev;
4707         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4708         struct drm_plane *p;
4709         int pipe = intel_crtc->pipe;
4710
4711         intel_crtc_dpms_overlay_disable(intel_crtc);
4712
4713         drm_for_each_plane_mask(p, dev, plane_mask)
4714                 to_intel_plane(p)->disable_plane(p, crtc);
4715
4716         /*
4717          * FIXME: Once we grow proper nuclear flip support out of this we need
4718          * to compute the mask of flip planes precisely. For the time being
4719          * consider this a flip to a NULL plane.
4720          */
4721         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4722 }
4723
4724 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4725 {
4726         struct drm_device *dev = crtc->dev;
4727         struct drm_i915_private *dev_priv = dev->dev_private;
4728         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4729         struct intel_encoder *encoder;
4730         int pipe = intel_crtc->pipe;
4731         struct intel_crtc_state *pipe_config =
4732                 to_intel_crtc_state(crtc->state);
4733
4734         if (WARN_ON(intel_crtc->active))
4735                 return;
4736
4737         /*
4738          * Sometimes spurious CPU pipe underruns happen during FDI
4739          * training, at least with VGA+HDMI cloning. Suppress them.
4740          *
4741          * On ILK we get an occasional spurious CPU pipe underruns
4742          * between eDP port A enable and vdd enable. Also PCH port
4743          * enable seems to result in the occasional CPU pipe underrun.
4744          *
4745          * Spurious PCH underruns also occur during PCH enabling.
4746          */
4747         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4748                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4749         if (intel_crtc->config->has_pch_encoder)
4750                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4751
4752         if (intel_crtc->config->has_pch_encoder)
4753                 intel_prepare_shared_dpll(intel_crtc);
4754
4755         if (intel_crtc->config->has_dp_encoder)
4756                 intel_dp_set_m_n(intel_crtc, M1_N1);
4757
4758         intel_set_pipe_timings(intel_crtc);
4759         intel_set_pipe_src_size(intel_crtc);
4760
4761         if (intel_crtc->config->has_pch_encoder) {
4762                 intel_cpu_transcoder_set_m_n(intel_crtc,
4763                                      &intel_crtc->config->fdi_m_n, NULL);
4764         }
4765
4766         ironlake_set_pipeconf(crtc);
4767
4768         intel_crtc->active = true;
4769
4770         for_each_encoder_on_crtc(dev, crtc, encoder)
4771                 if (encoder->pre_enable)
4772                         encoder->pre_enable(encoder);
4773
4774         if (intel_crtc->config->has_pch_encoder) {
4775                 /* Note: FDI PLL enabling _must_ be done before we enable the
4776                  * cpu pipes, hence this is separate from all the other fdi/pch
4777                  * enabling. */
4778                 ironlake_fdi_pll_enable(intel_crtc);
4779         } else {
4780                 assert_fdi_tx_disabled(dev_priv, pipe);
4781                 assert_fdi_rx_disabled(dev_priv, pipe);
4782         }
4783
4784         ironlake_pfit_enable(intel_crtc);
4785
4786         /*
4787          * On ILK+ LUT must be loaded before the pipe is running but with
4788          * clocks enabled
4789          */
4790         intel_color_load_luts(&pipe_config->base);
4791
4792         if (dev_priv->display.initial_watermarks != NULL)
4793                 dev_priv->display.initial_watermarks(intel_crtc->config);
4794         intel_enable_pipe(intel_crtc);
4795
4796         if (intel_crtc->config->has_pch_encoder)
4797                 ironlake_pch_enable(crtc);
4798
4799         assert_vblank_disabled(crtc);
4800         drm_crtc_vblank_on(crtc);
4801
4802         for_each_encoder_on_crtc(dev, crtc, encoder)
4803                 encoder->enable(encoder);
4804
4805         if (HAS_PCH_CPT(dev))
4806                 cpt_verify_modeset(dev, intel_crtc->pipe);
4807
4808         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4809         if (intel_crtc->config->has_pch_encoder)
4810                 intel_wait_for_vblank(dev, pipe);
4811         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4812         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4813 }
4814
4815 /* IPS only exists on ULT machines and is tied to pipe A. */
4816 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4817 {
4818         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4819 }
4820
4821 static void haswell_crtc_enable(struct drm_crtc *crtc)
4822 {
4823         struct drm_device *dev = crtc->dev;
4824         struct drm_i915_private *dev_priv = dev->dev_private;
4825         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4826         struct intel_encoder *encoder;
4827         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4828         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4829         struct intel_crtc_state *pipe_config =
4830                 to_intel_crtc_state(crtc->state);
4831
4832         if (WARN_ON(intel_crtc->active))
4833                 return;
4834
4835         if (intel_crtc->config->has_pch_encoder)
4836                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4837                                                       false);
4838
4839         if (intel_crtc->config->shared_dpll)
4840                 intel_enable_shared_dpll(intel_crtc);
4841
4842         if (intel_crtc->config->has_dp_encoder)
4843                 intel_dp_set_m_n(intel_crtc, M1_N1);
4844
4845         if (!intel_crtc->config->has_dsi_encoder)
4846                 intel_set_pipe_timings(intel_crtc);
4847
4848         intel_set_pipe_src_size(intel_crtc);
4849
4850         if (cpu_transcoder != TRANSCODER_EDP &&
4851             !transcoder_is_dsi(cpu_transcoder)) {
4852                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4853                            intel_crtc->config->pixel_multiplier - 1);
4854         }
4855
4856         if (intel_crtc->config->has_pch_encoder) {
4857                 intel_cpu_transcoder_set_m_n(intel_crtc,
4858                                      &intel_crtc->config->fdi_m_n, NULL);
4859         }
4860
4861         if (!intel_crtc->config->has_dsi_encoder)
4862                 haswell_set_pipeconf(crtc);
4863
4864         haswell_set_pipemisc(crtc);
4865
4866         intel_color_set_csc(&pipe_config->base);
4867
4868         intel_crtc->active = true;
4869
4870         if (intel_crtc->config->has_pch_encoder)
4871                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4872         else
4873                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4874
4875         for_each_encoder_on_crtc(dev, crtc, encoder) {
4876                 if (encoder->pre_enable)
4877                         encoder->pre_enable(encoder);
4878         }
4879
4880         if (intel_crtc->config->has_pch_encoder)
4881                 dev_priv->display.fdi_link_train(crtc);
4882
4883         if (!intel_crtc->config->has_dsi_encoder)
4884                 intel_ddi_enable_pipe_clock(intel_crtc);
4885
4886         if (INTEL_INFO(dev)->gen >= 9)
4887                 skylake_pfit_enable(intel_crtc);
4888         else
4889                 ironlake_pfit_enable(intel_crtc);
4890
4891         /*
4892          * On ILK+ LUT must be loaded before the pipe is running but with
4893          * clocks enabled
4894          */
4895         intel_color_load_luts(&pipe_config->base);
4896
4897         intel_ddi_set_pipe_settings(crtc);
4898         if (!intel_crtc->config->has_dsi_encoder)
4899                 intel_ddi_enable_transcoder_func(crtc);
4900
4901         if (dev_priv->display.initial_watermarks != NULL)
4902                 dev_priv->display.initial_watermarks(pipe_config);
4903         else
4904                 intel_update_watermarks(crtc);
4905
4906         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4907         if (!intel_crtc->config->has_dsi_encoder)
4908                 intel_enable_pipe(intel_crtc);
4909
4910         if (intel_crtc->config->has_pch_encoder)
4911                 lpt_pch_enable(crtc);
4912
4913         if (intel_crtc->config->dp_encoder_is_mst)
4914                 intel_ddi_set_vc_payload_alloc(crtc, true);
4915
4916         assert_vblank_disabled(crtc);
4917         drm_crtc_vblank_on(crtc);
4918
4919         for_each_encoder_on_crtc(dev, crtc, encoder) {
4920                 encoder->enable(encoder);
4921                 intel_opregion_notify_encoder(encoder, true);
4922         }
4923
4924         if (intel_crtc->config->has_pch_encoder) {
4925                 intel_wait_for_vblank(dev, pipe);
4926                 intel_wait_for_vblank(dev, pipe);
4927                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4928                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4929                                                       true);
4930         }
4931
4932         /* If we change the relative order between pipe/planes enabling, we need
4933          * to change the workaround. */
4934         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4935         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4936                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4937                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4938         }
4939 }
4940
4941 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4942 {
4943         struct drm_device *dev = crtc->base.dev;
4944         struct drm_i915_private *dev_priv = dev->dev_private;
4945         int pipe = crtc->pipe;
4946
4947         /* To avoid upsetting the power well on haswell only disable the pfit if
4948          * it's in use. The hw state code will make sure we get this right. */
4949         if (force || crtc->config->pch_pfit.enabled) {
4950                 I915_WRITE(PF_CTL(pipe), 0);
4951                 I915_WRITE(PF_WIN_POS(pipe), 0);
4952                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4953         }
4954 }
4955
4956 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4957 {
4958         struct drm_device *dev = crtc->dev;
4959         struct drm_i915_private *dev_priv = dev->dev_private;
4960         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4961         struct intel_encoder *encoder;
4962         int pipe = intel_crtc->pipe;
4963
4964         /*
4965          * Sometimes spurious CPU pipe underruns happen when the
4966          * pipe is already disabled, but FDI RX/TX is still enabled.
4967          * Happens at least with VGA+HDMI cloning. Suppress them.
4968          */
4969         if (intel_crtc->config->has_pch_encoder) {
4970                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4971                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4972         }
4973
4974         for_each_encoder_on_crtc(dev, crtc, encoder)
4975                 encoder->disable(encoder);
4976
4977         drm_crtc_vblank_off(crtc);
4978         assert_vblank_disabled(crtc);
4979
4980         intel_disable_pipe(intel_crtc);
4981
4982         ironlake_pfit_disable(intel_crtc, false);
4983
4984         if (intel_crtc->config->has_pch_encoder)
4985                 ironlake_fdi_disable(crtc);
4986
4987         for_each_encoder_on_crtc(dev, crtc, encoder)
4988                 if (encoder->post_disable)
4989                         encoder->post_disable(encoder);
4990
4991         if (intel_crtc->config->has_pch_encoder) {
4992                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4993
4994                 if (HAS_PCH_CPT(dev)) {
4995                         i915_reg_t reg;
4996                         u32 temp;
4997
4998                         /* disable TRANS_DP_CTL */
4999                         reg = TRANS_DP_CTL(pipe);
5000                         temp = I915_READ(reg);
5001                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5002                                   TRANS_DP_PORT_SEL_MASK);
5003                         temp |= TRANS_DP_PORT_SEL_NONE;
5004                         I915_WRITE(reg, temp);
5005
5006                         /* disable DPLL_SEL */
5007                         temp = I915_READ(PCH_DPLL_SEL);
5008                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5009                         I915_WRITE(PCH_DPLL_SEL, temp);
5010                 }
5011
5012                 ironlake_fdi_pll_disable(intel_crtc);
5013         }
5014
5015         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5016         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5017 }
5018
5019 static void haswell_crtc_disable(struct drm_crtc *crtc)
5020 {
5021         struct drm_device *dev = crtc->dev;
5022         struct drm_i915_private *dev_priv = dev->dev_private;
5023         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5024         struct intel_encoder *encoder;
5025         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5026
5027         if (intel_crtc->config->has_pch_encoder)
5028                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5029                                                       false);
5030
5031         for_each_encoder_on_crtc(dev, crtc, encoder) {
5032                 intel_opregion_notify_encoder(encoder, false);
5033                 encoder->disable(encoder);
5034         }
5035
5036         drm_crtc_vblank_off(crtc);
5037         assert_vblank_disabled(crtc);
5038
5039         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5040         if (!intel_crtc->config->has_dsi_encoder)
5041                 intel_disable_pipe(intel_crtc);
5042
5043         if (intel_crtc->config->dp_encoder_is_mst)
5044                 intel_ddi_set_vc_payload_alloc(crtc, false);
5045
5046         if (!intel_crtc->config->has_dsi_encoder)
5047                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5048
5049         if (INTEL_INFO(dev)->gen >= 9)
5050                 skylake_scaler_disable(intel_crtc);
5051         else
5052                 ironlake_pfit_disable(intel_crtc, false);
5053
5054         if (!intel_crtc->config->has_dsi_encoder)
5055                 intel_ddi_disable_pipe_clock(intel_crtc);
5056
5057         for_each_encoder_on_crtc(dev, crtc, encoder)
5058                 if (encoder->post_disable)
5059                         encoder->post_disable(encoder);
5060
5061         if (intel_crtc->config->has_pch_encoder) {
5062                 lpt_disable_pch_transcoder(dev_priv);
5063                 lpt_disable_iclkip(dev_priv);
5064                 intel_ddi_fdi_disable(crtc);
5065
5066                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5067                                                       true);
5068         }
5069 }
5070
5071 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5072 {
5073         struct drm_device *dev = crtc->base.dev;
5074         struct drm_i915_private *dev_priv = dev->dev_private;
5075         struct intel_crtc_state *pipe_config = crtc->config;
5076
5077         if (!pipe_config->gmch_pfit.control)
5078                 return;
5079
5080         /*
5081          * The panel fitter should only be adjusted whilst the pipe is disabled,
5082          * according to register description and PRM.
5083          */
5084         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5085         assert_pipe_disabled(dev_priv, crtc->pipe);
5086
5087         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5088         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5089
5090         /* Border color in case we don't scale up to the full screen. Black by
5091          * default, change to something else for debugging. */
5092         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5093 }
5094
5095 static enum intel_display_power_domain port_to_power_domain(enum port port)
5096 {
5097         switch (port) {
5098         case PORT_A:
5099                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5100         case PORT_B:
5101                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5102         case PORT_C:
5103                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5104         case PORT_D:
5105                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5106         case PORT_E:
5107                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5108         default:
5109                 MISSING_CASE(port);
5110                 return POWER_DOMAIN_PORT_OTHER;
5111         }
5112 }
5113
5114 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5115 {
5116         switch (port) {
5117         case PORT_A:
5118                 return POWER_DOMAIN_AUX_A;
5119         case PORT_B:
5120                 return POWER_DOMAIN_AUX_B;
5121         case PORT_C:
5122                 return POWER_DOMAIN_AUX_C;
5123         case PORT_D:
5124                 return POWER_DOMAIN_AUX_D;
5125         case PORT_E:
5126                 /* FIXME: Check VBT for actual wiring of PORT E */
5127                 return POWER_DOMAIN_AUX_D;
5128         default:
5129                 MISSING_CASE(port);
5130                 return POWER_DOMAIN_AUX_A;
5131         }
5132 }
5133
5134 enum intel_display_power_domain
5135 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5136 {
5137         struct drm_device *dev = intel_encoder->base.dev;
5138         struct intel_digital_port *intel_dig_port;
5139
5140         switch (intel_encoder->type) {
5141         case INTEL_OUTPUT_UNKNOWN:
5142                 /* Only DDI platforms should ever use this output type */
5143                 WARN_ON_ONCE(!HAS_DDI(dev));
5144         case INTEL_OUTPUT_DISPLAYPORT:
5145         case INTEL_OUTPUT_HDMI:
5146         case INTEL_OUTPUT_EDP:
5147                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5148                 return port_to_power_domain(intel_dig_port->port);
5149         case INTEL_OUTPUT_DP_MST:
5150                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5151                 return port_to_power_domain(intel_dig_port->port);
5152         case INTEL_OUTPUT_ANALOG:
5153                 return POWER_DOMAIN_PORT_CRT;
5154         case INTEL_OUTPUT_DSI:
5155                 return POWER_DOMAIN_PORT_DSI;
5156         default:
5157                 return POWER_DOMAIN_PORT_OTHER;
5158         }
5159 }
5160
5161 enum intel_display_power_domain
5162 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5163 {
5164         struct drm_device *dev = intel_encoder->base.dev;
5165         struct intel_digital_port *intel_dig_port;
5166
5167         switch (intel_encoder->type) {
5168         case INTEL_OUTPUT_UNKNOWN:
5169         case INTEL_OUTPUT_HDMI:
5170                 /*
5171                  * Only DDI platforms should ever use these output types.
5172                  * We can get here after the HDMI detect code has already set
5173                  * the type of the shared encoder. Since we can't be sure
5174                  * what's the status of the given connectors, play safe and
5175                  * run the DP detection too.
5176                  */
5177                 WARN_ON_ONCE(!HAS_DDI(dev));
5178         case INTEL_OUTPUT_DISPLAYPORT:
5179         case INTEL_OUTPUT_EDP:
5180                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5181                 return port_to_aux_power_domain(intel_dig_port->port);
5182         case INTEL_OUTPUT_DP_MST:
5183                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5184                 return port_to_aux_power_domain(intel_dig_port->port);
5185         default:
5186                 MISSING_CASE(intel_encoder->type);
5187                 return POWER_DOMAIN_AUX_A;
5188         }
5189 }
5190
5191 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5192                                             struct intel_crtc_state *crtc_state)
5193 {
5194         struct drm_device *dev = crtc->dev;
5195         struct drm_encoder *encoder;
5196         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5197         enum pipe pipe = intel_crtc->pipe;
5198         unsigned long mask;
5199         enum transcoder transcoder = crtc_state->cpu_transcoder;
5200
5201         if (!crtc_state->base.active)
5202                 return 0;
5203
5204         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5205         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5206         if (crtc_state->pch_pfit.enabled ||
5207             crtc_state->pch_pfit.force_thru)
5208                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5209
5210         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5211                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5212
5213                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5214         }
5215
5216         if (crtc_state->shared_dpll)
5217                 mask |= BIT(POWER_DOMAIN_PLLS);
5218
5219         return mask;
5220 }
5221
5222 static unsigned long
5223 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5224                                struct intel_crtc_state *crtc_state)
5225 {
5226         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5227         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5228         enum intel_display_power_domain domain;
5229         unsigned long domains, new_domains, old_domains;
5230
5231         old_domains = intel_crtc->enabled_power_domains;
5232         intel_crtc->enabled_power_domains = new_domains =
5233                 get_crtc_power_domains(crtc, crtc_state);
5234
5235         domains = new_domains & ~old_domains;
5236
5237         for_each_power_domain(domain, domains)
5238                 intel_display_power_get(dev_priv, domain);
5239
5240         return old_domains & ~new_domains;
5241 }
5242
5243 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5244                                       unsigned long domains)
5245 {
5246         enum intel_display_power_domain domain;
5247
5248         for_each_power_domain(domain, domains)
5249                 intel_display_power_put(dev_priv, domain);
5250 }
5251
5252 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5253 {
5254         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5255
5256         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5257             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5258                 return max_cdclk_freq;
5259         else if (IS_CHERRYVIEW(dev_priv))
5260                 return max_cdclk_freq*95/100;
5261         else if (INTEL_INFO(dev_priv)->gen < 4)
5262                 return 2*max_cdclk_freq*90/100;
5263         else
5264                 return max_cdclk_freq*90/100;
5265 }
5266
5267 static void intel_update_max_cdclk(struct drm_device *dev)
5268 {
5269         struct drm_i915_private *dev_priv = dev->dev_private;
5270
5271         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5272                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5273
5274                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5275                         dev_priv->max_cdclk_freq = 675000;
5276                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5277                         dev_priv->max_cdclk_freq = 540000;
5278                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5279                         dev_priv->max_cdclk_freq = 450000;
5280                 else
5281                         dev_priv->max_cdclk_freq = 337500;
5282         } else if (IS_BROXTON(dev)) {
5283                 dev_priv->max_cdclk_freq = 624000;
5284         } else if (IS_BROADWELL(dev))  {
5285                 /*
5286                  * FIXME with extra cooling we can allow
5287                  * 540 MHz for ULX and 675 Mhz for ULT.
5288                  * How can we know if extra cooling is
5289                  * available? PCI ID, VTB, something else?
5290                  */
5291                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5292                         dev_priv->max_cdclk_freq = 450000;
5293                 else if (IS_BDW_ULX(dev))
5294                         dev_priv->max_cdclk_freq = 450000;
5295                 else if (IS_BDW_ULT(dev))
5296                         dev_priv->max_cdclk_freq = 540000;
5297                 else
5298                         dev_priv->max_cdclk_freq = 675000;
5299         } else if (IS_CHERRYVIEW(dev)) {
5300                 dev_priv->max_cdclk_freq = 320000;
5301         } else if (IS_VALLEYVIEW(dev)) {
5302                 dev_priv->max_cdclk_freq = 400000;
5303         } else {
5304                 /* otherwise assume cdclk is fixed */
5305                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5306         }
5307
5308         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5309
5310         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5311                          dev_priv->max_cdclk_freq);
5312
5313         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5314                          dev_priv->max_dotclk_freq);
5315 }
5316
5317 static void intel_update_cdclk(struct drm_device *dev)
5318 {
5319         struct drm_i915_private *dev_priv = dev->dev_private;
5320
5321         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5322         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5323                          dev_priv->cdclk_freq);
5324
5325         /*
5326          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5327          * Programmng [sic] note: bit[9:2] should be programmed to the number
5328          * of cdclk that generates 4MHz reference clock freq which is used to
5329          * generate GMBus clock. This will vary with the cdclk freq.
5330          */
5331         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5332                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5333
5334         if (dev_priv->max_cdclk_freq == 0)
5335                 intel_update_max_cdclk(dev);
5336 }
5337
5338 static void broxton_set_cdclk(struct drm_i915_private *dev_priv, int frequency)
5339 {
5340         uint32_t divider;
5341         uint32_t ratio;
5342         uint32_t current_freq;
5343         int ret;
5344
5345         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5346         switch (frequency) {
5347         case 144000:
5348                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5349                 ratio = BXT_DE_PLL_RATIO(60);
5350                 break;
5351         case 288000:
5352                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5353                 ratio = BXT_DE_PLL_RATIO(60);
5354                 break;
5355         case 384000:
5356                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5357                 ratio = BXT_DE_PLL_RATIO(60);
5358                 break;
5359         case 576000:
5360                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5361                 ratio = BXT_DE_PLL_RATIO(60);
5362                 break;
5363         case 624000:
5364                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5365                 ratio = BXT_DE_PLL_RATIO(65);
5366                 break;
5367         case 19200:
5368                 /*
5369                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5370                  * to suppress GCC warning.
5371                  */
5372                 ratio = 0;
5373                 divider = 0;
5374                 break;
5375         default:
5376                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5377
5378                 return;
5379         }
5380
5381         mutex_lock(&dev_priv->rps.hw_lock);
5382         /* Inform power controller of upcoming frequency change */
5383         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5384                                       0x80000000);
5385         mutex_unlock(&dev_priv->rps.hw_lock);
5386
5387         if (ret) {
5388                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5389                           ret, frequency);
5390                 return;
5391         }
5392
5393         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5394         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5395         current_freq = current_freq * 500 + 1000;
5396
5397         /*
5398          * DE PLL has to be disabled when
5399          * - setting to 19.2MHz (bypass, PLL isn't used)
5400          * - before setting to 624MHz (PLL needs toggling)
5401          * - before setting to any frequency from 624MHz (PLL needs toggling)
5402          */
5403         if (frequency == 19200 || frequency == 624000 ||
5404             current_freq == 624000) {
5405                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5406                 /* Timeout 200us */
5407                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5408                              1))
5409                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5410         }
5411
5412         if (frequency != 19200) {
5413                 uint32_t val;
5414
5415                 val = I915_READ(BXT_DE_PLL_CTL);
5416                 val &= ~BXT_DE_PLL_RATIO_MASK;
5417                 val |= ratio;
5418                 I915_WRITE(BXT_DE_PLL_CTL, val);
5419
5420                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5421                 /* Timeout 200us */
5422                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5423                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5424
5425                 val = I915_READ(CDCLK_CTL);
5426                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5427                 val |= divider;
5428                 /*
5429                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5430                  * enable otherwise.
5431                  */
5432                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5433                 if (frequency >= 500000)
5434                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5435
5436                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5437                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5438                 val |= (frequency - 1000) / 500;
5439                 I915_WRITE(CDCLK_CTL, val);
5440         }
5441
5442         mutex_lock(&dev_priv->rps.hw_lock);
5443         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5444                                       DIV_ROUND_UP(frequency, 25000));
5445         mutex_unlock(&dev_priv->rps.hw_lock);
5446
5447         if (ret) {
5448                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5449                           ret, frequency);
5450                 return;
5451         }
5452
5453         intel_update_cdclk(dev_priv->dev);
5454 }
5455
5456 static bool broxton_cdclk_is_enabled(struct drm_i915_private *dev_priv)
5457 {
5458         if (!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE))
5459                 return false;
5460
5461         /* TODO: Check for a valid CDCLK rate */
5462
5463         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_REQUEST)) {
5464                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power not requested\n");
5465
5466                 return false;
5467         }
5468
5469         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE)) {
5470                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power hasn't settled\n");
5471
5472                 return false;
5473         }
5474
5475         return true;
5476 }
5477
5478 bool broxton_cdclk_verify_state(struct drm_i915_private *dev_priv)
5479 {
5480         return broxton_cdclk_is_enabled(dev_priv);
5481 }
5482
5483 void broxton_init_cdclk(struct drm_i915_private *dev_priv)
5484 {
5485         /* check if cd clock is enabled */
5486         if (broxton_cdclk_is_enabled(dev_priv)) {
5487                 DRM_DEBUG_KMS("CDCLK already enabled, won't reprogram it\n");
5488                 return;
5489         }
5490
5491         DRM_DEBUG_KMS("CDCLK not enabled, enabling it\n");
5492
5493         /*
5494          * FIXME:
5495          * - The initial CDCLK needs to be read from VBT.
5496          *   Need to make this change after VBT has changes for BXT.
5497          * - check if setting the max (or any) cdclk freq is really necessary
5498          *   here, it belongs to modeset time
5499          */
5500         broxton_set_cdclk(dev_priv, 624000);
5501
5502         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5503         POSTING_READ(DBUF_CTL);
5504
5505         udelay(10);
5506
5507         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5508                 DRM_ERROR("DBuf power enable timeout!\n");
5509 }
5510
5511 void broxton_uninit_cdclk(struct drm_i915_private *dev_priv)
5512 {
5513         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5514         POSTING_READ(DBUF_CTL);
5515
5516         udelay(10);
5517
5518         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5519                 DRM_ERROR("DBuf power disable timeout!\n");
5520
5521         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5522         broxton_set_cdclk(dev_priv, 19200);
5523 }
5524
5525 static const struct skl_cdclk_entry {
5526         unsigned int freq;
5527         unsigned int vco;
5528 } skl_cdclk_frequencies[] = {
5529         { .freq = 308570, .vco = 8640 },
5530         { .freq = 337500, .vco = 8100 },
5531         { .freq = 432000, .vco = 8640 },
5532         { .freq = 450000, .vco = 8100 },
5533         { .freq = 540000, .vco = 8100 },
5534         { .freq = 617140, .vco = 8640 },
5535         { .freq = 675000, .vco = 8100 },
5536 };
5537
5538 static unsigned int skl_cdclk_decimal(unsigned int freq)
5539 {
5540         return (freq - 1000) / 500;
5541 }
5542
5543 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5544 {
5545         unsigned int i;
5546
5547         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5548                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5549
5550                 if (e->freq == freq)
5551                         return e->vco;
5552         }
5553
5554         return 8100;
5555 }
5556
5557 static void
5558 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5559 {
5560         unsigned int min_freq;
5561         u32 val;
5562
5563         /* select the minimum CDCLK before enabling DPLL 0 */
5564         val = I915_READ(CDCLK_CTL);
5565         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5566         val |= CDCLK_FREQ_337_308;
5567
5568         if (required_vco == 8640)
5569                 min_freq = 308570;
5570         else
5571                 min_freq = 337500;
5572
5573         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5574
5575         I915_WRITE(CDCLK_CTL, val);
5576         POSTING_READ(CDCLK_CTL);
5577
5578         /*
5579          * We always enable DPLL0 with the lowest link rate possible, but still
5580          * taking into account the VCO required to operate the eDP panel at the
5581          * desired frequency. The usual DP link rates operate with a VCO of
5582          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5583          * The modeset code is responsible for the selection of the exact link
5584          * rate later on, with the constraint of choosing a frequency that
5585          * works with required_vco.
5586          */
5587         val = I915_READ(DPLL_CTRL1);
5588
5589         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5590                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5591         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5592         if (required_vco == 8640)
5593                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5594                                             SKL_DPLL0);
5595         else
5596                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5597                                             SKL_DPLL0);
5598
5599         I915_WRITE(DPLL_CTRL1, val);
5600         POSTING_READ(DPLL_CTRL1);
5601
5602         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5603
5604         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5605                 DRM_ERROR("DPLL0 not locked\n");
5606 }
5607
5608 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5609 {
5610         int ret;
5611         u32 val;
5612
5613         /* inform PCU we want to change CDCLK */
5614         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5615         mutex_lock(&dev_priv->rps.hw_lock);
5616         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5617         mutex_unlock(&dev_priv->rps.hw_lock);
5618
5619         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5620 }
5621
5622 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5623 {
5624         unsigned int i;
5625
5626         for (i = 0; i < 15; i++) {
5627                 if (skl_cdclk_pcu_ready(dev_priv))
5628                         return true;
5629                 udelay(10);
5630         }
5631
5632         return false;
5633 }
5634
5635 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5636 {
5637         struct drm_device *dev = dev_priv->dev;
5638         u32 freq_select, pcu_ack;
5639
5640         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5641
5642         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5643                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5644                 return;
5645         }
5646
5647         /* set CDCLK_CTL */
5648         switch(freq) {
5649         case 450000:
5650         case 432000:
5651                 freq_select = CDCLK_FREQ_450_432;
5652                 pcu_ack = 1;
5653                 break;
5654         case 540000:
5655                 freq_select = CDCLK_FREQ_540;
5656                 pcu_ack = 2;
5657                 break;
5658         case 308570:
5659         case 337500:
5660         default:
5661                 freq_select = CDCLK_FREQ_337_308;
5662                 pcu_ack = 0;
5663                 break;
5664         case 617140:
5665         case 675000:
5666                 freq_select = CDCLK_FREQ_675_617;
5667                 pcu_ack = 3;
5668                 break;
5669         }
5670
5671         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5672         POSTING_READ(CDCLK_CTL);
5673
5674         /* inform PCU of the change */
5675         mutex_lock(&dev_priv->rps.hw_lock);
5676         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5677         mutex_unlock(&dev_priv->rps.hw_lock);
5678
5679         intel_update_cdclk(dev);
5680 }
5681
5682 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5683 {
5684         /* disable DBUF power */
5685         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5686         POSTING_READ(DBUF_CTL);
5687
5688         udelay(10);
5689
5690         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5691                 DRM_ERROR("DBuf power disable timeout\n");
5692
5693         /* disable DPLL0 */
5694         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5695         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5696                 DRM_ERROR("Couldn't disable DPLL0\n");
5697 }
5698
5699 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5700 {
5701         unsigned int required_vco;
5702
5703         /* DPLL0 not enabled (happens on early BIOS versions) */
5704         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5705                 /* enable DPLL0 */
5706                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5707                 skl_dpll0_enable(dev_priv, required_vco);
5708         }
5709
5710         /* set CDCLK to the frequency the BIOS chose */
5711         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5712
5713         /* enable DBUF power */
5714         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5715         POSTING_READ(DBUF_CTL);
5716
5717         udelay(10);
5718
5719         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5720                 DRM_ERROR("DBuf power enable timeout\n");
5721 }
5722
5723 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5724 {
5725         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5726         uint32_t cdctl = I915_READ(CDCLK_CTL);
5727         int freq = dev_priv->skl_boot_cdclk;
5728
5729         /*
5730          * check if the pre-os intialized the display
5731          * There is SWF18 scratchpad register defined which is set by the
5732          * pre-os which can be used by the OS drivers to check the status
5733          */
5734         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5735                 goto sanitize;
5736
5737         /* Is PLL enabled and locked ? */
5738         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5739                 goto sanitize;
5740
5741         /* DPLL okay; verify the cdclock
5742          *
5743          * Noticed in some instances that the freq selection is correct but
5744          * decimal part is programmed wrong from BIOS where pre-os does not
5745          * enable display. Verify the same as well.
5746          */
5747         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5748                 /* All well; nothing to sanitize */
5749                 return false;
5750 sanitize:
5751         /*
5752          * As of now initialize with max cdclk till
5753          * we get dynamic cdclk support
5754          * */
5755         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5756         skl_init_cdclk(dev_priv);
5757
5758         /* we did have to sanitize */
5759         return true;
5760 }
5761
5762 /* Adjust CDclk dividers to allow high res or save power if possible */
5763 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5764 {
5765         struct drm_i915_private *dev_priv = dev->dev_private;
5766         u32 val, cmd;
5767
5768         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5769                                         != dev_priv->cdclk_freq);
5770
5771         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5772                 cmd = 2;
5773         else if (cdclk == 266667)
5774                 cmd = 1;
5775         else
5776                 cmd = 0;
5777
5778         mutex_lock(&dev_priv->rps.hw_lock);
5779         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5780         val &= ~DSPFREQGUAR_MASK;
5781         val |= (cmd << DSPFREQGUAR_SHIFT);
5782         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5783         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5784                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5785                      50)) {
5786                 DRM_ERROR("timed out waiting for CDclk change\n");
5787         }
5788         mutex_unlock(&dev_priv->rps.hw_lock);
5789
5790         mutex_lock(&dev_priv->sb_lock);
5791
5792         if (cdclk == 400000) {
5793                 u32 divider;
5794
5795                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5796
5797                 /* adjust cdclk divider */
5798                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5799                 val &= ~CCK_FREQUENCY_VALUES;
5800                 val |= divider;
5801                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5802
5803                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5804                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5805                              50))
5806                         DRM_ERROR("timed out waiting for CDclk change\n");
5807         }
5808
5809         /* adjust self-refresh exit latency value */
5810         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5811         val &= ~0x7f;
5812
5813         /*
5814          * For high bandwidth configs, we set a higher latency in the bunit
5815          * so that the core display fetch happens in time to avoid underruns.
5816          */
5817         if (cdclk == 400000)
5818                 val |= 4500 / 250; /* 4.5 usec */
5819         else
5820                 val |= 3000 / 250; /* 3.0 usec */
5821         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5822
5823         mutex_unlock(&dev_priv->sb_lock);
5824
5825         intel_update_cdclk(dev);
5826 }
5827
5828 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5829 {
5830         struct drm_i915_private *dev_priv = dev->dev_private;
5831         u32 val, cmd;
5832
5833         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5834                                                 != dev_priv->cdclk_freq);
5835
5836         switch (cdclk) {
5837         case 333333:
5838         case 320000:
5839         case 266667:
5840         case 200000:
5841                 break;
5842         default:
5843                 MISSING_CASE(cdclk);
5844                 return;
5845         }
5846
5847         /*
5848          * Specs are full of misinformation, but testing on actual
5849          * hardware has shown that we just need to write the desired
5850          * CCK divider into the Punit register.
5851          */
5852         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5853
5854         mutex_lock(&dev_priv->rps.hw_lock);
5855         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5856         val &= ~DSPFREQGUAR_MASK_CHV;
5857         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5858         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5859         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5860                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5861                      50)) {
5862                 DRM_ERROR("timed out waiting for CDclk change\n");
5863         }
5864         mutex_unlock(&dev_priv->rps.hw_lock);
5865
5866         intel_update_cdclk(dev);
5867 }
5868
5869 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5870                                  int max_pixclk)
5871 {
5872         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5873         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5874
5875         /*
5876          * Really only a few cases to deal with, as only 4 CDclks are supported:
5877          *   200MHz
5878          *   267MHz
5879          *   320/333MHz (depends on HPLL freq)
5880          *   400MHz (VLV only)
5881          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5882          * of the lower bin and adjust if needed.
5883          *
5884          * We seem to get an unstable or solid color picture at 200MHz.
5885          * Not sure what's wrong. For now use 200MHz only when all pipes
5886          * are off.
5887          */
5888         if (!IS_CHERRYVIEW(dev_priv) &&
5889             max_pixclk > freq_320*limit/100)
5890                 return 400000;
5891         else if (max_pixclk > 266667*limit/100)
5892                 return freq_320;
5893         else if (max_pixclk > 0)
5894                 return 266667;
5895         else
5896                 return 200000;
5897 }
5898
5899 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5900                               int max_pixclk)
5901 {
5902         /*
5903          * FIXME:
5904          * - remove the guardband, it's not needed on BXT
5905          * - set 19.2MHz bypass frequency if there are no active pipes
5906          */
5907         if (max_pixclk > 576000*9/10)
5908                 return 624000;
5909         else if (max_pixclk > 384000*9/10)
5910                 return 576000;
5911         else if (max_pixclk > 288000*9/10)
5912                 return 384000;
5913         else if (max_pixclk > 144000*9/10)
5914                 return 288000;
5915         else
5916                 return 144000;
5917 }
5918
5919 /* Compute the max pixel clock for new configuration. */
5920 static int intel_mode_max_pixclk(struct drm_device *dev,
5921                                  struct drm_atomic_state *state)
5922 {
5923         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5924         struct drm_i915_private *dev_priv = dev->dev_private;
5925         struct drm_crtc *crtc;
5926         struct drm_crtc_state *crtc_state;
5927         unsigned max_pixclk = 0, i;
5928         enum pipe pipe;
5929
5930         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5931                sizeof(intel_state->min_pixclk));
5932
5933         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5934                 int pixclk = 0;
5935
5936                 if (crtc_state->enable)
5937                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5938
5939                 intel_state->min_pixclk[i] = pixclk;
5940         }
5941
5942         for_each_pipe(dev_priv, pipe)
5943                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5944
5945         return max_pixclk;
5946 }
5947
5948 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5949 {
5950         struct drm_device *dev = state->dev;
5951         struct drm_i915_private *dev_priv = dev->dev_private;
5952         int max_pixclk = intel_mode_max_pixclk(dev, state);
5953         struct intel_atomic_state *intel_state =
5954                 to_intel_atomic_state(state);
5955
5956         intel_state->cdclk = intel_state->dev_cdclk =
5957                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5958
5959         if (!intel_state->active_crtcs)
5960                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
5961
5962         return 0;
5963 }
5964
5965 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5966 {
5967         struct drm_device *dev = state->dev;
5968         struct drm_i915_private *dev_priv = dev->dev_private;
5969         int max_pixclk = intel_mode_max_pixclk(dev, state);
5970         struct intel_atomic_state *intel_state =
5971                 to_intel_atomic_state(state);
5972
5973         intel_state->cdclk = intel_state->dev_cdclk =
5974                 broxton_calc_cdclk(dev_priv, max_pixclk);
5975
5976         if (!intel_state->active_crtcs)
5977                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
5978
5979         return 0;
5980 }
5981
5982 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5983 {
5984         unsigned int credits, default_credits;
5985
5986         if (IS_CHERRYVIEW(dev_priv))
5987                 default_credits = PFI_CREDIT(12);
5988         else
5989                 default_credits = PFI_CREDIT(8);
5990
5991         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
5992                 /* CHV suggested value is 31 or 63 */
5993                 if (IS_CHERRYVIEW(dev_priv))
5994                         credits = PFI_CREDIT_63;
5995                 else
5996                         credits = PFI_CREDIT(15);
5997         } else {
5998                 credits = default_credits;
5999         }
6000
6001         /*
6002          * WA - write default credits before re-programming
6003          * FIXME: should we also set the resend bit here?
6004          */
6005         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6006                    default_credits);
6007
6008         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6009                    credits | PFI_CREDIT_RESEND);
6010
6011         /*
6012          * FIXME is this guaranteed to clear
6013          * immediately or should we poll for it?
6014          */
6015         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6016 }
6017
6018 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6019 {
6020         struct drm_device *dev = old_state->dev;
6021         struct drm_i915_private *dev_priv = dev->dev_private;
6022         struct intel_atomic_state *old_intel_state =
6023                 to_intel_atomic_state(old_state);
6024         unsigned req_cdclk = old_intel_state->dev_cdclk;
6025
6026         /*
6027          * FIXME: We can end up here with all power domains off, yet
6028          * with a CDCLK frequency other than the minimum. To account
6029          * for this take the PIPE-A power domain, which covers the HW
6030          * blocks needed for the following programming. This can be
6031          * removed once it's guaranteed that we get here either with
6032          * the minimum CDCLK set, or the required power domains
6033          * enabled.
6034          */
6035         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6036
6037         if (IS_CHERRYVIEW(dev))
6038                 cherryview_set_cdclk(dev, req_cdclk);
6039         else
6040                 valleyview_set_cdclk(dev, req_cdclk);
6041
6042         vlv_program_pfi_credits(dev_priv);
6043
6044         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6045 }
6046
6047 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6048 {
6049         struct drm_device *dev = crtc->dev;
6050         struct drm_i915_private *dev_priv = to_i915(dev);
6051         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6052         struct intel_encoder *encoder;
6053         struct intel_crtc_state *pipe_config =
6054                 to_intel_crtc_state(crtc->state);
6055         int pipe = intel_crtc->pipe;
6056
6057         if (WARN_ON(intel_crtc->active))
6058                 return;
6059
6060         if (intel_crtc->config->has_dp_encoder)
6061                 intel_dp_set_m_n(intel_crtc, M1_N1);
6062
6063         intel_set_pipe_timings(intel_crtc);
6064         intel_set_pipe_src_size(intel_crtc);
6065
6066         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6067                 struct drm_i915_private *dev_priv = dev->dev_private;
6068
6069                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6070                 I915_WRITE(CHV_CANVAS(pipe), 0);
6071         }
6072
6073         i9xx_set_pipeconf(intel_crtc);
6074
6075         intel_crtc->active = true;
6076
6077         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6078
6079         for_each_encoder_on_crtc(dev, crtc, encoder)
6080                 if (encoder->pre_pll_enable)
6081                         encoder->pre_pll_enable(encoder);
6082
6083         if (IS_CHERRYVIEW(dev)) {
6084                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6085                 chv_enable_pll(intel_crtc, intel_crtc->config);
6086         } else {
6087                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6088                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6089         }
6090
6091         for_each_encoder_on_crtc(dev, crtc, encoder)
6092                 if (encoder->pre_enable)
6093                         encoder->pre_enable(encoder);
6094
6095         i9xx_pfit_enable(intel_crtc);
6096
6097         intel_color_load_luts(&pipe_config->base);
6098
6099         intel_update_watermarks(crtc);
6100         intel_enable_pipe(intel_crtc);
6101
6102         assert_vblank_disabled(crtc);
6103         drm_crtc_vblank_on(crtc);
6104
6105         for_each_encoder_on_crtc(dev, crtc, encoder)
6106                 encoder->enable(encoder);
6107 }
6108
6109 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6110 {
6111         struct drm_device *dev = crtc->base.dev;
6112         struct drm_i915_private *dev_priv = dev->dev_private;
6113
6114         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6115         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6116 }
6117
6118 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6119 {
6120         struct drm_device *dev = crtc->dev;
6121         struct drm_i915_private *dev_priv = to_i915(dev);
6122         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6123         struct intel_encoder *encoder;
6124         struct intel_crtc_state *pipe_config =
6125                 to_intel_crtc_state(crtc->state);
6126         enum pipe pipe = intel_crtc->pipe;
6127
6128         if (WARN_ON(intel_crtc->active))
6129                 return;
6130
6131         i9xx_set_pll_dividers(intel_crtc);
6132
6133         if (intel_crtc->config->has_dp_encoder)
6134                 intel_dp_set_m_n(intel_crtc, M1_N1);
6135
6136         intel_set_pipe_timings(intel_crtc);
6137         intel_set_pipe_src_size(intel_crtc);
6138
6139         i9xx_set_pipeconf(intel_crtc);
6140
6141         intel_crtc->active = true;
6142
6143         if (!IS_GEN2(dev))
6144                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6145
6146         for_each_encoder_on_crtc(dev, crtc, encoder)
6147                 if (encoder->pre_enable)
6148                         encoder->pre_enable(encoder);
6149
6150         i9xx_enable_pll(intel_crtc);
6151
6152         i9xx_pfit_enable(intel_crtc);
6153
6154         intel_color_load_luts(&pipe_config->base);
6155
6156         intel_update_watermarks(crtc);
6157         intel_enable_pipe(intel_crtc);
6158
6159         assert_vblank_disabled(crtc);
6160         drm_crtc_vblank_on(crtc);
6161
6162         for_each_encoder_on_crtc(dev, crtc, encoder)
6163                 encoder->enable(encoder);
6164 }
6165
6166 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6167 {
6168         struct drm_device *dev = crtc->base.dev;
6169         struct drm_i915_private *dev_priv = dev->dev_private;
6170
6171         if (!crtc->config->gmch_pfit.control)
6172                 return;
6173
6174         assert_pipe_disabled(dev_priv, crtc->pipe);
6175
6176         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6177                          I915_READ(PFIT_CONTROL));
6178         I915_WRITE(PFIT_CONTROL, 0);
6179 }
6180
6181 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6182 {
6183         struct drm_device *dev = crtc->dev;
6184         struct drm_i915_private *dev_priv = dev->dev_private;
6185         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6186         struct intel_encoder *encoder;
6187         int pipe = intel_crtc->pipe;
6188
6189         /*
6190          * On gen2 planes are double buffered but the pipe isn't, so we must
6191          * wait for planes to fully turn off before disabling the pipe.
6192          */
6193         if (IS_GEN2(dev))
6194                 intel_wait_for_vblank(dev, pipe);
6195
6196         for_each_encoder_on_crtc(dev, crtc, encoder)
6197                 encoder->disable(encoder);
6198
6199         drm_crtc_vblank_off(crtc);
6200         assert_vblank_disabled(crtc);
6201
6202         intel_disable_pipe(intel_crtc);
6203
6204         i9xx_pfit_disable(intel_crtc);
6205
6206         for_each_encoder_on_crtc(dev, crtc, encoder)
6207                 if (encoder->post_disable)
6208                         encoder->post_disable(encoder);
6209
6210         if (!intel_crtc->config->has_dsi_encoder) {
6211                 if (IS_CHERRYVIEW(dev))
6212                         chv_disable_pll(dev_priv, pipe);
6213                 else if (IS_VALLEYVIEW(dev))
6214                         vlv_disable_pll(dev_priv, pipe);
6215                 else
6216                         i9xx_disable_pll(intel_crtc);
6217         }
6218
6219         for_each_encoder_on_crtc(dev, crtc, encoder)
6220                 if (encoder->post_pll_disable)
6221                         encoder->post_pll_disable(encoder);
6222
6223         if (!IS_GEN2(dev))
6224                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6225 }
6226
6227 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6228 {
6229         struct intel_encoder *encoder;
6230         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6231         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6232         enum intel_display_power_domain domain;
6233         unsigned long domains;
6234
6235         if (!intel_crtc->active)
6236                 return;
6237
6238         if (to_intel_plane_state(crtc->primary->state)->visible) {
6239                 WARN_ON(intel_crtc->unpin_work);
6240
6241                 intel_pre_disable_primary_noatomic(crtc);
6242
6243                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6244                 to_intel_plane_state(crtc->primary->state)->visible = false;
6245         }
6246
6247         dev_priv->display.crtc_disable(crtc);
6248
6249         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6250                       crtc->base.id);
6251
6252         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6253         crtc->state->active = false;
6254         intel_crtc->active = false;
6255         crtc->enabled = false;
6256         crtc->state->connector_mask = 0;
6257         crtc->state->encoder_mask = 0;
6258
6259         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6260                 encoder->base.crtc = NULL;
6261
6262         intel_fbc_disable(intel_crtc);
6263         intel_update_watermarks(crtc);
6264         intel_disable_shared_dpll(intel_crtc);
6265
6266         domains = intel_crtc->enabled_power_domains;
6267         for_each_power_domain(domain, domains)
6268                 intel_display_power_put(dev_priv, domain);
6269         intel_crtc->enabled_power_domains = 0;
6270
6271         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6272         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6273 }
6274
6275 /*
6276  * turn all crtc's off, but do not adjust state
6277  * This has to be paired with a call to intel_modeset_setup_hw_state.
6278  */
6279 int intel_display_suspend(struct drm_device *dev)
6280 {
6281         struct drm_i915_private *dev_priv = to_i915(dev);
6282         struct drm_atomic_state *state;
6283         int ret;
6284
6285         state = drm_atomic_helper_suspend(dev);
6286         ret = PTR_ERR_OR_ZERO(state);
6287         if (ret)
6288                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6289         else
6290                 dev_priv->modeset_restore_state = state;
6291         return ret;
6292 }
6293
6294 void intel_encoder_destroy(struct drm_encoder *encoder)
6295 {
6296         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6297
6298         drm_encoder_cleanup(encoder);
6299         kfree(intel_encoder);
6300 }
6301
6302 /* Cross check the actual hw state with our own modeset state tracking (and it's
6303  * internal consistency). */
6304 static void intel_connector_verify_state(struct intel_connector *connector)
6305 {
6306         struct drm_crtc *crtc = connector->base.state->crtc;
6307
6308         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6309                       connector->base.base.id,
6310                       connector->base.name);
6311
6312         if (connector->get_hw_state(connector)) {
6313                 struct intel_encoder *encoder = connector->encoder;
6314                 struct drm_connector_state *conn_state = connector->base.state;
6315
6316                 I915_STATE_WARN(!crtc,
6317                          "connector enabled without attached crtc\n");
6318
6319                 if (!crtc)
6320                         return;
6321
6322                 I915_STATE_WARN(!crtc->state->active,
6323                       "connector is active, but attached crtc isn't\n");
6324
6325                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6326                         return;
6327
6328                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6329                         "atomic encoder doesn't match attached encoder\n");
6330
6331                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6332                         "attached encoder crtc differs from connector crtc\n");
6333         } else {
6334                 I915_STATE_WARN(crtc && crtc->state->active,
6335                         "attached crtc is active, but connector isn't\n");
6336                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6337                         "best encoder set without crtc!\n");
6338         }
6339 }
6340
6341 int intel_connector_init(struct intel_connector *connector)
6342 {
6343         drm_atomic_helper_connector_reset(&connector->base);
6344
6345         if (!connector->base.state)
6346                 return -ENOMEM;
6347
6348         return 0;
6349 }
6350
6351 struct intel_connector *intel_connector_alloc(void)
6352 {
6353         struct intel_connector *connector;
6354
6355         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6356         if (!connector)
6357                 return NULL;
6358
6359         if (intel_connector_init(connector) < 0) {
6360                 kfree(connector);
6361                 return NULL;
6362         }
6363
6364         return connector;
6365 }
6366
6367 /* Simple connector->get_hw_state implementation for encoders that support only
6368  * one connector and no cloning and hence the encoder state determines the state
6369  * of the connector. */
6370 bool intel_connector_get_hw_state(struct intel_connector *connector)
6371 {
6372         enum pipe pipe = 0;
6373         struct intel_encoder *encoder = connector->encoder;
6374
6375         return encoder->get_hw_state(encoder, &pipe);
6376 }
6377
6378 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6379 {
6380         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6381                 return crtc_state->fdi_lanes;
6382
6383         return 0;
6384 }
6385
6386 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6387                                      struct intel_crtc_state *pipe_config)
6388 {
6389         struct drm_atomic_state *state = pipe_config->base.state;
6390         struct intel_crtc *other_crtc;
6391         struct intel_crtc_state *other_crtc_state;
6392
6393         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6394                       pipe_name(pipe), pipe_config->fdi_lanes);
6395         if (pipe_config->fdi_lanes > 4) {
6396                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6397                               pipe_name(pipe), pipe_config->fdi_lanes);
6398                 return -EINVAL;
6399         }
6400
6401         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6402                 if (pipe_config->fdi_lanes > 2) {
6403                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6404                                       pipe_config->fdi_lanes);
6405                         return -EINVAL;
6406                 } else {
6407                         return 0;
6408                 }
6409         }
6410
6411         if (INTEL_INFO(dev)->num_pipes == 2)
6412                 return 0;
6413
6414         /* Ivybridge 3 pipe is really complicated */
6415         switch (pipe) {
6416         case PIPE_A:
6417                 return 0;
6418         case PIPE_B:
6419                 if (pipe_config->fdi_lanes <= 2)
6420                         return 0;
6421
6422                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6423                 other_crtc_state =
6424                         intel_atomic_get_crtc_state(state, other_crtc);
6425                 if (IS_ERR(other_crtc_state))
6426                         return PTR_ERR(other_crtc_state);
6427
6428                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6429                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6430                                       pipe_name(pipe), pipe_config->fdi_lanes);
6431                         return -EINVAL;
6432                 }
6433                 return 0;
6434         case PIPE_C:
6435                 if (pipe_config->fdi_lanes > 2) {
6436                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6437                                       pipe_name(pipe), pipe_config->fdi_lanes);
6438                         return -EINVAL;
6439                 }
6440
6441                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6442                 other_crtc_state =
6443                         intel_atomic_get_crtc_state(state, other_crtc);
6444                 if (IS_ERR(other_crtc_state))
6445                         return PTR_ERR(other_crtc_state);
6446
6447                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6448                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6449                         return -EINVAL;
6450                 }
6451                 return 0;
6452         default:
6453                 BUG();
6454         }
6455 }
6456
6457 #define RETRY 1
6458 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6459                                        struct intel_crtc_state *pipe_config)
6460 {
6461         struct drm_device *dev = intel_crtc->base.dev;
6462         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6463         int lane, link_bw, fdi_dotclock, ret;
6464         bool needs_recompute = false;
6465
6466 retry:
6467         /* FDI is a binary signal running at ~2.7GHz, encoding
6468          * each output octet as 10 bits. The actual frequency
6469          * is stored as a divider into a 100MHz clock, and the
6470          * mode pixel clock is stored in units of 1KHz.
6471          * Hence the bw of each lane in terms of the mode signal
6472          * is:
6473          */
6474         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6475
6476         fdi_dotclock = adjusted_mode->crtc_clock;
6477
6478         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6479                                            pipe_config->pipe_bpp);
6480
6481         pipe_config->fdi_lanes = lane;
6482
6483         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6484                                link_bw, &pipe_config->fdi_m_n);
6485
6486         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6487         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6488                 pipe_config->pipe_bpp -= 2*3;
6489                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6490                               pipe_config->pipe_bpp);
6491                 needs_recompute = true;
6492                 pipe_config->bw_constrained = true;
6493
6494                 goto retry;
6495         }
6496
6497         if (needs_recompute)
6498                 return RETRY;
6499
6500         return ret;
6501 }
6502
6503 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6504                                      struct intel_crtc_state *pipe_config)
6505 {
6506         if (pipe_config->pipe_bpp > 24)
6507                 return false;
6508
6509         /* HSW can handle pixel rate up to cdclk? */
6510         if (IS_HASWELL(dev_priv))
6511                 return true;
6512
6513         /*
6514          * We compare against max which means we must take
6515          * the increased cdclk requirement into account when
6516          * calculating the new cdclk.
6517          *
6518          * Should measure whether using a lower cdclk w/o IPS
6519          */
6520         return ilk_pipe_pixel_rate(pipe_config) <=
6521                 dev_priv->max_cdclk_freq * 95 / 100;
6522 }
6523
6524 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6525                                    struct intel_crtc_state *pipe_config)
6526 {
6527         struct drm_device *dev = crtc->base.dev;
6528         struct drm_i915_private *dev_priv = dev->dev_private;
6529
6530         pipe_config->ips_enabled = i915.enable_ips &&
6531                 hsw_crtc_supports_ips(crtc) &&
6532                 pipe_config_supports_ips(dev_priv, pipe_config);
6533 }
6534
6535 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6536 {
6537         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6538
6539         /* GDG double wide on either pipe, otherwise pipe A only */
6540         return INTEL_INFO(dev_priv)->gen < 4 &&
6541                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6542 }
6543
6544 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6545                                      struct intel_crtc_state *pipe_config)
6546 {
6547         struct drm_device *dev = crtc->base.dev;
6548         struct drm_i915_private *dev_priv = dev->dev_private;
6549         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6550
6551         /* FIXME should check pixel clock limits on all platforms */
6552         if (INTEL_INFO(dev)->gen < 4) {
6553                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6554
6555                 /*
6556                  * Enable double wide mode when the dot clock
6557                  * is > 90% of the (display) core speed.
6558                  */
6559                 if (intel_crtc_supports_double_wide(crtc) &&
6560                     adjusted_mode->crtc_clock > clock_limit) {
6561                         clock_limit *= 2;
6562                         pipe_config->double_wide = true;
6563                 }
6564
6565                 if (adjusted_mode->crtc_clock > clock_limit) {
6566                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6567                                       adjusted_mode->crtc_clock, clock_limit,
6568                                       yesno(pipe_config->double_wide));
6569                         return -EINVAL;
6570                 }
6571         }
6572
6573         /*
6574          * Pipe horizontal size must be even in:
6575          * - DVO ganged mode
6576          * - LVDS dual channel mode
6577          * - Double wide pipe
6578          */
6579         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6580              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6581                 pipe_config->pipe_src_w &= ~1;
6582
6583         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6584          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6585          */
6586         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6587                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6588                 return -EINVAL;
6589
6590         if (HAS_IPS(dev))
6591                 hsw_compute_ips_config(crtc, pipe_config);
6592
6593         if (pipe_config->has_pch_encoder)
6594                 return ironlake_fdi_compute_config(crtc, pipe_config);
6595
6596         return 0;
6597 }
6598
6599 static int skylake_get_display_clock_speed(struct drm_device *dev)
6600 {
6601         struct drm_i915_private *dev_priv = to_i915(dev);
6602         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6603         uint32_t cdctl = I915_READ(CDCLK_CTL);
6604         uint32_t linkrate;
6605
6606         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6607                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6608
6609         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6610                 return 540000;
6611
6612         linkrate = (I915_READ(DPLL_CTRL1) &
6613                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6614
6615         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6616             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6617                 /* vco 8640 */
6618                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6619                 case CDCLK_FREQ_450_432:
6620                         return 432000;
6621                 case CDCLK_FREQ_337_308:
6622                         return 308570;
6623                 case CDCLK_FREQ_675_617:
6624                         return 617140;
6625                 default:
6626                         WARN(1, "Unknown cd freq selection\n");
6627                 }
6628         } else {
6629                 /* vco 8100 */
6630                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6631                 case CDCLK_FREQ_450_432:
6632                         return 450000;
6633                 case CDCLK_FREQ_337_308:
6634                         return 337500;
6635                 case CDCLK_FREQ_675_617:
6636                         return 675000;
6637                 default:
6638                         WARN(1, "Unknown cd freq selection\n");
6639                 }
6640         }
6641
6642         /* error case, do as if DPLL0 isn't enabled */
6643         return 24000;
6644 }
6645
6646 static int broxton_get_display_clock_speed(struct drm_device *dev)
6647 {
6648         struct drm_i915_private *dev_priv = to_i915(dev);
6649         uint32_t cdctl = I915_READ(CDCLK_CTL);
6650         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6651         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6652         int cdclk;
6653
6654         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6655                 return 19200;
6656
6657         cdclk = 19200 * pll_ratio / 2;
6658
6659         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6660         case BXT_CDCLK_CD2X_DIV_SEL_1:
6661                 return cdclk;  /* 576MHz or 624MHz */
6662         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6663                 return cdclk * 2 / 3; /* 384MHz */
6664         case BXT_CDCLK_CD2X_DIV_SEL_2:
6665                 return cdclk / 2; /* 288MHz */
6666         case BXT_CDCLK_CD2X_DIV_SEL_4:
6667                 return cdclk / 4; /* 144MHz */
6668         }
6669
6670         /* error case, do as if DE PLL isn't enabled */
6671         return 19200;
6672 }
6673
6674 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6675 {
6676         struct drm_i915_private *dev_priv = dev->dev_private;
6677         uint32_t lcpll = I915_READ(LCPLL_CTL);
6678         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6679
6680         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6681                 return 800000;
6682         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6683                 return 450000;
6684         else if (freq == LCPLL_CLK_FREQ_450)
6685                 return 450000;
6686         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6687                 return 540000;
6688         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6689                 return 337500;
6690         else
6691                 return 675000;
6692 }
6693
6694 static int haswell_get_display_clock_speed(struct drm_device *dev)
6695 {
6696         struct drm_i915_private *dev_priv = dev->dev_private;
6697         uint32_t lcpll = I915_READ(LCPLL_CTL);
6698         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6699
6700         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6701                 return 800000;
6702         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6703                 return 450000;
6704         else if (freq == LCPLL_CLK_FREQ_450)
6705                 return 450000;
6706         else if (IS_HSW_ULT(dev))
6707                 return 337500;
6708         else
6709                 return 540000;
6710 }
6711
6712 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6713 {
6714         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6715                                       CCK_DISPLAY_CLOCK_CONTROL);
6716 }
6717
6718 static int ilk_get_display_clock_speed(struct drm_device *dev)
6719 {
6720         return 450000;
6721 }
6722
6723 static int i945_get_display_clock_speed(struct drm_device *dev)
6724 {
6725         return 400000;
6726 }
6727
6728 static int i915_get_display_clock_speed(struct drm_device *dev)
6729 {
6730         return 333333;
6731 }
6732
6733 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6734 {
6735         return 200000;
6736 }
6737
6738 static int pnv_get_display_clock_speed(struct drm_device *dev)
6739 {
6740         u16 gcfgc = 0;
6741
6742         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6743
6744         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6745         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6746                 return 266667;
6747         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6748                 return 333333;
6749         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6750                 return 444444;
6751         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6752                 return 200000;
6753         default:
6754                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6755         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6756                 return 133333;
6757         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6758                 return 166667;
6759         }
6760 }
6761
6762 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6763 {
6764         u16 gcfgc = 0;
6765
6766         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6767
6768         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6769                 return 133333;
6770         else {
6771                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6772                 case GC_DISPLAY_CLOCK_333_MHZ:
6773                         return 333333;
6774                 default:
6775                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6776                         return 190000;
6777                 }
6778         }
6779 }
6780
6781 static int i865_get_display_clock_speed(struct drm_device *dev)
6782 {
6783         return 266667;
6784 }
6785
6786 static int i85x_get_display_clock_speed(struct drm_device *dev)
6787 {
6788         u16 hpllcc = 0;
6789
6790         /*
6791          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6792          * encoding is different :(
6793          * FIXME is this the right way to detect 852GM/852GMV?
6794          */
6795         if (dev->pdev->revision == 0x1)
6796                 return 133333;
6797
6798         pci_bus_read_config_word(dev->pdev->bus,
6799                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6800
6801         /* Assume that the hardware is in the high speed state.  This
6802          * should be the default.
6803          */
6804         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6805         case GC_CLOCK_133_200:
6806         case GC_CLOCK_133_200_2:
6807         case GC_CLOCK_100_200:
6808                 return 200000;
6809         case GC_CLOCK_166_250:
6810                 return 250000;
6811         case GC_CLOCK_100_133:
6812                 return 133333;
6813         case GC_CLOCK_133_266:
6814         case GC_CLOCK_133_266_2:
6815         case GC_CLOCK_166_266:
6816                 return 266667;
6817         }
6818
6819         /* Shouldn't happen */
6820         return 0;
6821 }
6822
6823 static int i830_get_display_clock_speed(struct drm_device *dev)
6824 {
6825         return 133333;
6826 }
6827
6828 static unsigned int intel_hpll_vco(struct drm_device *dev)
6829 {
6830         struct drm_i915_private *dev_priv = dev->dev_private;
6831         static const unsigned int blb_vco[8] = {
6832                 [0] = 3200000,
6833                 [1] = 4000000,
6834                 [2] = 5333333,
6835                 [3] = 4800000,
6836                 [4] = 6400000,
6837         };
6838         static const unsigned int pnv_vco[8] = {
6839                 [0] = 3200000,
6840                 [1] = 4000000,
6841                 [2] = 5333333,
6842                 [3] = 4800000,
6843                 [4] = 2666667,
6844         };
6845         static const unsigned int cl_vco[8] = {
6846                 [0] = 3200000,
6847                 [1] = 4000000,
6848                 [2] = 5333333,
6849                 [3] = 6400000,
6850                 [4] = 3333333,
6851                 [5] = 3566667,
6852                 [6] = 4266667,
6853         };
6854         static const unsigned int elk_vco[8] = {
6855                 [0] = 3200000,
6856                 [1] = 4000000,
6857                 [2] = 5333333,
6858                 [3] = 4800000,
6859         };
6860         static const unsigned int ctg_vco[8] = {
6861                 [0] = 3200000,
6862                 [1] = 4000000,
6863                 [2] = 5333333,
6864                 [3] = 6400000,
6865                 [4] = 2666667,
6866                 [5] = 4266667,
6867         };
6868         const unsigned int *vco_table;
6869         unsigned int vco;
6870         uint8_t tmp = 0;
6871
6872         /* FIXME other chipsets? */
6873         if (IS_GM45(dev))
6874                 vco_table = ctg_vco;
6875         else if (IS_G4X(dev))
6876                 vco_table = elk_vco;
6877         else if (IS_CRESTLINE(dev))
6878                 vco_table = cl_vco;
6879         else if (IS_PINEVIEW(dev))
6880                 vco_table = pnv_vco;
6881         else if (IS_G33(dev))
6882                 vco_table = blb_vco;
6883         else
6884                 return 0;
6885
6886         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6887
6888         vco = vco_table[tmp & 0x7];
6889         if (vco == 0)
6890                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6891         else
6892                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6893
6894         return vco;
6895 }
6896
6897 static int gm45_get_display_clock_speed(struct drm_device *dev)
6898 {
6899         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6900         uint16_t tmp = 0;
6901
6902         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6903
6904         cdclk_sel = (tmp >> 12) & 0x1;
6905
6906         switch (vco) {
6907         case 2666667:
6908         case 4000000:
6909         case 5333333:
6910                 return cdclk_sel ? 333333 : 222222;
6911         case 3200000:
6912                 return cdclk_sel ? 320000 : 228571;
6913         default:
6914                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6915                 return 222222;
6916         }
6917 }
6918
6919 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6920 {
6921         static const uint8_t div_3200[] = { 16, 10,  8 };
6922         static const uint8_t div_4000[] = { 20, 12, 10 };
6923         static const uint8_t div_5333[] = { 24, 16, 14 };
6924         const uint8_t *div_table;
6925         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6926         uint16_t tmp = 0;
6927
6928         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6929
6930         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6931
6932         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6933                 goto fail;
6934
6935         switch (vco) {
6936         case 3200000:
6937                 div_table = div_3200;
6938                 break;
6939         case 4000000:
6940                 div_table = div_4000;
6941                 break;
6942         case 5333333:
6943                 div_table = div_5333;
6944                 break;
6945         default:
6946                 goto fail;
6947         }
6948
6949         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6950
6951 fail:
6952         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6953         return 200000;
6954 }
6955
6956 static int g33_get_display_clock_speed(struct drm_device *dev)
6957 {
6958         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6959         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6960         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6961         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6962         const uint8_t *div_table;
6963         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6964         uint16_t tmp = 0;
6965
6966         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6967
6968         cdclk_sel = (tmp >> 4) & 0x7;
6969
6970         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6971                 goto fail;
6972
6973         switch (vco) {
6974         case 3200000:
6975                 div_table = div_3200;
6976                 break;
6977         case 4000000:
6978                 div_table = div_4000;
6979                 break;
6980         case 4800000:
6981                 div_table = div_4800;
6982                 break;
6983         case 5333333:
6984                 div_table = div_5333;
6985                 break;
6986         default:
6987                 goto fail;
6988         }
6989
6990         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6991
6992 fail:
6993         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6994         return 190476;
6995 }
6996
6997 static void
6998 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6999 {
7000         while (*num > DATA_LINK_M_N_MASK ||
7001                *den > DATA_LINK_M_N_MASK) {
7002                 *num >>= 1;
7003                 *den >>= 1;
7004         }
7005 }
7006
7007 static void compute_m_n(unsigned int m, unsigned int n,
7008                         uint32_t *ret_m, uint32_t *ret_n)
7009 {
7010         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7011         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7012         intel_reduce_m_n_ratio(ret_m, ret_n);
7013 }
7014
7015 void
7016 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7017                        int pixel_clock, int link_clock,
7018                        struct intel_link_m_n *m_n)
7019 {
7020         m_n->tu = 64;
7021
7022         compute_m_n(bits_per_pixel * pixel_clock,
7023                     link_clock * nlanes * 8,
7024                     &m_n->gmch_m, &m_n->gmch_n);
7025
7026         compute_m_n(pixel_clock, link_clock,
7027                     &m_n->link_m, &m_n->link_n);
7028 }
7029
7030 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7031 {
7032         if (i915.panel_use_ssc >= 0)
7033                 return i915.panel_use_ssc != 0;
7034         return dev_priv->vbt.lvds_use_ssc
7035                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7036 }
7037
7038 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7039 {
7040         return (1 << dpll->n) << 16 | dpll->m2;
7041 }
7042
7043 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7044 {
7045         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7046 }
7047
7048 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7049                                      struct intel_crtc_state *crtc_state,
7050                                      struct dpll *reduced_clock)
7051 {
7052         struct drm_device *dev = crtc->base.dev;
7053         u32 fp, fp2 = 0;
7054
7055         if (IS_PINEVIEW(dev)) {
7056                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7057                 if (reduced_clock)
7058                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7059         } else {
7060                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7061                 if (reduced_clock)
7062                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7063         }
7064
7065         crtc_state->dpll_hw_state.fp0 = fp;
7066
7067         crtc->lowfreq_avail = false;
7068         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7069             reduced_clock) {
7070                 crtc_state->dpll_hw_state.fp1 = fp2;
7071                 crtc->lowfreq_avail = true;
7072         } else {
7073                 crtc_state->dpll_hw_state.fp1 = fp;
7074         }
7075 }
7076
7077 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7078                 pipe)
7079 {
7080         u32 reg_val;
7081
7082         /*
7083          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7084          * and set it to a reasonable value instead.
7085          */
7086         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7087         reg_val &= 0xffffff00;
7088         reg_val |= 0x00000030;
7089         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7090
7091         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7092         reg_val &= 0x8cffffff;
7093         reg_val = 0x8c000000;
7094         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7095
7096         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7097         reg_val &= 0xffffff00;
7098         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7099
7100         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7101         reg_val &= 0x00ffffff;
7102         reg_val |= 0xb0000000;
7103         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7104 }
7105
7106 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7107                                          struct intel_link_m_n *m_n)
7108 {
7109         struct drm_device *dev = crtc->base.dev;
7110         struct drm_i915_private *dev_priv = dev->dev_private;
7111         int pipe = crtc->pipe;
7112
7113         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7114         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7115         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7116         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7117 }
7118
7119 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7120                                          struct intel_link_m_n *m_n,
7121                                          struct intel_link_m_n *m2_n2)
7122 {
7123         struct drm_device *dev = crtc->base.dev;
7124         struct drm_i915_private *dev_priv = dev->dev_private;
7125         int pipe = crtc->pipe;
7126         enum transcoder transcoder = crtc->config->cpu_transcoder;
7127
7128         if (INTEL_INFO(dev)->gen >= 5) {
7129                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7130                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7131                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7132                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7133                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7134                  * for gen < 8) and if DRRS is supported (to make sure the
7135                  * registers are not unnecessarily accessed).
7136                  */
7137                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7138                         crtc->config->has_drrs) {
7139                         I915_WRITE(PIPE_DATA_M2(transcoder),
7140                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7141                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7142                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7143                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7144                 }
7145         } else {
7146                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7147                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7148                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7149                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7150         }
7151 }
7152
7153 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7154 {
7155         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7156
7157         if (m_n == M1_N1) {
7158                 dp_m_n = &crtc->config->dp_m_n;
7159                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7160         } else if (m_n == M2_N2) {
7161
7162                 /*
7163                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7164                  * needs to be programmed into M1_N1.
7165                  */
7166                 dp_m_n = &crtc->config->dp_m2_n2;
7167         } else {
7168                 DRM_ERROR("Unsupported divider value\n");
7169                 return;
7170         }
7171
7172         if (crtc->config->has_pch_encoder)
7173                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7174         else
7175                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7176 }
7177
7178 static void vlv_compute_dpll(struct intel_crtc *crtc,
7179                              struct intel_crtc_state *pipe_config)
7180 {
7181         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7182                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7183         if (crtc->pipe != PIPE_A)
7184                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7185
7186         /* DPLL not used with DSI, but still need the rest set up */
7187         if (!pipe_config->has_dsi_encoder)
7188                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7189                         DPLL_EXT_BUFFER_ENABLE_VLV;
7190
7191         pipe_config->dpll_hw_state.dpll_md =
7192                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7193 }
7194
7195 static void chv_compute_dpll(struct intel_crtc *crtc,
7196                              struct intel_crtc_state *pipe_config)
7197 {
7198         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7199                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7200         if (crtc->pipe != PIPE_A)
7201                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7202
7203         /* DPLL not used with DSI, but still need the rest set up */
7204         if (!pipe_config->has_dsi_encoder)
7205                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7206
7207         pipe_config->dpll_hw_state.dpll_md =
7208                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7209 }
7210
7211 static void vlv_prepare_pll(struct intel_crtc *crtc,
7212                             const struct intel_crtc_state *pipe_config)
7213 {
7214         struct drm_device *dev = crtc->base.dev;
7215         struct drm_i915_private *dev_priv = dev->dev_private;
7216         enum pipe pipe = crtc->pipe;
7217         u32 mdiv;
7218         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7219         u32 coreclk, reg_val;
7220
7221         /* Enable Refclk */
7222         I915_WRITE(DPLL(pipe),
7223                    pipe_config->dpll_hw_state.dpll &
7224                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7225
7226         /* No need to actually set up the DPLL with DSI */
7227         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7228                 return;
7229
7230         mutex_lock(&dev_priv->sb_lock);
7231
7232         bestn = pipe_config->dpll.n;
7233         bestm1 = pipe_config->dpll.m1;
7234         bestm2 = pipe_config->dpll.m2;
7235         bestp1 = pipe_config->dpll.p1;
7236         bestp2 = pipe_config->dpll.p2;
7237
7238         /* See eDP HDMI DPIO driver vbios notes doc */
7239
7240         /* PLL B needs special handling */
7241         if (pipe == PIPE_B)
7242                 vlv_pllb_recal_opamp(dev_priv, pipe);
7243
7244         /* Set up Tx target for periodic Rcomp update */
7245         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7246
7247         /* Disable target IRef on PLL */
7248         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7249         reg_val &= 0x00ffffff;
7250         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7251
7252         /* Disable fast lock */
7253         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7254
7255         /* Set idtafcrecal before PLL is enabled */
7256         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7257         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7258         mdiv |= ((bestn << DPIO_N_SHIFT));
7259         mdiv |= (1 << DPIO_K_SHIFT);
7260
7261         /*
7262          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7263          * but we don't support that).
7264          * Note: don't use the DAC post divider as it seems unstable.
7265          */
7266         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7267         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7268
7269         mdiv |= DPIO_ENABLE_CALIBRATION;
7270         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7271
7272         /* Set HBR and RBR LPF coefficients */
7273         if (pipe_config->port_clock == 162000 ||
7274             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7275             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7276                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7277                                  0x009f0003);
7278         else
7279                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7280                                  0x00d0000f);
7281
7282         if (pipe_config->has_dp_encoder) {
7283                 /* Use SSC source */
7284                 if (pipe == PIPE_A)
7285                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7286                                          0x0df40000);
7287                 else
7288                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7289                                          0x0df70000);
7290         } else { /* HDMI or VGA */
7291                 /* Use bend source */
7292                 if (pipe == PIPE_A)
7293                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7294                                          0x0df70000);
7295                 else
7296                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7297                                          0x0df40000);
7298         }
7299
7300         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7301         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7302         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7303             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7304                 coreclk |= 0x01000000;
7305         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7306
7307         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7308         mutex_unlock(&dev_priv->sb_lock);
7309 }
7310
7311 static void chv_prepare_pll(struct intel_crtc *crtc,
7312                             const struct intel_crtc_state *pipe_config)
7313 {
7314         struct drm_device *dev = crtc->base.dev;
7315         struct drm_i915_private *dev_priv = dev->dev_private;
7316         enum pipe pipe = crtc->pipe;
7317         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7318         u32 loopfilter, tribuf_calcntr;
7319         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7320         u32 dpio_val;
7321         int vco;
7322
7323         /* Enable Refclk and SSC */
7324         I915_WRITE(DPLL(pipe),
7325                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7326
7327         /* No need to actually set up the DPLL with DSI */
7328         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7329                 return;
7330
7331         bestn = pipe_config->dpll.n;
7332         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7333         bestm1 = pipe_config->dpll.m1;
7334         bestm2 = pipe_config->dpll.m2 >> 22;
7335         bestp1 = pipe_config->dpll.p1;
7336         bestp2 = pipe_config->dpll.p2;
7337         vco = pipe_config->dpll.vco;
7338         dpio_val = 0;
7339         loopfilter = 0;
7340
7341         mutex_lock(&dev_priv->sb_lock);
7342
7343         /* p1 and p2 divider */
7344         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7345                         5 << DPIO_CHV_S1_DIV_SHIFT |
7346                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7347                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7348                         1 << DPIO_CHV_K_DIV_SHIFT);
7349
7350         /* Feedback post-divider - m2 */
7351         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7352
7353         /* Feedback refclk divider - n and m1 */
7354         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7355                         DPIO_CHV_M1_DIV_BY_2 |
7356                         1 << DPIO_CHV_N_DIV_SHIFT);
7357
7358         /* M2 fraction division */
7359         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7360
7361         /* M2 fraction division enable */
7362         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7363         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7364         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7365         if (bestm2_frac)
7366                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7367         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7368
7369         /* Program digital lock detect threshold */
7370         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7371         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7372                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7373         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7374         if (!bestm2_frac)
7375                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7376         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7377
7378         /* Loop filter */
7379         if (vco == 5400000) {
7380                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7381                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7382                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7383                 tribuf_calcntr = 0x9;
7384         } else if (vco <= 6200000) {
7385                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7386                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7387                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7388                 tribuf_calcntr = 0x9;
7389         } else if (vco <= 6480000) {
7390                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7391                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7392                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7393                 tribuf_calcntr = 0x8;
7394         } else {
7395                 /* Not supported. Apply the same limits as in the max case */
7396                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7397                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7398                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7399                 tribuf_calcntr = 0;
7400         }
7401         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7402
7403         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7404         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7405         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7406         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7407
7408         /* AFC Recal */
7409         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7410                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7411                         DPIO_AFC_RECAL);
7412
7413         mutex_unlock(&dev_priv->sb_lock);
7414 }
7415
7416 /**
7417  * vlv_force_pll_on - forcibly enable just the PLL
7418  * @dev_priv: i915 private structure
7419  * @pipe: pipe PLL to enable
7420  * @dpll: PLL configuration
7421  *
7422  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7423  * in cases where we need the PLL enabled even when @pipe is not going to
7424  * be enabled.
7425  */
7426 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7427                      const struct dpll *dpll)
7428 {
7429         struct intel_crtc *crtc =
7430                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7431         struct intel_crtc_state *pipe_config;
7432
7433         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7434         if (!pipe_config)
7435                 return -ENOMEM;
7436
7437         pipe_config->base.crtc = &crtc->base;
7438         pipe_config->pixel_multiplier = 1;
7439         pipe_config->dpll = *dpll;
7440
7441         if (IS_CHERRYVIEW(dev)) {
7442                 chv_compute_dpll(crtc, pipe_config);
7443                 chv_prepare_pll(crtc, pipe_config);
7444                 chv_enable_pll(crtc, pipe_config);
7445         } else {
7446                 vlv_compute_dpll(crtc, pipe_config);
7447                 vlv_prepare_pll(crtc, pipe_config);
7448                 vlv_enable_pll(crtc, pipe_config);
7449         }
7450
7451         kfree(pipe_config);
7452
7453         return 0;
7454 }
7455
7456 /**
7457  * vlv_force_pll_off - forcibly disable just the PLL
7458  * @dev_priv: i915 private structure
7459  * @pipe: pipe PLL to disable
7460  *
7461  * Disable the PLL for @pipe. To be used in cases where we need
7462  * the PLL enabled even when @pipe is not going to be enabled.
7463  */
7464 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7465 {
7466         if (IS_CHERRYVIEW(dev))
7467                 chv_disable_pll(to_i915(dev), pipe);
7468         else
7469                 vlv_disable_pll(to_i915(dev), pipe);
7470 }
7471
7472 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7473                               struct intel_crtc_state *crtc_state,
7474                               struct dpll *reduced_clock)
7475 {
7476         struct drm_device *dev = crtc->base.dev;
7477         struct drm_i915_private *dev_priv = dev->dev_private;
7478         u32 dpll;
7479         bool is_sdvo;
7480         struct dpll *clock = &crtc_state->dpll;
7481
7482         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7483
7484         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7485                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7486
7487         dpll = DPLL_VGA_MODE_DIS;
7488
7489         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7490                 dpll |= DPLLB_MODE_LVDS;
7491         else
7492                 dpll |= DPLLB_MODE_DAC_SERIAL;
7493
7494         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7495                 dpll |= (crtc_state->pixel_multiplier - 1)
7496                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7497         }
7498
7499         if (is_sdvo)
7500                 dpll |= DPLL_SDVO_HIGH_SPEED;
7501
7502         if (crtc_state->has_dp_encoder)
7503                 dpll |= DPLL_SDVO_HIGH_SPEED;
7504
7505         /* compute bitmask from p1 value */
7506         if (IS_PINEVIEW(dev))
7507                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7508         else {
7509                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7510                 if (IS_G4X(dev) && reduced_clock)
7511                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7512         }
7513         switch (clock->p2) {
7514         case 5:
7515                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7516                 break;
7517         case 7:
7518                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7519                 break;
7520         case 10:
7521                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7522                 break;
7523         case 14:
7524                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7525                 break;
7526         }
7527         if (INTEL_INFO(dev)->gen >= 4)
7528                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7529
7530         if (crtc_state->sdvo_tv_clock)
7531                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7532         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7533                  intel_panel_use_ssc(dev_priv))
7534                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7535         else
7536                 dpll |= PLL_REF_INPUT_DREFCLK;
7537
7538         dpll |= DPLL_VCO_ENABLE;
7539         crtc_state->dpll_hw_state.dpll = dpll;
7540
7541         if (INTEL_INFO(dev)->gen >= 4) {
7542                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7543                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7544                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7545         }
7546 }
7547
7548 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7549                               struct intel_crtc_state *crtc_state,
7550                               struct dpll *reduced_clock)
7551 {
7552         struct drm_device *dev = crtc->base.dev;
7553         struct drm_i915_private *dev_priv = dev->dev_private;
7554         u32 dpll;
7555         struct dpll *clock = &crtc_state->dpll;
7556
7557         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7558
7559         dpll = DPLL_VGA_MODE_DIS;
7560
7561         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7562                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7563         } else {
7564                 if (clock->p1 == 2)
7565                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7566                 else
7567                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7568                 if (clock->p2 == 4)
7569                         dpll |= PLL_P2_DIVIDE_BY_4;
7570         }
7571
7572         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7573                 dpll |= DPLL_DVO_2X_MODE;
7574
7575         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7576             intel_panel_use_ssc(dev_priv))
7577                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7578         else
7579                 dpll |= PLL_REF_INPUT_DREFCLK;
7580
7581         dpll |= DPLL_VCO_ENABLE;
7582         crtc_state->dpll_hw_state.dpll = dpll;
7583 }
7584
7585 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7586 {
7587         struct drm_device *dev = intel_crtc->base.dev;
7588         struct drm_i915_private *dev_priv = dev->dev_private;
7589         enum pipe pipe = intel_crtc->pipe;
7590         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7591         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7592         uint32_t crtc_vtotal, crtc_vblank_end;
7593         int vsyncshift = 0;
7594
7595         /* We need to be careful not to changed the adjusted mode, for otherwise
7596          * the hw state checker will get angry at the mismatch. */
7597         crtc_vtotal = adjusted_mode->crtc_vtotal;
7598         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7599
7600         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7601                 /* the chip adds 2 halflines automatically */
7602                 crtc_vtotal -= 1;
7603                 crtc_vblank_end -= 1;
7604
7605                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7606                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7607                 else
7608                         vsyncshift = adjusted_mode->crtc_hsync_start -
7609                                 adjusted_mode->crtc_htotal / 2;
7610                 if (vsyncshift < 0)
7611                         vsyncshift += adjusted_mode->crtc_htotal;
7612         }
7613
7614         if (INTEL_INFO(dev)->gen > 3)
7615                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7616
7617         I915_WRITE(HTOTAL(cpu_transcoder),
7618                    (adjusted_mode->crtc_hdisplay - 1) |
7619                    ((adjusted_mode->crtc_htotal - 1) << 16));
7620         I915_WRITE(HBLANK(cpu_transcoder),
7621                    (adjusted_mode->crtc_hblank_start - 1) |
7622                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7623         I915_WRITE(HSYNC(cpu_transcoder),
7624                    (adjusted_mode->crtc_hsync_start - 1) |
7625                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7626
7627         I915_WRITE(VTOTAL(cpu_transcoder),
7628                    (adjusted_mode->crtc_vdisplay - 1) |
7629                    ((crtc_vtotal - 1) << 16));
7630         I915_WRITE(VBLANK(cpu_transcoder),
7631                    (adjusted_mode->crtc_vblank_start - 1) |
7632                    ((crtc_vblank_end - 1) << 16));
7633         I915_WRITE(VSYNC(cpu_transcoder),
7634                    (adjusted_mode->crtc_vsync_start - 1) |
7635                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7636
7637         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7638          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7639          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7640          * bits. */
7641         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7642             (pipe == PIPE_B || pipe == PIPE_C))
7643                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7644
7645 }
7646
7647 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7648 {
7649         struct drm_device *dev = intel_crtc->base.dev;
7650         struct drm_i915_private *dev_priv = dev->dev_private;
7651         enum pipe pipe = intel_crtc->pipe;
7652
7653         /* pipesrc controls the size that is scaled from, which should
7654          * always be the user's requested size.
7655          */
7656         I915_WRITE(PIPESRC(pipe),
7657                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7658                    (intel_crtc->config->pipe_src_h - 1));
7659 }
7660
7661 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7662                                    struct intel_crtc_state *pipe_config)
7663 {
7664         struct drm_device *dev = crtc->base.dev;
7665         struct drm_i915_private *dev_priv = dev->dev_private;
7666         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7667         uint32_t tmp;
7668
7669         tmp = I915_READ(HTOTAL(cpu_transcoder));
7670         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7671         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7672         tmp = I915_READ(HBLANK(cpu_transcoder));
7673         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7674         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7675         tmp = I915_READ(HSYNC(cpu_transcoder));
7676         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7677         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7678
7679         tmp = I915_READ(VTOTAL(cpu_transcoder));
7680         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7681         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7682         tmp = I915_READ(VBLANK(cpu_transcoder));
7683         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7684         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7685         tmp = I915_READ(VSYNC(cpu_transcoder));
7686         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7687         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7688
7689         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7690                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7691                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7692                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7693         }
7694 }
7695
7696 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7697                                     struct intel_crtc_state *pipe_config)
7698 {
7699         struct drm_device *dev = crtc->base.dev;
7700         struct drm_i915_private *dev_priv = dev->dev_private;
7701         u32 tmp;
7702
7703         tmp = I915_READ(PIPESRC(crtc->pipe));
7704         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7705         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7706
7707         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7708         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7709 }
7710
7711 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7712                                  struct intel_crtc_state *pipe_config)
7713 {
7714         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7715         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7716         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7717         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7718
7719         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7720         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7721         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7722         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7723
7724         mode->flags = pipe_config->base.adjusted_mode.flags;
7725         mode->type = DRM_MODE_TYPE_DRIVER;
7726
7727         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7728         mode->flags |= pipe_config->base.adjusted_mode.flags;
7729
7730         mode->hsync = drm_mode_hsync(mode);
7731         mode->vrefresh = drm_mode_vrefresh(mode);
7732         drm_mode_set_name(mode);
7733 }
7734
7735 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7736 {
7737         struct drm_device *dev = intel_crtc->base.dev;
7738         struct drm_i915_private *dev_priv = dev->dev_private;
7739         uint32_t pipeconf;
7740
7741         pipeconf = 0;
7742
7743         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7744             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7745                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7746
7747         if (intel_crtc->config->double_wide)
7748                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7749
7750         /* only g4x and later have fancy bpc/dither controls */
7751         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7752                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7753                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7754                         pipeconf |= PIPECONF_DITHER_EN |
7755                                     PIPECONF_DITHER_TYPE_SP;
7756
7757                 switch (intel_crtc->config->pipe_bpp) {
7758                 case 18:
7759                         pipeconf |= PIPECONF_6BPC;
7760                         break;
7761                 case 24:
7762                         pipeconf |= PIPECONF_8BPC;
7763                         break;
7764                 case 30:
7765                         pipeconf |= PIPECONF_10BPC;
7766                         break;
7767                 default:
7768                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7769                         BUG();
7770                 }
7771         }
7772
7773         if (HAS_PIPE_CXSR(dev)) {
7774                 if (intel_crtc->lowfreq_avail) {
7775                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7776                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7777                 } else {
7778                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7779                 }
7780         }
7781
7782         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7783                 if (INTEL_INFO(dev)->gen < 4 ||
7784                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7785                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7786                 else
7787                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7788         } else
7789                 pipeconf |= PIPECONF_PROGRESSIVE;
7790
7791         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7792              intel_crtc->config->limited_color_range)
7793                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7794
7795         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7796         POSTING_READ(PIPECONF(intel_crtc->pipe));
7797 }
7798
7799 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7800                                    struct intel_crtc_state *crtc_state)
7801 {
7802         struct drm_device *dev = crtc->base.dev;
7803         struct drm_i915_private *dev_priv = dev->dev_private;
7804         const struct intel_limit *limit;
7805         int refclk = 48000;
7806
7807         memset(&crtc_state->dpll_hw_state, 0,
7808                sizeof(crtc_state->dpll_hw_state));
7809
7810         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7811                 if (intel_panel_use_ssc(dev_priv)) {
7812                         refclk = dev_priv->vbt.lvds_ssc_freq;
7813                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7814                 }
7815
7816                 limit = &intel_limits_i8xx_lvds;
7817         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7818                 limit = &intel_limits_i8xx_dvo;
7819         } else {
7820                 limit = &intel_limits_i8xx_dac;
7821         }
7822
7823         if (!crtc_state->clock_set &&
7824             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7825                                  refclk, NULL, &crtc_state->dpll)) {
7826                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7827                 return -EINVAL;
7828         }
7829
7830         i8xx_compute_dpll(crtc, crtc_state, NULL);
7831
7832         return 0;
7833 }
7834
7835 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7836                                   struct intel_crtc_state *crtc_state)
7837 {
7838         struct drm_device *dev = crtc->base.dev;
7839         struct drm_i915_private *dev_priv = dev->dev_private;
7840         const struct intel_limit *limit;
7841         int refclk = 96000;
7842
7843         memset(&crtc_state->dpll_hw_state, 0,
7844                sizeof(crtc_state->dpll_hw_state));
7845
7846         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7847                 if (intel_panel_use_ssc(dev_priv)) {
7848                         refclk = dev_priv->vbt.lvds_ssc_freq;
7849                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7850                 }
7851
7852                 if (intel_is_dual_link_lvds(dev))
7853                         limit = &intel_limits_g4x_dual_channel_lvds;
7854                 else
7855                         limit = &intel_limits_g4x_single_channel_lvds;
7856         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7857                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7858                 limit = &intel_limits_g4x_hdmi;
7859         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7860                 limit = &intel_limits_g4x_sdvo;
7861         } else {
7862                 /* The option is for other outputs */
7863                 limit = &intel_limits_i9xx_sdvo;
7864         }
7865
7866         if (!crtc_state->clock_set &&
7867             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7868                                 refclk, NULL, &crtc_state->dpll)) {
7869                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7870                 return -EINVAL;
7871         }
7872
7873         i9xx_compute_dpll(crtc, crtc_state, NULL);
7874
7875         return 0;
7876 }
7877
7878 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7879                                   struct intel_crtc_state *crtc_state)
7880 {
7881         struct drm_device *dev = crtc->base.dev;
7882         struct drm_i915_private *dev_priv = dev->dev_private;
7883         const struct intel_limit *limit;
7884         int refclk = 96000;
7885
7886         memset(&crtc_state->dpll_hw_state, 0,
7887                sizeof(crtc_state->dpll_hw_state));
7888
7889         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7890                 if (intel_panel_use_ssc(dev_priv)) {
7891                         refclk = dev_priv->vbt.lvds_ssc_freq;
7892                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7893                 }
7894
7895                 limit = &intel_limits_pineview_lvds;
7896         } else {
7897                 limit = &intel_limits_pineview_sdvo;
7898         }
7899
7900         if (!crtc_state->clock_set &&
7901             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7902                                 refclk, NULL, &crtc_state->dpll)) {
7903                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7904                 return -EINVAL;
7905         }
7906
7907         i9xx_compute_dpll(crtc, crtc_state, NULL);
7908
7909         return 0;
7910 }
7911
7912 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7913                                    struct intel_crtc_state *crtc_state)
7914 {
7915         struct drm_device *dev = crtc->base.dev;
7916         struct drm_i915_private *dev_priv = dev->dev_private;
7917         const struct intel_limit *limit;
7918         int refclk = 96000;
7919
7920         memset(&crtc_state->dpll_hw_state, 0,
7921                sizeof(crtc_state->dpll_hw_state));
7922
7923         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7924                 if (intel_panel_use_ssc(dev_priv)) {
7925                         refclk = dev_priv->vbt.lvds_ssc_freq;
7926                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7927                 }
7928
7929                 limit = &intel_limits_i9xx_lvds;
7930         } else {
7931                 limit = &intel_limits_i9xx_sdvo;
7932         }
7933
7934         if (!crtc_state->clock_set &&
7935             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7936                                  refclk, NULL, &crtc_state->dpll)) {
7937                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7938                 return -EINVAL;
7939         }
7940
7941         i9xx_compute_dpll(crtc, crtc_state, NULL);
7942
7943         return 0;
7944 }
7945
7946 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7947                                   struct intel_crtc_state *crtc_state)
7948 {
7949         int refclk = 100000;
7950         const struct intel_limit *limit = &intel_limits_chv;
7951
7952         memset(&crtc_state->dpll_hw_state, 0,
7953                sizeof(crtc_state->dpll_hw_state));
7954
7955         if (!crtc_state->clock_set &&
7956             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7957                                 refclk, NULL, &crtc_state->dpll)) {
7958                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7959                 return -EINVAL;
7960         }
7961
7962         chv_compute_dpll(crtc, crtc_state);
7963
7964         return 0;
7965 }
7966
7967 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7968                                   struct intel_crtc_state *crtc_state)
7969 {
7970         int refclk = 100000;
7971         const struct intel_limit *limit = &intel_limits_vlv;
7972
7973         memset(&crtc_state->dpll_hw_state, 0,
7974                sizeof(crtc_state->dpll_hw_state));
7975
7976         if (!crtc_state->clock_set &&
7977             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7978                                 refclk, NULL, &crtc_state->dpll)) {
7979                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7980                 return -EINVAL;
7981         }
7982
7983         vlv_compute_dpll(crtc, crtc_state);
7984
7985         return 0;
7986 }
7987
7988 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7989                                  struct intel_crtc_state *pipe_config)
7990 {
7991         struct drm_device *dev = crtc->base.dev;
7992         struct drm_i915_private *dev_priv = dev->dev_private;
7993         uint32_t tmp;
7994
7995         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7996                 return;
7997
7998         tmp = I915_READ(PFIT_CONTROL);
7999         if (!(tmp & PFIT_ENABLE))
8000                 return;
8001
8002         /* Check whether the pfit is attached to our pipe. */
8003         if (INTEL_INFO(dev)->gen < 4) {
8004                 if (crtc->pipe != PIPE_B)
8005                         return;
8006         } else {
8007                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8008                         return;
8009         }
8010
8011         pipe_config->gmch_pfit.control = tmp;
8012         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8013 }
8014
8015 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8016                                struct intel_crtc_state *pipe_config)
8017 {
8018         struct drm_device *dev = crtc->base.dev;
8019         struct drm_i915_private *dev_priv = dev->dev_private;
8020         int pipe = pipe_config->cpu_transcoder;
8021         struct dpll clock;
8022         u32 mdiv;
8023         int refclk = 100000;
8024
8025         /* In case of DSI, DPLL will not be used */
8026         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8027                 return;
8028
8029         mutex_lock(&dev_priv->sb_lock);
8030         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8031         mutex_unlock(&dev_priv->sb_lock);
8032
8033         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8034         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8035         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8036         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8037         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8038
8039         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8040 }
8041
8042 static void
8043 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8044                               struct intel_initial_plane_config *plane_config)
8045 {
8046         struct drm_device *dev = crtc->base.dev;
8047         struct drm_i915_private *dev_priv = dev->dev_private;
8048         u32 val, base, offset;
8049         int pipe = crtc->pipe, plane = crtc->plane;
8050         int fourcc, pixel_format;
8051         unsigned int aligned_height;
8052         struct drm_framebuffer *fb;
8053         struct intel_framebuffer *intel_fb;
8054
8055         val = I915_READ(DSPCNTR(plane));
8056         if (!(val & DISPLAY_PLANE_ENABLE))
8057                 return;
8058
8059         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8060         if (!intel_fb) {
8061                 DRM_DEBUG_KMS("failed to alloc fb\n");
8062                 return;
8063         }
8064
8065         fb = &intel_fb->base;
8066
8067         if (INTEL_INFO(dev)->gen >= 4) {
8068                 if (val & DISPPLANE_TILED) {
8069                         plane_config->tiling = I915_TILING_X;
8070                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8071                 }
8072         }
8073
8074         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8075         fourcc = i9xx_format_to_fourcc(pixel_format);
8076         fb->pixel_format = fourcc;
8077         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8078
8079         if (INTEL_INFO(dev)->gen >= 4) {
8080                 if (plane_config->tiling)
8081                         offset = I915_READ(DSPTILEOFF(plane));
8082                 else
8083                         offset = I915_READ(DSPLINOFF(plane));
8084                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8085         } else {
8086                 base = I915_READ(DSPADDR(plane));
8087         }
8088         plane_config->base = base;
8089
8090         val = I915_READ(PIPESRC(pipe));
8091         fb->width = ((val >> 16) & 0xfff) + 1;
8092         fb->height = ((val >> 0) & 0xfff) + 1;
8093
8094         val = I915_READ(DSPSTRIDE(pipe));
8095         fb->pitches[0] = val & 0xffffffc0;
8096
8097         aligned_height = intel_fb_align_height(dev, fb->height,
8098                                                fb->pixel_format,
8099                                                fb->modifier[0]);
8100
8101         plane_config->size = fb->pitches[0] * aligned_height;
8102
8103         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8104                       pipe_name(pipe), plane, fb->width, fb->height,
8105                       fb->bits_per_pixel, base, fb->pitches[0],
8106                       plane_config->size);
8107
8108         plane_config->fb = intel_fb;
8109 }
8110
8111 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8112                                struct intel_crtc_state *pipe_config)
8113 {
8114         struct drm_device *dev = crtc->base.dev;
8115         struct drm_i915_private *dev_priv = dev->dev_private;
8116         int pipe = pipe_config->cpu_transcoder;
8117         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8118         struct dpll clock;
8119         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8120         int refclk = 100000;
8121
8122         /* In case of DSI, DPLL will not be used */
8123         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8124                 return;
8125
8126         mutex_lock(&dev_priv->sb_lock);
8127         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8128         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8129         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8130         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8131         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8132         mutex_unlock(&dev_priv->sb_lock);
8133
8134         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8135         clock.m2 = (pll_dw0 & 0xff) << 22;
8136         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8137                 clock.m2 |= pll_dw2 & 0x3fffff;
8138         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8139         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8140         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8141
8142         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8143 }
8144
8145 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8146                                  struct intel_crtc_state *pipe_config)
8147 {
8148         struct drm_device *dev = crtc->base.dev;
8149         struct drm_i915_private *dev_priv = dev->dev_private;
8150         enum intel_display_power_domain power_domain;
8151         uint32_t tmp;
8152         bool ret;
8153
8154         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8155         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8156                 return false;
8157
8158         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8159         pipe_config->shared_dpll = NULL;
8160
8161         ret = false;
8162
8163         tmp = I915_READ(PIPECONF(crtc->pipe));
8164         if (!(tmp & PIPECONF_ENABLE))
8165                 goto out;
8166
8167         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8168                 switch (tmp & PIPECONF_BPC_MASK) {
8169                 case PIPECONF_6BPC:
8170                         pipe_config->pipe_bpp = 18;
8171                         break;
8172                 case PIPECONF_8BPC:
8173                         pipe_config->pipe_bpp = 24;
8174                         break;
8175                 case PIPECONF_10BPC:
8176                         pipe_config->pipe_bpp = 30;
8177                         break;
8178                 default:
8179                         break;
8180                 }
8181         }
8182
8183         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8184             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8185                 pipe_config->limited_color_range = true;
8186
8187         if (INTEL_INFO(dev)->gen < 4)
8188                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8189
8190         intel_get_pipe_timings(crtc, pipe_config);
8191         intel_get_pipe_src_size(crtc, pipe_config);
8192
8193         i9xx_get_pfit_config(crtc, pipe_config);
8194
8195         if (INTEL_INFO(dev)->gen >= 4) {
8196                 /* No way to read it out on pipes B and C */
8197                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8198                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8199                 else
8200                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8201                 pipe_config->pixel_multiplier =
8202                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8203                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8204                 pipe_config->dpll_hw_state.dpll_md = tmp;
8205         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8206                 tmp = I915_READ(DPLL(crtc->pipe));
8207                 pipe_config->pixel_multiplier =
8208                         ((tmp & SDVO_MULTIPLIER_MASK)
8209                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8210         } else {
8211                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8212                  * port and will be fixed up in the encoder->get_config
8213                  * function. */
8214                 pipe_config->pixel_multiplier = 1;
8215         }
8216         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8217         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8218                 /*
8219                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8220                  * on 830. Filter it out here so that we don't
8221                  * report errors due to that.
8222                  */
8223                 if (IS_I830(dev))
8224                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8225
8226                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8227                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8228         } else {
8229                 /* Mask out read-only status bits. */
8230                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8231                                                      DPLL_PORTC_READY_MASK |
8232                                                      DPLL_PORTB_READY_MASK);
8233         }
8234
8235         if (IS_CHERRYVIEW(dev))
8236                 chv_crtc_clock_get(crtc, pipe_config);
8237         else if (IS_VALLEYVIEW(dev))
8238                 vlv_crtc_clock_get(crtc, pipe_config);
8239         else
8240                 i9xx_crtc_clock_get(crtc, pipe_config);
8241
8242         /*
8243          * Normally the dotclock is filled in by the encoder .get_config()
8244          * but in case the pipe is enabled w/o any ports we need a sane
8245          * default.
8246          */
8247         pipe_config->base.adjusted_mode.crtc_clock =
8248                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8249
8250         ret = true;
8251
8252 out:
8253         intel_display_power_put(dev_priv, power_domain);
8254
8255         return ret;
8256 }
8257
8258 static void ironlake_init_pch_refclk(struct drm_device *dev)
8259 {
8260         struct drm_i915_private *dev_priv = dev->dev_private;
8261         struct intel_encoder *encoder;
8262         u32 val, final;
8263         bool has_lvds = false;
8264         bool has_cpu_edp = false;
8265         bool has_panel = false;
8266         bool has_ck505 = false;
8267         bool can_ssc = false;
8268
8269         /* We need to take the global config into account */
8270         for_each_intel_encoder(dev, encoder) {
8271                 switch (encoder->type) {
8272                 case INTEL_OUTPUT_LVDS:
8273                         has_panel = true;
8274                         has_lvds = true;
8275                         break;
8276                 case INTEL_OUTPUT_EDP:
8277                         has_panel = true;
8278                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8279                                 has_cpu_edp = true;
8280                         break;
8281                 default:
8282                         break;
8283                 }
8284         }
8285
8286         if (HAS_PCH_IBX(dev)) {
8287                 has_ck505 = dev_priv->vbt.display_clock_mode;
8288                 can_ssc = has_ck505;
8289         } else {
8290                 has_ck505 = false;
8291                 can_ssc = true;
8292         }
8293
8294         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8295                       has_panel, has_lvds, has_ck505);
8296
8297         /* Ironlake: try to setup display ref clock before DPLL
8298          * enabling. This is only under driver's control after
8299          * PCH B stepping, previous chipset stepping should be
8300          * ignoring this setting.
8301          */
8302         val = I915_READ(PCH_DREF_CONTROL);
8303
8304         /* As we must carefully and slowly disable/enable each source in turn,
8305          * compute the final state we want first and check if we need to
8306          * make any changes at all.
8307          */
8308         final = val;
8309         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8310         if (has_ck505)
8311                 final |= DREF_NONSPREAD_CK505_ENABLE;
8312         else
8313                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8314
8315         final &= ~DREF_SSC_SOURCE_MASK;
8316         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8317         final &= ~DREF_SSC1_ENABLE;
8318
8319         if (has_panel) {
8320                 final |= DREF_SSC_SOURCE_ENABLE;
8321
8322                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8323                         final |= DREF_SSC1_ENABLE;
8324
8325                 if (has_cpu_edp) {
8326                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8327                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8328                         else
8329                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8330                 } else
8331                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8332         } else {
8333                 final |= DREF_SSC_SOURCE_DISABLE;
8334                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8335         }
8336
8337         if (final == val)
8338                 return;
8339
8340         /* Always enable nonspread source */
8341         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8342
8343         if (has_ck505)
8344                 val |= DREF_NONSPREAD_CK505_ENABLE;
8345         else
8346                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8347
8348         if (has_panel) {
8349                 val &= ~DREF_SSC_SOURCE_MASK;
8350                 val |= DREF_SSC_SOURCE_ENABLE;
8351
8352                 /* SSC must be turned on before enabling the CPU output  */
8353                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8354                         DRM_DEBUG_KMS("Using SSC on panel\n");
8355                         val |= DREF_SSC1_ENABLE;
8356                 } else
8357                         val &= ~DREF_SSC1_ENABLE;
8358
8359                 /* Get SSC going before enabling the outputs */
8360                 I915_WRITE(PCH_DREF_CONTROL, val);
8361                 POSTING_READ(PCH_DREF_CONTROL);
8362                 udelay(200);
8363
8364                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8365
8366                 /* Enable CPU source on CPU attached eDP */
8367                 if (has_cpu_edp) {
8368                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8369                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8370                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8371                         } else
8372                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8373                 } else
8374                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8375
8376                 I915_WRITE(PCH_DREF_CONTROL, val);
8377                 POSTING_READ(PCH_DREF_CONTROL);
8378                 udelay(200);
8379         } else {
8380                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8381
8382                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8383
8384                 /* Turn off CPU output */
8385                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8386
8387                 I915_WRITE(PCH_DREF_CONTROL, val);
8388                 POSTING_READ(PCH_DREF_CONTROL);
8389                 udelay(200);
8390
8391                 /* Turn off the SSC source */
8392                 val &= ~DREF_SSC_SOURCE_MASK;
8393                 val |= DREF_SSC_SOURCE_DISABLE;
8394
8395                 /* Turn off SSC1 */
8396                 val &= ~DREF_SSC1_ENABLE;
8397
8398                 I915_WRITE(PCH_DREF_CONTROL, val);
8399                 POSTING_READ(PCH_DREF_CONTROL);
8400                 udelay(200);
8401         }
8402
8403         BUG_ON(val != final);
8404 }
8405
8406 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8407 {
8408         uint32_t tmp;
8409
8410         tmp = I915_READ(SOUTH_CHICKEN2);
8411         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8412         I915_WRITE(SOUTH_CHICKEN2, tmp);
8413
8414         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8415                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8416                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8417
8418         tmp = I915_READ(SOUTH_CHICKEN2);
8419         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8420         I915_WRITE(SOUTH_CHICKEN2, tmp);
8421
8422         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8423                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8424                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8425 }
8426
8427 /* WaMPhyProgramming:hsw */
8428 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8429 {
8430         uint32_t tmp;
8431
8432         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8433         tmp &= ~(0xFF << 24);
8434         tmp |= (0x12 << 24);
8435         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8436
8437         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8438         tmp |= (1 << 11);
8439         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8440
8441         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8442         tmp |= (1 << 11);
8443         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8444
8445         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8446         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8447         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8448
8449         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8450         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8451         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8452
8453         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8454         tmp &= ~(7 << 13);
8455         tmp |= (5 << 13);
8456         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8457
8458         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8459         tmp &= ~(7 << 13);
8460         tmp |= (5 << 13);
8461         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8462
8463         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8464         tmp &= ~0xFF;
8465         tmp |= 0x1C;
8466         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8467
8468         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8469         tmp &= ~0xFF;
8470         tmp |= 0x1C;
8471         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8472
8473         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8474         tmp &= ~(0xFF << 16);
8475         tmp |= (0x1C << 16);
8476         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8477
8478         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8479         tmp &= ~(0xFF << 16);
8480         tmp |= (0x1C << 16);
8481         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8482
8483         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8484         tmp |= (1 << 27);
8485         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8486
8487         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8488         tmp |= (1 << 27);
8489         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8490
8491         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8492         tmp &= ~(0xF << 28);
8493         tmp |= (4 << 28);
8494         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8495
8496         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8497         tmp &= ~(0xF << 28);
8498         tmp |= (4 << 28);
8499         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8500 }
8501
8502 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8503  * Programming" based on the parameters passed:
8504  * - Sequence to enable CLKOUT_DP
8505  * - Sequence to enable CLKOUT_DP without spread
8506  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8507  */
8508 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8509                                  bool with_fdi)
8510 {
8511         struct drm_i915_private *dev_priv = dev->dev_private;
8512         uint32_t reg, tmp;
8513
8514         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8515                 with_spread = true;
8516         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8517                 with_fdi = false;
8518
8519         mutex_lock(&dev_priv->sb_lock);
8520
8521         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8522         tmp &= ~SBI_SSCCTL_DISABLE;
8523         tmp |= SBI_SSCCTL_PATHALT;
8524         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8525
8526         udelay(24);
8527
8528         if (with_spread) {
8529                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8530                 tmp &= ~SBI_SSCCTL_PATHALT;
8531                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8532
8533                 if (with_fdi) {
8534                         lpt_reset_fdi_mphy(dev_priv);
8535                         lpt_program_fdi_mphy(dev_priv);
8536                 }
8537         }
8538
8539         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8540         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8541         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8542         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8543
8544         mutex_unlock(&dev_priv->sb_lock);
8545 }
8546
8547 /* Sequence to disable CLKOUT_DP */
8548 static void lpt_disable_clkout_dp(struct drm_device *dev)
8549 {
8550         struct drm_i915_private *dev_priv = dev->dev_private;
8551         uint32_t reg, tmp;
8552
8553         mutex_lock(&dev_priv->sb_lock);
8554
8555         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8556         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8557         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8558         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8559
8560         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8561         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8562                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8563                         tmp |= SBI_SSCCTL_PATHALT;
8564                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8565                         udelay(32);
8566                 }
8567                 tmp |= SBI_SSCCTL_DISABLE;
8568                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8569         }
8570
8571         mutex_unlock(&dev_priv->sb_lock);
8572 }
8573
8574 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8575
8576 static const uint16_t sscdivintphase[] = {
8577         [BEND_IDX( 50)] = 0x3B23,
8578         [BEND_IDX( 45)] = 0x3B23,
8579         [BEND_IDX( 40)] = 0x3C23,
8580         [BEND_IDX( 35)] = 0x3C23,
8581         [BEND_IDX( 30)] = 0x3D23,
8582         [BEND_IDX( 25)] = 0x3D23,
8583         [BEND_IDX( 20)] = 0x3E23,
8584         [BEND_IDX( 15)] = 0x3E23,
8585         [BEND_IDX( 10)] = 0x3F23,
8586         [BEND_IDX(  5)] = 0x3F23,
8587         [BEND_IDX(  0)] = 0x0025,
8588         [BEND_IDX( -5)] = 0x0025,
8589         [BEND_IDX(-10)] = 0x0125,
8590         [BEND_IDX(-15)] = 0x0125,
8591         [BEND_IDX(-20)] = 0x0225,
8592         [BEND_IDX(-25)] = 0x0225,
8593         [BEND_IDX(-30)] = 0x0325,
8594         [BEND_IDX(-35)] = 0x0325,
8595         [BEND_IDX(-40)] = 0x0425,
8596         [BEND_IDX(-45)] = 0x0425,
8597         [BEND_IDX(-50)] = 0x0525,
8598 };
8599
8600 /*
8601  * Bend CLKOUT_DP
8602  * steps -50 to 50 inclusive, in steps of 5
8603  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8604  * change in clock period = -(steps / 10) * 5.787 ps
8605  */
8606 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8607 {
8608         uint32_t tmp;
8609         int idx = BEND_IDX(steps);
8610
8611         if (WARN_ON(steps % 5 != 0))
8612                 return;
8613
8614         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8615                 return;
8616
8617         mutex_lock(&dev_priv->sb_lock);
8618
8619         if (steps % 10 != 0)
8620                 tmp = 0xAAAAAAAB;
8621         else
8622                 tmp = 0x00000000;
8623         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8624
8625         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8626         tmp &= 0xffff0000;
8627         tmp |= sscdivintphase[idx];
8628         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8629
8630         mutex_unlock(&dev_priv->sb_lock);
8631 }
8632
8633 #undef BEND_IDX
8634
8635 static void lpt_init_pch_refclk(struct drm_device *dev)
8636 {
8637         struct intel_encoder *encoder;
8638         bool has_vga = false;
8639
8640         for_each_intel_encoder(dev, encoder) {
8641                 switch (encoder->type) {
8642                 case INTEL_OUTPUT_ANALOG:
8643                         has_vga = true;
8644                         break;
8645                 default:
8646                         break;
8647                 }
8648         }
8649
8650         if (has_vga) {
8651                 lpt_bend_clkout_dp(to_i915(dev), 0);
8652                 lpt_enable_clkout_dp(dev, true, true);
8653         } else {
8654                 lpt_disable_clkout_dp(dev);
8655         }
8656 }
8657
8658 /*
8659  * Initialize reference clocks when the driver loads
8660  */
8661 void intel_init_pch_refclk(struct drm_device *dev)
8662 {
8663         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8664                 ironlake_init_pch_refclk(dev);
8665         else if (HAS_PCH_LPT(dev))
8666                 lpt_init_pch_refclk(dev);
8667 }
8668
8669 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8670 {
8671         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8672         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8673         int pipe = intel_crtc->pipe;
8674         uint32_t val;
8675
8676         val = 0;
8677
8678         switch (intel_crtc->config->pipe_bpp) {
8679         case 18:
8680                 val |= PIPECONF_6BPC;
8681                 break;
8682         case 24:
8683                 val |= PIPECONF_8BPC;
8684                 break;
8685         case 30:
8686                 val |= PIPECONF_10BPC;
8687                 break;
8688         case 36:
8689                 val |= PIPECONF_12BPC;
8690                 break;
8691         default:
8692                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8693                 BUG();
8694         }
8695
8696         if (intel_crtc->config->dither)
8697                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8698
8699         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8700                 val |= PIPECONF_INTERLACED_ILK;
8701         else
8702                 val |= PIPECONF_PROGRESSIVE;
8703
8704         if (intel_crtc->config->limited_color_range)
8705                 val |= PIPECONF_COLOR_RANGE_SELECT;
8706
8707         I915_WRITE(PIPECONF(pipe), val);
8708         POSTING_READ(PIPECONF(pipe));
8709 }
8710
8711 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8712 {
8713         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8714         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8715         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8716         u32 val = 0;
8717
8718         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8719                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8720
8721         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8722                 val |= PIPECONF_INTERLACED_ILK;
8723         else
8724                 val |= PIPECONF_PROGRESSIVE;
8725
8726         I915_WRITE(PIPECONF(cpu_transcoder), val);
8727         POSTING_READ(PIPECONF(cpu_transcoder));
8728 }
8729
8730 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8731 {
8732         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8733         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8734
8735         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8736                 u32 val = 0;
8737
8738                 switch (intel_crtc->config->pipe_bpp) {
8739                 case 18:
8740                         val |= PIPEMISC_DITHER_6_BPC;
8741                         break;
8742                 case 24:
8743                         val |= PIPEMISC_DITHER_8_BPC;
8744                         break;
8745                 case 30:
8746                         val |= PIPEMISC_DITHER_10_BPC;
8747                         break;
8748                 case 36:
8749                         val |= PIPEMISC_DITHER_12_BPC;
8750                         break;
8751                 default:
8752                         /* Case prevented by pipe_config_set_bpp. */
8753                         BUG();
8754                 }
8755
8756                 if (intel_crtc->config->dither)
8757                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8758
8759                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8760         }
8761 }
8762
8763 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8764 {
8765         /*
8766          * Account for spread spectrum to avoid
8767          * oversubscribing the link. Max center spread
8768          * is 2.5%; use 5% for safety's sake.
8769          */
8770         u32 bps = target_clock * bpp * 21 / 20;
8771         return DIV_ROUND_UP(bps, link_bw * 8);
8772 }
8773
8774 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8775 {
8776         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8777 }
8778
8779 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8780                                   struct intel_crtc_state *crtc_state,
8781                                   struct dpll *reduced_clock)
8782 {
8783         struct drm_crtc *crtc = &intel_crtc->base;
8784         struct drm_device *dev = crtc->dev;
8785         struct drm_i915_private *dev_priv = dev->dev_private;
8786         struct drm_atomic_state *state = crtc_state->base.state;
8787         struct drm_connector *connector;
8788         struct drm_connector_state *connector_state;
8789         struct intel_encoder *encoder;
8790         u32 dpll, fp, fp2;
8791         int factor, i;
8792         bool is_lvds = false, is_sdvo = false;
8793
8794         for_each_connector_in_state(state, connector, connector_state, i) {
8795                 if (connector_state->crtc != crtc_state->base.crtc)
8796                         continue;
8797
8798                 encoder = to_intel_encoder(connector_state->best_encoder);
8799
8800                 switch (encoder->type) {
8801                 case INTEL_OUTPUT_LVDS:
8802                         is_lvds = true;
8803                         break;
8804                 case INTEL_OUTPUT_SDVO:
8805                 case INTEL_OUTPUT_HDMI:
8806                         is_sdvo = true;
8807                         break;
8808                 default:
8809                         break;
8810                 }
8811         }
8812
8813         /* Enable autotuning of the PLL clock (if permissible) */
8814         factor = 21;
8815         if (is_lvds) {
8816                 if ((intel_panel_use_ssc(dev_priv) &&
8817                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8818                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8819                         factor = 25;
8820         } else if (crtc_state->sdvo_tv_clock)
8821                 factor = 20;
8822
8823         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8824
8825         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8826                 fp |= FP_CB_TUNE;
8827
8828         if (reduced_clock) {
8829                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8830
8831                 if (reduced_clock->m < factor * reduced_clock->n)
8832                         fp2 |= FP_CB_TUNE;
8833         } else {
8834                 fp2 = fp;
8835         }
8836
8837         dpll = 0;
8838
8839         if (is_lvds)
8840                 dpll |= DPLLB_MODE_LVDS;
8841         else
8842                 dpll |= DPLLB_MODE_DAC_SERIAL;
8843
8844         dpll |= (crtc_state->pixel_multiplier - 1)
8845                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8846
8847         if (is_sdvo)
8848                 dpll |= DPLL_SDVO_HIGH_SPEED;
8849         if (crtc_state->has_dp_encoder)
8850                 dpll |= DPLL_SDVO_HIGH_SPEED;
8851
8852         /* compute bitmask from p1 value */
8853         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8854         /* also FPA1 */
8855         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8856
8857         switch (crtc_state->dpll.p2) {
8858         case 5:
8859                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8860                 break;
8861         case 7:
8862                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8863                 break;
8864         case 10:
8865                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8866                 break;
8867         case 14:
8868                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8869                 break;
8870         }
8871
8872         if (is_lvds && intel_panel_use_ssc(dev_priv))
8873                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8874         else
8875                 dpll |= PLL_REF_INPUT_DREFCLK;
8876
8877         dpll |= DPLL_VCO_ENABLE;
8878
8879         crtc_state->dpll_hw_state.dpll = dpll;
8880         crtc_state->dpll_hw_state.fp0 = fp;
8881         crtc_state->dpll_hw_state.fp1 = fp2;
8882 }
8883
8884 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8885                                        struct intel_crtc_state *crtc_state)
8886 {
8887         struct drm_device *dev = crtc->base.dev;
8888         struct drm_i915_private *dev_priv = dev->dev_private;
8889         struct dpll reduced_clock;
8890         bool has_reduced_clock = false;
8891         struct intel_shared_dpll *pll;
8892         const struct intel_limit *limit;
8893         int refclk = 120000;
8894
8895         memset(&crtc_state->dpll_hw_state, 0,
8896                sizeof(crtc_state->dpll_hw_state));
8897
8898         crtc->lowfreq_avail = false;
8899
8900         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8901         if (!crtc_state->has_pch_encoder)
8902                 return 0;
8903
8904         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8905                 if (intel_panel_use_ssc(dev_priv)) {
8906                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8907                                       dev_priv->vbt.lvds_ssc_freq);
8908                         refclk = dev_priv->vbt.lvds_ssc_freq;
8909                 }
8910
8911                 if (intel_is_dual_link_lvds(dev)) {
8912                         if (refclk == 100000)
8913                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8914                         else
8915                                 limit = &intel_limits_ironlake_dual_lvds;
8916                 } else {
8917                         if (refclk == 100000)
8918                                 limit = &intel_limits_ironlake_single_lvds_100m;
8919                         else
8920                                 limit = &intel_limits_ironlake_single_lvds;
8921                 }
8922         } else {
8923                 limit = &intel_limits_ironlake_dac;
8924         }
8925
8926         if (!crtc_state->clock_set &&
8927             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8928                                 refclk, NULL, &crtc_state->dpll)) {
8929                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8930                 return -EINVAL;
8931         }
8932
8933         ironlake_compute_dpll(crtc, crtc_state,
8934                               has_reduced_clock ? &reduced_clock : NULL);
8935
8936         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8937         if (pll == NULL) {
8938                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8939                                  pipe_name(crtc->pipe));
8940                 return -EINVAL;
8941         }
8942
8943         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8944             has_reduced_clock)
8945                 crtc->lowfreq_avail = true;
8946
8947         return 0;
8948 }
8949
8950 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8951                                          struct intel_link_m_n *m_n)
8952 {
8953         struct drm_device *dev = crtc->base.dev;
8954         struct drm_i915_private *dev_priv = dev->dev_private;
8955         enum pipe pipe = crtc->pipe;
8956
8957         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8958         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8959         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8960                 & ~TU_SIZE_MASK;
8961         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8962         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8963                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8964 }
8965
8966 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8967                                          enum transcoder transcoder,
8968                                          struct intel_link_m_n *m_n,
8969                                          struct intel_link_m_n *m2_n2)
8970 {
8971         struct drm_device *dev = crtc->base.dev;
8972         struct drm_i915_private *dev_priv = dev->dev_private;
8973         enum pipe pipe = crtc->pipe;
8974
8975         if (INTEL_INFO(dev)->gen >= 5) {
8976                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8977                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8978                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8979                         & ~TU_SIZE_MASK;
8980                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8981                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8982                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8983                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8984                  * gen < 8) and if DRRS is supported (to make sure the
8985                  * registers are not unnecessarily read).
8986                  */
8987                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8988                         crtc->config->has_drrs) {
8989                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8990                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8991                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8992                                         & ~TU_SIZE_MASK;
8993                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8994                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8995                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8996                 }
8997         } else {
8998                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8999                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9000                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9001                         & ~TU_SIZE_MASK;
9002                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9003                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9004                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9005         }
9006 }
9007
9008 void intel_dp_get_m_n(struct intel_crtc *crtc,
9009                       struct intel_crtc_state *pipe_config)
9010 {
9011         if (pipe_config->has_pch_encoder)
9012                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9013         else
9014                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9015                                              &pipe_config->dp_m_n,
9016                                              &pipe_config->dp_m2_n2);
9017 }
9018
9019 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9020                                         struct intel_crtc_state *pipe_config)
9021 {
9022         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9023                                      &pipe_config->fdi_m_n, NULL);
9024 }
9025
9026 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9027                                     struct intel_crtc_state *pipe_config)
9028 {
9029         struct drm_device *dev = crtc->base.dev;
9030         struct drm_i915_private *dev_priv = dev->dev_private;
9031         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9032         uint32_t ps_ctrl = 0;
9033         int id = -1;
9034         int i;
9035
9036         /* find scaler attached to this pipe */
9037         for (i = 0; i < crtc->num_scalers; i++) {
9038                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9039                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9040                         id = i;
9041                         pipe_config->pch_pfit.enabled = true;
9042                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9043                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9044                         break;
9045                 }
9046         }
9047
9048         scaler_state->scaler_id = id;
9049         if (id >= 0) {
9050                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9051         } else {
9052                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9053         }
9054 }
9055
9056 static void
9057 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9058                                  struct intel_initial_plane_config *plane_config)
9059 {
9060         struct drm_device *dev = crtc->base.dev;
9061         struct drm_i915_private *dev_priv = dev->dev_private;
9062         u32 val, base, offset, stride_mult, tiling;
9063         int pipe = crtc->pipe;
9064         int fourcc, pixel_format;
9065         unsigned int aligned_height;
9066         struct drm_framebuffer *fb;
9067         struct intel_framebuffer *intel_fb;
9068
9069         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9070         if (!intel_fb) {
9071                 DRM_DEBUG_KMS("failed to alloc fb\n");
9072                 return;
9073         }
9074
9075         fb = &intel_fb->base;
9076
9077         val = I915_READ(PLANE_CTL(pipe, 0));
9078         if (!(val & PLANE_CTL_ENABLE))
9079                 goto error;
9080
9081         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9082         fourcc = skl_format_to_fourcc(pixel_format,
9083                                       val & PLANE_CTL_ORDER_RGBX,
9084                                       val & PLANE_CTL_ALPHA_MASK);
9085         fb->pixel_format = fourcc;
9086         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9087
9088         tiling = val & PLANE_CTL_TILED_MASK;
9089         switch (tiling) {
9090         case PLANE_CTL_TILED_LINEAR:
9091                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9092                 break;
9093         case PLANE_CTL_TILED_X:
9094                 plane_config->tiling = I915_TILING_X;
9095                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9096                 break;
9097         case PLANE_CTL_TILED_Y:
9098                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9099                 break;
9100         case PLANE_CTL_TILED_YF:
9101                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9102                 break;
9103         default:
9104                 MISSING_CASE(tiling);
9105                 goto error;
9106         }
9107
9108         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9109         plane_config->base = base;
9110
9111         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9112
9113         val = I915_READ(PLANE_SIZE(pipe, 0));
9114         fb->height = ((val >> 16) & 0xfff) + 1;
9115         fb->width = ((val >> 0) & 0x1fff) + 1;
9116
9117         val = I915_READ(PLANE_STRIDE(pipe, 0));
9118         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9119                                                 fb->pixel_format);
9120         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9121
9122         aligned_height = intel_fb_align_height(dev, fb->height,
9123                                                fb->pixel_format,
9124                                                fb->modifier[0]);
9125
9126         plane_config->size = fb->pitches[0] * aligned_height;
9127
9128         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9129                       pipe_name(pipe), fb->width, fb->height,
9130                       fb->bits_per_pixel, base, fb->pitches[0],
9131                       plane_config->size);
9132
9133         plane_config->fb = intel_fb;
9134         return;
9135
9136 error:
9137         kfree(fb);
9138 }
9139
9140 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9141                                      struct intel_crtc_state *pipe_config)
9142 {
9143         struct drm_device *dev = crtc->base.dev;
9144         struct drm_i915_private *dev_priv = dev->dev_private;
9145         uint32_t tmp;
9146
9147         tmp = I915_READ(PF_CTL(crtc->pipe));
9148
9149         if (tmp & PF_ENABLE) {
9150                 pipe_config->pch_pfit.enabled = true;
9151                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9152                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9153
9154                 /* We currently do not free assignements of panel fitters on
9155                  * ivb/hsw (since we don't use the higher upscaling modes which
9156                  * differentiates them) so just WARN about this case for now. */
9157                 if (IS_GEN7(dev)) {
9158                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9159                                 PF_PIPE_SEL_IVB(crtc->pipe));
9160                 }
9161         }
9162 }
9163
9164 static void
9165 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9166                                   struct intel_initial_plane_config *plane_config)
9167 {
9168         struct drm_device *dev = crtc->base.dev;
9169         struct drm_i915_private *dev_priv = dev->dev_private;
9170         u32 val, base, offset;
9171         int pipe = crtc->pipe;
9172         int fourcc, pixel_format;
9173         unsigned int aligned_height;
9174         struct drm_framebuffer *fb;
9175         struct intel_framebuffer *intel_fb;
9176
9177         val = I915_READ(DSPCNTR(pipe));
9178         if (!(val & DISPLAY_PLANE_ENABLE))
9179                 return;
9180
9181         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9182         if (!intel_fb) {
9183                 DRM_DEBUG_KMS("failed to alloc fb\n");
9184                 return;
9185         }
9186
9187         fb = &intel_fb->base;
9188
9189         if (INTEL_INFO(dev)->gen >= 4) {
9190                 if (val & DISPPLANE_TILED) {
9191                         plane_config->tiling = I915_TILING_X;
9192                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9193                 }
9194         }
9195
9196         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9197         fourcc = i9xx_format_to_fourcc(pixel_format);
9198         fb->pixel_format = fourcc;
9199         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9200
9201         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9202         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9203                 offset = I915_READ(DSPOFFSET(pipe));
9204         } else {
9205                 if (plane_config->tiling)
9206                         offset = I915_READ(DSPTILEOFF(pipe));
9207                 else
9208                         offset = I915_READ(DSPLINOFF(pipe));
9209         }
9210         plane_config->base = base;
9211
9212         val = I915_READ(PIPESRC(pipe));
9213         fb->width = ((val >> 16) & 0xfff) + 1;
9214         fb->height = ((val >> 0) & 0xfff) + 1;
9215
9216         val = I915_READ(DSPSTRIDE(pipe));
9217         fb->pitches[0] = val & 0xffffffc0;
9218
9219         aligned_height = intel_fb_align_height(dev, fb->height,
9220                                                fb->pixel_format,
9221                                                fb->modifier[0]);
9222
9223         plane_config->size = fb->pitches[0] * aligned_height;
9224
9225         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9226                       pipe_name(pipe), fb->width, fb->height,
9227                       fb->bits_per_pixel, base, fb->pitches[0],
9228                       plane_config->size);
9229
9230         plane_config->fb = intel_fb;
9231 }
9232
9233 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9234                                      struct intel_crtc_state *pipe_config)
9235 {
9236         struct drm_device *dev = crtc->base.dev;
9237         struct drm_i915_private *dev_priv = dev->dev_private;
9238         enum intel_display_power_domain power_domain;
9239         uint32_t tmp;
9240         bool ret;
9241
9242         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9243         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9244                 return false;
9245
9246         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9247         pipe_config->shared_dpll = NULL;
9248
9249         ret = false;
9250         tmp = I915_READ(PIPECONF(crtc->pipe));
9251         if (!(tmp & PIPECONF_ENABLE))
9252                 goto out;
9253
9254         switch (tmp & PIPECONF_BPC_MASK) {
9255         case PIPECONF_6BPC:
9256                 pipe_config->pipe_bpp = 18;
9257                 break;
9258         case PIPECONF_8BPC:
9259                 pipe_config->pipe_bpp = 24;
9260                 break;
9261         case PIPECONF_10BPC:
9262                 pipe_config->pipe_bpp = 30;
9263                 break;
9264         case PIPECONF_12BPC:
9265                 pipe_config->pipe_bpp = 36;
9266                 break;
9267         default:
9268                 break;
9269         }
9270
9271         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9272                 pipe_config->limited_color_range = true;
9273
9274         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9275                 struct intel_shared_dpll *pll;
9276                 enum intel_dpll_id pll_id;
9277
9278                 pipe_config->has_pch_encoder = true;
9279
9280                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9281                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9282                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9283
9284                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9285
9286                 if (HAS_PCH_IBX(dev_priv)) {
9287                         /*
9288                          * The pipe->pch transcoder and pch transcoder->pll
9289                          * mapping is fixed.
9290                          */
9291                         pll_id = (enum intel_dpll_id) crtc->pipe;
9292                 } else {
9293                         tmp = I915_READ(PCH_DPLL_SEL);
9294                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9295                                 pll_id = DPLL_ID_PCH_PLL_B;
9296                         else
9297                                 pll_id= DPLL_ID_PCH_PLL_A;
9298                 }
9299
9300                 pipe_config->shared_dpll =
9301                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9302                 pll = pipe_config->shared_dpll;
9303
9304                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9305                                                  &pipe_config->dpll_hw_state));
9306
9307                 tmp = pipe_config->dpll_hw_state.dpll;
9308                 pipe_config->pixel_multiplier =
9309                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9310                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9311
9312                 ironlake_pch_clock_get(crtc, pipe_config);
9313         } else {
9314                 pipe_config->pixel_multiplier = 1;
9315         }
9316
9317         intel_get_pipe_timings(crtc, pipe_config);
9318         intel_get_pipe_src_size(crtc, pipe_config);
9319
9320         ironlake_get_pfit_config(crtc, pipe_config);
9321
9322         ret = true;
9323
9324 out:
9325         intel_display_power_put(dev_priv, power_domain);
9326
9327         return ret;
9328 }
9329
9330 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9331 {
9332         struct drm_device *dev = dev_priv->dev;
9333         struct intel_crtc *crtc;
9334
9335         for_each_intel_crtc(dev, crtc)
9336                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9337                      pipe_name(crtc->pipe));
9338
9339         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9340         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9341         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9342         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9343         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9344         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9345              "CPU PWM1 enabled\n");
9346         if (IS_HASWELL(dev))
9347                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9348                      "CPU PWM2 enabled\n");
9349         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9350              "PCH PWM1 enabled\n");
9351         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9352              "Utility pin enabled\n");
9353         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9354
9355         /*
9356          * In theory we can still leave IRQs enabled, as long as only the HPD
9357          * interrupts remain enabled. We used to check for that, but since it's
9358          * gen-specific and since we only disable LCPLL after we fully disable
9359          * the interrupts, the check below should be enough.
9360          */
9361         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9362 }
9363
9364 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9365 {
9366         struct drm_device *dev = dev_priv->dev;
9367
9368         if (IS_HASWELL(dev))
9369                 return I915_READ(D_COMP_HSW);
9370         else
9371                 return I915_READ(D_COMP_BDW);
9372 }
9373
9374 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9375 {
9376         struct drm_device *dev = dev_priv->dev;
9377
9378         if (IS_HASWELL(dev)) {
9379                 mutex_lock(&dev_priv->rps.hw_lock);
9380                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9381                                             val))
9382                         DRM_ERROR("Failed to write to D_COMP\n");
9383                 mutex_unlock(&dev_priv->rps.hw_lock);
9384         } else {
9385                 I915_WRITE(D_COMP_BDW, val);
9386                 POSTING_READ(D_COMP_BDW);
9387         }
9388 }
9389
9390 /*
9391  * This function implements pieces of two sequences from BSpec:
9392  * - Sequence for display software to disable LCPLL
9393  * - Sequence for display software to allow package C8+
9394  * The steps implemented here are just the steps that actually touch the LCPLL
9395  * register. Callers should take care of disabling all the display engine
9396  * functions, doing the mode unset, fixing interrupts, etc.
9397  */
9398 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9399                               bool switch_to_fclk, bool allow_power_down)
9400 {
9401         uint32_t val;
9402
9403         assert_can_disable_lcpll(dev_priv);
9404
9405         val = I915_READ(LCPLL_CTL);
9406
9407         if (switch_to_fclk) {
9408                 val |= LCPLL_CD_SOURCE_FCLK;
9409                 I915_WRITE(LCPLL_CTL, val);
9410
9411                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9412                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9413                         DRM_ERROR("Switching to FCLK failed\n");
9414
9415                 val = I915_READ(LCPLL_CTL);
9416         }
9417
9418         val |= LCPLL_PLL_DISABLE;
9419         I915_WRITE(LCPLL_CTL, val);
9420         POSTING_READ(LCPLL_CTL);
9421
9422         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9423                 DRM_ERROR("LCPLL still locked\n");
9424
9425         val = hsw_read_dcomp(dev_priv);
9426         val |= D_COMP_COMP_DISABLE;
9427         hsw_write_dcomp(dev_priv, val);
9428         ndelay(100);
9429
9430         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9431                      1))
9432                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9433
9434         if (allow_power_down) {
9435                 val = I915_READ(LCPLL_CTL);
9436                 val |= LCPLL_POWER_DOWN_ALLOW;
9437                 I915_WRITE(LCPLL_CTL, val);
9438                 POSTING_READ(LCPLL_CTL);
9439         }
9440 }
9441
9442 /*
9443  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9444  * source.
9445  */
9446 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9447 {
9448         uint32_t val;
9449
9450         val = I915_READ(LCPLL_CTL);
9451
9452         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9453                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9454                 return;
9455
9456         /*
9457          * Make sure we're not on PC8 state before disabling PC8, otherwise
9458          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9459          */
9460         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9461
9462         if (val & LCPLL_POWER_DOWN_ALLOW) {
9463                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9464                 I915_WRITE(LCPLL_CTL, val);
9465                 POSTING_READ(LCPLL_CTL);
9466         }
9467
9468         val = hsw_read_dcomp(dev_priv);
9469         val |= D_COMP_COMP_FORCE;
9470         val &= ~D_COMP_COMP_DISABLE;
9471         hsw_write_dcomp(dev_priv, val);
9472
9473         val = I915_READ(LCPLL_CTL);
9474         val &= ~LCPLL_PLL_DISABLE;
9475         I915_WRITE(LCPLL_CTL, val);
9476
9477         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9478                 DRM_ERROR("LCPLL not locked yet\n");
9479
9480         if (val & LCPLL_CD_SOURCE_FCLK) {
9481                 val = I915_READ(LCPLL_CTL);
9482                 val &= ~LCPLL_CD_SOURCE_FCLK;
9483                 I915_WRITE(LCPLL_CTL, val);
9484
9485                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9486                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9487                         DRM_ERROR("Switching back to LCPLL failed\n");
9488         }
9489
9490         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9491         intel_update_cdclk(dev_priv->dev);
9492 }
9493
9494 /*
9495  * Package states C8 and deeper are really deep PC states that can only be
9496  * reached when all the devices on the system allow it, so even if the graphics
9497  * device allows PC8+, it doesn't mean the system will actually get to these
9498  * states. Our driver only allows PC8+ when going into runtime PM.
9499  *
9500  * The requirements for PC8+ are that all the outputs are disabled, the power
9501  * well is disabled and most interrupts are disabled, and these are also
9502  * requirements for runtime PM. When these conditions are met, we manually do
9503  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9504  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9505  * hang the machine.
9506  *
9507  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9508  * the state of some registers, so when we come back from PC8+ we need to
9509  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9510  * need to take care of the registers kept by RC6. Notice that this happens even
9511  * if we don't put the device in PCI D3 state (which is what currently happens
9512  * because of the runtime PM support).
9513  *
9514  * For more, read "Display Sequences for Package C8" on the hardware
9515  * documentation.
9516  */
9517 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9518 {
9519         struct drm_device *dev = dev_priv->dev;
9520         uint32_t val;
9521
9522         DRM_DEBUG_KMS("Enabling package C8+\n");
9523
9524         if (HAS_PCH_LPT_LP(dev)) {
9525                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9526                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9527                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9528         }
9529
9530         lpt_disable_clkout_dp(dev);
9531         hsw_disable_lcpll(dev_priv, true, true);
9532 }
9533
9534 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9535 {
9536         struct drm_device *dev = dev_priv->dev;
9537         uint32_t val;
9538
9539         DRM_DEBUG_KMS("Disabling package C8+\n");
9540
9541         hsw_restore_lcpll(dev_priv);
9542         lpt_init_pch_refclk(dev);
9543
9544         if (HAS_PCH_LPT_LP(dev)) {
9545                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9546                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9547                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9548         }
9549 }
9550
9551 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9552 {
9553         struct drm_device *dev = old_state->dev;
9554         struct intel_atomic_state *old_intel_state =
9555                 to_intel_atomic_state(old_state);
9556         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9557
9558         broxton_set_cdclk(to_i915(dev), req_cdclk);
9559 }
9560
9561 /* compute the max rate for new configuration */
9562 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9563 {
9564         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9565         struct drm_i915_private *dev_priv = state->dev->dev_private;
9566         struct drm_crtc *crtc;
9567         struct drm_crtc_state *cstate;
9568         struct intel_crtc_state *crtc_state;
9569         unsigned max_pixel_rate = 0, i;
9570         enum pipe pipe;
9571
9572         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9573                sizeof(intel_state->min_pixclk));
9574
9575         for_each_crtc_in_state(state, crtc, cstate, i) {
9576                 int pixel_rate;
9577
9578                 crtc_state = to_intel_crtc_state(cstate);
9579                 if (!crtc_state->base.enable) {
9580                         intel_state->min_pixclk[i] = 0;
9581                         continue;
9582                 }
9583
9584                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9585
9586                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9587                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9588                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9589
9590                 intel_state->min_pixclk[i] = pixel_rate;
9591         }
9592
9593         for_each_pipe(dev_priv, pipe)
9594                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9595
9596         return max_pixel_rate;
9597 }
9598
9599 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9600 {
9601         struct drm_i915_private *dev_priv = dev->dev_private;
9602         uint32_t val, data;
9603         int ret;
9604
9605         if (WARN((I915_READ(LCPLL_CTL) &
9606                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9607                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9608                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9609                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9610                  "trying to change cdclk frequency with cdclk not enabled\n"))
9611                 return;
9612
9613         mutex_lock(&dev_priv->rps.hw_lock);
9614         ret = sandybridge_pcode_write(dev_priv,
9615                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9616         mutex_unlock(&dev_priv->rps.hw_lock);
9617         if (ret) {
9618                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9619                 return;
9620         }
9621
9622         val = I915_READ(LCPLL_CTL);
9623         val |= LCPLL_CD_SOURCE_FCLK;
9624         I915_WRITE(LCPLL_CTL, val);
9625
9626         if (wait_for_us(I915_READ(LCPLL_CTL) &
9627                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9628                 DRM_ERROR("Switching to FCLK failed\n");
9629
9630         val = I915_READ(LCPLL_CTL);
9631         val &= ~LCPLL_CLK_FREQ_MASK;
9632
9633         switch (cdclk) {
9634         case 450000:
9635                 val |= LCPLL_CLK_FREQ_450;
9636                 data = 0;
9637                 break;
9638         case 540000:
9639                 val |= LCPLL_CLK_FREQ_54O_BDW;
9640                 data = 1;
9641                 break;
9642         case 337500:
9643                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9644                 data = 2;
9645                 break;
9646         case 675000:
9647                 val |= LCPLL_CLK_FREQ_675_BDW;
9648                 data = 3;
9649                 break;
9650         default:
9651                 WARN(1, "invalid cdclk frequency\n");
9652                 return;
9653         }
9654
9655         I915_WRITE(LCPLL_CTL, val);
9656
9657         val = I915_READ(LCPLL_CTL);
9658         val &= ~LCPLL_CD_SOURCE_FCLK;
9659         I915_WRITE(LCPLL_CTL, val);
9660
9661         if (wait_for_us((I915_READ(LCPLL_CTL) &
9662                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9663                 DRM_ERROR("Switching back to LCPLL failed\n");
9664
9665         mutex_lock(&dev_priv->rps.hw_lock);
9666         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9667         mutex_unlock(&dev_priv->rps.hw_lock);
9668
9669         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9670
9671         intel_update_cdclk(dev);
9672
9673         WARN(cdclk != dev_priv->cdclk_freq,
9674              "cdclk requested %d kHz but got %d kHz\n",
9675              cdclk, dev_priv->cdclk_freq);
9676 }
9677
9678 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9679 {
9680         struct drm_i915_private *dev_priv = to_i915(state->dev);
9681         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9682         int max_pixclk = ilk_max_pixel_rate(state);
9683         int cdclk;
9684
9685         /*
9686          * FIXME should also account for plane ratio
9687          * once 64bpp pixel formats are supported.
9688          */
9689         if (max_pixclk > 540000)
9690                 cdclk = 675000;
9691         else if (max_pixclk > 450000)
9692                 cdclk = 540000;
9693         else if (max_pixclk > 337500)
9694                 cdclk = 450000;
9695         else
9696                 cdclk = 337500;
9697
9698         if (cdclk > dev_priv->max_cdclk_freq) {
9699                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9700                               cdclk, dev_priv->max_cdclk_freq);
9701                 return -EINVAL;
9702         }
9703
9704         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9705         if (!intel_state->active_crtcs)
9706                 intel_state->dev_cdclk = 337500;
9707
9708         return 0;
9709 }
9710
9711 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9712 {
9713         struct drm_device *dev = old_state->dev;
9714         struct intel_atomic_state *old_intel_state =
9715                 to_intel_atomic_state(old_state);
9716         unsigned req_cdclk = old_intel_state->dev_cdclk;
9717
9718         broadwell_set_cdclk(dev, req_cdclk);
9719 }
9720
9721 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9722                                       struct intel_crtc_state *crtc_state)
9723 {
9724         struct intel_encoder *intel_encoder =
9725                 intel_ddi_get_crtc_new_encoder(crtc_state);
9726
9727         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9728                 if (!intel_ddi_pll_select(crtc, crtc_state))
9729                         return -EINVAL;
9730         }
9731
9732         crtc->lowfreq_avail = false;
9733
9734         return 0;
9735 }
9736
9737 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9738                                 enum port port,
9739                                 struct intel_crtc_state *pipe_config)
9740 {
9741         enum intel_dpll_id id;
9742
9743         switch (port) {
9744         case PORT_A:
9745                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9746                 id = DPLL_ID_SKL_DPLL0;
9747                 break;
9748         case PORT_B:
9749                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9750                 id = DPLL_ID_SKL_DPLL1;
9751                 break;
9752         case PORT_C:
9753                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9754                 id = DPLL_ID_SKL_DPLL2;
9755                 break;
9756         default:
9757                 DRM_ERROR("Incorrect port type\n");
9758                 return;
9759         }
9760
9761         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9762 }
9763
9764 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9765                                 enum port port,
9766                                 struct intel_crtc_state *pipe_config)
9767 {
9768         enum intel_dpll_id id;
9769         u32 temp;
9770
9771         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9772         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9773
9774         switch (pipe_config->ddi_pll_sel) {
9775         case SKL_DPLL0:
9776                 id = DPLL_ID_SKL_DPLL0;
9777                 break;
9778         case SKL_DPLL1:
9779                 id = DPLL_ID_SKL_DPLL1;
9780                 break;
9781         case SKL_DPLL2:
9782                 id = DPLL_ID_SKL_DPLL2;
9783                 break;
9784         case SKL_DPLL3:
9785                 id = DPLL_ID_SKL_DPLL3;
9786                 break;
9787         default:
9788                 MISSING_CASE(pipe_config->ddi_pll_sel);
9789                 return;
9790         }
9791
9792         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9793 }
9794
9795 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9796                                 enum port port,
9797                                 struct intel_crtc_state *pipe_config)
9798 {
9799         enum intel_dpll_id id;
9800
9801         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9802
9803         switch (pipe_config->ddi_pll_sel) {
9804         case PORT_CLK_SEL_WRPLL1:
9805                 id = DPLL_ID_WRPLL1;
9806                 break;
9807         case PORT_CLK_SEL_WRPLL2:
9808                 id = DPLL_ID_WRPLL2;
9809                 break;
9810         case PORT_CLK_SEL_SPLL:
9811                 id = DPLL_ID_SPLL;
9812                 break;
9813         case PORT_CLK_SEL_LCPLL_810:
9814                 id = DPLL_ID_LCPLL_810;
9815                 break;
9816         case PORT_CLK_SEL_LCPLL_1350:
9817                 id = DPLL_ID_LCPLL_1350;
9818                 break;
9819         case PORT_CLK_SEL_LCPLL_2700:
9820                 id = DPLL_ID_LCPLL_2700;
9821                 break;
9822         default:
9823                 MISSING_CASE(pipe_config->ddi_pll_sel);
9824                 /* fall through */
9825         case PORT_CLK_SEL_NONE:
9826                 return;
9827         }
9828
9829         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9830 }
9831
9832 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9833                                      struct intel_crtc_state *pipe_config,
9834                                      unsigned long *power_domain_mask)
9835 {
9836         struct drm_device *dev = crtc->base.dev;
9837         struct drm_i915_private *dev_priv = dev->dev_private;
9838         enum intel_display_power_domain power_domain;
9839         u32 tmp;
9840
9841         /*
9842          * The pipe->transcoder mapping is fixed with the exception of the eDP
9843          * transcoder handled below.
9844          */
9845         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9846
9847         /*
9848          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9849          * consistency and less surprising code; it's in always on power).
9850          */
9851         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9852         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9853                 enum pipe trans_edp_pipe;
9854                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9855                 default:
9856                         WARN(1, "unknown pipe linked to edp transcoder\n");
9857                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9858                 case TRANS_DDI_EDP_INPUT_A_ON:
9859                         trans_edp_pipe = PIPE_A;
9860                         break;
9861                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9862                         trans_edp_pipe = PIPE_B;
9863                         break;
9864                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9865                         trans_edp_pipe = PIPE_C;
9866                         break;
9867                 }
9868
9869                 if (trans_edp_pipe == crtc->pipe)
9870                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9871         }
9872
9873         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9874         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9875                 return false;
9876         *power_domain_mask |= BIT(power_domain);
9877
9878         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9879
9880         return tmp & PIPECONF_ENABLE;
9881 }
9882
9883 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9884                                          struct intel_crtc_state *pipe_config,
9885                                          unsigned long *power_domain_mask)
9886 {
9887         struct drm_device *dev = crtc->base.dev;
9888         struct drm_i915_private *dev_priv = dev->dev_private;
9889         enum intel_display_power_domain power_domain;
9890         enum port port;
9891         enum transcoder cpu_transcoder;
9892         u32 tmp;
9893
9894         pipe_config->has_dsi_encoder = false;
9895
9896         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9897                 if (port == PORT_A)
9898                         cpu_transcoder = TRANSCODER_DSI_A;
9899                 else
9900                         cpu_transcoder = TRANSCODER_DSI_C;
9901
9902                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9903                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9904                         continue;
9905                 *power_domain_mask |= BIT(power_domain);
9906
9907                 /*
9908                  * The PLL needs to be enabled with a valid divider
9909                  * configuration, otherwise accessing DSI registers will hang
9910                  * the machine. See BSpec North Display Engine
9911                  * registers/MIPI[BXT]. We can break out here early, since we
9912                  * need the same DSI PLL to be enabled for both DSI ports.
9913                  */
9914                 if (!intel_dsi_pll_is_enabled(dev_priv))
9915                         break;
9916
9917                 /* XXX: this works for video mode only */
9918                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9919                 if (!(tmp & DPI_ENABLE))
9920                         continue;
9921
9922                 tmp = I915_READ(MIPI_CTRL(port));
9923                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9924                         continue;
9925
9926                 pipe_config->cpu_transcoder = cpu_transcoder;
9927                 pipe_config->has_dsi_encoder = true;
9928                 break;
9929         }
9930
9931         return pipe_config->has_dsi_encoder;
9932 }
9933
9934 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9935                                        struct intel_crtc_state *pipe_config)
9936 {
9937         struct drm_device *dev = crtc->base.dev;
9938         struct drm_i915_private *dev_priv = dev->dev_private;
9939         struct intel_shared_dpll *pll;
9940         enum port port;
9941         uint32_t tmp;
9942
9943         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9944
9945         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9946
9947         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9948                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9949         else if (IS_BROXTON(dev))
9950                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9951         else
9952                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9953
9954         pll = pipe_config->shared_dpll;
9955         if (pll) {
9956                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9957                                                  &pipe_config->dpll_hw_state));
9958         }
9959
9960         /*
9961          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9962          * DDI E. So just check whether this pipe is wired to DDI E and whether
9963          * the PCH transcoder is on.
9964          */
9965         if (INTEL_INFO(dev)->gen < 9 &&
9966             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9967                 pipe_config->has_pch_encoder = true;
9968
9969                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9970                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9971                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9972
9973                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9974         }
9975 }
9976
9977 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9978                                     struct intel_crtc_state *pipe_config)
9979 {
9980         struct drm_device *dev = crtc->base.dev;
9981         struct drm_i915_private *dev_priv = dev->dev_private;
9982         enum intel_display_power_domain power_domain;
9983         unsigned long power_domain_mask;
9984         bool active;
9985
9986         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9987         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9988                 return false;
9989         power_domain_mask = BIT(power_domain);
9990
9991         pipe_config->shared_dpll = NULL;
9992
9993         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9994
9995         if (IS_BROXTON(dev_priv)) {
9996                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
9997                                              &power_domain_mask);
9998                 WARN_ON(active && pipe_config->has_dsi_encoder);
9999                 if (pipe_config->has_dsi_encoder)
10000                         active = true;
10001         }
10002
10003         if (!active)
10004                 goto out;
10005
10006         if (!pipe_config->has_dsi_encoder) {
10007                 haswell_get_ddi_port_state(crtc, pipe_config);
10008                 intel_get_pipe_timings(crtc, pipe_config);
10009         }
10010
10011         intel_get_pipe_src_size(crtc, pipe_config);
10012
10013         pipe_config->gamma_mode =
10014                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10015
10016         if (INTEL_INFO(dev)->gen >= 9) {
10017                 skl_init_scalers(dev, crtc, pipe_config);
10018         }
10019
10020         if (INTEL_INFO(dev)->gen >= 9) {
10021                 pipe_config->scaler_state.scaler_id = -1;
10022                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10023         }
10024
10025         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10026         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10027                 power_domain_mask |= BIT(power_domain);
10028                 if (INTEL_INFO(dev)->gen >= 9)
10029                         skylake_get_pfit_config(crtc, pipe_config);
10030                 else
10031                         ironlake_get_pfit_config(crtc, pipe_config);
10032         }
10033
10034         if (IS_HASWELL(dev))
10035                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10036                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10037
10038         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10039             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10040                 pipe_config->pixel_multiplier =
10041                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10042         } else {
10043                 pipe_config->pixel_multiplier = 1;
10044         }
10045
10046 out:
10047         for_each_power_domain(power_domain, power_domain_mask)
10048                 intel_display_power_put(dev_priv, power_domain);
10049
10050         return active;
10051 }
10052
10053 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10054                                const struct intel_plane_state *plane_state)
10055 {
10056         struct drm_device *dev = crtc->dev;
10057         struct drm_i915_private *dev_priv = dev->dev_private;
10058         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10059         uint32_t cntl = 0, size = 0;
10060
10061         if (plane_state && plane_state->visible) {
10062                 unsigned int width = plane_state->base.crtc_w;
10063                 unsigned int height = plane_state->base.crtc_h;
10064                 unsigned int stride = roundup_pow_of_two(width) * 4;
10065
10066                 switch (stride) {
10067                 default:
10068                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10069                                   width, stride);
10070                         stride = 256;
10071                         /* fallthrough */
10072                 case 256:
10073                 case 512:
10074                 case 1024:
10075                 case 2048:
10076                         break;
10077                 }
10078
10079                 cntl |= CURSOR_ENABLE |
10080                         CURSOR_GAMMA_ENABLE |
10081                         CURSOR_FORMAT_ARGB |
10082                         CURSOR_STRIDE(stride);
10083
10084                 size = (height << 12) | width;
10085         }
10086
10087         if (intel_crtc->cursor_cntl != 0 &&
10088             (intel_crtc->cursor_base != base ||
10089              intel_crtc->cursor_size != size ||
10090              intel_crtc->cursor_cntl != cntl)) {
10091                 /* On these chipsets we can only modify the base/size/stride
10092                  * whilst the cursor is disabled.
10093                  */
10094                 I915_WRITE(CURCNTR(PIPE_A), 0);
10095                 POSTING_READ(CURCNTR(PIPE_A));
10096                 intel_crtc->cursor_cntl = 0;
10097         }
10098
10099         if (intel_crtc->cursor_base != base) {
10100                 I915_WRITE(CURBASE(PIPE_A), base);
10101                 intel_crtc->cursor_base = base;
10102         }
10103
10104         if (intel_crtc->cursor_size != size) {
10105                 I915_WRITE(CURSIZE, size);
10106                 intel_crtc->cursor_size = size;
10107         }
10108
10109         if (intel_crtc->cursor_cntl != cntl) {
10110                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10111                 POSTING_READ(CURCNTR(PIPE_A));
10112                 intel_crtc->cursor_cntl = cntl;
10113         }
10114 }
10115
10116 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10117                                const struct intel_plane_state *plane_state)
10118 {
10119         struct drm_device *dev = crtc->dev;
10120         struct drm_i915_private *dev_priv = dev->dev_private;
10121         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10122         int pipe = intel_crtc->pipe;
10123         uint32_t cntl = 0;
10124
10125         if (plane_state && plane_state->visible) {
10126                 cntl = MCURSOR_GAMMA_ENABLE;
10127                 switch (plane_state->base.crtc_w) {
10128                         case 64:
10129                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10130                                 break;
10131                         case 128:
10132                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10133                                 break;
10134                         case 256:
10135                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10136                                 break;
10137                         default:
10138                                 MISSING_CASE(plane_state->base.crtc_w);
10139                                 return;
10140                 }
10141                 cntl |= pipe << 28; /* Connect to correct pipe */
10142
10143                 if (HAS_DDI(dev))
10144                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10145
10146                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10147                         cntl |= CURSOR_ROTATE_180;
10148         }
10149
10150         if (intel_crtc->cursor_cntl != cntl) {
10151                 I915_WRITE(CURCNTR(pipe), cntl);
10152                 POSTING_READ(CURCNTR(pipe));
10153                 intel_crtc->cursor_cntl = cntl;
10154         }
10155
10156         /* and commit changes on next vblank */
10157         I915_WRITE(CURBASE(pipe), base);
10158         POSTING_READ(CURBASE(pipe));
10159
10160         intel_crtc->cursor_base = base;
10161 }
10162
10163 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10164 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10165                                      const struct intel_plane_state *plane_state)
10166 {
10167         struct drm_device *dev = crtc->dev;
10168         struct drm_i915_private *dev_priv = dev->dev_private;
10169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10170         int pipe = intel_crtc->pipe;
10171         u32 base = intel_crtc->cursor_addr;
10172         u32 pos = 0;
10173
10174         if (plane_state) {
10175                 int x = plane_state->base.crtc_x;
10176                 int y = plane_state->base.crtc_y;
10177
10178                 if (x < 0) {
10179                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10180                         x = -x;
10181                 }
10182                 pos |= x << CURSOR_X_SHIFT;
10183
10184                 if (y < 0) {
10185                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10186                         y = -y;
10187                 }
10188                 pos |= y << CURSOR_Y_SHIFT;
10189
10190                 /* ILK+ do this automagically */
10191                 if (HAS_GMCH_DISPLAY(dev) &&
10192                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10193                         base += (plane_state->base.crtc_h *
10194                                  plane_state->base.crtc_w - 1) * 4;
10195                 }
10196         }
10197
10198         I915_WRITE(CURPOS(pipe), pos);
10199
10200         if (IS_845G(dev) || IS_I865G(dev))
10201                 i845_update_cursor(crtc, base, plane_state);
10202         else
10203                 i9xx_update_cursor(crtc, base, plane_state);
10204 }
10205
10206 static bool cursor_size_ok(struct drm_device *dev,
10207                            uint32_t width, uint32_t height)
10208 {
10209         if (width == 0 || height == 0)
10210                 return false;
10211
10212         /*
10213          * 845g/865g are special in that they are only limited by
10214          * the width of their cursors, the height is arbitrary up to
10215          * the precision of the register. Everything else requires
10216          * square cursors, limited to a few power-of-two sizes.
10217          */
10218         if (IS_845G(dev) || IS_I865G(dev)) {
10219                 if ((width & 63) != 0)
10220                         return false;
10221
10222                 if (width > (IS_845G(dev) ? 64 : 512))
10223                         return false;
10224
10225                 if (height > 1023)
10226                         return false;
10227         } else {
10228                 switch (width | height) {
10229                 case 256:
10230                 case 128:
10231                         if (IS_GEN2(dev))
10232                                 return false;
10233                 case 64:
10234                         break;
10235                 default:
10236                         return false;
10237                 }
10238         }
10239
10240         return true;
10241 }
10242
10243 /* VESA 640x480x72Hz mode to set on the pipe */
10244 static struct drm_display_mode load_detect_mode = {
10245         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10246                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10247 };
10248
10249 struct drm_framebuffer *
10250 __intel_framebuffer_create(struct drm_device *dev,
10251                            struct drm_mode_fb_cmd2 *mode_cmd,
10252                            struct drm_i915_gem_object *obj)
10253 {
10254         struct intel_framebuffer *intel_fb;
10255         int ret;
10256
10257         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10258         if (!intel_fb)
10259                 return ERR_PTR(-ENOMEM);
10260
10261         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10262         if (ret)
10263                 goto err;
10264
10265         return &intel_fb->base;
10266
10267 err:
10268         kfree(intel_fb);
10269         return ERR_PTR(ret);
10270 }
10271
10272 static struct drm_framebuffer *
10273 intel_framebuffer_create(struct drm_device *dev,
10274                          struct drm_mode_fb_cmd2 *mode_cmd,
10275                          struct drm_i915_gem_object *obj)
10276 {
10277         struct drm_framebuffer *fb;
10278         int ret;
10279
10280         ret = i915_mutex_lock_interruptible(dev);
10281         if (ret)
10282                 return ERR_PTR(ret);
10283         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10284         mutex_unlock(&dev->struct_mutex);
10285
10286         return fb;
10287 }
10288
10289 static u32
10290 intel_framebuffer_pitch_for_width(int width, int bpp)
10291 {
10292         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10293         return ALIGN(pitch, 64);
10294 }
10295
10296 static u32
10297 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10298 {
10299         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10300         return PAGE_ALIGN(pitch * mode->vdisplay);
10301 }
10302
10303 static struct drm_framebuffer *
10304 intel_framebuffer_create_for_mode(struct drm_device *dev,
10305                                   struct drm_display_mode *mode,
10306                                   int depth, int bpp)
10307 {
10308         struct drm_framebuffer *fb;
10309         struct drm_i915_gem_object *obj;
10310         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10311
10312         obj = i915_gem_object_create(dev,
10313                                     intel_framebuffer_size_for_mode(mode, bpp));
10314         if (IS_ERR(obj))
10315                 return ERR_CAST(obj);
10316
10317         mode_cmd.width = mode->hdisplay;
10318         mode_cmd.height = mode->vdisplay;
10319         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10320                                                                 bpp);
10321         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10322
10323         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10324         if (IS_ERR(fb))
10325                 drm_gem_object_unreference_unlocked(&obj->base);
10326
10327         return fb;
10328 }
10329
10330 static struct drm_framebuffer *
10331 mode_fits_in_fbdev(struct drm_device *dev,
10332                    struct drm_display_mode *mode)
10333 {
10334 #ifdef CONFIG_DRM_FBDEV_EMULATION
10335         struct drm_i915_private *dev_priv = dev->dev_private;
10336         struct drm_i915_gem_object *obj;
10337         struct drm_framebuffer *fb;
10338
10339         if (!dev_priv->fbdev)
10340                 return NULL;
10341
10342         if (!dev_priv->fbdev->fb)
10343                 return NULL;
10344
10345         obj = dev_priv->fbdev->fb->obj;
10346         BUG_ON(!obj);
10347
10348         fb = &dev_priv->fbdev->fb->base;
10349         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10350                                                                fb->bits_per_pixel))
10351                 return NULL;
10352
10353         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10354                 return NULL;
10355
10356         drm_framebuffer_reference(fb);
10357         return fb;
10358 #else
10359         return NULL;
10360 #endif
10361 }
10362
10363 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10364                                            struct drm_crtc *crtc,
10365                                            struct drm_display_mode *mode,
10366                                            struct drm_framebuffer *fb,
10367                                            int x, int y)
10368 {
10369         struct drm_plane_state *plane_state;
10370         int hdisplay, vdisplay;
10371         int ret;
10372
10373         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10374         if (IS_ERR(plane_state))
10375                 return PTR_ERR(plane_state);
10376
10377         if (mode)
10378                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10379         else
10380                 hdisplay = vdisplay = 0;
10381
10382         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10383         if (ret)
10384                 return ret;
10385         drm_atomic_set_fb_for_plane(plane_state, fb);
10386         plane_state->crtc_x = 0;
10387         plane_state->crtc_y = 0;
10388         plane_state->crtc_w = hdisplay;
10389         plane_state->crtc_h = vdisplay;
10390         plane_state->src_x = x << 16;
10391         plane_state->src_y = y << 16;
10392         plane_state->src_w = hdisplay << 16;
10393         plane_state->src_h = vdisplay << 16;
10394
10395         return 0;
10396 }
10397
10398 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10399                                 struct drm_display_mode *mode,
10400                                 struct intel_load_detect_pipe *old,
10401                                 struct drm_modeset_acquire_ctx *ctx)
10402 {
10403         struct intel_crtc *intel_crtc;
10404         struct intel_encoder *intel_encoder =
10405                 intel_attached_encoder(connector);
10406         struct drm_crtc *possible_crtc;
10407         struct drm_encoder *encoder = &intel_encoder->base;
10408         struct drm_crtc *crtc = NULL;
10409         struct drm_device *dev = encoder->dev;
10410         struct drm_framebuffer *fb;
10411         struct drm_mode_config *config = &dev->mode_config;
10412         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10413         struct drm_connector_state *connector_state;
10414         struct intel_crtc_state *crtc_state;
10415         int ret, i = -1;
10416
10417         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10418                       connector->base.id, connector->name,
10419                       encoder->base.id, encoder->name);
10420
10421         old->restore_state = NULL;
10422
10423 retry:
10424         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10425         if (ret)
10426                 goto fail;
10427
10428         /*
10429          * Algorithm gets a little messy:
10430          *
10431          *   - if the connector already has an assigned crtc, use it (but make
10432          *     sure it's on first)
10433          *
10434          *   - try to find the first unused crtc that can drive this connector,
10435          *     and use that if we find one
10436          */
10437
10438         /* See if we already have a CRTC for this connector */
10439         if (connector->state->crtc) {
10440                 crtc = connector->state->crtc;
10441
10442                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10443                 if (ret)
10444                         goto fail;
10445
10446                 /* Make sure the crtc and connector are running */
10447                 goto found;
10448         }
10449
10450         /* Find an unused one (if possible) */
10451         for_each_crtc(dev, possible_crtc) {
10452                 i++;
10453                 if (!(encoder->possible_crtcs & (1 << i)))
10454                         continue;
10455
10456                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10457                 if (ret)
10458                         goto fail;
10459
10460                 if (possible_crtc->state->enable) {
10461                         drm_modeset_unlock(&possible_crtc->mutex);
10462                         continue;
10463                 }
10464
10465                 crtc = possible_crtc;
10466                 break;
10467         }
10468
10469         /*
10470          * If we didn't find an unused CRTC, don't use any.
10471          */
10472         if (!crtc) {
10473                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10474                 goto fail;
10475         }
10476
10477 found:
10478         intel_crtc = to_intel_crtc(crtc);
10479
10480         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10481         if (ret)
10482                 goto fail;
10483
10484         state = drm_atomic_state_alloc(dev);
10485         restore_state = drm_atomic_state_alloc(dev);
10486         if (!state || !restore_state) {
10487                 ret = -ENOMEM;
10488                 goto fail;
10489         }
10490
10491         state->acquire_ctx = ctx;
10492         restore_state->acquire_ctx = ctx;
10493
10494         connector_state = drm_atomic_get_connector_state(state, connector);
10495         if (IS_ERR(connector_state)) {
10496                 ret = PTR_ERR(connector_state);
10497                 goto fail;
10498         }
10499
10500         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10501         if (ret)
10502                 goto fail;
10503
10504         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10505         if (IS_ERR(crtc_state)) {
10506                 ret = PTR_ERR(crtc_state);
10507                 goto fail;
10508         }
10509
10510         crtc_state->base.active = crtc_state->base.enable = true;
10511
10512         if (!mode)
10513                 mode = &load_detect_mode;
10514
10515         /* We need a framebuffer large enough to accommodate all accesses
10516          * that the plane may generate whilst we perform load detection.
10517          * We can not rely on the fbcon either being present (we get called
10518          * during its initialisation to detect all boot displays, or it may
10519          * not even exist) or that it is large enough to satisfy the
10520          * requested mode.
10521          */
10522         fb = mode_fits_in_fbdev(dev, mode);
10523         if (fb == NULL) {
10524                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10525                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10526         } else
10527                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10528         if (IS_ERR(fb)) {
10529                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10530                 goto fail;
10531         }
10532
10533         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10534         if (ret)
10535                 goto fail;
10536
10537         drm_framebuffer_unreference(fb);
10538
10539         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10540         if (ret)
10541                 goto fail;
10542
10543         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10544         if (!ret)
10545                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10546         if (!ret)
10547                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10548         if (ret) {
10549                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10550                 goto fail;
10551         }
10552
10553         ret = drm_atomic_commit(state);
10554         if (ret) {
10555                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10556                 goto fail;
10557         }
10558
10559         old->restore_state = restore_state;
10560
10561         /* let the connector get through one full cycle before testing */
10562         intel_wait_for_vblank(dev, intel_crtc->pipe);
10563         return true;
10564
10565 fail:
10566         drm_atomic_state_free(state);
10567         drm_atomic_state_free(restore_state);
10568         restore_state = state = NULL;
10569
10570         if (ret == -EDEADLK) {
10571                 drm_modeset_backoff(ctx);
10572                 goto retry;
10573         }
10574
10575         return false;
10576 }
10577
10578 void intel_release_load_detect_pipe(struct drm_connector *connector,
10579                                     struct intel_load_detect_pipe *old,
10580                                     struct drm_modeset_acquire_ctx *ctx)
10581 {
10582         struct intel_encoder *intel_encoder =
10583                 intel_attached_encoder(connector);
10584         struct drm_encoder *encoder = &intel_encoder->base;
10585         struct drm_atomic_state *state = old->restore_state;
10586         int ret;
10587
10588         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10589                       connector->base.id, connector->name,
10590                       encoder->base.id, encoder->name);
10591
10592         if (!state)
10593                 return;
10594
10595         ret = drm_atomic_commit(state);
10596         if (ret) {
10597                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10598                 drm_atomic_state_free(state);
10599         }
10600 }
10601
10602 static int i9xx_pll_refclk(struct drm_device *dev,
10603                            const struct intel_crtc_state *pipe_config)
10604 {
10605         struct drm_i915_private *dev_priv = dev->dev_private;
10606         u32 dpll = pipe_config->dpll_hw_state.dpll;
10607
10608         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10609                 return dev_priv->vbt.lvds_ssc_freq;
10610         else if (HAS_PCH_SPLIT(dev))
10611                 return 120000;
10612         else if (!IS_GEN2(dev))
10613                 return 96000;
10614         else
10615                 return 48000;
10616 }
10617
10618 /* Returns the clock of the currently programmed mode of the given pipe. */
10619 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10620                                 struct intel_crtc_state *pipe_config)
10621 {
10622         struct drm_device *dev = crtc->base.dev;
10623         struct drm_i915_private *dev_priv = dev->dev_private;
10624         int pipe = pipe_config->cpu_transcoder;
10625         u32 dpll = pipe_config->dpll_hw_state.dpll;
10626         u32 fp;
10627         struct dpll clock;
10628         int port_clock;
10629         int refclk = i9xx_pll_refclk(dev, pipe_config);
10630
10631         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10632                 fp = pipe_config->dpll_hw_state.fp0;
10633         else
10634                 fp = pipe_config->dpll_hw_state.fp1;
10635
10636         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10637         if (IS_PINEVIEW(dev)) {
10638                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10639                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10640         } else {
10641                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10642                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10643         }
10644
10645         if (!IS_GEN2(dev)) {
10646                 if (IS_PINEVIEW(dev))
10647                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10648                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10649                 else
10650                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10651                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10652
10653                 switch (dpll & DPLL_MODE_MASK) {
10654                 case DPLLB_MODE_DAC_SERIAL:
10655                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10656                                 5 : 10;
10657                         break;
10658                 case DPLLB_MODE_LVDS:
10659                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10660                                 7 : 14;
10661                         break;
10662                 default:
10663                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10664                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10665                         return;
10666                 }
10667
10668                 if (IS_PINEVIEW(dev))
10669                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10670                 else
10671                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10672         } else {
10673                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10674                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10675
10676                 if (is_lvds) {
10677                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10678                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10679
10680                         if (lvds & LVDS_CLKB_POWER_UP)
10681                                 clock.p2 = 7;
10682                         else
10683                                 clock.p2 = 14;
10684                 } else {
10685                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10686                                 clock.p1 = 2;
10687                         else {
10688                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10689                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10690                         }
10691                         if (dpll & PLL_P2_DIVIDE_BY_4)
10692                                 clock.p2 = 4;
10693                         else
10694                                 clock.p2 = 2;
10695                 }
10696
10697                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10698         }
10699
10700         /*
10701          * This value includes pixel_multiplier. We will use
10702          * port_clock to compute adjusted_mode.crtc_clock in the
10703          * encoder's get_config() function.
10704          */
10705         pipe_config->port_clock = port_clock;
10706 }
10707
10708 int intel_dotclock_calculate(int link_freq,
10709                              const struct intel_link_m_n *m_n)
10710 {
10711         /*
10712          * The calculation for the data clock is:
10713          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10714          * But we want to avoid losing precison if possible, so:
10715          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10716          *
10717          * and the link clock is simpler:
10718          * link_clock = (m * link_clock) / n
10719          */
10720
10721         if (!m_n->link_n)
10722                 return 0;
10723
10724         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10725 }
10726
10727 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10728                                    struct intel_crtc_state *pipe_config)
10729 {
10730         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10731
10732         /* read out port_clock from the DPLL */
10733         i9xx_crtc_clock_get(crtc, pipe_config);
10734
10735         /*
10736          * In case there is an active pipe without active ports,
10737          * we may need some idea for the dotclock anyway.
10738          * Calculate one based on the FDI configuration.
10739          */
10740         pipe_config->base.adjusted_mode.crtc_clock =
10741                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10742                                          &pipe_config->fdi_m_n);
10743 }
10744
10745 /** Returns the currently programmed mode of the given pipe. */
10746 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10747                                              struct drm_crtc *crtc)
10748 {
10749         struct drm_i915_private *dev_priv = dev->dev_private;
10750         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10751         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10752         struct drm_display_mode *mode;
10753         struct intel_crtc_state *pipe_config;
10754         int htot = I915_READ(HTOTAL(cpu_transcoder));
10755         int hsync = I915_READ(HSYNC(cpu_transcoder));
10756         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10757         int vsync = I915_READ(VSYNC(cpu_transcoder));
10758         enum pipe pipe = intel_crtc->pipe;
10759
10760         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10761         if (!mode)
10762                 return NULL;
10763
10764         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10765         if (!pipe_config) {
10766                 kfree(mode);
10767                 return NULL;
10768         }
10769
10770         /*
10771          * Construct a pipe_config sufficient for getting the clock info
10772          * back out of crtc_clock_get.
10773          *
10774          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10775          * to use a real value here instead.
10776          */
10777         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10778         pipe_config->pixel_multiplier = 1;
10779         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10780         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10781         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10782         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10783
10784         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10785         mode->hdisplay = (htot & 0xffff) + 1;
10786         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10787         mode->hsync_start = (hsync & 0xffff) + 1;
10788         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10789         mode->vdisplay = (vtot & 0xffff) + 1;
10790         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10791         mode->vsync_start = (vsync & 0xffff) + 1;
10792         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10793
10794         drm_mode_set_name(mode);
10795
10796         kfree(pipe_config);
10797
10798         return mode;
10799 }
10800
10801 void intel_mark_busy(struct drm_i915_private *dev_priv)
10802 {
10803         if (dev_priv->mm.busy)
10804                 return;
10805
10806         intel_runtime_pm_get(dev_priv);
10807         i915_update_gfx_val(dev_priv);
10808         if (INTEL_GEN(dev_priv) >= 6)
10809                 gen6_rps_busy(dev_priv);
10810         dev_priv->mm.busy = true;
10811 }
10812
10813 void intel_mark_idle(struct drm_i915_private *dev_priv)
10814 {
10815         if (!dev_priv->mm.busy)
10816                 return;
10817
10818         dev_priv->mm.busy = false;
10819
10820         if (INTEL_GEN(dev_priv) >= 6)
10821                 gen6_rps_idle(dev_priv);
10822
10823         intel_runtime_pm_put(dev_priv);
10824 }
10825
10826 static void intel_crtc_destroy(struct drm_crtc *crtc)
10827 {
10828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10829         struct drm_device *dev = crtc->dev;
10830         struct intel_unpin_work *work;
10831
10832         spin_lock_irq(&dev->event_lock);
10833         work = intel_crtc->unpin_work;
10834         intel_crtc->unpin_work = NULL;
10835         spin_unlock_irq(&dev->event_lock);
10836
10837         if (work) {
10838                 cancel_work_sync(&work->work);
10839                 kfree(work);
10840         }
10841
10842         drm_crtc_cleanup(crtc);
10843
10844         kfree(intel_crtc);
10845 }
10846
10847 static void intel_unpin_work_fn(struct work_struct *__work)
10848 {
10849         struct intel_unpin_work *work =
10850                 container_of(__work, struct intel_unpin_work, work);
10851         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10852         struct drm_device *dev = crtc->base.dev;
10853         struct drm_plane *primary = crtc->base.primary;
10854
10855         mutex_lock(&dev->struct_mutex);
10856         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10857         drm_gem_object_unreference(&work->pending_flip_obj->base);
10858
10859         if (work->flip_queued_req)
10860                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10861         mutex_unlock(&dev->struct_mutex);
10862
10863         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10864         intel_fbc_post_update(crtc);
10865         drm_framebuffer_unreference(work->old_fb);
10866
10867         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10868         atomic_dec(&crtc->unpin_work_count);
10869
10870         kfree(work);
10871 }
10872
10873 static void do_intel_finish_page_flip(struct drm_i915_private *dev_priv,
10874                                       struct drm_crtc *crtc)
10875 {
10876         struct drm_device *dev = dev_priv->dev;
10877         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10878         struct intel_unpin_work *work;
10879         unsigned long flags;
10880
10881         /* Ignore early vblank irqs */
10882         if (intel_crtc == NULL)
10883                 return;
10884
10885         /*
10886          * This is called both by irq handlers and the reset code (to complete
10887          * lost pageflips) so needs the full irqsave spinlocks.
10888          */
10889         spin_lock_irqsave(&dev->event_lock, flags);
10890         work = intel_crtc->unpin_work;
10891
10892         /* Ensure we don't miss a work->pending update ... */
10893         smp_rmb();
10894
10895         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10896                 spin_unlock_irqrestore(&dev->event_lock, flags);
10897                 return;
10898         }
10899
10900         page_flip_completed(intel_crtc);
10901
10902         spin_unlock_irqrestore(&dev->event_lock, flags);
10903 }
10904
10905 void intel_finish_page_flip(struct drm_i915_private *dev_priv, int pipe)
10906 {
10907         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10908
10909         do_intel_finish_page_flip(dev_priv, crtc);
10910 }
10911
10912 void intel_finish_page_flip_plane(struct drm_i915_private *dev_priv, int plane)
10913 {
10914         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10915
10916         do_intel_finish_page_flip(dev_priv, crtc);
10917 }
10918
10919 /* Is 'a' after or equal to 'b'? */
10920 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10921 {
10922         return !((a - b) & 0x80000000);
10923 }
10924
10925 static bool page_flip_finished(struct intel_crtc *crtc)
10926 {
10927         struct drm_device *dev = crtc->base.dev;
10928         struct drm_i915_private *dev_priv = dev->dev_private;
10929         unsigned reset_counter;
10930
10931         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
10932         if (crtc->reset_counter != reset_counter)
10933                 return true;
10934
10935         /*
10936          * The relevant registers doen't exist on pre-ctg.
10937          * As the flip done interrupt doesn't trigger for mmio
10938          * flips on gmch platforms, a flip count check isn't
10939          * really needed there. But since ctg has the registers,
10940          * include it in the check anyway.
10941          */
10942         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10943                 return true;
10944
10945         /*
10946          * BDW signals flip done immediately if the plane
10947          * is disabled, even if the plane enable is already
10948          * armed to occur at the next vblank :(
10949          */
10950
10951         /*
10952          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10953          * used the same base address. In that case the mmio flip might
10954          * have completed, but the CS hasn't even executed the flip yet.
10955          *
10956          * A flip count check isn't enough as the CS might have updated
10957          * the base address just after start of vblank, but before we
10958          * managed to process the interrupt. This means we'd complete the
10959          * CS flip too soon.
10960          *
10961          * Combining both checks should get us a good enough result. It may
10962          * still happen that the CS flip has been executed, but has not
10963          * yet actually completed. But in case the base address is the same
10964          * anyway, we don't really care.
10965          */
10966         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10967                 crtc->unpin_work->gtt_offset &&
10968                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10969                                     crtc->unpin_work->flip_count);
10970 }
10971
10972 void intel_prepare_page_flip(struct drm_i915_private *dev_priv, int plane)
10973 {
10974         struct drm_device *dev = dev_priv->dev;
10975         struct intel_crtc *intel_crtc =
10976                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10977         unsigned long flags;
10978
10979
10980         /*
10981          * This is called both by irq handlers and the reset code (to complete
10982          * lost pageflips) so needs the full irqsave spinlocks.
10983          *
10984          * NB: An MMIO update of the plane base pointer will also
10985          * generate a page-flip completion irq, i.e. every modeset
10986          * is also accompanied by a spurious intel_prepare_page_flip().
10987          */
10988         spin_lock_irqsave(&dev->event_lock, flags);
10989         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10990                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10991         spin_unlock_irqrestore(&dev->event_lock, flags);
10992 }
10993
10994 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
10995 {
10996         /* Ensure that the work item is consistent when activating it ... */
10997         smp_wmb();
10998         atomic_set(&work->pending, INTEL_FLIP_PENDING);
10999         /* and that it is marked active as soon as the irq could fire. */
11000         smp_wmb();
11001 }
11002
11003 static int intel_gen2_queue_flip(struct drm_device *dev,
11004                                  struct drm_crtc *crtc,
11005                                  struct drm_framebuffer *fb,
11006                                  struct drm_i915_gem_object *obj,
11007                                  struct drm_i915_gem_request *req,
11008                                  uint32_t flags)
11009 {
11010         struct intel_engine_cs *engine = req->engine;
11011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11012         u32 flip_mask;
11013         int ret;
11014
11015         ret = intel_ring_begin(req, 6);
11016         if (ret)
11017                 return ret;
11018
11019         /* Can't queue multiple flips, so wait for the previous
11020          * one to finish before executing the next.
11021          */
11022         if (intel_crtc->plane)
11023                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11024         else
11025                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11026         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11027         intel_ring_emit(engine, MI_NOOP);
11028         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11029                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11030         intel_ring_emit(engine, fb->pitches[0]);
11031         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11032         intel_ring_emit(engine, 0); /* aux display base address, unused */
11033
11034         intel_mark_page_flip_active(intel_crtc->unpin_work);
11035         return 0;
11036 }
11037
11038 static int intel_gen3_queue_flip(struct drm_device *dev,
11039                                  struct drm_crtc *crtc,
11040                                  struct drm_framebuffer *fb,
11041                                  struct drm_i915_gem_object *obj,
11042                                  struct drm_i915_gem_request *req,
11043                                  uint32_t flags)
11044 {
11045         struct intel_engine_cs *engine = req->engine;
11046         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11047         u32 flip_mask;
11048         int ret;
11049
11050         ret = intel_ring_begin(req, 6);
11051         if (ret)
11052                 return ret;
11053
11054         if (intel_crtc->plane)
11055                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11056         else
11057                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11058         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11059         intel_ring_emit(engine, MI_NOOP);
11060         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11061                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11062         intel_ring_emit(engine, fb->pitches[0]);
11063         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11064         intel_ring_emit(engine, MI_NOOP);
11065
11066         intel_mark_page_flip_active(intel_crtc->unpin_work);
11067         return 0;
11068 }
11069
11070 static int intel_gen4_queue_flip(struct drm_device *dev,
11071                                  struct drm_crtc *crtc,
11072                                  struct drm_framebuffer *fb,
11073                                  struct drm_i915_gem_object *obj,
11074                                  struct drm_i915_gem_request *req,
11075                                  uint32_t flags)
11076 {
11077         struct intel_engine_cs *engine = req->engine;
11078         struct drm_i915_private *dev_priv = dev->dev_private;
11079         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11080         uint32_t pf, pipesrc;
11081         int ret;
11082
11083         ret = intel_ring_begin(req, 4);
11084         if (ret)
11085                 return ret;
11086
11087         /* i965+ uses the linear or tiled offsets from the
11088          * Display Registers (which do not change across a page-flip)
11089          * so we need only reprogram the base address.
11090          */
11091         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11092                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11093         intel_ring_emit(engine, fb->pitches[0]);
11094         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11095                         obj->tiling_mode);
11096
11097         /* XXX Enabling the panel-fitter across page-flip is so far
11098          * untested on non-native modes, so ignore it for now.
11099          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11100          */
11101         pf = 0;
11102         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11103         intel_ring_emit(engine, pf | pipesrc);
11104
11105         intel_mark_page_flip_active(intel_crtc->unpin_work);
11106         return 0;
11107 }
11108
11109 static int intel_gen6_queue_flip(struct drm_device *dev,
11110                                  struct drm_crtc *crtc,
11111                                  struct drm_framebuffer *fb,
11112                                  struct drm_i915_gem_object *obj,
11113                                  struct drm_i915_gem_request *req,
11114                                  uint32_t flags)
11115 {
11116         struct intel_engine_cs *engine = req->engine;
11117         struct drm_i915_private *dev_priv = dev->dev_private;
11118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11119         uint32_t pf, pipesrc;
11120         int ret;
11121
11122         ret = intel_ring_begin(req, 4);
11123         if (ret)
11124                 return ret;
11125
11126         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11127                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11128         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11129         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11130
11131         /* Contrary to the suggestions in the documentation,
11132          * "Enable Panel Fitter" does not seem to be required when page
11133          * flipping with a non-native mode, and worse causes a normal
11134          * modeset to fail.
11135          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11136          */
11137         pf = 0;
11138         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11139         intel_ring_emit(engine, pf | pipesrc);
11140
11141         intel_mark_page_flip_active(intel_crtc->unpin_work);
11142         return 0;
11143 }
11144
11145 static int intel_gen7_queue_flip(struct drm_device *dev,
11146                                  struct drm_crtc *crtc,
11147                                  struct drm_framebuffer *fb,
11148                                  struct drm_i915_gem_object *obj,
11149                                  struct drm_i915_gem_request *req,
11150                                  uint32_t flags)
11151 {
11152         struct intel_engine_cs *engine = req->engine;
11153         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11154         uint32_t plane_bit = 0;
11155         int len, ret;
11156
11157         switch (intel_crtc->plane) {
11158         case PLANE_A:
11159                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11160                 break;
11161         case PLANE_B:
11162                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11163                 break;
11164         case PLANE_C:
11165                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11166                 break;
11167         default:
11168                 WARN_ONCE(1, "unknown plane in flip command\n");
11169                 return -ENODEV;
11170         }
11171
11172         len = 4;
11173         if (engine->id == RCS) {
11174                 len += 6;
11175                 /*
11176                  * On Gen 8, SRM is now taking an extra dword to accommodate
11177                  * 48bits addresses, and we need a NOOP for the batch size to
11178                  * stay even.
11179                  */
11180                 if (IS_GEN8(dev))
11181                         len += 2;
11182         }
11183
11184         /*
11185          * BSpec MI_DISPLAY_FLIP for IVB:
11186          * "The full packet must be contained within the same cache line."
11187          *
11188          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11189          * cacheline, if we ever start emitting more commands before
11190          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11191          * then do the cacheline alignment, and finally emit the
11192          * MI_DISPLAY_FLIP.
11193          */
11194         ret = intel_ring_cacheline_align(req);
11195         if (ret)
11196                 return ret;
11197
11198         ret = intel_ring_begin(req, len);
11199         if (ret)
11200                 return ret;
11201
11202         /* Unmask the flip-done completion message. Note that the bspec says that
11203          * we should do this for both the BCS and RCS, and that we must not unmask
11204          * more than one flip event at any time (or ensure that one flip message
11205          * can be sent by waiting for flip-done prior to queueing new flips).
11206          * Experimentation says that BCS works despite DERRMR masking all
11207          * flip-done completion events and that unmasking all planes at once
11208          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11209          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11210          */
11211         if (engine->id == RCS) {
11212                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11213                 intel_ring_emit_reg(engine, DERRMR);
11214                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11215                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11216                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11217                 if (IS_GEN8(dev))
11218                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11219                                               MI_SRM_LRM_GLOBAL_GTT);
11220                 else
11221                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11222                                               MI_SRM_LRM_GLOBAL_GTT);
11223                 intel_ring_emit_reg(engine, DERRMR);
11224                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11225                 if (IS_GEN8(dev)) {
11226                         intel_ring_emit(engine, 0);
11227                         intel_ring_emit(engine, MI_NOOP);
11228                 }
11229         }
11230
11231         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11232         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11233         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11234         intel_ring_emit(engine, (MI_NOOP));
11235
11236         intel_mark_page_flip_active(intel_crtc->unpin_work);
11237         return 0;
11238 }
11239
11240 static bool use_mmio_flip(struct intel_engine_cs *engine,
11241                           struct drm_i915_gem_object *obj)
11242 {
11243         /*
11244          * This is not being used for older platforms, because
11245          * non-availability of flip done interrupt forces us to use
11246          * CS flips. Older platforms derive flip done using some clever
11247          * tricks involving the flip_pending status bits and vblank irqs.
11248          * So using MMIO flips there would disrupt this mechanism.
11249          */
11250
11251         if (engine == NULL)
11252                 return true;
11253
11254         if (INTEL_GEN(engine->i915) < 5)
11255                 return false;
11256
11257         if (i915.use_mmio_flip < 0)
11258                 return false;
11259         else if (i915.use_mmio_flip > 0)
11260                 return true;
11261         else if (i915.enable_execlists)
11262                 return true;
11263         else if (obj->base.dma_buf &&
11264                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11265                                                        false))
11266                 return true;
11267         else
11268                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11269 }
11270
11271 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11272                              unsigned int rotation,
11273                              struct intel_unpin_work *work)
11274 {
11275         struct drm_device *dev = intel_crtc->base.dev;
11276         struct drm_i915_private *dev_priv = dev->dev_private;
11277         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11278         const enum pipe pipe = intel_crtc->pipe;
11279         u32 ctl, stride, tile_height;
11280
11281         ctl = I915_READ(PLANE_CTL(pipe, 0));
11282         ctl &= ~PLANE_CTL_TILED_MASK;
11283         switch (fb->modifier[0]) {
11284         case DRM_FORMAT_MOD_NONE:
11285                 break;
11286         case I915_FORMAT_MOD_X_TILED:
11287                 ctl |= PLANE_CTL_TILED_X;
11288                 break;
11289         case I915_FORMAT_MOD_Y_TILED:
11290                 ctl |= PLANE_CTL_TILED_Y;
11291                 break;
11292         case I915_FORMAT_MOD_Yf_TILED:
11293                 ctl |= PLANE_CTL_TILED_YF;
11294                 break;
11295         default:
11296                 MISSING_CASE(fb->modifier[0]);
11297         }
11298
11299         /*
11300          * The stride is either expressed as a multiple of 64 bytes chunks for
11301          * linear buffers or in number of tiles for tiled buffers.
11302          */
11303         if (intel_rotation_90_or_270(rotation)) {
11304                 /* stride = Surface height in tiles */
11305                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11306                 stride = DIV_ROUND_UP(fb->height, tile_height);
11307         } else {
11308                 stride = fb->pitches[0] /
11309                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11310                                                   fb->pixel_format);
11311         }
11312
11313         /*
11314          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11315          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11316          */
11317         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11318         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11319
11320         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11321         POSTING_READ(PLANE_SURF(pipe, 0));
11322 }
11323
11324 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11325                              struct intel_unpin_work *work)
11326 {
11327         struct drm_device *dev = intel_crtc->base.dev;
11328         struct drm_i915_private *dev_priv = dev->dev_private;
11329         struct intel_framebuffer *intel_fb =
11330                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11331         struct drm_i915_gem_object *obj = intel_fb->obj;
11332         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11333         u32 dspcntr;
11334
11335         dspcntr = I915_READ(reg);
11336
11337         if (obj->tiling_mode != I915_TILING_NONE)
11338                 dspcntr |= DISPPLANE_TILED;
11339         else
11340                 dspcntr &= ~DISPPLANE_TILED;
11341
11342         I915_WRITE(reg, dspcntr);
11343
11344         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11345         POSTING_READ(DSPSURF(intel_crtc->plane));
11346 }
11347
11348 /*
11349  * XXX: This is the temporary way to update the plane registers until we get
11350  * around to using the usual plane update functions for MMIO flips
11351  */
11352 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11353 {
11354         struct intel_crtc *crtc = mmio_flip->crtc;
11355         struct intel_unpin_work *work;
11356
11357         spin_lock_irq(&crtc->base.dev->event_lock);
11358         work = crtc->unpin_work;
11359         spin_unlock_irq(&crtc->base.dev->event_lock);
11360         if (work == NULL)
11361                 return;
11362
11363         intel_mark_page_flip_active(work);
11364
11365         intel_pipe_update_start(crtc);
11366
11367         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11368                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11369         else
11370                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11371                 ilk_do_mmio_flip(crtc, work);
11372
11373         intel_pipe_update_end(crtc);
11374 }
11375
11376 static void intel_mmio_flip_work_func(struct work_struct *work)
11377 {
11378         struct intel_mmio_flip *mmio_flip =
11379                 container_of(work, struct intel_mmio_flip, work);
11380         struct intel_framebuffer *intel_fb =
11381                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11382         struct drm_i915_gem_object *obj = intel_fb->obj;
11383
11384         if (mmio_flip->req) {
11385                 WARN_ON(__i915_wait_request(mmio_flip->req,
11386                                             false, NULL,
11387                                             &mmio_flip->i915->rps.mmioflips));
11388                 i915_gem_request_unreference(mmio_flip->req);
11389         }
11390
11391         /* For framebuffer backed by dmabuf, wait for fence */
11392         if (obj->base.dma_buf)
11393                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11394                                                             false, false,
11395                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11396
11397         intel_do_mmio_flip(mmio_flip);
11398         kfree(mmio_flip);
11399 }
11400
11401 static int intel_queue_mmio_flip(struct drm_device *dev,
11402                                  struct drm_crtc *crtc,
11403                                  struct drm_i915_gem_object *obj)
11404 {
11405         struct intel_mmio_flip *mmio_flip;
11406
11407         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11408         if (mmio_flip == NULL)
11409                 return -ENOMEM;
11410
11411         mmio_flip->i915 = to_i915(dev);
11412         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11413         mmio_flip->crtc = to_intel_crtc(crtc);
11414         mmio_flip->rotation = crtc->primary->state->rotation;
11415
11416         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11417         schedule_work(&mmio_flip->work);
11418
11419         return 0;
11420 }
11421
11422 static int intel_default_queue_flip(struct drm_device *dev,
11423                                     struct drm_crtc *crtc,
11424                                     struct drm_framebuffer *fb,
11425                                     struct drm_i915_gem_object *obj,
11426                                     struct drm_i915_gem_request *req,
11427                                     uint32_t flags)
11428 {
11429         return -ENODEV;
11430 }
11431
11432 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11433                                          struct drm_crtc *crtc)
11434 {
11435         struct drm_i915_private *dev_priv = dev->dev_private;
11436         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11437         struct intel_unpin_work *work = intel_crtc->unpin_work;
11438         u32 addr;
11439
11440         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11441                 return true;
11442
11443         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11444                 return false;
11445
11446         if (!work->enable_stall_check)
11447                 return false;
11448
11449         if (work->flip_ready_vblank == 0) {
11450                 if (work->flip_queued_req &&
11451                     !i915_gem_request_completed(work->flip_queued_req, true))
11452                         return false;
11453
11454                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11455         }
11456
11457         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11458                 return false;
11459
11460         /* Potential stall - if we see that the flip has happened,
11461          * assume a missed interrupt. */
11462         if (INTEL_INFO(dev)->gen >= 4)
11463                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11464         else
11465                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11466
11467         /* There is a potential issue here with a false positive after a flip
11468          * to the same address. We could address this by checking for a
11469          * non-incrementing frame counter.
11470          */
11471         return addr == work->gtt_offset;
11472 }
11473
11474 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11475 {
11476         struct drm_device *dev = dev_priv->dev;
11477         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11478         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11479         struct intel_unpin_work *work;
11480
11481         WARN_ON(!in_interrupt());
11482
11483         if (crtc == NULL)
11484                 return;
11485
11486         spin_lock(&dev->event_lock);
11487         work = intel_crtc->unpin_work;
11488         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11489                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11490                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11491                 page_flip_completed(intel_crtc);
11492                 work = NULL;
11493         }
11494         if (work != NULL &&
11495             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11496                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11497         spin_unlock(&dev->event_lock);
11498 }
11499
11500 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11501                                 struct drm_framebuffer *fb,
11502                                 struct drm_pending_vblank_event *event,
11503                                 uint32_t page_flip_flags)
11504 {
11505         struct drm_device *dev = crtc->dev;
11506         struct drm_i915_private *dev_priv = dev->dev_private;
11507         struct drm_framebuffer *old_fb = crtc->primary->fb;
11508         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11509         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11510         struct drm_plane *primary = crtc->primary;
11511         enum pipe pipe = intel_crtc->pipe;
11512         struct intel_unpin_work *work;
11513         struct intel_engine_cs *engine;
11514         bool mmio_flip;
11515         struct drm_i915_gem_request *request = NULL;
11516         int ret;
11517
11518         /*
11519          * drm_mode_page_flip_ioctl() should already catch this, but double
11520          * check to be safe.  In the future we may enable pageflipping from
11521          * a disabled primary plane.
11522          */
11523         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11524                 return -EBUSY;
11525
11526         /* Can't change pixel format via MI display flips. */
11527         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11528                 return -EINVAL;
11529
11530         /*
11531          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11532          * Note that pitch changes could also affect these register.
11533          */
11534         if (INTEL_INFO(dev)->gen > 3 &&
11535             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11536              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11537                 return -EINVAL;
11538
11539         if (i915_terminally_wedged(&dev_priv->gpu_error))
11540                 goto out_hang;
11541
11542         work = kzalloc(sizeof(*work), GFP_KERNEL);
11543         if (work == NULL)
11544                 return -ENOMEM;
11545
11546         work->event = event;
11547         work->crtc = crtc;
11548         work->old_fb = old_fb;
11549         INIT_WORK(&work->work, intel_unpin_work_fn);
11550
11551         ret = drm_crtc_vblank_get(crtc);
11552         if (ret)
11553                 goto free_work;
11554
11555         /* We borrow the event spin lock for protecting unpin_work */
11556         spin_lock_irq(&dev->event_lock);
11557         if (intel_crtc->unpin_work) {
11558                 /* Before declaring the flip queue wedged, check if
11559                  * the hardware completed the operation behind our backs.
11560                  */
11561                 if (__intel_pageflip_stall_check(dev, crtc)) {
11562                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11563                         page_flip_completed(intel_crtc);
11564                 } else {
11565                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11566                         spin_unlock_irq(&dev->event_lock);
11567
11568                         drm_crtc_vblank_put(crtc);
11569                         kfree(work);
11570                         return -EBUSY;
11571                 }
11572         }
11573         intel_crtc->unpin_work = work;
11574         spin_unlock_irq(&dev->event_lock);
11575
11576         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11577                 flush_workqueue(dev_priv->wq);
11578
11579         /* Reference the objects for the scheduled work. */
11580         drm_framebuffer_reference(work->old_fb);
11581         drm_gem_object_reference(&obj->base);
11582
11583         crtc->primary->fb = fb;
11584         update_state_fb(crtc->primary);
11585         intel_fbc_pre_update(intel_crtc);
11586
11587         work->pending_flip_obj = obj;
11588
11589         ret = i915_mutex_lock_interruptible(dev);
11590         if (ret)
11591                 goto cleanup;
11592
11593         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11594         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11595                 ret = -EIO;
11596                 goto cleanup;
11597         }
11598
11599         atomic_inc(&intel_crtc->unpin_work_count);
11600
11601         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11602                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11603
11604         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11605                 engine = &dev_priv->engine[BCS];
11606                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11607                         /* vlv: DISPLAY_FLIP fails to change tiling */
11608                         engine = NULL;
11609         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11610                 engine = &dev_priv->engine[BCS];
11611         } else if (INTEL_INFO(dev)->gen >= 7) {
11612                 engine = i915_gem_request_get_engine(obj->last_write_req);
11613                 if (engine == NULL || engine->id != RCS)
11614                         engine = &dev_priv->engine[BCS];
11615         } else {
11616                 engine = &dev_priv->engine[RCS];
11617         }
11618
11619         mmio_flip = use_mmio_flip(engine, obj);
11620
11621         /* When using CS flips, we want to emit semaphores between rings.
11622          * However, when using mmio flips we will create a task to do the
11623          * synchronisation, so all we want here is to pin the framebuffer
11624          * into the display plane and skip any waits.
11625          */
11626         if (!mmio_flip) {
11627                 ret = i915_gem_object_sync(obj, engine, &request);
11628                 if (ret)
11629                         goto cleanup_pending;
11630         }
11631
11632         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11633         if (ret)
11634                 goto cleanup_pending;
11635
11636         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11637                                                   obj, 0);
11638         work->gtt_offset += intel_crtc->dspaddr_offset;
11639
11640         if (mmio_flip) {
11641                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11642                 if (ret)
11643                         goto cleanup_unpin;
11644
11645                 i915_gem_request_assign(&work->flip_queued_req,
11646                                         obj->last_write_req);
11647         } else {
11648                 if (!request) {
11649                         request = i915_gem_request_alloc(engine, NULL);
11650                         if (IS_ERR(request)) {
11651                                 ret = PTR_ERR(request);
11652                                 goto cleanup_unpin;
11653                         }
11654                 }
11655
11656                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11657                                                    page_flip_flags);
11658                 if (ret)
11659                         goto cleanup_unpin;
11660
11661                 i915_gem_request_assign(&work->flip_queued_req, request);
11662         }
11663
11664         if (request)
11665                 i915_add_request_no_flush(request);
11666
11667         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11668         work->enable_stall_check = true;
11669
11670         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11671                           to_intel_plane(primary)->frontbuffer_bit);
11672         mutex_unlock(&dev->struct_mutex);
11673
11674         intel_frontbuffer_flip_prepare(dev,
11675                                        to_intel_plane(primary)->frontbuffer_bit);
11676
11677         trace_i915_flip_request(intel_crtc->plane, obj);
11678
11679         return 0;
11680
11681 cleanup_unpin:
11682         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11683 cleanup_pending:
11684         if (!IS_ERR_OR_NULL(request))
11685                 i915_add_request_no_flush(request);
11686         atomic_dec(&intel_crtc->unpin_work_count);
11687         mutex_unlock(&dev->struct_mutex);
11688 cleanup:
11689         crtc->primary->fb = old_fb;
11690         update_state_fb(crtc->primary);
11691
11692         drm_gem_object_unreference_unlocked(&obj->base);
11693         drm_framebuffer_unreference(work->old_fb);
11694
11695         spin_lock_irq(&dev->event_lock);
11696         intel_crtc->unpin_work = NULL;
11697         spin_unlock_irq(&dev->event_lock);
11698
11699         drm_crtc_vblank_put(crtc);
11700 free_work:
11701         kfree(work);
11702
11703         if (ret == -EIO) {
11704                 struct drm_atomic_state *state;
11705                 struct drm_plane_state *plane_state;
11706
11707 out_hang:
11708                 state = drm_atomic_state_alloc(dev);
11709                 if (!state)
11710                         return -ENOMEM;
11711                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11712
11713 retry:
11714                 plane_state = drm_atomic_get_plane_state(state, primary);
11715                 ret = PTR_ERR_OR_ZERO(plane_state);
11716                 if (!ret) {
11717                         drm_atomic_set_fb_for_plane(plane_state, fb);
11718
11719                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11720                         if (!ret)
11721                                 ret = drm_atomic_commit(state);
11722                 }
11723
11724                 if (ret == -EDEADLK) {
11725                         drm_modeset_backoff(state->acquire_ctx);
11726                         drm_atomic_state_clear(state);
11727                         goto retry;
11728                 }
11729
11730                 if (ret)
11731                         drm_atomic_state_free(state);
11732
11733                 if (ret == 0 && event) {
11734                         spin_lock_irq(&dev->event_lock);
11735                         drm_crtc_send_vblank_event(crtc, event);
11736                         spin_unlock_irq(&dev->event_lock);
11737                 }
11738         }
11739         return ret;
11740 }
11741
11742
11743 /**
11744  * intel_wm_need_update - Check whether watermarks need updating
11745  * @plane: drm plane
11746  * @state: new plane state
11747  *
11748  * Check current plane state versus the new one to determine whether
11749  * watermarks need to be recalculated.
11750  *
11751  * Returns true or false.
11752  */
11753 static bool intel_wm_need_update(struct drm_plane *plane,
11754                                  struct drm_plane_state *state)
11755 {
11756         struct intel_plane_state *new = to_intel_plane_state(state);
11757         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11758
11759         /* Update watermarks on tiling or size changes. */
11760         if (new->visible != cur->visible)
11761                 return true;
11762
11763         if (!cur->base.fb || !new->base.fb)
11764                 return false;
11765
11766         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11767             cur->base.rotation != new->base.rotation ||
11768             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11769             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11770             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11771             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11772                 return true;
11773
11774         return false;
11775 }
11776
11777 static bool needs_scaling(struct intel_plane_state *state)
11778 {
11779         int src_w = drm_rect_width(&state->src) >> 16;
11780         int src_h = drm_rect_height(&state->src) >> 16;
11781         int dst_w = drm_rect_width(&state->dst);
11782         int dst_h = drm_rect_height(&state->dst);
11783
11784         return (src_w != dst_w || src_h != dst_h);
11785 }
11786
11787 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11788                                     struct drm_plane_state *plane_state)
11789 {
11790         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11791         struct drm_crtc *crtc = crtc_state->crtc;
11792         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11793         struct drm_plane *plane = plane_state->plane;
11794         struct drm_device *dev = crtc->dev;
11795         struct drm_i915_private *dev_priv = to_i915(dev);
11796         struct intel_plane_state *old_plane_state =
11797                 to_intel_plane_state(plane->state);
11798         int idx = intel_crtc->base.base.id, ret;
11799         bool mode_changed = needs_modeset(crtc_state);
11800         bool was_crtc_enabled = crtc->state->active;
11801         bool is_crtc_enabled = crtc_state->active;
11802         bool turn_off, turn_on, visible, was_visible;
11803         struct drm_framebuffer *fb = plane_state->fb;
11804
11805         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11806             plane->type != DRM_PLANE_TYPE_CURSOR) {
11807                 ret = skl_update_scaler_plane(
11808                         to_intel_crtc_state(crtc_state),
11809                         to_intel_plane_state(plane_state));
11810                 if (ret)
11811                         return ret;
11812         }
11813
11814         was_visible = old_plane_state->visible;
11815         visible = to_intel_plane_state(plane_state)->visible;
11816
11817         if (!was_crtc_enabled && WARN_ON(was_visible))
11818                 was_visible = false;
11819
11820         /*
11821          * Visibility is calculated as if the crtc was on, but
11822          * after scaler setup everything depends on it being off
11823          * when the crtc isn't active.
11824          *
11825          * FIXME this is wrong for watermarks. Watermarks should also
11826          * be computed as if the pipe would be active. Perhaps move
11827          * per-plane wm computation to the .check_plane() hook, and
11828          * only combine the results from all planes in the current place?
11829          */
11830         if (!is_crtc_enabled)
11831                 to_intel_plane_state(plane_state)->visible = visible = false;
11832
11833         if (!was_visible && !visible)
11834                 return 0;
11835
11836         if (fb != old_plane_state->base.fb)
11837                 pipe_config->fb_changed = true;
11838
11839         turn_off = was_visible && (!visible || mode_changed);
11840         turn_on = visible && (!was_visible || mode_changed);
11841
11842         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11843                          plane->base.id, fb ? fb->base.id : -1);
11844
11845         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11846                          plane->base.id, was_visible, visible,
11847                          turn_off, turn_on, mode_changed);
11848
11849         if (turn_on) {
11850                 pipe_config->update_wm_pre = true;
11851
11852                 /* must disable cxsr around plane enable/disable */
11853                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11854                         pipe_config->disable_cxsr = true;
11855         } else if (turn_off) {
11856                 pipe_config->update_wm_post = true;
11857
11858                 /* must disable cxsr around plane enable/disable */
11859                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11860                         pipe_config->disable_cxsr = true;
11861         } else if (intel_wm_need_update(plane, plane_state)) {
11862                 /* FIXME bollocks */
11863                 pipe_config->update_wm_pre = true;
11864                 pipe_config->update_wm_post = true;
11865         }
11866
11867         /* Pre-gen9 platforms need two-step watermark updates */
11868         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11869             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11870                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11871
11872         if (visible || was_visible)
11873                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11874
11875         /*
11876          * WaCxSRDisabledForSpriteScaling:ivb
11877          *
11878          * cstate->update_wm was already set above, so this flag will
11879          * take effect when we commit and program watermarks.
11880          */
11881         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11882             needs_scaling(to_intel_plane_state(plane_state)) &&
11883             !needs_scaling(old_plane_state))
11884                 pipe_config->disable_lp_wm = true;
11885
11886         return 0;
11887 }
11888
11889 static bool encoders_cloneable(const struct intel_encoder *a,
11890                                const struct intel_encoder *b)
11891 {
11892         /* masks could be asymmetric, so check both ways */
11893         return a == b || (a->cloneable & (1 << b->type) &&
11894                           b->cloneable & (1 << a->type));
11895 }
11896
11897 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11898                                          struct intel_crtc *crtc,
11899                                          struct intel_encoder *encoder)
11900 {
11901         struct intel_encoder *source_encoder;
11902         struct drm_connector *connector;
11903         struct drm_connector_state *connector_state;
11904         int i;
11905
11906         for_each_connector_in_state(state, connector, connector_state, i) {
11907                 if (connector_state->crtc != &crtc->base)
11908                         continue;
11909
11910                 source_encoder =
11911                         to_intel_encoder(connector_state->best_encoder);
11912                 if (!encoders_cloneable(encoder, source_encoder))
11913                         return false;
11914         }
11915
11916         return true;
11917 }
11918
11919 static bool check_encoder_cloning(struct drm_atomic_state *state,
11920                                   struct intel_crtc *crtc)
11921 {
11922         struct intel_encoder *encoder;
11923         struct drm_connector *connector;
11924         struct drm_connector_state *connector_state;
11925         int i;
11926
11927         for_each_connector_in_state(state, connector, connector_state, i) {
11928                 if (connector_state->crtc != &crtc->base)
11929                         continue;
11930
11931                 encoder = to_intel_encoder(connector_state->best_encoder);
11932                 if (!check_single_encoder_cloning(state, crtc, encoder))
11933                         return false;
11934         }
11935
11936         return true;
11937 }
11938
11939 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11940                                    struct drm_crtc_state *crtc_state)
11941 {
11942         struct drm_device *dev = crtc->dev;
11943         struct drm_i915_private *dev_priv = dev->dev_private;
11944         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11945         struct intel_crtc_state *pipe_config =
11946                 to_intel_crtc_state(crtc_state);
11947         struct drm_atomic_state *state = crtc_state->state;
11948         int ret;
11949         bool mode_changed = needs_modeset(crtc_state);
11950
11951         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11952                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11953                 return -EINVAL;
11954         }
11955
11956         if (mode_changed && !crtc_state->active)
11957                 pipe_config->update_wm_post = true;
11958
11959         if (mode_changed && crtc_state->enable &&
11960             dev_priv->display.crtc_compute_clock &&
11961             !WARN_ON(pipe_config->shared_dpll)) {
11962                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11963                                                            pipe_config);
11964                 if (ret)
11965                         return ret;
11966         }
11967
11968         if (crtc_state->color_mgmt_changed) {
11969                 ret = intel_color_check(crtc, crtc_state);
11970                 if (ret)
11971                         return ret;
11972         }
11973
11974         ret = 0;
11975         if (dev_priv->display.compute_pipe_wm) {
11976                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11977                 if (ret) {
11978                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11979                         return ret;
11980                 }
11981         }
11982
11983         if (dev_priv->display.compute_intermediate_wm &&
11984             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11985                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11986                         return 0;
11987
11988                 /*
11989                  * Calculate 'intermediate' watermarks that satisfy both the
11990                  * old state and the new state.  We can program these
11991                  * immediately.
11992                  */
11993                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11994                                                                 intel_crtc,
11995                                                                 pipe_config);
11996                 if (ret) {
11997                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11998                         return ret;
11999                 }
12000         }
12001
12002         if (INTEL_INFO(dev)->gen >= 9) {
12003                 if (mode_changed)
12004                         ret = skl_update_scaler_crtc(pipe_config);
12005
12006                 if (!ret)
12007                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12008                                                          pipe_config);
12009         }
12010
12011         return ret;
12012 }
12013
12014 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12015         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12016         .atomic_begin = intel_begin_crtc_commit,
12017         .atomic_flush = intel_finish_crtc_commit,
12018         .atomic_check = intel_crtc_atomic_check,
12019 };
12020
12021 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12022 {
12023         struct intel_connector *connector;
12024
12025         for_each_intel_connector(dev, connector) {
12026                 if (connector->base.encoder) {
12027                         connector->base.state->best_encoder =
12028                                 connector->base.encoder;
12029                         connector->base.state->crtc =
12030                                 connector->base.encoder->crtc;
12031                 } else {
12032                         connector->base.state->best_encoder = NULL;
12033                         connector->base.state->crtc = NULL;
12034                 }
12035         }
12036 }
12037
12038 static void
12039 connected_sink_compute_bpp(struct intel_connector *connector,
12040                            struct intel_crtc_state *pipe_config)
12041 {
12042         int bpp = pipe_config->pipe_bpp;
12043
12044         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12045                 connector->base.base.id,
12046                 connector->base.name);
12047
12048         /* Don't use an invalid EDID bpc value */
12049         if (connector->base.display_info.bpc &&
12050             connector->base.display_info.bpc * 3 < bpp) {
12051                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12052                               bpp, connector->base.display_info.bpc*3);
12053                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12054         }
12055
12056         /* Clamp bpp to default limit on screens without EDID 1.4 */
12057         if (connector->base.display_info.bpc == 0) {
12058                 int type = connector->base.connector_type;
12059                 int clamp_bpp = 24;
12060
12061                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12062                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12063                     type == DRM_MODE_CONNECTOR_eDP)
12064                         clamp_bpp = 18;
12065
12066                 if (bpp > clamp_bpp) {
12067                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12068                                       bpp, clamp_bpp);
12069                         pipe_config->pipe_bpp = clamp_bpp;
12070                 }
12071         }
12072 }
12073
12074 static int
12075 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12076                           struct intel_crtc_state *pipe_config)
12077 {
12078         struct drm_device *dev = crtc->base.dev;
12079         struct drm_atomic_state *state;
12080         struct drm_connector *connector;
12081         struct drm_connector_state *connector_state;
12082         int bpp, i;
12083
12084         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12085                 bpp = 10*3;
12086         else if (INTEL_INFO(dev)->gen >= 5)
12087                 bpp = 12*3;
12088         else
12089                 bpp = 8*3;
12090
12091
12092         pipe_config->pipe_bpp = bpp;
12093
12094         state = pipe_config->base.state;
12095
12096         /* Clamp display bpp to EDID value */
12097         for_each_connector_in_state(state, connector, connector_state, i) {
12098                 if (connector_state->crtc != &crtc->base)
12099                         continue;
12100
12101                 connected_sink_compute_bpp(to_intel_connector(connector),
12102                                            pipe_config);
12103         }
12104
12105         return bpp;
12106 }
12107
12108 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12109 {
12110         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12111                         "type: 0x%x flags: 0x%x\n",
12112                 mode->crtc_clock,
12113                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12114                 mode->crtc_hsync_end, mode->crtc_htotal,
12115                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12116                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12117 }
12118
12119 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12120                                    struct intel_crtc_state *pipe_config,
12121                                    const char *context)
12122 {
12123         struct drm_device *dev = crtc->base.dev;
12124         struct drm_plane *plane;
12125         struct intel_plane *intel_plane;
12126         struct intel_plane_state *state;
12127         struct drm_framebuffer *fb;
12128
12129         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12130                       context, pipe_config, pipe_name(crtc->pipe));
12131
12132         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12133         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12134                       pipe_config->pipe_bpp, pipe_config->dither);
12135         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12136                       pipe_config->has_pch_encoder,
12137                       pipe_config->fdi_lanes,
12138                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12139                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12140                       pipe_config->fdi_m_n.tu);
12141         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12142                       pipe_config->has_dp_encoder,
12143                       pipe_config->lane_count,
12144                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12145                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12146                       pipe_config->dp_m_n.tu);
12147
12148         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12149                       pipe_config->has_dp_encoder,
12150                       pipe_config->lane_count,
12151                       pipe_config->dp_m2_n2.gmch_m,
12152                       pipe_config->dp_m2_n2.gmch_n,
12153                       pipe_config->dp_m2_n2.link_m,
12154                       pipe_config->dp_m2_n2.link_n,
12155                       pipe_config->dp_m2_n2.tu);
12156
12157         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12158                       pipe_config->has_audio,
12159                       pipe_config->has_infoframe);
12160
12161         DRM_DEBUG_KMS("requested mode:\n");
12162         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12163         DRM_DEBUG_KMS("adjusted mode:\n");
12164         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12165         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12166         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12167         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12168                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12169         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12170                       crtc->num_scalers,
12171                       pipe_config->scaler_state.scaler_users,
12172                       pipe_config->scaler_state.scaler_id);
12173         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12174                       pipe_config->gmch_pfit.control,
12175                       pipe_config->gmch_pfit.pgm_ratios,
12176                       pipe_config->gmch_pfit.lvds_border_bits);
12177         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12178                       pipe_config->pch_pfit.pos,
12179                       pipe_config->pch_pfit.size,
12180                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12181         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12182         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12183
12184         if (IS_BROXTON(dev)) {
12185                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12186                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12187                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12188                               pipe_config->ddi_pll_sel,
12189                               pipe_config->dpll_hw_state.ebb0,
12190                               pipe_config->dpll_hw_state.ebb4,
12191                               pipe_config->dpll_hw_state.pll0,
12192                               pipe_config->dpll_hw_state.pll1,
12193                               pipe_config->dpll_hw_state.pll2,
12194                               pipe_config->dpll_hw_state.pll3,
12195                               pipe_config->dpll_hw_state.pll6,
12196                               pipe_config->dpll_hw_state.pll8,
12197                               pipe_config->dpll_hw_state.pll9,
12198                               pipe_config->dpll_hw_state.pll10,
12199                               pipe_config->dpll_hw_state.pcsdw12);
12200         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12201                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12202                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12203                               pipe_config->ddi_pll_sel,
12204                               pipe_config->dpll_hw_state.ctrl1,
12205                               pipe_config->dpll_hw_state.cfgcr1,
12206                               pipe_config->dpll_hw_state.cfgcr2);
12207         } else if (HAS_DDI(dev)) {
12208                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12209                               pipe_config->ddi_pll_sel,
12210                               pipe_config->dpll_hw_state.wrpll,
12211                               pipe_config->dpll_hw_state.spll);
12212         } else {
12213                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12214                               "fp0: 0x%x, fp1: 0x%x\n",
12215                               pipe_config->dpll_hw_state.dpll,
12216                               pipe_config->dpll_hw_state.dpll_md,
12217                               pipe_config->dpll_hw_state.fp0,
12218                               pipe_config->dpll_hw_state.fp1);
12219         }
12220
12221         DRM_DEBUG_KMS("planes on this crtc\n");
12222         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12223                 intel_plane = to_intel_plane(plane);
12224                 if (intel_plane->pipe != crtc->pipe)
12225                         continue;
12226
12227                 state = to_intel_plane_state(plane->state);
12228                 fb = state->base.fb;
12229                 if (!fb) {
12230                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12231                                 "disabled, scaler_id = %d\n",
12232                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12233                                 plane->base.id, intel_plane->pipe,
12234                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12235                                 drm_plane_index(plane), state->scaler_id);
12236                         continue;
12237                 }
12238
12239                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12240                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12241                         plane->base.id, intel_plane->pipe,
12242                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12243                         drm_plane_index(plane));
12244                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12245                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12246                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12247                         state->scaler_id,
12248                         state->src.x1 >> 16, state->src.y1 >> 16,
12249                         drm_rect_width(&state->src) >> 16,
12250                         drm_rect_height(&state->src) >> 16,
12251                         state->dst.x1, state->dst.y1,
12252                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12253         }
12254 }
12255
12256 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12257 {
12258         struct drm_device *dev = state->dev;
12259         struct drm_connector *connector;
12260         unsigned int used_ports = 0;
12261
12262         /*
12263          * Walk the connector list instead of the encoder
12264          * list to detect the problem on ddi platforms
12265          * where there's just one encoder per digital port.
12266          */
12267         drm_for_each_connector(connector, dev) {
12268                 struct drm_connector_state *connector_state;
12269                 struct intel_encoder *encoder;
12270
12271                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12272                 if (!connector_state)
12273                         connector_state = connector->state;
12274
12275                 if (!connector_state->best_encoder)
12276                         continue;
12277
12278                 encoder = to_intel_encoder(connector_state->best_encoder);
12279
12280                 WARN_ON(!connector_state->crtc);
12281
12282                 switch (encoder->type) {
12283                         unsigned int port_mask;
12284                 case INTEL_OUTPUT_UNKNOWN:
12285                         if (WARN_ON(!HAS_DDI(dev)))
12286                                 break;
12287                 case INTEL_OUTPUT_DISPLAYPORT:
12288                 case INTEL_OUTPUT_HDMI:
12289                 case INTEL_OUTPUT_EDP:
12290                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12291
12292                         /* the same port mustn't appear more than once */
12293                         if (used_ports & port_mask)
12294                                 return false;
12295
12296                         used_ports |= port_mask;
12297                 default:
12298                         break;
12299                 }
12300         }
12301
12302         return true;
12303 }
12304
12305 static void
12306 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12307 {
12308         struct drm_crtc_state tmp_state;
12309         struct intel_crtc_scaler_state scaler_state;
12310         struct intel_dpll_hw_state dpll_hw_state;
12311         struct intel_shared_dpll *shared_dpll;
12312         uint32_t ddi_pll_sel;
12313         bool force_thru;
12314
12315         /* FIXME: before the switch to atomic started, a new pipe_config was
12316          * kzalloc'd. Code that depends on any field being zero should be
12317          * fixed, so that the crtc_state can be safely duplicated. For now,
12318          * only fields that are know to not cause problems are preserved. */
12319
12320         tmp_state = crtc_state->base;
12321         scaler_state = crtc_state->scaler_state;
12322         shared_dpll = crtc_state->shared_dpll;
12323         dpll_hw_state = crtc_state->dpll_hw_state;
12324         ddi_pll_sel = crtc_state->ddi_pll_sel;
12325         force_thru = crtc_state->pch_pfit.force_thru;
12326
12327         memset(crtc_state, 0, sizeof *crtc_state);
12328
12329         crtc_state->base = tmp_state;
12330         crtc_state->scaler_state = scaler_state;
12331         crtc_state->shared_dpll = shared_dpll;
12332         crtc_state->dpll_hw_state = dpll_hw_state;
12333         crtc_state->ddi_pll_sel = ddi_pll_sel;
12334         crtc_state->pch_pfit.force_thru = force_thru;
12335 }
12336
12337 static int
12338 intel_modeset_pipe_config(struct drm_crtc *crtc,
12339                           struct intel_crtc_state *pipe_config)
12340 {
12341         struct drm_atomic_state *state = pipe_config->base.state;
12342         struct intel_encoder *encoder;
12343         struct drm_connector *connector;
12344         struct drm_connector_state *connector_state;
12345         int base_bpp, ret = -EINVAL;
12346         int i;
12347         bool retry = true;
12348
12349         clear_intel_crtc_state(pipe_config);
12350
12351         pipe_config->cpu_transcoder =
12352                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12353
12354         /*
12355          * Sanitize sync polarity flags based on requested ones. If neither
12356          * positive or negative polarity is requested, treat this as meaning
12357          * negative polarity.
12358          */
12359         if (!(pipe_config->base.adjusted_mode.flags &
12360               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12361                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12362
12363         if (!(pipe_config->base.adjusted_mode.flags &
12364               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12365                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12366
12367         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12368                                              pipe_config);
12369         if (base_bpp < 0)
12370                 goto fail;
12371
12372         /*
12373          * Determine the real pipe dimensions. Note that stereo modes can
12374          * increase the actual pipe size due to the frame doubling and
12375          * insertion of additional space for blanks between the frame. This
12376          * is stored in the crtc timings. We use the requested mode to do this
12377          * computation to clearly distinguish it from the adjusted mode, which
12378          * can be changed by the connectors in the below retry loop.
12379          */
12380         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12381                                &pipe_config->pipe_src_w,
12382                                &pipe_config->pipe_src_h);
12383
12384 encoder_retry:
12385         /* Ensure the port clock defaults are reset when retrying. */
12386         pipe_config->port_clock = 0;
12387         pipe_config->pixel_multiplier = 1;
12388
12389         /* Fill in default crtc timings, allow encoders to overwrite them. */
12390         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12391                               CRTC_STEREO_DOUBLE);
12392
12393         /* Pass our mode to the connectors and the CRTC to give them a chance to
12394          * adjust it according to limitations or connector properties, and also
12395          * a chance to reject the mode entirely.
12396          */
12397         for_each_connector_in_state(state, connector, connector_state, i) {
12398                 if (connector_state->crtc != crtc)
12399                         continue;
12400
12401                 encoder = to_intel_encoder(connector_state->best_encoder);
12402
12403                 if (!(encoder->compute_config(encoder, pipe_config))) {
12404                         DRM_DEBUG_KMS("Encoder config failure\n");
12405                         goto fail;
12406                 }
12407         }
12408
12409         /* Set default port clock if not overwritten by the encoder. Needs to be
12410          * done afterwards in case the encoder adjusts the mode. */
12411         if (!pipe_config->port_clock)
12412                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12413                         * pipe_config->pixel_multiplier;
12414
12415         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12416         if (ret < 0) {
12417                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12418                 goto fail;
12419         }
12420
12421         if (ret == RETRY) {
12422                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12423                         ret = -EINVAL;
12424                         goto fail;
12425                 }
12426
12427                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12428                 retry = false;
12429                 goto encoder_retry;
12430         }
12431
12432         /* Dithering seems to not pass-through bits correctly when it should, so
12433          * only enable it on 6bpc panels. */
12434         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12435         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12436                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12437
12438 fail:
12439         return ret;
12440 }
12441
12442 static void
12443 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12444 {
12445         struct drm_crtc *crtc;
12446         struct drm_crtc_state *crtc_state;
12447         int i;
12448
12449         /* Double check state. */
12450         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12451                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12452
12453                 /* Update hwmode for vblank functions */
12454                 if (crtc->state->active)
12455                         crtc->hwmode = crtc->state->adjusted_mode;
12456                 else
12457                         crtc->hwmode.crtc_clock = 0;
12458
12459                 /*
12460                  * Update legacy state to satisfy fbc code. This can
12461                  * be removed when fbc uses the atomic state.
12462                  */
12463                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12464                         struct drm_plane_state *plane_state = crtc->primary->state;
12465
12466                         crtc->primary->fb = plane_state->fb;
12467                         crtc->x = plane_state->src_x >> 16;
12468                         crtc->y = plane_state->src_y >> 16;
12469                 }
12470         }
12471 }
12472
12473 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12474 {
12475         int diff;
12476
12477         if (clock1 == clock2)
12478                 return true;
12479
12480         if (!clock1 || !clock2)
12481                 return false;
12482
12483         diff = abs(clock1 - clock2);
12484
12485         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12486                 return true;
12487
12488         return false;
12489 }
12490
12491 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12492         list_for_each_entry((intel_crtc), \
12493                             &(dev)->mode_config.crtc_list, \
12494                             base.head) \
12495                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12496
12497 static bool
12498 intel_compare_m_n(unsigned int m, unsigned int n,
12499                   unsigned int m2, unsigned int n2,
12500                   bool exact)
12501 {
12502         if (m == m2 && n == n2)
12503                 return true;
12504
12505         if (exact || !m || !n || !m2 || !n2)
12506                 return false;
12507
12508         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12509
12510         if (n > n2) {
12511                 while (n > n2) {
12512                         m2 <<= 1;
12513                         n2 <<= 1;
12514                 }
12515         } else if (n < n2) {
12516                 while (n < n2) {
12517                         m <<= 1;
12518                         n <<= 1;
12519                 }
12520         }
12521
12522         if (n != n2)
12523                 return false;
12524
12525         return intel_fuzzy_clock_check(m, m2);
12526 }
12527
12528 static bool
12529 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12530                        struct intel_link_m_n *m2_n2,
12531                        bool adjust)
12532 {
12533         if (m_n->tu == m2_n2->tu &&
12534             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12535                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12536             intel_compare_m_n(m_n->link_m, m_n->link_n,
12537                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12538                 if (adjust)
12539                         *m2_n2 = *m_n;
12540
12541                 return true;
12542         }
12543
12544         return false;
12545 }
12546
12547 static bool
12548 intel_pipe_config_compare(struct drm_device *dev,
12549                           struct intel_crtc_state *current_config,
12550                           struct intel_crtc_state *pipe_config,
12551                           bool adjust)
12552 {
12553         bool ret = true;
12554
12555 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12556         do { \
12557                 if (!adjust) \
12558                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12559                 else \
12560                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12561         } while (0)
12562
12563 #define PIPE_CONF_CHECK_X(name) \
12564         if (current_config->name != pipe_config->name) { \
12565                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12566                           "(expected 0x%08x, found 0x%08x)\n", \
12567                           current_config->name, \
12568                           pipe_config->name); \
12569                 ret = false; \
12570         }
12571
12572 #define PIPE_CONF_CHECK_I(name) \
12573         if (current_config->name != pipe_config->name) { \
12574                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12575                           "(expected %i, found %i)\n", \
12576                           current_config->name, \
12577                           pipe_config->name); \
12578                 ret = false; \
12579         }
12580
12581 #define PIPE_CONF_CHECK_P(name) \
12582         if (current_config->name != pipe_config->name) { \
12583                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12584                           "(expected %p, found %p)\n", \
12585                           current_config->name, \
12586                           pipe_config->name); \
12587                 ret = false; \
12588         }
12589
12590 #define PIPE_CONF_CHECK_M_N(name) \
12591         if (!intel_compare_link_m_n(&current_config->name, \
12592                                     &pipe_config->name,\
12593                                     adjust)) { \
12594                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12595                           "(expected tu %i gmch %i/%i link %i/%i, " \
12596                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12597                           current_config->name.tu, \
12598                           current_config->name.gmch_m, \
12599                           current_config->name.gmch_n, \
12600                           current_config->name.link_m, \
12601                           current_config->name.link_n, \
12602                           pipe_config->name.tu, \
12603                           pipe_config->name.gmch_m, \
12604                           pipe_config->name.gmch_n, \
12605                           pipe_config->name.link_m, \
12606                           pipe_config->name.link_n); \
12607                 ret = false; \
12608         }
12609
12610 /* This is required for BDW+ where there is only one set of registers for
12611  * switching between high and low RR.
12612  * This macro can be used whenever a comparison has to be made between one
12613  * hw state and multiple sw state variables.
12614  */
12615 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12616         if (!intel_compare_link_m_n(&current_config->name, \
12617                                     &pipe_config->name, adjust) && \
12618             !intel_compare_link_m_n(&current_config->alt_name, \
12619                                     &pipe_config->name, adjust)) { \
12620                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12621                           "(expected tu %i gmch %i/%i link %i/%i, " \
12622                           "or tu %i gmch %i/%i link %i/%i, " \
12623                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12624                           current_config->name.tu, \
12625                           current_config->name.gmch_m, \
12626                           current_config->name.gmch_n, \
12627                           current_config->name.link_m, \
12628                           current_config->name.link_n, \
12629                           current_config->alt_name.tu, \
12630                           current_config->alt_name.gmch_m, \
12631                           current_config->alt_name.gmch_n, \
12632                           current_config->alt_name.link_m, \
12633                           current_config->alt_name.link_n, \
12634                           pipe_config->name.tu, \
12635                           pipe_config->name.gmch_m, \
12636                           pipe_config->name.gmch_n, \
12637                           pipe_config->name.link_m, \
12638                           pipe_config->name.link_n); \
12639                 ret = false; \
12640         }
12641
12642 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12643         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12644                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12645                           "(expected %i, found %i)\n", \
12646                           current_config->name & (mask), \
12647                           pipe_config->name & (mask)); \
12648                 ret = false; \
12649         }
12650
12651 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12652         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12653                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12654                           "(expected %i, found %i)\n", \
12655                           current_config->name, \
12656                           pipe_config->name); \
12657                 ret = false; \
12658         }
12659
12660 #define PIPE_CONF_QUIRK(quirk)  \
12661         ((current_config->quirks | pipe_config->quirks) & (quirk))
12662
12663         PIPE_CONF_CHECK_I(cpu_transcoder);
12664
12665         PIPE_CONF_CHECK_I(has_pch_encoder);
12666         PIPE_CONF_CHECK_I(fdi_lanes);
12667         PIPE_CONF_CHECK_M_N(fdi_m_n);
12668
12669         PIPE_CONF_CHECK_I(has_dp_encoder);
12670         PIPE_CONF_CHECK_I(lane_count);
12671
12672         if (INTEL_INFO(dev)->gen < 8) {
12673                 PIPE_CONF_CHECK_M_N(dp_m_n);
12674
12675                 if (current_config->has_drrs)
12676                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12677         } else
12678                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12679
12680         PIPE_CONF_CHECK_I(has_dsi_encoder);
12681
12682         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12683         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12684         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12685         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12686         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12687         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12688
12689         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12690         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12691         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12692         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12693         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12694         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12695
12696         PIPE_CONF_CHECK_I(pixel_multiplier);
12697         PIPE_CONF_CHECK_I(has_hdmi_sink);
12698         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12699             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12700                 PIPE_CONF_CHECK_I(limited_color_range);
12701         PIPE_CONF_CHECK_I(has_infoframe);
12702
12703         PIPE_CONF_CHECK_I(has_audio);
12704
12705         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12706                               DRM_MODE_FLAG_INTERLACE);
12707
12708         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12709                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12710                                       DRM_MODE_FLAG_PHSYNC);
12711                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12712                                       DRM_MODE_FLAG_NHSYNC);
12713                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12714                                       DRM_MODE_FLAG_PVSYNC);
12715                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12716                                       DRM_MODE_FLAG_NVSYNC);
12717         }
12718
12719         PIPE_CONF_CHECK_X(gmch_pfit.control);
12720         /* pfit ratios are autocomputed by the hw on gen4+ */
12721         if (INTEL_INFO(dev)->gen < 4)
12722                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12723         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12724
12725         if (!adjust) {
12726                 PIPE_CONF_CHECK_I(pipe_src_w);
12727                 PIPE_CONF_CHECK_I(pipe_src_h);
12728
12729                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12730                 if (current_config->pch_pfit.enabled) {
12731                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12732                         PIPE_CONF_CHECK_X(pch_pfit.size);
12733                 }
12734
12735                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12736         }
12737
12738         /* BDW+ don't expose a synchronous way to read the state */
12739         if (IS_HASWELL(dev))
12740                 PIPE_CONF_CHECK_I(ips_enabled);
12741
12742         PIPE_CONF_CHECK_I(double_wide);
12743
12744         PIPE_CONF_CHECK_X(ddi_pll_sel);
12745
12746         PIPE_CONF_CHECK_P(shared_dpll);
12747         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12748         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12749         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12750         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12751         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12752         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12753         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12754         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12755         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12756
12757         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12758         PIPE_CONF_CHECK_X(dsi_pll.div);
12759
12760         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12761                 PIPE_CONF_CHECK_I(pipe_bpp);
12762
12763         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12764         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12765
12766 #undef PIPE_CONF_CHECK_X
12767 #undef PIPE_CONF_CHECK_I
12768 #undef PIPE_CONF_CHECK_P
12769 #undef PIPE_CONF_CHECK_FLAGS
12770 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12771 #undef PIPE_CONF_QUIRK
12772 #undef INTEL_ERR_OR_DBG_KMS
12773
12774         return ret;
12775 }
12776
12777 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12778                                            const struct intel_crtc_state *pipe_config)
12779 {
12780         if (pipe_config->has_pch_encoder) {
12781                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12782                                                             &pipe_config->fdi_m_n);
12783                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12784
12785                 /*
12786                  * FDI already provided one idea for the dotclock.
12787                  * Yell if the encoder disagrees.
12788                  */
12789                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12790                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12791                      fdi_dotclock, dotclock);
12792         }
12793 }
12794
12795 static void verify_wm_state(struct drm_crtc *crtc,
12796                             struct drm_crtc_state *new_state)
12797 {
12798         struct drm_device *dev = crtc->dev;
12799         struct drm_i915_private *dev_priv = dev->dev_private;
12800         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12801         struct skl_ddb_entry *hw_entry, *sw_entry;
12802         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12803         const enum pipe pipe = intel_crtc->pipe;
12804         int plane;
12805
12806         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12807                 return;
12808
12809         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12810         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12811
12812         /* planes */
12813         for_each_plane(dev_priv, pipe, plane) {
12814                 hw_entry = &hw_ddb.plane[pipe][plane];
12815                 sw_entry = &sw_ddb->plane[pipe][plane];
12816
12817                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12818                         continue;
12819
12820                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12821                           "(expected (%u,%u), found (%u,%u))\n",
12822                           pipe_name(pipe), plane + 1,
12823                           sw_entry->start, sw_entry->end,
12824                           hw_entry->start, hw_entry->end);
12825         }
12826
12827         /* cursor */
12828         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12829         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12830
12831         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12832                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12833                           "(expected (%u,%u), found (%u,%u))\n",
12834                           pipe_name(pipe),
12835                           sw_entry->start, sw_entry->end,
12836                           hw_entry->start, hw_entry->end);
12837         }
12838 }
12839
12840 static void
12841 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12842 {
12843         struct drm_connector *connector;
12844
12845         drm_for_each_connector(connector, dev) {
12846                 struct drm_encoder *encoder = connector->encoder;
12847                 struct drm_connector_state *state = connector->state;
12848
12849                 if (state->crtc != crtc)
12850                         continue;
12851
12852                 intel_connector_verify_state(to_intel_connector(connector));
12853
12854                 I915_STATE_WARN(state->best_encoder != encoder,
12855                      "connector's atomic encoder doesn't match legacy encoder\n");
12856         }
12857 }
12858
12859 static void
12860 verify_encoder_state(struct drm_device *dev)
12861 {
12862         struct intel_encoder *encoder;
12863         struct intel_connector *connector;
12864
12865         for_each_intel_encoder(dev, encoder) {
12866                 bool enabled = false;
12867                 enum pipe pipe;
12868
12869                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12870                               encoder->base.base.id,
12871                               encoder->base.name);
12872
12873                 for_each_intel_connector(dev, connector) {
12874                         if (connector->base.state->best_encoder != &encoder->base)
12875                                 continue;
12876                         enabled = true;
12877
12878                         I915_STATE_WARN(connector->base.state->crtc !=
12879                                         encoder->base.crtc,
12880                              "connector's crtc doesn't match encoder crtc\n");
12881                 }
12882
12883                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12884                      "encoder's enabled state mismatch "
12885                      "(expected %i, found %i)\n",
12886                      !!encoder->base.crtc, enabled);
12887
12888                 if (!encoder->base.crtc) {
12889                         bool active;
12890
12891                         active = encoder->get_hw_state(encoder, &pipe);
12892                         I915_STATE_WARN(active,
12893                              "encoder detached but still enabled on pipe %c.\n",
12894                              pipe_name(pipe));
12895                 }
12896         }
12897 }
12898
12899 static void
12900 verify_crtc_state(struct drm_crtc *crtc,
12901                   struct drm_crtc_state *old_crtc_state,
12902                   struct drm_crtc_state *new_crtc_state)
12903 {
12904         struct drm_device *dev = crtc->dev;
12905         struct drm_i915_private *dev_priv = dev->dev_private;
12906         struct intel_encoder *encoder;
12907         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12908         struct intel_crtc_state *pipe_config, *sw_config;
12909         struct drm_atomic_state *old_state;
12910         bool active;
12911
12912         old_state = old_crtc_state->state;
12913         __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12914         pipe_config = to_intel_crtc_state(old_crtc_state);
12915         memset(pipe_config, 0, sizeof(*pipe_config));
12916         pipe_config->base.crtc = crtc;
12917         pipe_config->base.state = old_state;
12918
12919         DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
12920
12921         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12922
12923         /* hw state is inconsistent with the pipe quirk */
12924         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12925             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12926                 active = new_crtc_state->active;
12927
12928         I915_STATE_WARN(new_crtc_state->active != active,
12929              "crtc active state doesn't match with hw state "
12930              "(expected %i, found %i)\n", new_crtc_state->active, active);
12931
12932         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12933              "transitional active state does not match atomic hw state "
12934              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12935
12936         for_each_encoder_on_crtc(dev, crtc, encoder) {
12937                 enum pipe pipe;
12938
12939                 active = encoder->get_hw_state(encoder, &pipe);
12940                 I915_STATE_WARN(active != new_crtc_state->active,
12941                         "[ENCODER:%i] active %i with crtc active %i\n",
12942                         encoder->base.base.id, active, new_crtc_state->active);
12943
12944                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12945                                 "Encoder connected to wrong pipe %c\n",
12946                                 pipe_name(pipe));
12947
12948                 if (active)
12949                         encoder->get_config(encoder, pipe_config);
12950         }
12951
12952         if (!new_crtc_state->active)
12953                 return;
12954
12955         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12956
12957         sw_config = to_intel_crtc_state(crtc->state);
12958         if (!intel_pipe_config_compare(dev, sw_config,
12959                                        pipe_config, false)) {
12960                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12961                 intel_dump_pipe_config(intel_crtc, pipe_config,
12962                                        "[hw state]");
12963                 intel_dump_pipe_config(intel_crtc, sw_config,
12964                                        "[sw state]");
12965         }
12966 }
12967
12968 static void
12969 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12970                          struct intel_shared_dpll *pll,
12971                          struct drm_crtc *crtc,
12972                          struct drm_crtc_state *new_state)
12973 {
12974         struct intel_dpll_hw_state dpll_hw_state;
12975         unsigned crtc_mask;
12976         bool active;
12977
12978         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12979
12980         DRM_DEBUG_KMS("%s\n", pll->name);
12981
12982         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12983
12984         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12985                 I915_STATE_WARN(!pll->on && pll->active_mask,
12986                      "pll in active use but not on in sw tracking\n");
12987                 I915_STATE_WARN(pll->on && !pll->active_mask,
12988                      "pll is on but not used by any active crtc\n");
12989                 I915_STATE_WARN(pll->on != active,
12990                      "pll on state mismatch (expected %i, found %i)\n",
12991                      pll->on, active);
12992         }
12993
12994         if (!crtc) {
12995                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12996                                 "more active pll users than references: %x vs %x\n",
12997                                 pll->active_mask, pll->config.crtc_mask);
12998
12999                 return;
13000         }
13001
13002         crtc_mask = 1 << drm_crtc_index(crtc);
13003
13004         if (new_state->active)
13005                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13006                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13007                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13008         else
13009                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13010                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13011                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13012
13013         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13014                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13015                         crtc_mask, pll->config.crtc_mask);
13016
13017         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13018                                           &dpll_hw_state,
13019                                           sizeof(dpll_hw_state)),
13020                         "pll hw state mismatch\n");
13021 }
13022
13023 static void
13024 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13025                          struct drm_crtc_state *old_crtc_state,
13026                          struct drm_crtc_state *new_crtc_state)
13027 {
13028         struct drm_i915_private *dev_priv = dev->dev_private;
13029         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13030         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13031
13032         if (new_state->shared_dpll)
13033                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13034
13035         if (old_state->shared_dpll &&
13036             old_state->shared_dpll != new_state->shared_dpll) {
13037                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13038                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13039
13040                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13041                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13042                                 pipe_name(drm_crtc_index(crtc)));
13043                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13044                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13045                                 pipe_name(drm_crtc_index(crtc)));
13046         }
13047 }
13048
13049 static void
13050 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13051                          struct drm_crtc_state *old_state,
13052                          struct drm_crtc_state *new_state)
13053 {
13054         if (!needs_modeset(new_state) &&
13055             !to_intel_crtc_state(new_state)->update_pipe)
13056                 return;
13057
13058         verify_wm_state(crtc, new_state);
13059         verify_connector_state(crtc->dev, crtc);
13060         verify_crtc_state(crtc, old_state, new_state);
13061         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13062 }
13063
13064 static void
13065 verify_disabled_dpll_state(struct drm_device *dev)
13066 {
13067         struct drm_i915_private *dev_priv = dev->dev_private;
13068         int i;
13069
13070         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13071                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13072 }
13073
13074 static void
13075 intel_modeset_verify_disabled(struct drm_device *dev)
13076 {
13077         verify_encoder_state(dev);
13078         verify_connector_state(dev, NULL);
13079         verify_disabled_dpll_state(dev);
13080 }
13081
13082 static void update_scanline_offset(struct intel_crtc *crtc)
13083 {
13084         struct drm_device *dev = crtc->base.dev;
13085
13086         /*
13087          * The scanline counter increments at the leading edge of hsync.
13088          *
13089          * On most platforms it starts counting from vtotal-1 on the
13090          * first active line. That means the scanline counter value is
13091          * always one less than what we would expect. Ie. just after
13092          * start of vblank, which also occurs at start of hsync (on the
13093          * last active line), the scanline counter will read vblank_start-1.
13094          *
13095          * On gen2 the scanline counter starts counting from 1 instead
13096          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13097          * to keep the value positive), instead of adding one.
13098          *
13099          * On HSW+ the behaviour of the scanline counter depends on the output
13100          * type. For DP ports it behaves like most other platforms, but on HDMI
13101          * there's an extra 1 line difference. So we need to add two instead of
13102          * one to the value.
13103          */
13104         if (IS_GEN2(dev)) {
13105                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13106                 int vtotal;
13107
13108                 vtotal = adjusted_mode->crtc_vtotal;
13109                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13110                         vtotal /= 2;
13111
13112                 crtc->scanline_offset = vtotal - 1;
13113         } else if (HAS_DDI(dev) &&
13114                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13115                 crtc->scanline_offset = 2;
13116         } else
13117                 crtc->scanline_offset = 1;
13118 }
13119
13120 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13121 {
13122         struct drm_device *dev = state->dev;
13123         struct drm_i915_private *dev_priv = to_i915(dev);
13124         struct intel_shared_dpll_config *shared_dpll = NULL;
13125         struct drm_crtc *crtc;
13126         struct drm_crtc_state *crtc_state;
13127         int i;
13128
13129         if (!dev_priv->display.crtc_compute_clock)
13130                 return;
13131
13132         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13133                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13134                 struct intel_shared_dpll *old_dpll =
13135                         to_intel_crtc_state(crtc->state)->shared_dpll;
13136
13137                 if (!needs_modeset(crtc_state))
13138                         continue;
13139
13140                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13141
13142                 if (!old_dpll)
13143                         continue;
13144
13145                 if (!shared_dpll)
13146                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13147
13148                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13149         }
13150 }
13151
13152 /*
13153  * This implements the workaround described in the "notes" section of the mode
13154  * set sequence documentation. When going from no pipes or single pipe to
13155  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13156  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13157  */
13158 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13159 {
13160         struct drm_crtc_state *crtc_state;
13161         struct intel_crtc *intel_crtc;
13162         struct drm_crtc *crtc;
13163         struct intel_crtc_state *first_crtc_state = NULL;
13164         struct intel_crtc_state *other_crtc_state = NULL;
13165         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13166         int i;
13167
13168         /* look at all crtc's that are going to be enabled in during modeset */
13169         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13170                 intel_crtc = to_intel_crtc(crtc);
13171
13172                 if (!crtc_state->active || !needs_modeset(crtc_state))
13173                         continue;
13174
13175                 if (first_crtc_state) {
13176                         other_crtc_state = to_intel_crtc_state(crtc_state);
13177                         break;
13178                 } else {
13179                         first_crtc_state = to_intel_crtc_state(crtc_state);
13180                         first_pipe = intel_crtc->pipe;
13181                 }
13182         }
13183
13184         /* No workaround needed? */
13185         if (!first_crtc_state)
13186                 return 0;
13187
13188         /* w/a possibly needed, check how many crtc's are already enabled. */
13189         for_each_intel_crtc(state->dev, intel_crtc) {
13190                 struct intel_crtc_state *pipe_config;
13191
13192                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13193                 if (IS_ERR(pipe_config))
13194                         return PTR_ERR(pipe_config);
13195
13196                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13197
13198                 if (!pipe_config->base.active ||
13199                     needs_modeset(&pipe_config->base))
13200                         continue;
13201
13202                 /* 2 or more enabled crtcs means no need for w/a */
13203                 if (enabled_pipe != INVALID_PIPE)
13204                         return 0;
13205
13206                 enabled_pipe = intel_crtc->pipe;
13207         }
13208
13209         if (enabled_pipe != INVALID_PIPE)
13210                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13211         else if (other_crtc_state)
13212                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13213
13214         return 0;
13215 }
13216
13217 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13218 {
13219         struct drm_crtc *crtc;
13220         struct drm_crtc_state *crtc_state;
13221         int ret = 0;
13222
13223         /* add all active pipes to the state */
13224         for_each_crtc(state->dev, crtc) {
13225                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13226                 if (IS_ERR(crtc_state))
13227                         return PTR_ERR(crtc_state);
13228
13229                 if (!crtc_state->active || needs_modeset(crtc_state))
13230                         continue;
13231
13232                 crtc_state->mode_changed = true;
13233
13234                 ret = drm_atomic_add_affected_connectors(state, crtc);
13235                 if (ret)
13236                         break;
13237
13238                 ret = drm_atomic_add_affected_planes(state, crtc);
13239                 if (ret)
13240                         break;
13241         }
13242
13243         return ret;
13244 }
13245
13246 static int intel_modeset_checks(struct drm_atomic_state *state)
13247 {
13248         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13249         struct drm_i915_private *dev_priv = state->dev->dev_private;
13250         struct drm_crtc *crtc;
13251         struct drm_crtc_state *crtc_state;
13252         int ret = 0, i;
13253
13254         if (!check_digital_port_conflicts(state)) {
13255                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13256                 return -EINVAL;
13257         }
13258
13259         intel_state->modeset = true;
13260         intel_state->active_crtcs = dev_priv->active_crtcs;
13261
13262         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13263                 if (crtc_state->active)
13264                         intel_state->active_crtcs |= 1 << i;
13265                 else
13266                         intel_state->active_crtcs &= ~(1 << i);
13267
13268                 if (crtc_state->active != crtc->state->active)
13269                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13270         }
13271
13272         /*
13273          * See if the config requires any additional preparation, e.g.
13274          * to adjust global state with pipes off.  We need to do this
13275          * here so we can get the modeset_pipe updated config for the new
13276          * mode set on this crtc.  For other crtcs we need to use the
13277          * adjusted_mode bits in the crtc directly.
13278          */
13279         if (dev_priv->display.modeset_calc_cdclk) {
13280                 ret = dev_priv->display.modeset_calc_cdclk(state);
13281
13282                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13283                         ret = intel_modeset_all_pipes(state);
13284
13285                 if (ret < 0)
13286                         return ret;
13287
13288                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13289                               intel_state->cdclk, intel_state->dev_cdclk);
13290         } else
13291                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13292
13293         intel_modeset_clear_plls(state);
13294
13295         if (IS_HASWELL(dev_priv))
13296                 return haswell_mode_set_planes_workaround(state);
13297
13298         return 0;
13299 }
13300
13301 /*
13302  * Handle calculation of various watermark data at the end of the atomic check
13303  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13304  * handlers to ensure that all derived state has been updated.
13305  */
13306 static int calc_watermark_data(struct drm_atomic_state *state)
13307 {
13308         struct drm_device *dev = state->dev;
13309         struct drm_i915_private *dev_priv = to_i915(dev);
13310
13311         /* Is there platform-specific watermark information to calculate? */
13312         if (dev_priv->display.compute_global_watermarks)
13313                 return dev_priv->display.compute_global_watermarks(state);
13314
13315         return 0;
13316 }
13317
13318 /**
13319  * intel_atomic_check - validate state object
13320  * @dev: drm device
13321  * @state: state to validate
13322  */
13323 static int intel_atomic_check(struct drm_device *dev,
13324                               struct drm_atomic_state *state)
13325 {
13326         struct drm_i915_private *dev_priv = to_i915(dev);
13327         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13328         struct drm_crtc *crtc;
13329         struct drm_crtc_state *crtc_state;
13330         int ret, i;
13331         bool any_ms = false;
13332
13333         ret = drm_atomic_helper_check_modeset(dev, state);
13334         if (ret)
13335                 return ret;
13336
13337         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13338                 struct intel_crtc_state *pipe_config =
13339                         to_intel_crtc_state(crtc_state);
13340
13341                 /* Catch I915_MODE_FLAG_INHERITED */
13342                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13343                         crtc_state->mode_changed = true;
13344
13345                 if (!crtc_state->enable) {
13346                         if (needs_modeset(crtc_state))
13347                                 any_ms = true;
13348                         continue;
13349                 }
13350
13351                 if (!needs_modeset(crtc_state))
13352                         continue;
13353
13354                 /* FIXME: For only active_changed we shouldn't need to do any
13355                  * state recomputation at all. */
13356
13357                 ret = drm_atomic_add_affected_connectors(state, crtc);
13358                 if (ret)
13359                         return ret;
13360
13361                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13362                 if (ret) {
13363                         intel_dump_pipe_config(to_intel_crtc(crtc),
13364                                                pipe_config, "[failed]");
13365                         return ret;
13366                 }
13367
13368                 if (i915.fastboot &&
13369                     intel_pipe_config_compare(dev,
13370                                         to_intel_crtc_state(crtc->state),
13371                                         pipe_config, true)) {
13372                         crtc_state->mode_changed = false;
13373                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13374                 }
13375
13376                 if (needs_modeset(crtc_state)) {
13377                         any_ms = true;
13378
13379                         ret = drm_atomic_add_affected_planes(state, crtc);
13380                         if (ret)
13381                                 return ret;
13382                 }
13383
13384                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13385                                        needs_modeset(crtc_state) ?
13386                                        "[modeset]" : "[fastset]");
13387         }
13388
13389         if (any_ms) {
13390                 ret = intel_modeset_checks(state);
13391
13392                 if (ret)
13393                         return ret;
13394         } else
13395                 intel_state->cdclk = dev_priv->cdclk_freq;
13396
13397         ret = drm_atomic_helper_check_planes(dev, state);
13398         if (ret)
13399                 return ret;
13400
13401         intel_fbc_choose_crtc(dev_priv, state);
13402         return calc_watermark_data(state);
13403 }
13404
13405 static int intel_atomic_prepare_commit(struct drm_device *dev,
13406                                        struct drm_atomic_state *state,
13407                                        bool async)
13408 {
13409         struct drm_i915_private *dev_priv = dev->dev_private;
13410         struct drm_plane_state *plane_state;
13411         struct drm_crtc_state *crtc_state;
13412         struct drm_plane *plane;
13413         struct drm_crtc *crtc;
13414         int i, ret;
13415
13416         if (async) {
13417                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13418                 return -EINVAL;
13419         }
13420
13421         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13422                 if (state->legacy_cursor_update)
13423                         continue;
13424
13425                 ret = intel_crtc_wait_for_pending_flips(crtc);
13426                 if (ret)
13427                         return ret;
13428
13429                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13430                         flush_workqueue(dev_priv->wq);
13431         }
13432
13433         ret = mutex_lock_interruptible(&dev->struct_mutex);
13434         if (ret)
13435                 return ret;
13436
13437         ret = drm_atomic_helper_prepare_planes(dev, state);
13438         mutex_unlock(&dev->struct_mutex);
13439
13440         if (!ret && !async) {
13441                 for_each_plane_in_state(state, plane, plane_state, i) {
13442                         struct intel_plane_state *intel_plane_state =
13443                                 to_intel_plane_state(plane_state);
13444
13445                         if (!intel_plane_state->wait_req)
13446                                 continue;
13447
13448                         ret = __i915_wait_request(intel_plane_state->wait_req,
13449                                                   true, NULL, NULL);
13450                         if (ret) {
13451                                 /* Any hang should be swallowed by the wait */
13452                                 WARN_ON(ret == -EIO);
13453                                 mutex_lock(&dev->struct_mutex);
13454                                 drm_atomic_helper_cleanup_planes(dev, state);
13455                                 mutex_unlock(&dev->struct_mutex);
13456                                 break;
13457                         }
13458                 }
13459         }
13460
13461         return ret;
13462 }
13463
13464 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13465                                           struct drm_i915_private *dev_priv,
13466                                           unsigned crtc_mask)
13467 {
13468         unsigned last_vblank_count[I915_MAX_PIPES];
13469         enum pipe pipe;
13470         int ret;
13471
13472         if (!crtc_mask)
13473                 return;
13474
13475         for_each_pipe(dev_priv, pipe) {
13476                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13477
13478                 if (!((1 << pipe) & crtc_mask))
13479                         continue;
13480
13481                 ret = drm_crtc_vblank_get(crtc);
13482                 if (WARN_ON(ret != 0)) {
13483                         crtc_mask &= ~(1 << pipe);
13484                         continue;
13485                 }
13486
13487                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13488         }
13489
13490         for_each_pipe(dev_priv, pipe) {
13491                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13492                 long lret;
13493
13494                 if (!((1 << pipe) & crtc_mask))
13495                         continue;
13496
13497                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13498                                 last_vblank_count[pipe] !=
13499                                         drm_crtc_vblank_count(crtc),
13500                                 msecs_to_jiffies(50));
13501
13502                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13503
13504                 drm_crtc_vblank_put(crtc);
13505         }
13506 }
13507
13508 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13509 {
13510         /* fb updated, need to unpin old fb */
13511         if (crtc_state->fb_changed)
13512                 return true;
13513
13514         /* wm changes, need vblank before final wm's */
13515         if (crtc_state->update_wm_post)
13516                 return true;
13517
13518         /*
13519          * cxsr is re-enabled after vblank.
13520          * This is already handled by crtc_state->update_wm_post,
13521          * but added for clarity.
13522          */
13523         if (crtc_state->disable_cxsr)
13524                 return true;
13525
13526         return false;
13527 }
13528
13529 /**
13530  * intel_atomic_commit - commit validated state object
13531  * @dev: DRM device
13532  * @state: the top-level driver state object
13533  * @async: asynchronous commit
13534  *
13535  * This function commits a top-level state object that has been validated
13536  * with drm_atomic_helper_check().
13537  *
13538  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13539  * we can only handle plane-related operations and do not yet support
13540  * asynchronous commit.
13541  *
13542  * RETURNS
13543  * Zero for success or -errno.
13544  */
13545 static int intel_atomic_commit(struct drm_device *dev,
13546                                struct drm_atomic_state *state,
13547                                bool async)
13548 {
13549         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13550         struct drm_i915_private *dev_priv = dev->dev_private;
13551         struct drm_crtc_state *old_crtc_state;
13552         struct drm_crtc *crtc;
13553         struct intel_crtc_state *intel_cstate;
13554         int ret = 0, i;
13555         bool hw_check = intel_state->modeset;
13556         unsigned long put_domains[I915_MAX_PIPES] = {};
13557         unsigned crtc_vblank_mask = 0;
13558
13559         ret = intel_atomic_prepare_commit(dev, state, async);
13560         if (ret) {
13561                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13562                 return ret;
13563         }
13564
13565         drm_atomic_helper_swap_state(dev, state);
13566         dev_priv->wm.distrust_bios_wm = false;
13567         dev_priv->wm.skl_results = intel_state->wm_results;
13568         intel_shared_dpll_commit(state);
13569
13570         if (intel_state->modeset) {
13571                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13572                        sizeof(intel_state->min_pixclk));
13573                 dev_priv->active_crtcs = intel_state->active_crtcs;
13574                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13575
13576                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13577         }
13578
13579         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13580                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13581
13582                 if (needs_modeset(crtc->state) ||
13583                     to_intel_crtc_state(crtc->state)->update_pipe) {
13584                         hw_check = true;
13585
13586                         put_domains[to_intel_crtc(crtc)->pipe] =
13587                                 modeset_get_crtc_power_domains(crtc,
13588                                         to_intel_crtc_state(crtc->state));
13589                 }
13590
13591                 if (!needs_modeset(crtc->state))
13592                         continue;
13593
13594                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13595
13596                 if (old_crtc_state->active) {
13597                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13598                         dev_priv->display.crtc_disable(crtc);
13599                         intel_crtc->active = false;
13600                         intel_fbc_disable(intel_crtc);
13601                         intel_disable_shared_dpll(intel_crtc);
13602
13603                         /*
13604                          * Underruns don't always raise
13605                          * interrupts, so check manually.
13606                          */
13607                         intel_check_cpu_fifo_underruns(dev_priv);
13608                         intel_check_pch_fifo_underruns(dev_priv);
13609
13610                         if (!crtc->state->active)
13611                                 intel_update_watermarks(crtc);
13612                 }
13613         }
13614
13615         /* Only after disabling all output pipelines that will be changed can we
13616          * update the the output configuration. */
13617         intel_modeset_update_crtc_state(state);
13618
13619         if (intel_state->modeset) {
13620                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13621
13622                 if (dev_priv->display.modeset_commit_cdclk &&
13623                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13624                         dev_priv->display.modeset_commit_cdclk(state);
13625
13626                 intel_modeset_verify_disabled(dev);
13627         }
13628
13629         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13630         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13631                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13632                 bool modeset = needs_modeset(crtc->state);
13633                 struct intel_crtc_state *pipe_config =
13634                         to_intel_crtc_state(crtc->state);
13635                 bool update_pipe = !modeset && pipe_config->update_pipe;
13636
13637                 if (modeset && crtc->state->active) {
13638                         update_scanline_offset(to_intel_crtc(crtc));
13639                         dev_priv->display.crtc_enable(crtc);
13640                 }
13641
13642                 if (!modeset)
13643                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13644
13645                 if (crtc->state->active &&
13646                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13647                         intel_fbc_enable(intel_crtc);
13648
13649                 if (crtc->state->active &&
13650                     (crtc->state->planes_changed || update_pipe))
13651                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13652
13653                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13654                         crtc_vblank_mask |= 1 << i;
13655         }
13656
13657         /* FIXME: add subpixel order */
13658
13659         if (!state->legacy_cursor_update)
13660                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13661
13662         /*
13663          * Now that the vblank has passed, we can go ahead and program the
13664          * optimal watermarks on platforms that need two-step watermark
13665          * programming.
13666          *
13667          * TODO: Move this (and other cleanup) to an async worker eventually.
13668          */
13669         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13670                 intel_cstate = to_intel_crtc_state(crtc->state);
13671
13672                 if (dev_priv->display.optimize_watermarks)
13673                         dev_priv->display.optimize_watermarks(intel_cstate);
13674         }
13675
13676         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13677                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13678
13679                 if (put_domains[i])
13680                         modeset_put_power_domains(dev_priv, put_domains[i]);
13681
13682                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13683         }
13684
13685         if (intel_state->modeset)
13686                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13687
13688         mutex_lock(&dev->struct_mutex);
13689         drm_atomic_helper_cleanup_planes(dev, state);
13690         mutex_unlock(&dev->struct_mutex);
13691
13692         drm_atomic_state_free(state);
13693
13694         /* As one of the primary mmio accessors, KMS has a high likelihood
13695          * of triggering bugs in unclaimed access. After we finish
13696          * modesetting, see if an error has been flagged, and if so
13697          * enable debugging for the next modeset - and hope we catch
13698          * the culprit.
13699          *
13700          * XXX note that we assume display power is on at this point.
13701          * This might hold true now but we need to add pm helper to check
13702          * unclaimed only when the hardware is on, as atomic commits
13703          * can happen also when the device is completely off.
13704          */
13705         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13706
13707         return 0;
13708 }
13709
13710 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13711 {
13712         struct drm_device *dev = crtc->dev;
13713         struct drm_atomic_state *state;
13714         struct drm_crtc_state *crtc_state;
13715         int ret;
13716
13717         state = drm_atomic_state_alloc(dev);
13718         if (!state) {
13719                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13720                               crtc->base.id);
13721                 return;
13722         }
13723
13724         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13725
13726 retry:
13727         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13728         ret = PTR_ERR_OR_ZERO(crtc_state);
13729         if (!ret) {
13730                 if (!crtc_state->active)
13731                         goto out;
13732
13733                 crtc_state->mode_changed = true;
13734                 ret = drm_atomic_commit(state);
13735         }
13736
13737         if (ret == -EDEADLK) {
13738                 drm_atomic_state_clear(state);
13739                 drm_modeset_backoff(state->acquire_ctx);
13740                 goto retry;
13741         }
13742
13743         if (ret)
13744 out:
13745                 drm_atomic_state_free(state);
13746 }
13747
13748 #undef for_each_intel_crtc_masked
13749
13750 static const struct drm_crtc_funcs intel_crtc_funcs = {
13751         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13752         .set_config = drm_atomic_helper_set_config,
13753         .set_property = drm_atomic_helper_crtc_set_property,
13754         .destroy = intel_crtc_destroy,
13755         .page_flip = intel_crtc_page_flip,
13756         .atomic_duplicate_state = intel_crtc_duplicate_state,
13757         .atomic_destroy_state = intel_crtc_destroy_state,
13758 };
13759
13760 /**
13761  * intel_prepare_plane_fb - Prepare fb for usage on plane
13762  * @plane: drm plane to prepare for
13763  * @fb: framebuffer to prepare for presentation
13764  *
13765  * Prepares a framebuffer for usage on a display plane.  Generally this
13766  * involves pinning the underlying object and updating the frontbuffer tracking
13767  * bits.  Some older platforms need special physical address handling for
13768  * cursor planes.
13769  *
13770  * Must be called with struct_mutex held.
13771  *
13772  * Returns 0 on success, negative error code on failure.
13773  */
13774 int
13775 intel_prepare_plane_fb(struct drm_plane *plane,
13776                        const struct drm_plane_state *new_state)
13777 {
13778         struct drm_device *dev = plane->dev;
13779         struct drm_framebuffer *fb = new_state->fb;
13780         struct intel_plane *intel_plane = to_intel_plane(plane);
13781         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13782         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13783         int ret = 0;
13784
13785         if (!obj && !old_obj)
13786                 return 0;
13787
13788         if (old_obj) {
13789                 struct drm_crtc_state *crtc_state =
13790                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13791
13792                 /* Big Hammer, we also need to ensure that any pending
13793                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13794                  * current scanout is retired before unpinning the old
13795                  * framebuffer. Note that we rely on userspace rendering
13796                  * into the buffer attached to the pipe they are waiting
13797                  * on. If not, userspace generates a GPU hang with IPEHR
13798                  * point to the MI_WAIT_FOR_EVENT.
13799                  *
13800                  * This should only fail upon a hung GPU, in which case we
13801                  * can safely continue.
13802                  */
13803                 if (needs_modeset(crtc_state))
13804                         ret = i915_gem_object_wait_rendering(old_obj, true);
13805                 if (ret) {
13806                         /* GPU hangs should have been swallowed by the wait */
13807                         WARN_ON(ret == -EIO);
13808                         return ret;
13809                 }
13810         }
13811
13812         /* For framebuffer backed by dmabuf, wait for fence */
13813         if (obj && obj->base.dma_buf) {
13814                 long lret;
13815
13816                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13817                                                            false, true,
13818                                                            MAX_SCHEDULE_TIMEOUT);
13819                 if (lret == -ERESTARTSYS)
13820                         return lret;
13821
13822                 WARN(lret < 0, "waiting returns %li\n", lret);
13823         }
13824
13825         if (!obj) {
13826                 ret = 0;
13827         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13828             INTEL_INFO(dev)->cursor_needs_physical) {
13829                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13830                 ret = i915_gem_object_attach_phys(obj, align);
13831                 if (ret)
13832                         DRM_DEBUG_KMS("failed to attach phys object\n");
13833         } else {
13834                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13835         }
13836
13837         if (ret == 0) {
13838                 if (obj) {
13839                         struct intel_plane_state *plane_state =
13840                                 to_intel_plane_state(new_state);
13841
13842                         i915_gem_request_assign(&plane_state->wait_req,
13843                                                 obj->last_write_req);
13844                 }
13845
13846                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13847         }
13848
13849         return ret;
13850 }
13851
13852 /**
13853  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13854  * @plane: drm plane to clean up for
13855  * @fb: old framebuffer that was on plane
13856  *
13857  * Cleans up a framebuffer that has just been removed from a plane.
13858  *
13859  * Must be called with struct_mutex held.
13860  */
13861 void
13862 intel_cleanup_plane_fb(struct drm_plane *plane,
13863                        const struct drm_plane_state *old_state)
13864 {
13865         struct drm_device *dev = plane->dev;
13866         struct intel_plane *intel_plane = to_intel_plane(plane);
13867         struct intel_plane_state *old_intel_state;
13868         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13869         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13870
13871         old_intel_state = to_intel_plane_state(old_state);
13872
13873         if (!obj && !old_obj)
13874                 return;
13875
13876         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13877             !INTEL_INFO(dev)->cursor_needs_physical))
13878                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13879
13880         /* prepare_fb aborted? */
13881         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13882             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13883                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13884
13885         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13886 }
13887
13888 int
13889 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13890 {
13891         int max_scale;
13892         struct drm_device *dev;
13893         struct drm_i915_private *dev_priv;
13894         int crtc_clock, cdclk;
13895
13896         if (!intel_crtc || !crtc_state->base.enable)
13897                 return DRM_PLANE_HELPER_NO_SCALING;
13898
13899         dev = intel_crtc->base.dev;
13900         dev_priv = dev->dev_private;
13901         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13902         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13903
13904         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13905                 return DRM_PLANE_HELPER_NO_SCALING;
13906
13907         /*
13908          * skl max scale is lower of:
13909          *    close to 3 but not 3, -1 is for that purpose
13910          *            or
13911          *    cdclk/crtc_clock
13912          */
13913         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13914
13915         return max_scale;
13916 }
13917
13918 static int
13919 intel_check_primary_plane(struct drm_plane *plane,
13920                           struct intel_crtc_state *crtc_state,
13921                           struct intel_plane_state *state)
13922 {
13923         struct drm_crtc *crtc = state->base.crtc;
13924         struct drm_framebuffer *fb = state->base.fb;
13925         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13926         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13927         bool can_position = false;
13928
13929         if (INTEL_INFO(plane->dev)->gen >= 9) {
13930                 /* use scaler when colorkey is not required */
13931                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13932                         min_scale = 1;
13933                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13934                 }
13935                 can_position = true;
13936         }
13937
13938         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13939                                              &state->dst, &state->clip,
13940                                              min_scale, max_scale,
13941                                              can_position, true,
13942                                              &state->visible);
13943 }
13944
13945 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13946                                     struct drm_crtc_state *old_crtc_state)
13947 {
13948         struct drm_device *dev = crtc->dev;
13949         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13950         struct intel_crtc_state *old_intel_state =
13951                 to_intel_crtc_state(old_crtc_state);
13952         bool modeset = needs_modeset(crtc->state);
13953
13954         /* Perform vblank evasion around commit operation */
13955         intel_pipe_update_start(intel_crtc);
13956
13957         if (modeset)
13958                 return;
13959
13960         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
13961                 intel_color_set_csc(crtc->state);
13962                 intel_color_load_luts(crtc->state);
13963         }
13964
13965         if (to_intel_crtc_state(crtc->state)->update_pipe)
13966                 intel_update_pipe_config(intel_crtc, old_intel_state);
13967         else if (INTEL_INFO(dev)->gen >= 9)
13968                 skl_detach_scalers(intel_crtc);
13969 }
13970
13971 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13972                                      struct drm_crtc_state *old_crtc_state)
13973 {
13974         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13975
13976         intel_pipe_update_end(intel_crtc);
13977 }
13978
13979 /**
13980  * intel_plane_destroy - destroy a plane
13981  * @plane: plane to destroy
13982  *
13983  * Common destruction function for all types of planes (primary, cursor,
13984  * sprite).
13985  */
13986 void intel_plane_destroy(struct drm_plane *plane)
13987 {
13988         struct intel_plane *intel_plane = to_intel_plane(plane);
13989         drm_plane_cleanup(plane);
13990         kfree(intel_plane);
13991 }
13992
13993 const struct drm_plane_funcs intel_plane_funcs = {
13994         .update_plane = drm_atomic_helper_update_plane,
13995         .disable_plane = drm_atomic_helper_disable_plane,
13996         .destroy = intel_plane_destroy,
13997         .set_property = drm_atomic_helper_plane_set_property,
13998         .atomic_get_property = intel_plane_atomic_get_property,
13999         .atomic_set_property = intel_plane_atomic_set_property,
14000         .atomic_duplicate_state = intel_plane_duplicate_state,
14001         .atomic_destroy_state = intel_plane_destroy_state,
14002
14003 };
14004
14005 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14006                                                     int pipe)
14007 {
14008         struct intel_plane *primary = NULL;
14009         struct intel_plane_state *state = NULL;
14010         const uint32_t *intel_primary_formats;
14011         unsigned int num_formats;
14012         int ret;
14013
14014         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14015         if (!primary)
14016                 goto fail;
14017
14018         state = intel_create_plane_state(&primary->base);
14019         if (!state)
14020                 goto fail;
14021         primary->base.state = &state->base;
14022
14023         primary->can_scale = false;
14024         primary->max_downscale = 1;
14025         if (INTEL_INFO(dev)->gen >= 9) {
14026                 primary->can_scale = true;
14027                 state->scaler_id = -1;
14028         }
14029         primary->pipe = pipe;
14030         primary->plane = pipe;
14031         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14032         primary->check_plane = intel_check_primary_plane;
14033         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14034                 primary->plane = !pipe;
14035
14036         if (INTEL_INFO(dev)->gen >= 9) {
14037                 intel_primary_formats = skl_primary_formats;
14038                 num_formats = ARRAY_SIZE(skl_primary_formats);
14039
14040                 primary->update_plane = skylake_update_primary_plane;
14041                 primary->disable_plane = skylake_disable_primary_plane;
14042         } else if (HAS_PCH_SPLIT(dev)) {
14043                 intel_primary_formats = i965_primary_formats;
14044                 num_formats = ARRAY_SIZE(i965_primary_formats);
14045
14046                 primary->update_plane = ironlake_update_primary_plane;
14047                 primary->disable_plane = i9xx_disable_primary_plane;
14048         } else if (INTEL_INFO(dev)->gen >= 4) {
14049                 intel_primary_formats = i965_primary_formats;
14050                 num_formats = ARRAY_SIZE(i965_primary_formats);
14051
14052                 primary->update_plane = i9xx_update_primary_plane;
14053                 primary->disable_plane = i9xx_disable_primary_plane;
14054         } else {
14055                 intel_primary_formats = i8xx_primary_formats;
14056                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14057
14058                 primary->update_plane = i9xx_update_primary_plane;
14059                 primary->disable_plane = i9xx_disable_primary_plane;
14060         }
14061
14062         ret = drm_universal_plane_init(dev, &primary->base, 0,
14063                                        &intel_plane_funcs,
14064                                        intel_primary_formats, num_formats,
14065                                        DRM_PLANE_TYPE_PRIMARY, NULL);
14066         if (ret)
14067                 goto fail;
14068
14069         if (INTEL_INFO(dev)->gen >= 4)
14070                 intel_create_rotation_property(dev, primary);
14071
14072         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14073
14074         return &primary->base;
14075
14076 fail:
14077         kfree(state);
14078         kfree(primary);
14079
14080         return NULL;
14081 }
14082
14083 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14084 {
14085         if (!dev->mode_config.rotation_property) {
14086                 unsigned long flags = BIT(DRM_ROTATE_0) |
14087                         BIT(DRM_ROTATE_180);
14088
14089                 if (INTEL_INFO(dev)->gen >= 9)
14090                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14091
14092                 dev->mode_config.rotation_property =
14093                         drm_mode_create_rotation_property(dev, flags);
14094         }
14095         if (dev->mode_config.rotation_property)
14096                 drm_object_attach_property(&plane->base.base,
14097                                 dev->mode_config.rotation_property,
14098                                 plane->base.state->rotation);
14099 }
14100
14101 static int
14102 intel_check_cursor_plane(struct drm_plane *plane,
14103                          struct intel_crtc_state *crtc_state,
14104                          struct intel_plane_state *state)
14105 {
14106         struct drm_crtc *crtc = crtc_state->base.crtc;
14107         struct drm_framebuffer *fb = state->base.fb;
14108         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14109         enum pipe pipe = to_intel_plane(plane)->pipe;
14110         unsigned stride;
14111         int ret;
14112
14113         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14114                                             &state->dst, &state->clip,
14115                                             DRM_PLANE_HELPER_NO_SCALING,
14116                                             DRM_PLANE_HELPER_NO_SCALING,
14117                                             true, true, &state->visible);
14118         if (ret)
14119                 return ret;
14120
14121         /* if we want to turn off the cursor ignore width and height */
14122         if (!obj)
14123                 return 0;
14124
14125         /* Check for which cursor types we support */
14126         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14127                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14128                           state->base.crtc_w, state->base.crtc_h);
14129                 return -EINVAL;
14130         }
14131
14132         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14133         if (obj->base.size < stride * state->base.crtc_h) {
14134                 DRM_DEBUG_KMS("buffer is too small\n");
14135                 return -ENOMEM;
14136         }
14137
14138         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14139                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14140                 return -EINVAL;
14141         }
14142
14143         /*
14144          * There's something wrong with the cursor on CHV pipe C.
14145          * If it straddles the left edge of the screen then
14146          * moving it away from the edge or disabling it often
14147          * results in a pipe underrun, and often that can lead to
14148          * dead pipe (constant underrun reported, and it scans
14149          * out just a solid color). To recover from that, the
14150          * display power well must be turned off and on again.
14151          * Refuse the put the cursor into that compromised position.
14152          */
14153         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14154             state->visible && state->base.crtc_x < 0) {
14155                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14156                 return -EINVAL;
14157         }
14158
14159         return 0;
14160 }
14161
14162 static void
14163 intel_disable_cursor_plane(struct drm_plane *plane,
14164                            struct drm_crtc *crtc)
14165 {
14166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14167
14168         intel_crtc->cursor_addr = 0;
14169         intel_crtc_update_cursor(crtc, NULL);
14170 }
14171
14172 static void
14173 intel_update_cursor_plane(struct drm_plane *plane,
14174                           const struct intel_crtc_state *crtc_state,
14175                           const struct intel_plane_state *state)
14176 {
14177         struct drm_crtc *crtc = crtc_state->base.crtc;
14178         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14179         struct drm_device *dev = plane->dev;
14180         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14181         uint32_t addr;
14182
14183         if (!obj)
14184                 addr = 0;
14185         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14186                 addr = i915_gem_obj_ggtt_offset(obj);
14187         else
14188                 addr = obj->phys_handle->busaddr;
14189
14190         intel_crtc->cursor_addr = addr;
14191         intel_crtc_update_cursor(crtc, state);
14192 }
14193
14194 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14195                                                    int pipe)
14196 {
14197         struct intel_plane *cursor = NULL;
14198         struct intel_plane_state *state = NULL;
14199         int ret;
14200
14201         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14202         if (!cursor)
14203                 goto fail;
14204
14205         state = intel_create_plane_state(&cursor->base);
14206         if (!state)
14207                 goto fail;
14208         cursor->base.state = &state->base;
14209
14210         cursor->can_scale = false;
14211         cursor->max_downscale = 1;
14212         cursor->pipe = pipe;
14213         cursor->plane = pipe;
14214         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14215         cursor->check_plane = intel_check_cursor_plane;
14216         cursor->update_plane = intel_update_cursor_plane;
14217         cursor->disable_plane = intel_disable_cursor_plane;
14218
14219         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14220                                        &intel_plane_funcs,
14221                                        intel_cursor_formats,
14222                                        ARRAY_SIZE(intel_cursor_formats),
14223                                        DRM_PLANE_TYPE_CURSOR, NULL);
14224         if (ret)
14225                 goto fail;
14226
14227         if (INTEL_INFO(dev)->gen >= 4) {
14228                 if (!dev->mode_config.rotation_property)
14229                         dev->mode_config.rotation_property =
14230                                 drm_mode_create_rotation_property(dev,
14231                                                         BIT(DRM_ROTATE_0) |
14232                                                         BIT(DRM_ROTATE_180));
14233                 if (dev->mode_config.rotation_property)
14234                         drm_object_attach_property(&cursor->base.base,
14235                                 dev->mode_config.rotation_property,
14236                                 state->base.rotation);
14237         }
14238
14239         if (INTEL_INFO(dev)->gen >=9)
14240                 state->scaler_id = -1;
14241
14242         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14243
14244         return &cursor->base;
14245
14246 fail:
14247         kfree(state);
14248         kfree(cursor);
14249
14250         return NULL;
14251 }
14252
14253 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14254         struct intel_crtc_state *crtc_state)
14255 {
14256         int i;
14257         struct intel_scaler *intel_scaler;
14258         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14259
14260         for (i = 0; i < intel_crtc->num_scalers; i++) {
14261                 intel_scaler = &scaler_state->scalers[i];
14262                 intel_scaler->in_use = 0;
14263                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14264         }
14265
14266         scaler_state->scaler_id = -1;
14267 }
14268
14269 static void intel_crtc_init(struct drm_device *dev, int pipe)
14270 {
14271         struct drm_i915_private *dev_priv = dev->dev_private;
14272         struct intel_crtc *intel_crtc;
14273         struct intel_crtc_state *crtc_state = NULL;
14274         struct drm_plane *primary = NULL;
14275         struct drm_plane *cursor = NULL;
14276         int ret;
14277
14278         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14279         if (intel_crtc == NULL)
14280                 return;
14281
14282         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14283         if (!crtc_state)
14284                 goto fail;
14285         intel_crtc->config = crtc_state;
14286         intel_crtc->base.state = &crtc_state->base;
14287         crtc_state->base.crtc = &intel_crtc->base;
14288
14289         /* initialize shared scalers */
14290         if (INTEL_INFO(dev)->gen >= 9) {
14291                 if (pipe == PIPE_C)
14292                         intel_crtc->num_scalers = 1;
14293                 else
14294                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14295
14296                 skl_init_scalers(dev, intel_crtc, crtc_state);
14297         }
14298
14299         primary = intel_primary_plane_create(dev, pipe);
14300         if (!primary)
14301                 goto fail;
14302
14303         cursor = intel_cursor_plane_create(dev, pipe);
14304         if (!cursor)
14305                 goto fail;
14306
14307         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14308                                         cursor, &intel_crtc_funcs, NULL);
14309         if (ret)
14310                 goto fail;
14311
14312         /*
14313          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14314          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14315          */
14316         intel_crtc->pipe = pipe;
14317         intel_crtc->plane = pipe;
14318         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14319                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14320                 intel_crtc->plane = !pipe;
14321         }
14322
14323         intel_crtc->cursor_base = ~0;
14324         intel_crtc->cursor_cntl = ~0;
14325         intel_crtc->cursor_size = ~0;
14326
14327         intel_crtc->wm.cxsr_allowed = true;
14328
14329         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14330                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14331         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14332         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14333
14334         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14335
14336         intel_color_init(&intel_crtc->base);
14337
14338         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14339         return;
14340
14341 fail:
14342         if (primary)
14343                 drm_plane_cleanup(primary);
14344         if (cursor)
14345                 drm_plane_cleanup(cursor);
14346         kfree(crtc_state);
14347         kfree(intel_crtc);
14348 }
14349
14350 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14351 {
14352         struct drm_encoder *encoder = connector->base.encoder;
14353         struct drm_device *dev = connector->base.dev;
14354
14355         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14356
14357         if (!encoder || WARN_ON(!encoder->crtc))
14358                 return INVALID_PIPE;
14359
14360         return to_intel_crtc(encoder->crtc)->pipe;
14361 }
14362
14363 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14364                                 struct drm_file *file)
14365 {
14366         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14367         struct drm_crtc *drmmode_crtc;
14368         struct intel_crtc *crtc;
14369
14370         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14371
14372         if (!drmmode_crtc) {
14373                 DRM_ERROR("no such CRTC id\n");
14374                 return -ENOENT;
14375         }
14376
14377         crtc = to_intel_crtc(drmmode_crtc);
14378         pipe_from_crtc_id->pipe = crtc->pipe;
14379
14380         return 0;
14381 }
14382
14383 static int intel_encoder_clones(struct intel_encoder *encoder)
14384 {
14385         struct drm_device *dev = encoder->base.dev;
14386         struct intel_encoder *source_encoder;
14387         int index_mask = 0;
14388         int entry = 0;
14389
14390         for_each_intel_encoder(dev, source_encoder) {
14391                 if (encoders_cloneable(encoder, source_encoder))
14392                         index_mask |= (1 << entry);
14393
14394                 entry++;
14395         }
14396
14397         return index_mask;
14398 }
14399
14400 static bool has_edp_a(struct drm_device *dev)
14401 {
14402         struct drm_i915_private *dev_priv = dev->dev_private;
14403
14404         if (!IS_MOBILE(dev))
14405                 return false;
14406
14407         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14408                 return false;
14409
14410         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14411                 return false;
14412
14413         return true;
14414 }
14415
14416 static bool intel_crt_present(struct drm_device *dev)
14417 {
14418         struct drm_i915_private *dev_priv = dev->dev_private;
14419
14420         if (INTEL_INFO(dev)->gen >= 9)
14421                 return false;
14422
14423         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14424                 return false;
14425
14426         if (IS_CHERRYVIEW(dev))
14427                 return false;
14428
14429         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14430                 return false;
14431
14432         /* DDI E can't be used if DDI A requires 4 lanes */
14433         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14434                 return false;
14435
14436         if (!dev_priv->vbt.int_crt_support)
14437                 return false;
14438
14439         return true;
14440 }
14441
14442 static void intel_setup_outputs(struct drm_device *dev)
14443 {
14444         struct drm_i915_private *dev_priv = dev->dev_private;
14445         struct intel_encoder *encoder;
14446         bool dpd_is_edp = false;
14447
14448         intel_lvds_init(dev);
14449
14450         if (intel_crt_present(dev))
14451                 intel_crt_init(dev);
14452
14453         if (IS_BROXTON(dev)) {
14454                 /*
14455                  * FIXME: Broxton doesn't support port detection via the
14456                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14457                  * detect the ports.
14458                  */
14459                 intel_ddi_init(dev, PORT_A);
14460                 intel_ddi_init(dev, PORT_B);
14461                 intel_ddi_init(dev, PORT_C);
14462
14463                 intel_dsi_init(dev);
14464         } else if (HAS_DDI(dev)) {
14465                 int found;
14466
14467                 /*
14468                  * Haswell uses DDI functions to detect digital outputs.
14469                  * On SKL pre-D0 the strap isn't connected, so we assume
14470                  * it's there.
14471                  */
14472                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14473                 /* WaIgnoreDDIAStrap: skl */
14474                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14475                         intel_ddi_init(dev, PORT_A);
14476
14477                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14478                  * register */
14479                 found = I915_READ(SFUSE_STRAP);
14480
14481                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14482                         intel_ddi_init(dev, PORT_B);
14483                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14484                         intel_ddi_init(dev, PORT_C);
14485                 if (found & SFUSE_STRAP_DDID_DETECTED)
14486                         intel_ddi_init(dev, PORT_D);
14487                 /*
14488                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14489                  */
14490                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14491                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14492                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14493                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14494                         intel_ddi_init(dev, PORT_E);
14495
14496         } else if (HAS_PCH_SPLIT(dev)) {
14497                 int found;
14498                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14499
14500                 if (has_edp_a(dev))
14501                         intel_dp_init(dev, DP_A, PORT_A);
14502
14503                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14504                         /* PCH SDVOB multiplex with HDMIB */
14505                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14506                         if (!found)
14507                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14508                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14509                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14510                 }
14511
14512                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14513                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14514
14515                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14516                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14517
14518                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14519                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14520
14521                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14522                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14523         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14524                 /*
14525                  * The DP_DETECTED bit is the latched state of the DDC
14526                  * SDA pin at boot. However since eDP doesn't require DDC
14527                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14528                  * eDP ports may have been muxed to an alternate function.
14529                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14530                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14531                  * detect eDP ports.
14532                  */
14533                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14534                     !intel_dp_is_edp(dev, PORT_B))
14535                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14536                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14537                     intel_dp_is_edp(dev, PORT_B))
14538                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14539
14540                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14541                     !intel_dp_is_edp(dev, PORT_C))
14542                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14543                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14544                     intel_dp_is_edp(dev, PORT_C))
14545                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14546
14547                 if (IS_CHERRYVIEW(dev)) {
14548                         /* eDP not supported on port D, so don't check VBT */
14549                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14550                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14551                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14552                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14553                 }
14554
14555                 intel_dsi_init(dev);
14556         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14557                 bool found = false;
14558
14559                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14560                         DRM_DEBUG_KMS("probing SDVOB\n");
14561                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14562                         if (!found && IS_G4X(dev)) {
14563                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14564                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14565                         }
14566
14567                         if (!found && IS_G4X(dev))
14568                                 intel_dp_init(dev, DP_B, PORT_B);
14569                 }
14570
14571                 /* Before G4X SDVOC doesn't have its own detect register */
14572
14573                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14574                         DRM_DEBUG_KMS("probing SDVOC\n");
14575                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14576                 }
14577
14578                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14579
14580                         if (IS_G4X(dev)) {
14581                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14582                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14583                         }
14584                         if (IS_G4X(dev))
14585                                 intel_dp_init(dev, DP_C, PORT_C);
14586                 }
14587
14588                 if (IS_G4X(dev) &&
14589                     (I915_READ(DP_D) & DP_DETECTED))
14590                         intel_dp_init(dev, DP_D, PORT_D);
14591         } else if (IS_GEN2(dev))
14592                 intel_dvo_init(dev);
14593
14594         if (SUPPORTS_TV(dev))
14595                 intel_tv_init(dev);
14596
14597         intel_psr_init(dev);
14598
14599         for_each_intel_encoder(dev, encoder) {
14600                 encoder->base.possible_crtcs = encoder->crtc_mask;
14601                 encoder->base.possible_clones =
14602                         intel_encoder_clones(encoder);
14603         }
14604
14605         intel_init_pch_refclk(dev);
14606
14607         drm_helper_move_panel_connectors_to_head(dev);
14608 }
14609
14610 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14611 {
14612         struct drm_device *dev = fb->dev;
14613         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14614
14615         drm_framebuffer_cleanup(fb);
14616         mutex_lock(&dev->struct_mutex);
14617         WARN_ON(!intel_fb->obj->framebuffer_references--);
14618         drm_gem_object_unreference(&intel_fb->obj->base);
14619         mutex_unlock(&dev->struct_mutex);
14620         kfree(intel_fb);
14621 }
14622
14623 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14624                                                 struct drm_file *file,
14625                                                 unsigned int *handle)
14626 {
14627         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14628         struct drm_i915_gem_object *obj = intel_fb->obj;
14629
14630         if (obj->userptr.mm) {
14631                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14632                 return -EINVAL;
14633         }
14634
14635         return drm_gem_handle_create(file, &obj->base, handle);
14636 }
14637
14638 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14639                                         struct drm_file *file,
14640                                         unsigned flags, unsigned color,
14641                                         struct drm_clip_rect *clips,
14642                                         unsigned num_clips)
14643 {
14644         struct drm_device *dev = fb->dev;
14645         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14646         struct drm_i915_gem_object *obj = intel_fb->obj;
14647
14648         mutex_lock(&dev->struct_mutex);
14649         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14650         mutex_unlock(&dev->struct_mutex);
14651
14652         return 0;
14653 }
14654
14655 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14656         .destroy = intel_user_framebuffer_destroy,
14657         .create_handle = intel_user_framebuffer_create_handle,
14658         .dirty = intel_user_framebuffer_dirty,
14659 };
14660
14661 static
14662 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14663                          uint32_t pixel_format)
14664 {
14665         u32 gen = INTEL_INFO(dev)->gen;
14666
14667         if (gen >= 9) {
14668                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14669
14670                 /* "The stride in bytes must not exceed the of the size of 8K
14671                  *  pixels and 32K bytes."
14672                  */
14673                 return min(8192 * cpp, 32768);
14674         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14675                 return 32*1024;
14676         } else if (gen >= 4) {
14677                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14678                         return 16*1024;
14679                 else
14680                         return 32*1024;
14681         } else if (gen >= 3) {
14682                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14683                         return 8*1024;
14684                 else
14685                         return 16*1024;
14686         } else {
14687                 /* XXX DSPC is limited to 4k tiled */
14688                 return 8*1024;
14689         }
14690 }
14691
14692 static int intel_framebuffer_init(struct drm_device *dev,
14693                                   struct intel_framebuffer *intel_fb,
14694                                   struct drm_mode_fb_cmd2 *mode_cmd,
14695                                   struct drm_i915_gem_object *obj)
14696 {
14697         struct drm_i915_private *dev_priv = to_i915(dev);
14698         unsigned int aligned_height;
14699         int ret;
14700         u32 pitch_limit, stride_alignment;
14701
14702         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14703
14704         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14705                 /* Enforce that fb modifier and tiling mode match, but only for
14706                  * X-tiled. This is needed for FBC. */
14707                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14708                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14709                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14710                         return -EINVAL;
14711                 }
14712         } else {
14713                 if (obj->tiling_mode == I915_TILING_X)
14714                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14715                 else if (obj->tiling_mode == I915_TILING_Y) {
14716                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14717                         return -EINVAL;
14718                 }
14719         }
14720
14721         /* Passed in modifier sanity checking. */
14722         switch (mode_cmd->modifier[0]) {
14723         case I915_FORMAT_MOD_Y_TILED:
14724         case I915_FORMAT_MOD_Yf_TILED:
14725                 if (INTEL_INFO(dev)->gen < 9) {
14726                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14727                                   mode_cmd->modifier[0]);
14728                         return -EINVAL;
14729                 }
14730         case DRM_FORMAT_MOD_NONE:
14731         case I915_FORMAT_MOD_X_TILED:
14732                 break;
14733         default:
14734                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14735                           mode_cmd->modifier[0]);
14736                 return -EINVAL;
14737         }
14738
14739         stride_alignment = intel_fb_stride_alignment(dev_priv,
14740                                                      mode_cmd->modifier[0],
14741                                                      mode_cmd->pixel_format);
14742         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14743                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14744                           mode_cmd->pitches[0], stride_alignment);
14745                 return -EINVAL;
14746         }
14747
14748         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14749                                            mode_cmd->pixel_format);
14750         if (mode_cmd->pitches[0] > pitch_limit) {
14751                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14752                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14753                           "tiled" : "linear",
14754                           mode_cmd->pitches[0], pitch_limit);
14755                 return -EINVAL;
14756         }
14757
14758         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14759             mode_cmd->pitches[0] != obj->stride) {
14760                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14761                           mode_cmd->pitches[0], obj->stride);
14762                 return -EINVAL;
14763         }
14764
14765         /* Reject formats not supported by any plane early. */
14766         switch (mode_cmd->pixel_format) {
14767         case DRM_FORMAT_C8:
14768         case DRM_FORMAT_RGB565:
14769         case DRM_FORMAT_XRGB8888:
14770         case DRM_FORMAT_ARGB8888:
14771                 break;
14772         case DRM_FORMAT_XRGB1555:
14773                 if (INTEL_INFO(dev)->gen > 3) {
14774                         DRM_DEBUG("unsupported pixel format: %s\n",
14775                                   drm_get_format_name(mode_cmd->pixel_format));
14776                         return -EINVAL;
14777                 }
14778                 break;
14779         case DRM_FORMAT_ABGR8888:
14780                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14781                     INTEL_INFO(dev)->gen < 9) {
14782                         DRM_DEBUG("unsupported pixel format: %s\n",
14783                                   drm_get_format_name(mode_cmd->pixel_format));
14784                         return -EINVAL;
14785                 }
14786                 break;
14787         case DRM_FORMAT_XBGR8888:
14788         case DRM_FORMAT_XRGB2101010:
14789         case DRM_FORMAT_XBGR2101010:
14790                 if (INTEL_INFO(dev)->gen < 4) {
14791                         DRM_DEBUG("unsupported pixel format: %s\n",
14792                                   drm_get_format_name(mode_cmd->pixel_format));
14793                         return -EINVAL;
14794                 }
14795                 break;
14796         case DRM_FORMAT_ABGR2101010:
14797                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14798                         DRM_DEBUG("unsupported pixel format: %s\n",
14799                                   drm_get_format_name(mode_cmd->pixel_format));
14800                         return -EINVAL;
14801                 }
14802                 break;
14803         case DRM_FORMAT_YUYV:
14804         case DRM_FORMAT_UYVY:
14805         case DRM_FORMAT_YVYU:
14806         case DRM_FORMAT_VYUY:
14807                 if (INTEL_INFO(dev)->gen < 5) {
14808                         DRM_DEBUG("unsupported pixel format: %s\n",
14809                                   drm_get_format_name(mode_cmd->pixel_format));
14810                         return -EINVAL;
14811                 }
14812                 break;
14813         default:
14814                 DRM_DEBUG("unsupported pixel format: %s\n",
14815                           drm_get_format_name(mode_cmd->pixel_format));
14816                 return -EINVAL;
14817         }
14818
14819         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14820         if (mode_cmd->offsets[0] != 0)
14821                 return -EINVAL;
14822
14823         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14824                                                mode_cmd->pixel_format,
14825                                                mode_cmd->modifier[0]);
14826         /* FIXME drm helper for size checks (especially planar formats)? */
14827         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14828                 return -EINVAL;
14829
14830         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14831         intel_fb->obj = obj;
14832
14833         intel_fill_fb_info(dev_priv, &intel_fb->base);
14834
14835         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14836         if (ret) {
14837                 DRM_ERROR("framebuffer init failed %d\n", ret);
14838                 return ret;
14839         }
14840
14841         intel_fb->obj->framebuffer_references++;
14842
14843         return 0;
14844 }
14845
14846 static struct drm_framebuffer *
14847 intel_user_framebuffer_create(struct drm_device *dev,
14848                               struct drm_file *filp,
14849                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14850 {
14851         struct drm_framebuffer *fb;
14852         struct drm_i915_gem_object *obj;
14853         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14854
14855         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14856                                                 mode_cmd.handles[0]));
14857         if (&obj->base == NULL)
14858                 return ERR_PTR(-ENOENT);
14859
14860         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14861         if (IS_ERR(fb))
14862                 drm_gem_object_unreference_unlocked(&obj->base);
14863
14864         return fb;
14865 }
14866
14867 #ifndef CONFIG_DRM_FBDEV_EMULATION
14868 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14869 {
14870 }
14871 #endif
14872
14873 static const struct drm_mode_config_funcs intel_mode_funcs = {
14874         .fb_create = intel_user_framebuffer_create,
14875         .output_poll_changed = intel_fbdev_output_poll_changed,
14876         .atomic_check = intel_atomic_check,
14877         .atomic_commit = intel_atomic_commit,
14878         .atomic_state_alloc = intel_atomic_state_alloc,
14879         .atomic_state_clear = intel_atomic_state_clear,
14880 };
14881
14882 /**
14883  * intel_init_display_hooks - initialize the display modesetting hooks
14884  * @dev_priv: device private
14885  */
14886 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14887 {
14888         if (INTEL_INFO(dev_priv)->gen >= 9) {
14889                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14890                 dev_priv->display.get_initial_plane_config =
14891                         skylake_get_initial_plane_config;
14892                 dev_priv->display.crtc_compute_clock =
14893                         haswell_crtc_compute_clock;
14894                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14895                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14896         } else if (HAS_DDI(dev_priv)) {
14897                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14898                 dev_priv->display.get_initial_plane_config =
14899                         ironlake_get_initial_plane_config;
14900                 dev_priv->display.crtc_compute_clock =
14901                         haswell_crtc_compute_clock;
14902                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14903                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14904         } else if (HAS_PCH_SPLIT(dev_priv)) {
14905                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14906                 dev_priv->display.get_initial_plane_config =
14907                         ironlake_get_initial_plane_config;
14908                 dev_priv->display.crtc_compute_clock =
14909                         ironlake_crtc_compute_clock;
14910                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14911                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14912         } else if (IS_CHERRYVIEW(dev_priv)) {
14913                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14914                 dev_priv->display.get_initial_plane_config =
14915                         i9xx_get_initial_plane_config;
14916                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14917                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14918                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14919         } else if (IS_VALLEYVIEW(dev_priv)) {
14920                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14921                 dev_priv->display.get_initial_plane_config =
14922                         i9xx_get_initial_plane_config;
14923                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14924                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14925                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14926         } else if (IS_G4X(dev_priv)) {
14927                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14928                 dev_priv->display.get_initial_plane_config =
14929                         i9xx_get_initial_plane_config;
14930                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14931                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14932                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14933         } else if (IS_PINEVIEW(dev_priv)) {
14934                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14935                 dev_priv->display.get_initial_plane_config =
14936                         i9xx_get_initial_plane_config;
14937                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14938                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14939                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14940         } else if (!IS_GEN2(dev_priv)) {
14941                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14942                 dev_priv->display.get_initial_plane_config =
14943                         i9xx_get_initial_plane_config;
14944                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14945                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14946                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14947         } else {
14948                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14949                 dev_priv->display.get_initial_plane_config =
14950                         i9xx_get_initial_plane_config;
14951                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14952                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14953                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14954         }
14955
14956         /* Returns the core display clock speed */
14957         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14958                 dev_priv->display.get_display_clock_speed =
14959                         skylake_get_display_clock_speed;
14960         else if (IS_BROXTON(dev_priv))
14961                 dev_priv->display.get_display_clock_speed =
14962                         broxton_get_display_clock_speed;
14963         else if (IS_BROADWELL(dev_priv))
14964                 dev_priv->display.get_display_clock_speed =
14965                         broadwell_get_display_clock_speed;
14966         else if (IS_HASWELL(dev_priv))
14967                 dev_priv->display.get_display_clock_speed =
14968                         haswell_get_display_clock_speed;
14969         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14970                 dev_priv->display.get_display_clock_speed =
14971                         valleyview_get_display_clock_speed;
14972         else if (IS_GEN5(dev_priv))
14973                 dev_priv->display.get_display_clock_speed =
14974                         ilk_get_display_clock_speed;
14975         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14976                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14977                 dev_priv->display.get_display_clock_speed =
14978                         i945_get_display_clock_speed;
14979         else if (IS_GM45(dev_priv))
14980                 dev_priv->display.get_display_clock_speed =
14981                         gm45_get_display_clock_speed;
14982         else if (IS_CRESTLINE(dev_priv))
14983                 dev_priv->display.get_display_clock_speed =
14984                         i965gm_get_display_clock_speed;
14985         else if (IS_PINEVIEW(dev_priv))
14986                 dev_priv->display.get_display_clock_speed =
14987                         pnv_get_display_clock_speed;
14988         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14989                 dev_priv->display.get_display_clock_speed =
14990                         g33_get_display_clock_speed;
14991         else if (IS_I915G(dev_priv))
14992                 dev_priv->display.get_display_clock_speed =
14993                         i915_get_display_clock_speed;
14994         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14995                 dev_priv->display.get_display_clock_speed =
14996                         i9xx_misc_get_display_clock_speed;
14997         else if (IS_I915GM(dev_priv))
14998                 dev_priv->display.get_display_clock_speed =
14999                         i915gm_get_display_clock_speed;
15000         else if (IS_I865G(dev_priv))
15001                 dev_priv->display.get_display_clock_speed =
15002                         i865_get_display_clock_speed;
15003         else if (IS_I85X(dev_priv))
15004                 dev_priv->display.get_display_clock_speed =
15005                         i85x_get_display_clock_speed;
15006         else { /* 830 */
15007                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15008                 dev_priv->display.get_display_clock_speed =
15009                         i830_get_display_clock_speed;
15010         }
15011
15012         if (IS_GEN5(dev_priv)) {
15013                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15014         } else if (IS_GEN6(dev_priv)) {
15015                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15016         } else if (IS_IVYBRIDGE(dev_priv)) {
15017                 /* FIXME: detect B0+ stepping and use auto training */
15018                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15019         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15020                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15021                 if (IS_BROADWELL(dev_priv)) {
15022                         dev_priv->display.modeset_commit_cdclk =
15023                                 broadwell_modeset_commit_cdclk;
15024                         dev_priv->display.modeset_calc_cdclk =
15025                                 broadwell_modeset_calc_cdclk;
15026                 }
15027         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15028                 dev_priv->display.modeset_commit_cdclk =
15029                         valleyview_modeset_commit_cdclk;
15030                 dev_priv->display.modeset_calc_cdclk =
15031                         valleyview_modeset_calc_cdclk;
15032         } else if (IS_BROXTON(dev_priv)) {
15033                 dev_priv->display.modeset_commit_cdclk =
15034                         broxton_modeset_commit_cdclk;
15035                 dev_priv->display.modeset_calc_cdclk =
15036                         broxton_modeset_calc_cdclk;
15037         }
15038
15039         switch (INTEL_INFO(dev_priv)->gen) {
15040         case 2:
15041                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15042                 break;
15043
15044         case 3:
15045                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15046                 break;
15047
15048         case 4:
15049         case 5:
15050                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15051                 break;
15052
15053         case 6:
15054                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15055                 break;
15056         case 7:
15057         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15058                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15059                 break;
15060         case 9:
15061                 /* Drop through - unsupported since execlist only. */
15062         default:
15063                 /* Default just returns -ENODEV to indicate unsupported */
15064                 dev_priv->display.queue_flip = intel_default_queue_flip;
15065         }
15066 }
15067
15068 /*
15069  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15070  * resume, or other times.  This quirk makes sure that's the case for
15071  * affected systems.
15072  */
15073 static void quirk_pipea_force(struct drm_device *dev)
15074 {
15075         struct drm_i915_private *dev_priv = dev->dev_private;
15076
15077         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15078         DRM_INFO("applying pipe a force quirk\n");
15079 }
15080
15081 static void quirk_pipeb_force(struct drm_device *dev)
15082 {
15083         struct drm_i915_private *dev_priv = dev->dev_private;
15084
15085         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15086         DRM_INFO("applying pipe b force quirk\n");
15087 }
15088
15089 /*
15090  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15091  */
15092 static void quirk_ssc_force_disable(struct drm_device *dev)
15093 {
15094         struct drm_i915_private *dev_priv = dev->dev_private;
15095         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15096         DRM_INFO("applying lvds SSC disable quirk\n");
15097 }
15098
15099 /*
15100  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15101  * brightness value
15102  */
15103 static void quirk_invert_brightness(struct drm_device *dev)
15104 {
15105         struct drm_i915_private *dev_priv = dev->dev_private;
15106         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15107         DRM_INFO("applying inverted panel brightness quirk\n");
15108 }
15109
15110 /* Some VBT's incorrectly indicate no backlight is present */
15111 static void quirk_backlight_present(struct drm_device *dev)
15112 {
15113         struct drm_i915_private *dev_priv = dev->dev_private;
15114         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15115         DRM_INFO("applying backlight present quirk\n");
15116 }
15117
15118 struct intel_quirk {
15119         int device;
15120         int subsystem_vendor;
15121         int subsystem_device;
15122         void (*hook)(struct drm_device *dev);
15123 };
15124
15125 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15126 struct intel_dmi_quirk {
15127         void (*hook)(struct drm_device *dev);
15128         const struct dmi_system_id (*dmi_id_list)[];
15129 };
15130
15131 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15132 {
15133         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15134         return 1;
15135 }
15136
15137 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15138         {
15139                 .dmi_id_list = &(const struct dmi_system_id[]) {
15140                         {
15141                                 .callback = intel_dmi_reverse_brightness,
15142                                 .ident = "NCR Corporation",
15143                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15144                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15145                                 },
15146                         },
15147                         { }  /* terminating entry */
15148                 },
15149                 .hook = quirk_invert_brightness,
15150         },
15151 };
15152
15153 static struct intel_quirk intel_quirks[] = {
15154         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15155         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15156
15157         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15158         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15159
15160         /* 830 needs to leave pipe A & dpll A up */
15161         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15162
15163         /* 830 needs to leave pipe B & dpll B up */
15164         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15165
15166         /* Lenovo U160 cannot use SSC on LVDS */
15167         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15168
15169         /* Sony Vaio Y cannot use SSC on LVDS */
15170         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15171
15172         /* Acer Aspire 5734Z must invert backlight brightness */
15173         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15174
15175         /* Acer/eMachines G725 */
15176         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15177
15178         /* Acer/eMachines e725 */
15179         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15180
15181         /* Acer/Packard Bell NCL20 */
15182         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15183
15184         /* Acer Aspire 4736Z */
15185         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15186
15187         /* Acer Aspire 5336 */
15188         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15189
15190         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15191         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15192
15193         /* Acer C720 Chromebook (Core i3 4005U) */
15194         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15195
15196         /* Apple Macbook 2,1 (Core 2 T7400) */
15197         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15198
15199         /* Apple Macbook 4,1 */
15200         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15201
15202         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15203         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15204
15205         /* HP Chromebook 14 (Celeron 2955U) */
15206         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15207
15208         /* Dell Chromebook 11 */
15209         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15210
15211         /* Dell Chromebook 11 (2015 version) */
15212         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15213 };
15214
15215 static void intel_init_quirks(struct drm_device *dev)
15216 {
15217         struct pci_dev *d = dev->pdev;
15218         int i;
15219
15220         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15221                 struct intel_quirk *q = &intel_quirks[i];
15222
15223                 if (d->device == q->device &&
15224                     (d->subsystem_vendor == q->subsystem_vendor ||
15225                      q->subsystem_vendor == PCI_ANY_ID) &&
15226                     (d->subsystem_device == q->subsystem_device ||
15227                      q->subsystem_device == PCI_ANY_ID))
15228                         q->hook(dev);
15229         }
15230         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15231                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15232                         intel_dmi_quirks[i].hook(dev);
15233         }
15234 }
15235
15236 /* Disable the VGA plane that we never use */
15237 static void i915_disable_vga(struct drm_device *dev)
15238 {
15239         struct drm_i915_private *dev_priv = dev->dev_private;
15240         u8 sr1;
15241         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15242
15243         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15244         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15245         outb(SR01, VGA_SR_INDEX);
15246         sr1 = inb(VGA_SR_DATA);
15247         outb(sr1 | 1<<5, VGA_SR_DATA);
15248         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15249         udelay(300);
15250
15251         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15252         POSTING_READ(vga_reg);
15253 }
15254
15255 void intel_modeset_init_hw(struct drm_device *dev)
15256 {
15257         struct drm_i915_private *dev_priv = dev->dev_private;
15258
15259         intel_update_cdclk(dev);
15260
15261         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15262
15263         intel_init_clock_gating(dev);
15264         intel_enable_gt_powersave(dev_priv);
15265 }
15266
15267 /*
15268  * Calculate what we think the watermarks should be for the state we've read
15269  * out of the hardware and then immediately program those watermarks so that
15270  * we ensure the hardware settings match our internal state.
15271  *
15272  * We can calculate what we think WM's should be by creating a duplicate of the
15273  * current state (which was constructed during hardware readout) and running it
15274  * through the atomic check code to calculate new watermark values in the
15275  * state object.
15276  */
15277 static void sanitize_watermarks(struct drm_device *dev)
15278 {
15279         struct drm_i915_private *dev_priv = to_i915(dev);
15280         struct drm_atomic_state *state;
15281         struct drm_crtc *crtc;
15282         struct drm_crtc_state *cstate;
15283         struct drm_modeset_acquire_ctx ctx;
15284         int ret;
15285         int i;
15286
15287         /* Only supported on platforms that use atomic watermark design */
15288         if (!dev_priv->display.optimize_watermarks)
15289                 return;
15290
15291         /*
15292          * We need to hold connection_mutex before calling duplicate_state so
15293          * that the connector loop is protected.
15294          */
15295         drm_modeset_acquire_init(&ctx, 0);
15296 retry:
15297         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15298         if (ret == -EDEADLK) {
15299                 drm_modeset_backoff(&ctx);
15300                 goto retry;
15301         } else if (WARN_ON(ret)) {
15302                 goto fail;
15303         }
15304
15305         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15306         if (WARN_ON(IS_ERR(state)))
15307                 goto fail;
15308
15309         /*
15310          * Hardware readout is the only time we don't want to calculate
15311          * intermediate watermarks (since we don't trust the current
15312          * watermarks).
15313          */
15314         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15315
15316         ret = intel_atomic_check(dev, state);
15317         if (ret) {
15318                 /*
15319                  * If we fail here, it means that the hardware appears to be
15320                  * programmed in a way that shouldn't be possible, given our
15321                  * understanding of watermark requirements.  This might mean a
15322                  * mistake in the hardware readout code or a mistake in the
15323                  * watermark calculations for a given platform.  Raise a WARN
15324                  * so that this is noticeable.
15325                  *
15326                  * If this actually happens, we'll have to just leave the
15327                  * BIOS-programmed watermarks untouched and hope for the best.
15328                  */
15329                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15330                 goto fail;
15331         }
15332
15333         /* Write calculated watermark values back */
15334         for_each_crtc_in_state(state, crtc, cstate, i) {
15335                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15336
15337                 cs->wm.need_postvbl_update = true;
15338                 dev_priv->display.optimize_watermarks(cs);
15339         }
15340
15341         drm_atomic_state_free(state);
15342 fail:
15343         drm_modeset_drop_locks(&ctx);
15344         drm_modeset_acquire_fini(&ctx);
15345 }
15346
15347 void intel_modeset_init(struct drm_device *dev)
15348 {
15349         struct drm_i915_private *dev_priv = to_i915(dev);
15350         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15351         int sprite, ret;
15352         enum pipe pipe;
15353         struct intel_crtc *crtc;
15354
15355         drm_mode_config_init(dev);
15356
15357         dev->mode_config.min_width = 0;
15358         dev->mode_config.min_height = 0;
15359
15360         dev->mode_config.preferred_depth = 24;
15361         dev->mode_config.prefer_shadow = 1;
15362
15363         dev->mode_config.allow_fb_modifiers = true;
15364
15365         dev->mode_config.funcs = &intel_mode_funcs;
15366
15367         intel_init_quirks(dev);
15368
15369         intel_init_pm(dev);
15370
15371         if (INTEL_INFO(dev)->num_pipes == 0)
15372                 return;
15373
15374         /*
15375          * There may be no VBT; and if the BIOS enabled SSC we can
15376          * just keep using it to avoid unnecessary flicker.  Whereas if the
15377          * BIOS isn't using it, don't assume it will work even if the VBT
15378          * indicates as much.
15379          */
15380         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15381                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15382                                             DREF_SSC1_ENABLE);
15383
15384                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15385                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15386                                      bios_lvds_use_ssc ? "en" : "dis",
15387                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15388                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15389                 }
15390         }
15391
15392         if (IS_GEN2(dev)) {
15393                 dev->mode_config.max_width = 2048;
15394                 dev->mode_config.max_height = 2048;
15395         } else if (IS_GEN3(dev)) {
15396                 dev->mode_config.max_width = 4096;
15397                 dev->mode_config.max_height = 4096;
15398         } else {
15399                 dev->mode_config.max_width = 8192;
15400                 dev->mode_config.max_height = 8192;
15401         }
15402
15403         if (IS_845G(dev) || IS_I865G(dev)) {
15404                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15405                 dev->mode_config.cursor_height = 1023;
15406         } else if (IS_GEN2(dev)) {
15407                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15408                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15409         } else {
15410                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15411                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15412         }
15413
15414         dev->mode_config.fb_base = ggtt->mappable_base;
15415
15416         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15417                       INTEL_INFO(dev)->num_pipes,
15418                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15419
15420         for_each_pipe(dev_priv, pipe) {
15421                 intel_crtc_init(dev, pipe);
15422                 for_each_sprite(dev_priv, pipe, sprite) {
15423                         ret = intel_plane_init(dev, pipe, sprite);
15424                         if (ret)
15425                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15426                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15427                 }
15428         }
15429
15430         intel_update_czclk(dev_priv);
15431         intel_update_cdclk(dev);
15432
15433         intel_shared_dpll_init(dev);
15434
15435         /* Just disable it once at startup */
15436         i915_disable_vga(dev);
15437         intel_setup_outputs(dev);
15438
15439         drm_modeset_lock_all(dev);
15440         intel_modeset_setup_hw_state(dev);
15441         drm_modeset_unlock_all(dev);
15442
15443         for_each_intel_crtc(dev, crtc) {
15444                 struct intel_initial_plane_config plane_config = {};
15445
15446                 if (!crtc->active)
15447                         continue;
15448
15449                 /*
15450                  * Note that reserving the BIOS fb up front prevents us
15451                  * from stuffing other stolen allocations like the ring
15452                  * on top.  This prevents some ugliness at boot time, and
15453                  * can even allow for smooth boot transitions if the BIOS
15454                  * fb is large enough for the active pipe configuration.
15455                  */
15456                 dev_priv->display.get_initial_plane_config(crtc,
15457                                                            &plane_config);
15458
15459                 /*
15460                  * If the fb is shared between multiple heads, we'll
15461                  * just get the first one.
15462                  */
15463                 intel_find_initial_plane_obj(crtc, &plane_config);
15464         }
15465
15466         /*
15467          * Make sure hardware watermarks really match the state we read out.
15468          * Note that we need to do this after reconstructing the BIOS fb's
15469          * since the watermark calculation done here will use pstate->fb.
15470          */
15471         sanitize_watermarks(dev);
15472 }
15473
15474 static void intel_enable_pipe_a(struct drm_device *dev)
15475 {
15476         struct intel_connector *connector;
15477         struct drm_connector *crt = NULL;
15478         struct intel_load_detect_pipe load_detect_temp;
15479         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15480
15481         /* We can't just switch on the pipe A, we need to set things up with a
15482          * proper mode and output configuration. As a gross hack, enable pipe A
15483          * by enabling the load detect pipe once. */
15484         for_each_intel_connector(dev, connector) {
15485                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15486                         crt = &connector->base;
15487                         break;
15488                 }
15489         }
15490
15491         if (!crt)
15492                 return;
15493
15494         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15495                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15496 }
15497
15498 static bool
15499 intel_check_plane_mapping(struct intel_crtc *crtc)
15500 {
15501         struct drm_device *dev = crtc->base.dev;
15502         struct drm_i915_private *dev_priv = dev->dev_private;
15503         u32 val;
15504
15505         if (INTEL_INFO(dev)->num_pipes == 1)
15506                 return true;
15507
15508         val = I915_READ(DSPCNTR(!crtc->plane));
15509
15510         if ((val & DISPLAY_PLANE_ENABLE) &&
15511             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15512                 return false;
15513
15514         return true;
15515 }
15516
15517 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15518 {
15519         struct drm_device *dev = crtc->base.dev;
15520         struct intel_encoder *encoder;
15521
15522         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15523                 return true;
15524
15525         return false;
15526 }
15527
15528 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15529 {
15530         struct drm_device *dev = encoder->base.dev;
15531         struct intel_connector *connector;
15532
15533         for_each_connector_on_encoder(dev, &encoder->base, connector)
15534                 return true;
15535
15536         return false;
15537 }
15538
15539 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15540 {
15541         struct drm_device *dev = crtc->base.dev;
15542         struct drm_i915_private *dev_priv = dev->dev_private;
15543         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15544
15545         /* Clear any frame start delays used for debugging left by the BIOS */
15546         if (!transcoder_is_dsi(cpu_transcoder)) {
15547                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15548
15549                 I915_WRITE(reg,
15550                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15551         }
15552
15553         /* restore vblank interrupts to correct state */
15554         drm_crtc_vblank_reset(&crtc->base);
15555         if (crtc->active) {
15556                 struct intel_plane *plane;
15557
15558                 drm_crtc_vblank_on(&crtc->base);
15559
15560                 /* Disable everything but the primary plane */
15561                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15562                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15563                                 continue;
15564
15565                         plane->disable_plane(&plane->base, &crtc->base);
15566                 }
15567         }
15568
15569         /* We need to sanitize the plane -> pipe mapping first because this will
15570          * disable the crtc (and hence change the state) if it is wrong. Note
15571          * that gen4+ has a fixed plane -> pipe mapping.  */
15572         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15573                 bool plane;
15574
15575                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15576                               crtc->base.base.id);
15577
15578                 /* Pipe has the wrong plane attached and the plane is active.
15579                  * Temporarily change the plane mapping and disable everything
15580                  * ...  */
15581                 plane = crtc->plane;
15582                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15583                 crtc->plane = !plane;
15584                 intel_crtc_disable_noatomic(&crtc->base);
15585                 crtc->plane = plane;
15586         }
15587
15588         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15589             crtc->pipe == PIPE_A && !crtc->active) {
15590                 /* BIOS forgot to enable pipe A, this mostly happens after
15591                  * resume. Force-enable the pipe to fix this, the update_dpms
15592                  * call below we restore the pipe to the right state, but leave
15593                  * the required bits on. */
15594                 intel_enable_pipe_a(dev);
15595         }
15596
15597         /* Adjust the state of the output pipe according to whether we
15598          * have active connectors/encoders. */
15599         if (crtc->active && !intel_crtc_has_encoders(crtc))
15600                 intel_crtc_disable_noatomic(&crtc->base);
15601
15602         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15603                 /*
15604                  * We start out with underrun reporting disabled to avoid races.
15605                  * For correct bookkeeping mark this on active crtcs.
15606                  *
15607                  * Also on gmch platforms we dont have any hardware bits to
15608                  * disable the underrun reporting. Which means we need to start
15609                  * out with underrun reporting disabled also on inactive pipes,
15610                  * since otherwise we'll complain about the garbage we read when
15611                  * e.g. coming up after runtime pm.
15612                  *
15613                  * No protection against concurrent access is required - at
15614                  * worst a fifo underrun happens which also sets this to false.
15615                  */
15616                 crtc->cpu_fifo_underrun_disabled = true;
15617                 crtc->pch_fifo_underrun_disabled = true;
15618         }
15619 }
15620
15621 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15622 {
15623         struct intel_connector *connector;
15624         struct drm_device *dev = encoder->base.dev;
15625
15626         /* We need to check both for a crtc link (meaning that the
15627          * encoder is active and trying to read from a pipe) and the
15628          * pipe itself being active. */
15629         bool has_active_crtc = encoder->base.crtc &&
15630                 to_intel_crtc(encoder->base.crtc)->active;
15631
15632         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15633                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15634                               encoder->base.base.id,
15635                               encoder->base.name);
15636
15637                 /* Connector is active, but has no active pipe. This is
15638                  * fallout from our resume register restoring. Disable
15639                  * the encoder manually again. */
15640                 if (encoder->base.crtc) {
15641                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15642                                       encoder->base.base.id,
15643                                       encoder->base.name);
15644                         encoder->disable(encoder);
15645                         if (encoder->post_disable)
15646                                 encoder->post_disable(encoder);
15647                 }
15648                 encoder->base.crtc = NULL;
15649
15650                 /* Inconsistent output/port/pipe state happens presumably due to
15651                  * a bug in one of the get_hw_state functions. Or someplace else
15652                  * in our code, like the register restore mess on resume. Clamp
15653                  * things to off as a safer default. */
15654                 for_each_intel_connector(dev, connector) {
15655                         if (connector->encoder != encoder)
15656                                 continue;
15657                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15658                         connector->base.encoder = NULL;
15659                 }
15660         }
15661         /* Enabled encoders without active connectors will be fixed in
15662          * the crtc fixup. */
15663 }
15664
15665 void i915_redisable_vga_power_on(struct drm_device *dev)
15666 {
15667         struct drm_i915_private *dev_priv = dev->dev_private;
15668         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15669
15670         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15671                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15672                 i915_disable_vga(dev);
15673         }
15674 }
15675
15676 void i915_redisable_vga(struct drm_device *dev)
15677 {
15678         struct drm_i915_private *dev_priv = dev->dev_private;
15679
15680         /* This function can be called both from intel_modeset_setup_hw_state or
15681          * at a very early point in our resume sequence, where the power well
15682          * structures are not yet restored. Since this function is at a very
15683          * paranoid "someone might have enabled VGA while we were not looking"
15684          * level, just check if the power well is enabled instead of trying to
15685          * follow the "don't touch the power well if we don't need it" policy
15686          * the rest of the driver uses. */
15687         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15688                 return;
15689
15690         i915_redisable_vga_power_on(dev);
15691
15692         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15693 }
15694
15695 static bool primary_get_hw_state(struct intel_plane *plane)
15696 {
15697         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15698
15699         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15700 }
15701
15702 /* FIXME read out full plane state for all planes */
15703 static void readout_plane_state(struct intel_crtc *crtc)
15704 {
15705         struct drm_plane *primary = crtc->base.primary;
15706         struct intel_plane_state *plane_state =
15707                 to_intel_plane_state(primary->state);
15708
15709         plane_state->visible = crtc->active &&
15710                 primary_get_hw_state(to_intel_plane(primary));
15711
15712         if (plane_state->visible)
15713                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15714 }
15715
15716 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15717 {
15718         struct drm_i915_private *dev_priv = dev->dev_private;
15719         enum pipe pipe;
15720         struct intel_crtc *crtc;
15721         struct intel_encoder *encoder;
15722         struct intel_connector *connector;
15723         int i;
15724
15725         dev_priv->active_crtcs = 0;
15726
15727         for_each_intel_crtc(dev, crtc) {
15728                 struct intel_crtc_state *crtc_state = crtc->config;
15729                 int pixclk = 0;
15730
15731                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15732                 memset(crtc_state, 0, sizeof(*crtc_state));
15733                 crtc_state->base.crtc = &crtc->base;
15734
15735                 crtc_state->base.active = crtc_state->base.enable =
15736                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15737
15738                 crtc->base.enabled = crtc_state->base.enable;
15739                 crtc->active = crtc_state->base.active;
15740
15741                 if (crtc_state->base.active) {
15742                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15743
15744                         if (IS_BROADWELL(dev_priv)) {
15745                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15746
15747                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15748                                 if (crtc_state->ips_enabled)
15749                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15750                         } else if (IS_VALLEYVIEW(dev_priv) ||
15751                                    IS_CHERRYVIEW(dev_priv) ||
15752                                    IS_BROXTON(dev_priv))
15753                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15754                         else
15755                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15756                 }
15757
15758                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15759
15760                 readout_plane_state(crtc);
15761
15762                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15763                               crtc->base.base.id,
15764                               crtc->active ? "enabled" : "disabled");
15765         }
15766
15767         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15768                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15769
15770                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15771                                                   &pll->config.hw_state);
15772                 pll->config.crtc_mask = 0;
15773                 for_each_intel_crtc(dev, crtc) {
15774                         if (crtc->active && crtc->config->shared_dpll == pll)
15775                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15776                 }
15777                 pll->active_mask = pll->config.crtc_mask;
15778
15779                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15780                               pll->name, pll->config.crtc_mask, pll->on);
15781         }
15782
15783         for_each_intel_encoder(dev, encoder) {
15784                 pipe = 0;
15785
15786                 if (encoder->get_hw_state(encoder, &pipe)) {
15787                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15788                         encoder->base.crtc = &crtc->base;
15789                         encoder->get_config(encoder, crtc->config);
15790                 } else {
15791                         encoder->base.crtc = NULL;
15792                 }
15793
15794                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15795                               encoder->base.base.id,
15796                               encoder->base.name,
15797                               encoder->base.crtc ? "enabled" : "disabled",
15798                               pipe_name(pipe));
15799         }
15800
15801         for_each_intel_connector(dev, connector) {
15802                 if (connector->get_hw_state(connector)) {
15803                         connector->base.dpms = DRM_MODE_DPMS_ON;
15804
15805                         encoder = connector->encoder;
15806                         connector->base.encoder = &encoder->base;
15807
15808                         if (encoder->base.crtc &&
15809                             encoder->base.crtc->state->active) {
15810                                 /*
15811                                  * This has to be done during hardware readout
15812                                  * because anything calling .crtc_disable may
15813                                  * rely on the connector_mask being accurate.
15814                                  */
15815                                 encoder->base.crtc->state->connector_mask |=
15816                                         1 << drm_connector_index(&connector->base);
15817                                 encoder->base.crtc->state->encoder_mask |=
15818                                         1 << drm_encoder_index(&encoder->base);
15819                         }
15820
15821                 } else {
15822                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15823                         connector->base.encoder = NULL;
15824                 }
15825                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15826                               connector->base.base.id,
15827                               connector->base.name,
15828                               connector->base.encoder ? "enabled" : "disabled");
15829         }
15830
15831         for_each_intel_crtc(dev, crtc) {
15832                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15833
15834                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15835                 if (crtc->base.state->active) {
15836                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15837                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15838                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15839
15840                         /*
15841                          * The initial mode needs to be set in order to keep
15842                          * the atomic core happy. It wants a valid mode if the
15843                          * crtc's enabled, so we do the above call.
15844                          *
15845                          * At this point some state updated by the connectors
15846                          * in their ->detect() callback has not run yet, so
15847                          * no recalculation can be done yet.
15848                          *
15849                          * Even if we could do a recalculation and modeset
15850                          * right now it would cause a double modeset if
15851                          * fbdev or userspace chooses a different initial mode.
15852                          *
15853                          * If that happens, someone indicated they wanted a
15854                          * mode change, which means it's safe to do a full
15855                          * recalculation.
15856                          */
15857                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15858
15859                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15860                         update_scanline_offset(crtc);
15861                 }
15862
15863                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15864         }
15865 }
15866
15867 /* Scan out the current hw modeset state,
15868  * and sanitizes it to the current state
15869  */
15870 static void
15871 intel_modeset_setup_hw_state(struct drm_device *dev)
15872 {
15873         struct drm_i915_private *dev_priv = dev->dev_private;
15874         enum pipe pipe;
15875         struct intel_crtc *crtc;
15876         struct intel_encoder *encoder;
15877         int i;
15878
15879         intel_modeset_readout_hw_state(dev);
15880
15881         /* HW state is read out, now we need to sanitize this mess. */
15882         for_each_intel_encoder(dev, encoder) {
15883                 intel_sanitize_encoder(encoder);
15884         }
15885
15886         for_each_pipe(dev_priv, pipe) {
15887                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15888                 intel_sanitize_crtc(crtc);
15889                 intel_dump_pipe_config(crtc, crtc->config,
15890                                        "[setup_hw_state]");
15891         }
15892
15893         intel_modeset_update_connector_atomic_state(dev);
15894
15895         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15896                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15897
15898                 if (!pll->on || pll->active_mask)
15899                         continue;
15900
15901                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15902
15903                 pll->funcs.disable(dev_priv, pll);
15904                 pll->on = false;
15905         }
15906
15907         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15908                 vlv_wm_get_hw_state(dev);
15909         else if (IS_GEN9(dev))
15910                 skl_wm_get_hw_state(dev);
15911         else if (HAS_PCH_SPLIT(dev))
15912                 ilk_wm_get_hw_state(dev);
15913
15914         for_each_intel_crtc(dev, crtc) {
15915                 unsigned long put_domains;
15916
15917                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15918                 if (WARN_ON(put_domains))
15919                         modeset_put_power_domains(dev_priv, put_domains);
15920         }
15921         intel_display_set_init_power(dev_priv, false);
15922
15923         intel_fbc_init_pipe_state(dev_priv);
15924 }
15925
15926 void intel_display_resume(struct drm_device *dev)
15927 {
15928         struct drm_i915_private *dev_priv = to_i915(dev);
15929         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15930         struct drm_modeset_acquire_ctx ctx;
15931         int ret;
15932         bool setup = false;
15933
15934         dev_priv->modeset_restore_state = NULL;
15935
15936         /*
15937          * This is a cludge because with real atomic modeset mode_config.mutex
15938          * won't be taken. Unfortunately some probed state like
15939          * audio_codec_enable is still protected by mode_config.mutex, so lock
15940          * it here for now.
15941          */
15942         mutex_lock(&dev->mode_config.mutex);
15943         drm_modeset_acquire_init(&ctx, 0);
15944
15945 retry:
15946         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15947
15948         if (ret == 0 && !setup) {
15949                 setup = true;
15950
15951                 intel_modeset_setup_hw_state(dev);
15952                 i915_redisable_vga(dev);
15953         }
15954
15955         if (ret == 0 && state) {
15956                 struct drm_crtc_state *crtc_state;
15957                 struct drm_crtc *crtc;
15958                 int i;
15959
15960                 state->acquire_ctx = &ctx;
15961
15962                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15963                         /*
15964                          * Force recalculation even if we restore
15965                          * current state. With fast modeset this may not result
15966                          * in a modeset when the state is compatible.
15967                          */
15968                         crtc_state->mode_changed = true;
15969                 }
15970
15971                 ret = drm_atomic_commit(state);
15972         }
15973
15974         if (ret == -EDEADLK) {
15975                 drm_modeset_backoff(&ctx);
15976                 goto retry;
15977         }
15978
15979         drm_modeset_drop_locks(&ctx);
15980         drm_modeset_acquire_fini(&ctx);
15981         mutex_unlock(&dev->mode_config.mutex);
15982
15983         if (ret) {
15984                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15985                 drm_atomic_state_free(state);
15986         }
15987 }
15988
15989 void intel_modeset_gem_init(struct drm_device *dev)
15990 {
15991         struct drm_i915_private *dev_priv = to_i915(dev);
15992         struct drm_crtc *c;
15993         struct drm_i915_gem_object *obj;
15994         int ret;
15995
15996         intel_init_gt_powersave(dev_priv);
15997
15998         intel_modeset_init_hw(dev);
15999
16000         intel_setup_overlay(dev_priv);
16001
16002         /*
16003          * Make sure any fbs we allocated at startup are properly
16004          * pinned & fenced.  When we do the allocation it's too early
16005          * for this.
16006          */
16007         for_each_crtc(dev, c) {
16008                 obj = intel_fb_obj(c->primary->fb);
16009                 if (obj == NULL)
16010                         continue;
16011
16012                 mutex_lock(&dev->struct_mutex);
16013                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16014                                                  c->primary->state->rotation);
16015                 mutex_unlock(&dev->struct_mutex);
16016                 if (ret) {
16017                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16018                                   to_intel_crtc(c)->pipe);
16019                         drm_framebuffer_unreference(c->primary->fb);
16020                         c->primary->fb = NULL;
16021                         c->primary->crtc = c->primary->state->crtc = NULL;
16022                         update_state_fb(c->primary);
16023                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16024                 }
16025         }
16026
16027         intel_backlight_register(dev);
16028 }
16029
16030 void intel_connector_unregister(struct intel_connector *intel_connector)
16031 {
16032         struct drm_connector *connector = &intel_connector->base;
16033
16034         intel_panel_destroy_backlight(connector);
16035         drm_connector_unregister(connector);
16036 }
16037
16038 void intel_modeset_cleanup(struct drm_device *dev)
16039 {
16040         struct drm_i915_private *dev_priv = dev->dev_private;
16041         struct intel_connector *connector;
16042
16043         intel_disable_gt_powersave(dev_priv);
16044
16045         intel_backlight_unregister(dev);
16046
16047         /*
16048          * Interrupts and polling as the first thing to avoid creating havoc.
16049          * Too much stuff here (turning of connectors, ...) would
16050          * experience fancy races otherwise.
16051          */
16052         intel_irq_uninstall(dev_priv);
16053
16054         /*
16055          * Due to the hpd irq storm handling the hotplug work can re-arm the
16056          * poll handlers. Hence disable polling after hpd handling is shut down.
16057          */
16058         drm_kms_helper_poll_fini(dev);
16059
16060         intel_unregister_dsm_handler();
16061
16062         intel_fbc_global_disable(dev_priv);
16063
16064         /* flush any delayed tasks or pending work */
16065         flush_scheduled_work();
16066
16067         /* destroy the backlight and sysfs files before encoders/connectors */
16068         for_each_intel_connector(dev, connector)
16069                 connector->unregister(connector);
16070
16071         drm_mode_config_cleanup(dev);
16072
16073         intel_cleanup_overlay(dev_priv);
16074
16075         intel_cleanup_gt_powersave(dev_priv);
16076
16077         intel_teardown_gmbus(dev);
16078 }
16079
16080 /*
16081  * Return which encoder is currently attached for connector.
16082  */
16083 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16084 {
16085         return &intel_attached_encoder(connector)->base;
16086 }
16087
16088 void intel_connector_attach_encoder(struct intel_connector *connector,
16089                                     struct intel_encoder *encoder)
16090 {
16091         connector->encoder = encoder;
16092         drm_mode_connector_attach_encoder(&connector->base,
16093                                           &encoder->base);
16094 }
16095
16096 /*
16097  * set vga decode state - true == enable VGA decode
16098  */
16099 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16100 {
16101         struct drm_i915_private *dev_priv = dev->dev_private;
16102         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16103         u16 gmch_ctrl;
16104
16105         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16106                 DRM_ERROR("failed to read control word\n");
16107                 return -EIO;
16108         }
16109
16110         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16111                 return 0;
16112
16113         if (state)
16114                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16115         else
16116                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16117
16118         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16119                 DRM_ERROR("failed to write control word\n");
16120                 return -EIO;
16121         }
16122
16123         return 0;
16124 }
16125
16126 struct intel_display_error_state {
16127
16128         u32 power_well_driver;
16129
16130         int num_transcoders;
16131
16132         struct intel_cursor_error_state {
16133                 u32 control;
16134                 u32 position;
16135                 u32 base;
16136                 u32 size;
16137         } cursor[I915_MAX_PIPES];
16138
16139         struct intel_pipe_error_state {
16140                 bool power_domain_on;
16141                 u32 source;
16142                 u32 stat;
16143         } pipe[I915_MAX_PIPES];
16144
16145         struct intel_plane_error_state {
16146                 u32 control;
16147                 u32 stride;
16148                 u32 size;
16149                 u32 pos;
16150                 u32 addr;
16151                 u32 surface;
16152                 u32 tile_offset;
16153         } plane[I915_MAX_PIPES];
16154
16155         struct intel_transcoder_error_state {
16156                 bool power_domain_on;
16157                 enum transcoder cpu_transcoder;
16158
16159                 u32 conf;
16160
16161                 u32 htotal;
16162                 u32 hblank;
16163                 u32 hsync;
16164                 u32 vtotal;
16165                 u32 vblank;
16166                 u32 vsync;
16167         } transcoder[4];
16168 };
16169
16170 struct intel_display_error_state *
16171 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16172 {
16173         struct intel_display_error_state *error;
16174         int transcoders[] = {
16175                 TRANSCODER_A,
16176                 TRANSCODER_B,
16177                 TRANSCODER_C,
16178                 TRANSCODER_EDP,
16179         };
16180         int i;
16181
16182         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16183                 return NULL;
16184
16185         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16186         if (error == NULL)
16187                 return NULL;
16188
16189         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16190                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16191
16192         for_each_pipe(dev_priv, i) {
16193                 error->pipe[i].power_domain_on =
16194                         __intel_display_power_is_enabled(dev_priv,
16195                                                          POWER_DOMAIN_PIPE(i));
16196                 if (!error->pipe[i].power_domain_on)
16197                         continue;
16198
16199                 error->cursor[i].control = I915_READ(CURCNTR(i));
16200                 error->cursor[i].position = I915_READ(CURPOS(i));
16201                 error->cursor[i].base = I915_READ(CURBASE(i));
16202
16203                 error->plane[i].control = I915_READ(DSPCNTR(i));
16204                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16205                 if (INTEL_GEN(dev_priv) <= 3) {
16206                         error->plane[i].size = I915_READ(DSPSIZE(i));
16207                         error->plane[i].pos = I915_READ(DSPPOS(i));
16208                 }
16209                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16210                         error->plane[i].addr = I915_READ(DSPADDR(i));
16211                 if (INTEL_GEN(dev_priv) >= 4) {
16212                         error->plane[i].surface = I915_READ(DSPSURF(i));
16213                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16214                 }
16215
16216                 error->pipe[i].source = I915_READ(PIPESRC(i));
16217
16218                 if (HAS_GMCH_DISPLAY(dev_priv))
16219                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16220         }
16221
16222         /* Note: this does not include DSI transcoders. */
16223         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16224         if (HAS_DDI(dev_priv))
16225                 error->num_transcoders++; /* Account for eDP. */
16226
16227         for (i = 0; i < error->num_transcoders; i++) {
16228                 enum transcoder cpu_transcoder = transcoders[i];
16229
16230                 error->transcoder[i].power_domain_on =
16231                         __intel_display_power_is_enabled(dev_priv,
16232                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16233                 if (!error->transcoder[i].power_domain_on)
16234                         continue;
16235
16236                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16237
16238                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16239                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16240                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16241                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16242                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16243                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16244                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16245         }
16246
16247         return error;
16248 }
16249
16250 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16251
16252 void
16253 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16254                                 struct drm_device *dev,
16255                                 struct intel_display_error_state *error)
16256 {
16257         struct drm_i915_private *dev_priv = dev->dev_private;
16258         int i;
16259
16260         if (!error)
16261                 return;
16262
16263         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16264         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16265                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16266                            error->power_well_driver);
16267         for_each_pipe(dev_priv, i) {
16268                 err_printf(m, "Pipe [%d]:\n", i);
16269                 err_printf(m, "  Power: %s\n",
16270                            onoff(error->pipe[i].power_domain_on));
16271                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16272                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16273
16274                 err_printf(m, "Plane [%d]:\n", i);
16275                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16276                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16277                 if (INTEL_INFO(dev)->gen <= 3) {
16278                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16279                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16280                 }
16281                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16282                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16283                 if (INTEL_INFO(dev)->gen >= 4) {
16284                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16285                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16286                 }
16287
16288                 err_printf(m, "Cursor [%d]:\n", i);
16289                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16290                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16291                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16292         }
16293
16294         for (i = 0; i < error->num_transcoders; i++) {
16295                 err_printf(m, "CPU transcoder: %s\n",
16296                            transcoder_name(error->transcoder[i].cpu_transcoder));
16297                 err_printf(m, "  Power: %s\n",
16298                            onoff(error->transcoder[i].power_domain_on));
16299                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16300                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16301                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16302                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16303                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16304                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16305                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16306         }
16307 }